Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use routes for code and preview #402

Merged
merged 5 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions packages/web/src/components/apps/bottom-drawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ export default function BottomDrawer() {
style={{ maxHeight: open ? `${maxHeightInPx}px` : '2rem' }}
>
<div className="flex-shrink-0 flex items-center justify-between border-t border-b h-8 px-1 w-full bg-muted">
<span
<button
onClick={() => togglePane()}
className="text-sm font-medium ml-2 select-none cursor-pointer"
className="px-2 text-sm font-medium h-6 select-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
Logs
</span>
</button>

<div className="flex items-center gap-1">
{open && logs.length > 0 && (
Expand Down Expand Up @@ -98,12 +98,12 @@ export default function BottomDrawer() {
<tbody>
{logs.map((log, index) => (
<tr key={index}>
<td className="align-top whitespace-nowrap select-none pointer-events-none whitespace-nowrap w-0 pr-4">
<td className="align-top select-none pointer-events-none whitespace-nowrap w-0 pr-4">
<span className="font-mono text-tertiary-foreground/80">
{log.timestamp.toISOString()}
</span>
</td>
<td className="align-top whitespace-nowrap select-none pointer-events-none whitespace-nowrap w-0 pr-4">
<td className="align-top select-none pointer-events-none whitespace-nowrap w-0 pr-4">
<span className="font-mono text-tertiary-foreground">{log.source}</span>
</td>
<td className="align-top">
Expand Down
7 changes: 3 additions & 4 deletions packages/web/src/components/apps/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,12 @@ import { exportApp } from '@/clients/http/apps';
import { toast } from 'sonner';
import { useLogs } from './use-logs';

export type EditorHeaderTab = 'code' | 'preview';
export type HeaderTab = 'code' | 'preview';

type PropsType = {
className?: string;
tab: EditorHeaderTab;
onChangeTab: (newTab: EditorHeaderTab) => void;
onShowPackagesPanel: () => void;
tab: HeaderTab;
onChangeTab: (newTab: HeaderTab) => void;
};

export default function EditorHeader(props: PropsType) {
Expand Down
15 changes: 15 additions & 0 deletions packages/web/src/components/apps/local-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { FileType } from '@srcbook/shared';

export function getLastOpenedFile(appId: string) {
const value = window.localStorage.getItem(`apps:${appId}:last_opened_file`);

if (typeof value === 'string') {
return JSON.parse(value);
}

return null;
}

export function setLastOpenedFile(appId: string, file: FileType) {
return window.localStorage.setItem(`apps:${appId}:last_opened_file`, JSON.stringify(file));
}
10 changes: 5 additions & 5 deletions packages/web/src/components/apps/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,19 @@ function getTitleForPanel(panel: PanelType | null): string | null {
}

type SidebarProps = {
panel: PanelType | null;
onChangePanel: (newPanel: PanelType | null) => void;
initialPanel: PanelType | null;
};

export default function Sidebar({ panel, onChangePanel }: SidebarProps) {
export default function Sidebar({ initialPanel }: SidebarProps) {
const { theme, toggleTheme } = useTheme();

const { status } = usePackageJson();
const [panel, _setPanel] = useState<PanelType | null>(initialPanel);
const [showShortcuts, setShowShortcuts] = useState(false);
const [showFeedback, setShowFeedback] = useState(false);
const { status } = usePackageJson();

function setPanel(nextPanel: PanelType) {
onChangePanel(nextPanel === panel ? null : nextPanel);
_setPanel(nextPanel === panel ? null : nextPanel);
}

return (
Expand Down
27 changes: 25 additions & 2 deletions packages/web/src/components/apps/use-app.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { createContext, useContext, useState } from 'react';
import { createContext, useContext, useEffect, useRef, useState } from 'react';
import type { AppType } from '@srcbook/shared';
import { updateApp as doUpdateApp } from '@/clients/http/apps';
import { AppChannel } from '@/clients/websocket';

export interface AppContextValue {
app: AppType;
channel: AppChannel;
updateApp: (attrs: { name: string }) => void;
}

Expand All @@ -17,12 +19,33 @@ type ProviderPropsType = {
export function AppProvider({ app: initialApp, children }: ProviderPropsType) {
const [app, setApp] = useState(initialApp);

const channelRef = useRef(AppChannel.create(app.id));

// This is only meant to be run one time, when the component mounts.
useEffect(() => {
channelRef.current.subscribe();
return () => channelRef.current.unsubscribe();
}, []);

useEffect(() => {
if (app.id === channelRef.current.appId) {
return;
}

channelRef.current.unsubscribe();
channelRef.current = AppChannel.create(app.id);
}, [app.id]);

async function updateApp(attrs: { name: string }) {
const { data: updatedApp } = await doUpdateApp(app.id, attrs);
setApp(updatedApp);
}

return <AppContext.Provider value={{ app, updateApp }}>{children}</AppContext.Provider>;
return (
<AppContext.Provider value={{ app, updateApp, channel: channelRef.current }}>
{children}
</AppContext.Provider>
);
}

export function useApp(): AppContextValue {
Expand Down
70 changes: 55 additions & 15 deletions packages/web/src/components/apps/use-files.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import React, { createContext, useCallback, useContext, useReducer, useRef, useState } from 'react';
import React, {
createContext,
useCallback,
useContext,
useEffect,
useReducer,
useRef,
useState,
} from 'react';

import type { FileType, DirEntryType, FileEntryType } from '@srcbook/shared';
import { AppChannel } from '@/clients/websocket';
Expand All @@ -10,7 +18,6 @@ import {
deleteDirectory,
renameDirectory,
loadDirectory,
loadFile,
} from '@/clients/http/apps';
import {
createNode,
Expand All @@ -21,11 +28,13 @@ import {
updateFileNode,
} from './lib/file-tree';
import { useApp } from './use-app';
import { useNavigate } from 'react-router-dom';
import { setLastOpenedFile } from './local-storage';

export interface FilesContextValue {
fileTree: DirEntryType;
openedFile: FileType | null;
openFile: (entry: FileEntryType) => Promise<void>;
openFile: (entry: FileEntryType) => void;
createFile: (dirname: string, basename: string, source?: string) => Promise<FileEntryType>;
updateFile: (file: FileType, attrs: Partial<FileType>) => void;
renameFile: (entry: FileEntryType, name: string) => Promise<void>;
Expand All @@ -44,10 +53,16 @@ const FilesContext = createContext<FilesContextValue | undefined>(undefined);
type ProviderPropsType = {
channel: AppChannel;
children: React.ReactNode;
initialOpenedFile: FileType | null;
rootDirEntries: DirEntryType;
};

export function FilesProvider({ channel, rootDirEntries, children }: ProviderPropsType) {
export function FilesProvider({
channel,
rootDirEntries,
initialOpenedFile,
children,
}: ProviderPropsType) {
// Because we use refs for our state, we need a way to trigger
// component re-renders when the ref state changes.
//
Expand All @@ -56,18 +71,43 @@ export function FilesProvider({ channel, rootDirEntries, children }: ProviderPro
const [, forceComponentRerender] = useReducer((x) => x + 1, 0);

const { app } = useApp();
const navigateTo = useNavigate();

const fileTreeRef = useRef<DirEntryType>(sortTree(rootDirEntries));
const openedDirectoriesRef = useRef<Set<string>>(new Set());
const [openedFile, _setOpenedFile] = useState<FileType | null>(initialOpenedFile);

const [openedFile, setOpenedFile] = useState<FileType | null>(null);
const setOpenedFile = useCallback(
(fn: (file: FileType | null) => FileType | null) => {
_setOpenedFile((prevOpenedFile) => {
const openedFile = fn(prevOpenedFile);
if (openedFile) {
setLastOpenedFile(app.id, openedFile);
}
return openedFile;
});
},
[app.id],
);

const navigateToFile = useCallback(
(file: { path: string }) => {
navigateTo(`/apps/${app.id}/files/${encodeURIComponent(file.path)}`);
},
[app.id, navigateTo],
);

useEffect(() => {
if (initialOpenedFile !== null && initialOpenedFile?.path !== openedFile?.path) {
setOpenedFile(() => initialOpenedFile);
}
}, [initialOpenedFile, openedFile?.path, setOpenedFile]);

const openFile = useCallback(
async (entry: FileEntryType) => {
const { data: file } = await loadFile(app.id, entry.path);
setOpenedFile(file);
(entry: FileEntryType) => {
navigateToFile(entry);
},
[app.id],
[navigateToFile],
);

const createFile = useCallback(
Expand All @@ -85,10 +125,10 @@ export function FilesProvider({ channel, rootDirEntries, children }: ProviderPro
(file: FileType, attrs: Partial<FileType>) => {
const updatedFile: FileType = { ...file, ...attrs };
channel.push('file:updated', { file: updatedFile });
setOpenedFile(updatedFile);
setOpenedFile(() => updatedFile);
forceComponentRerender();
},
[channel],
[channel, setOpenedFile],
);

const deleteFile = useCallback(
Expand All @@ -103,7 +143,7 @@ export function FilesProvider({ channel, rootDirEntries, children }: ProviderPro
fileTreeRef.current = deleteNode(fileTreeRef.current, entry.path);
forceComponentRerender(); // required
},
[app.id],
[app.id, setOpenedFile],
);

const renameFile = useCallback(
Expand All @@ -118,7 +158,7 @@ export function FilesProvider({ channel, rootDirEntries, children }: ProviderPro
fileTreeRef.current = updateFileNode(fileTreeRef.current, entry, newEntry);
forceComponentRerender(); // required
},
[app.id],
[app.id, setOpenedFile],
);

const isFolderOpen = useCallback((entry: DirEntryType) => {
Expand Down Expand Up @@ -176,7 +216,7 @@ export function FilesProvider({ channel, rootDirEntries, children }: ProviderPro
fileTreeRef.current = deleteNode(fileTreeRef.current, entry.path);
forceComponentRerender(); // required
},
[app.id],
[app.id, setOpenedFile],
);

const renameFolder = useCallback(
Expand All @@ -199,7 +239,7 @@ export function FilesProvider({ channel, rootDirEntries, children }: ProviderPro

forceComponentRerender(); // required
},
[app.id],
[app.id, setOpenedFile],
);

const context: FilesContextValue = {
Expand Down
55 changes: 0 additions & 55 deletions packages/web/src/components/apps/workspace/editor.tsx

This file was deleted.

Loading