Skip to content

Commit

Permalink
feat: branch swapping
Browse files Browse the repository at this point in the history
  • Loading branch information
rob-at-airwalk committed Jun 16, 2024
1 parent 53fe413 commit c2ec27f
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 107 deletions.
20 changes: 13 additions & 7 deletions src/_components/Layouts/ControlBar.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@ export default {
title: 'App Bar/ControlBar',
component: ControlBar,
tags: ['autodocs'],
parameters: { actions: { argTypesRegex: '^on.*|^handle*' } },
parameters: {
actions: { argTypesRegex: '^on.*|^handle*' },
nextjs: {
appDirectory: true,
},
},
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
result: { control: { type: 'radio' }, options: ['success', 'error'] },
// backgroundColor: { control: 'color' },
},

args: {
handleRefresh: fn(),
handlePrint: fn(),
Expand Down Expand Up @@ -155,10 +161,10 @@ export const DefaultBranch = {
const Template: StoryFn<StorybookControlBar> = (args) => {
// const [collection, setCollection] = useState(dummyCollection);
const [editMode, setEditMode] = useState(args.editMode || false);
const [context, setContext] = useState({
const context = {
...args.context,
branch: 'main',
});
};

// function fn()() {}

Expand All @@ -167,9 +173,9 @@ const Template: StoryFn<StorybookControlBar> = (args) => {
fn();
};

function onContextUpdate(newCollection: ExtendedContentItem) {
setContext(newCollection);
}
// function onContextUpdate(newCollection: ExtendedContentItem) {
// setContext(newCollection);
// }

function dummyDelay() {
fn();
Expand All @@ -194,7 +200,7 @@ const Template: StoryFn<StorybookControlBar> = (args) => {
handlePresentation={() => fn()}
handlePrint={() => fn()}
handleNewBranch={() => fn()}
onContextUpdate={() => onContextUpdate}
// onContextUpdate={() => onContextUpdate}
collection={args.collection}
context={context}
branches={args.branches}
Expand Down
43 changes: 29 additions & 14 deletions src/_components/Layouts/ControlBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ import {
} from '@mui/material';
import MuiAlert from '@mui/material/Alert';
import CircularProgress from '@mui/material/CircularProgress';
import { usePathname, useRouter } from 'next/navigation';
import React, { useEffect, useState } from 'react';

import { getLogger } from '@/lib/Logger';

const logger = getLogger().child({ namespace: 'ControlBar' });
logger.level = 'info';
export interface ControlBarProps {
open: boolean;
// height: number;
Expand All @@ -29,22 +34,22 @@ export interface ControlBarProps {
context: any;
branches: any[];
top?: number;
onContextUpdate: (context: any) => void;
// onContextUpdate: (context: any) => void;
editMode: boolean;
fetchBranches?: (collection: any) => void;
handleNewBranch?: () => void;
handlePR?: () => void;
}

interface BranchSelectorProps {
onBranchChange: (event: any, value: any) => void;
// onBranchChange: (event: any, value: any) => void;
branches: any[];
branch: any;
collection: any;
}

const BranchSelector: React.FC<BranchSelectorProps> = ({
onBranchChange,
// onBranchChange,
branches,
branch,
collection,
Expand All @@ -56,6 +61,16 @@ const BranchSelector: React.FC<BranchSelectorProps> = ({
error = true;
}

const router = useRouter();
const pathname = usePathname();
const onBranchChange = (value: any) => {
logger.info('handleContextUpdate', value);
const pathnameArray = pathname.split('/');
pathnameArray[3] = value;
const newPathname = pathnameArray.join('/');
router.push(newPathname);
};

return (
<Stack spacing={2} sx={{ width: 300 }}>
<Autocomplete
Expand Down Expand Up @@ -88,7 +103,7 @@ export const ControlBar: React.FC<ControlBarProps> = ({
context,
branches,
top = '64px',
onContextUpdate,
// onContextUpdate,
editMode,
fetchBranches = () => {},
handleNewBranch = () => {},
Expand All @@ -109,9 +124,9 @@ export const ControlBar: React.FC<ControlBarProps> = ({

const onBranchToggle = async (state = 'ignore') => {
if (changeBranch) {
const newCollection = { ...collection };
// const newCollection = { ...collection };
setBranch(collection.branch);
onContextUpdate(newCollection);
// onContextUpdate(newCollection);
if (typeof window !== 'undefined') {
const url = new URL(window.location.href);
if (url.searchParams.has('branch')) {
Expand All @@ -130,13 +145,13 @@ export const ControlBar: React.FC<ControlBarProps> = ({
}
};

const onBranchChange = async (value: any) => {
if (value) {
const newContext = { ...collection, branch: value };
setBranch(value);
onContextUpdate(newContext);
}
};
// const onBranchChange = async (value: any) => {
// if (value) {
// const newContext = { ...collection, branch: value };
// setBranch(value);
// onContextUpdate(newContext);
// }
// };

const handlePresentationClick = () => {
if (typeof handlePresentation === 'function') {
Expand Down Expand Up @@ -220,7 +235,7 @@ export const ControlBar: React.FC<ControlBarProps> = ({
<FormControlLabel
control={
<BranchSelector
onBranchChange={onBranchChange}
// onBranchChange={onBranchChange}
branches={branches}
branch={branch}
collection={collection}
Expand Down
37 changes: 12 additions & 25 deletions src/_components/Layouts/MenuWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import React, { Suspense, useState } from 'react';

import TopBar from '@/components/Layouts/TopBar';
import { DummyMenu, HeaderMinimalMenu } from '@/components/Menus';
import EditorWrapper from '@/features/Mdx/EditorWrapper';
import { getLogger } from '@/lib/Logger';
import type { ContentItem, MenuStructure } from '@/lib/Types';

Expand Down Expand Up @@ -134,30 +133,18 @@ export default function MenuWrapper({
/>
)}
<Suspense fallback={<p>Loading...</p>}>
{isEditing && (
<div
style={{
marginTop: topBarHeight,
paddingLeft: !menuOpen || loading ? 0 : navDrawerWidth,
}}
>
<EditorWrapper context={context} />
</div>
)}
{!isEditing && (
<div
style={{
marginTop: topBarHeight,
paddingLeft: !menuOpen || loading ? 0 : navDrawerWidth,
}}
>
{/* <Box sx={{ px: '2%' }} > */}
<Container sx={{ maxHeight: '100vh', pt: '2%', px: '2%' }}>
{children && children}
</Container>
{/* </Box> */}
</div>
)}
<div
style={{
marginTop: topBarHeight,
paddingLeft: !menuOpen || loading ? 0 : navDrawerWidth,
}}
>
{/* <Box sx={{ px: '2%' }} > */}
<Container sx={{ maxHeight: '100vh', pt: '2%', px: '2%' }}>
{children && children}
</Container>
{/* </Box> */}
</div>
</Suspense>
</>
);
Expand Down
80 changes: 23 additions & 57 deletions src/_features/Mdx/EditorWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,19 @@ import { getLogger } from '@/lib/Logger';
import type { ContentItem } from '@/lib/Types';

const logger = getLogger().child({ namespace: 'EditorWrapper' });
logger.level = 'warn';
logger.level = 'info';

interface EditorWrapperProps {
defaultContext: ContentItem | undefined;
context: ContentItem;
branches: { name: string; commit: { sha: string }; protected: boolean }[];
}

export default function EditorWrapper({ context }: EditorWrapperProps) {
export default function EditorWrapper({
defaultContext,
context,
branches,
}: EditorWrapperProps) {
const editorRef = useRef<MDXEditorMethods | null>(null);
const searchParams = `owner=${context.owner}&repo=${context.repo}&path=${context.file}&branch=${context.branch}`;
const [mdx, setMdx] = useState('');
Expand All @@ -31,63 +37,23 @@ export default function EditorWrapper({ context }: EditorWrapperProps) {

fetchData();
}, [context, searchParams]);

// const router = useRouter();
// const pathname = usePathname();
// const handleContextUpdate = (newContext: any) => {
// logger.info('handleContextUpdate', newContext);
// const pathnameArray = pathname.split('/');
// pathnameArray[2] = newContext.branch;
// const newPathname = pathnameArray.join('/');
// router.push(newPathname);
// };

return (
<>
<ControlBar
branches={[
{
commit: {
sha: '53bfd8457509778140caa47b01c6476d661f1b34',
url: 'https://api.github.com/repos/AirWalk-Digital/airwalk_patterns/commits/53bfd8457509778140caa47b01c6476d661f1b34',
},
name: 'main',
protected: true,
},
{
commit: {
sha: '53bfd8457509778140caa47b01c6476d661f1b34',
url: 'https://api.github.com/repos/AirWalk-Digital/airwalk_patterns/commits/53bfd8457509778140caa47b01c6476d661f1b34',
},
name: 'branch-1',
protected: false,
},
{
commit: {
sha: '09a01dc4e148c35412d3a6a00a384930a41b813b',
url: 'https://api.github.com/repos/AirWalk-Digital/airwalk_patterns/commits/09a01dc4e148c35412d3a6a00a384930a41b813b',
},
name: 'branch-2',
protected: false,
},
{
commit: {
sha: '7080423b89568b0427cb781f8b753f52fbc394e0',
url: 'https://api.github.com/repos/AirWalk-Digital/airwalk_patterns/commits/7080423b89568b0427cb781f8b753f52fbc394e0',
},
name: 'branch-3',
protected: false,
},
]}
collection={{
base_branch: 'main',
branch: 'main',
collections: ['services'],
owner: 'airwalk-digital',
path: 'providers',
reference: 'provider',
repo: 'airwalk_patterns',
source: 'github',
}}
context={{
base_branch: 'main',
branch: 'main',
collections: ['services'],
owner: 'airwalk-digital',
path: 'providers',
reference: 'provider',
repo: 'airwalk_patterns',
source: 'github',
}}
branches={branches}
collection={defaultContext}
context={context}
fetchBranches={() => {}}
handleAdd={() => {}}
handleEdit={() => {}}
Expand All @@ -96,7 +62,7 @@ export default function EditorWrapper({ context }: EditorWrapperProps) {
handlePresentation={() => {}}
handlePrint={() => {}}
// handleRefresh={() => {}}
onContextUpdate={() => {}}
// onContextUpdate={handleContextUpdate}
open
editMode
top={65}
Expand Down
16 changes: 13 additions & 3 deletions src/app/docs/[mode]/[branch]/[[...path]]/@edit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { notFound } from 'next/navigation';
import { getLogger } from '@/lib/Logger';
import type { ContentItem } from '@/lib/Types';
import EditorWrapper from '@/features/Mdx/EditorWrapper';
import { getBranches } from '@/lib/Github';

const logger = getLogger().child({ namespace: 'docs/page/@edit' });
logger.level = 'info';
Expand All @@ -18,7 +19,7 @@ export const metadata: Metadata = {
export default async function Page({
params,
}: {
params: { path?: string[] };
params: { mode: 'view' | 'edit' | 'print'; branch: string; path: string[] };
}) {
const topBarHeight = 65;
if (
Expand All @@ -39,11 +40,16 @@ export default async function Page({
}

const contentKey = params.path[0] as keyof typeof siteConfig.content;
const branch = () =>
params.branch === 'default'
? siteConfig?.content?.[contentKey]?.branch
: params.branch;
const contentConfig = {
...siteConfig?.content?.[contentKey],
file: file,
branch: branch(),
} as ContentItem;

const branches = await getBranches(contentConfig.owner, contentConfig.repo);
return (
<main>
<TopBar
Expand All @@ -61,7 +67,11 @@ export default async function Page({
paddingLeft: 0,
}}
>
<EditorWrapper context={contentConfig} />
<EditorWrapper
defaultContext={siteConfig.content[contentKey]}
context={contentConfig}
branches={branches}
/>
</div>
</Suspense>
</main>
Expand Down
7 changes: 6 additions & 1 deletion src/app/docs/[mode]/[branch]/[[...path]]/@view/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ async function checkFrontmatter(content: string, context: ContentItem) {
export default async function Page({
params,
}: {
params: { path?: string[] };
params: { mode: 'view' | 'edit' | 'print'; branch: string; path: string[] };
}) {
if (
params.path &&
Expand All @@ -89,9 +89,14 @@ export default async function Page({
let pageContentText;
let loading = false;
const contentKey = params.path[0] as keyof typeof siteConfig.content;
const branch = () =>
params.branch === 'default'
? siteConfig?.content?.[contentKey]?.branch
: params.branch;
const contentConfig = {
...siteConfig?.content?.[contentKey],
file: file,
branch: branch(),
} as ContentItem;

const menuConfig = (contentConfig: ContentItem) => {
Expand Down

0 comments on commit c2ec27f

Please sign in to comment.