refactor: reorganize src structure
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { DrawingSidebar, DrawingsToggle } from "./components/DrawingSidebar";
|
||||
import { EditorCanvas } from "./components/EditorCanvas";
|
||||
import { useDrawingSession } from "./hooks/useDrawingSession";
|
||||
import { useThemeTokenSync } from "./hooks/useThemeTokenSync";
|
||||
|
||||
export function App() {
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
const appShellRef = useRef<HTMLDivElement | null>(null);
|
||||
const scheduleThemeTokenSync = useThemeTokenSync(appShellRef);
|
||||
const {
|
||||
drawings,
|
||||
activeId,
|
||||
activeTitle,
|
||||
scene,
|
||||
loading,
|
||||
error,
|
||||
toastMessage,
|
||||
editorReloadNonce,
|
||||
setActiveTitle,
|
||||
submitTitle,
|
||||
handleSceneChange,
|
||||
selectDrawing,
|
||||
createDrawing,
|
||||
deleteDrawing,
|
||||
} = useDrawingSession();
|
||||
|
||||
useEffect(() => {
|
||||
if (!scene || loading) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleThemeTokenSync();
|
||||
}, [activeId, loading, scene, scheduleThemeTokenSync]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSidebarOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
setIsSidebarOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [isSidebarOpen]);
|
||||
|
||||
const openSidebar = useCallback(() => {
|
||||
setIsSidebarOpen(true);
|
||||
}, []);
|
||||
|
||||
const closeSidebar = useCallback(() => {
|
||||
setIsSidebarOpen(false);
|
||||
}, []);
|
||||
|
||||
const handleSelectDrawing = useCallback(
|
||||
(drawingId: string) => {
|
||||
setIsSidebarOpen(false);
|
||||
void selectDrawing(drawingId);
|
||||
},
|
||||
[selectDrawing],
|
||||
);
|
||||
|
||||
const handleCreateDrawing = useCallback(() => {
|
||||
setIsSidebarOpen(false);
|
||||
void createDrawing();
|
||||
}, [createDrawing]);
|
||||
|
||||
return (
|
||||
<div className="app-shell" ref={appShellRef}>
|
||||
{toastMessage && (
|
||||
<div className="toast-overlay" aria-live="polite">
|
||||
{toastMessage}
|
||||
</div>
|
||||
)}
|
||||
<main className="editor-shell">
|
||||
<div className="app-actions">
|
||||
<DrawingsToggle onClick={openSidebar} />
|
||||
</div>
|
||||
|
||||
<EditorCanvas
|
||||
activeId={activeId}
|
||||
scene={scene}
|
||||
loading={loading}
|
||||
error={error}
|
||||
editorReloadNonce={editorReloadNonce}
|
||||
onSceneChange={handleSceneChange}
|
||||
onEditorActivity={scheduleThemeTokenSync}
|
||||
/>
|
||||
</main>
|
||||
<DrawingSidebar
|
||||
open={isSidebarOpen}
|
||||
drawings={drawings}
|
||||
activeId={activeId}
|
||||
activeTitle={activeTitle}
|
||||
onClose={closeSidebar}
|
||||
onCreate={handleCreateDrawing}
|
||||
onSelect={handleSelectDrawing}
|
||||
onDelete={(drawingId) => void deleteDrawing(drawingId)}
|
||||
onTitleChange={setActiveTitle}
|
||||
onTitleSubmit={() => void submitTitle()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { type DrawingMeta } from "../../core/shared";
|
||||
|
||||
type DrawingSidebarProps = {
|
||||
open: boolean;
|
||||
drawings: DrawingMeta[];
|
||||
activeId: string | null;
|
||||
activeTitle: string;
|
||||
onClose: () => void;
|
||||
onCreate: () => void;
|
||||
onSelect: (drawingId: string) => void;
|
||||
onDelete: (drawingId: string) => void;
|
||||
onTitleChange: (title: string) => void;
|
||||
onTitleSubmit: () => void;
|
||||
};
|
||||
|
||||
function DrawerIcon() {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<rect x="3.5" y="5" width="17" height="14" rx="2.5" fill="none" stroke="currentColor" strokeWidth="1.8" />
|
||||
<path d="M9 5v14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M5.75 9h1.5M5.75 12h1.5M5.75 15h1.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function DrawingsToggle({ onClick }: { onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button app-actions-toggle"
|
||||
onClick={onClick}
|
||||
aria-label="Open drawings"
|
||||
>
|
||||
<DrawerIcon />
|
||||
<span className="sr-only">Open drawings</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function DrawingSidebar({
|
||||
open,
|
||||
drawings,
|
||||
activeId,
|
||||
activeTitle,
|
||||
onClose,
|
||||
onCreate,
|
||||
onSelect,
|
||||
onDelete,
|
||||
onTitleChange,
|
||||
onTitleSubmit,
|
||||
}: DrawingSidebarProps) {
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={open ? "sidebar-backdrop sidebar-backdrop-open" : "sidebar-backdrop"}
|
||||
onClick={onClose}
|
||||
aria-hidden={!open}
|
||||
/>
|
||||
<aside className={open ? "sidebar sidebar-open" : "sidebar"} aria-hidden={!open}>
|
||||
<div className="sidebar-header">
|
||||
<h1>excali-box</h1>
|
||||
<div className="sidebar-actions">
|
||||
<button type="button" className="primary-button" onClick={onCreate}>
|
||||
New
|
||||
</button>
|
||||
<button type="button" className="icon-button" onClick={onClose} aria-label="Close drawings">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="drawing-list">
|
||||
{drawings.map((drawing) => (
|
||||
<div
|
||||
key={drawing.id}
|
||||
className={drawing.id === activeId ? "drawing-item drawing-item-active" : "drawing-item"}
|
||||
>
|
||||
{drawing.id === activeId ? (
|
||||
<div className="drawing-link">
|
||||
<input
|
||||
className="title-input"
|
||||
value={activeTitle}
|
||||
onChange={(event) => onTitleChange(event.target.value)}
|
||||
onBlur={onTitleSubmit}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.currentTarget.blur();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<button type="button" className="drawing-link" onClick={() => onSelect(drawing.id)}>
|
||||
<span className="drawing-title">{drawing.title}</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="icon-button"
|
||||
onClick={() => onDelete(drawing.id)}
|
||||
aria-label={`Delete ${drawing.title}`}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import "../../../node_modules/@excalidraw/excalidraw/dist/prod/index.css";
|
||||
import { Excalidraw } from "@excalidraw/excalidraw";
|
||||
import type {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
ExcalidrawInitialDataState,
|
||||
} from "@excalidraw/excalidraw/types";
|
||||
import { type ScenePayload } from "../../core/shared";
|
||||
|
||||
type EditorCanvasProps = {
|
||||
activeId: string | null;
|
||||
scene: ScenePayload | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
editorReloadNonce: number;
|
||||
onSceneChange: (scene: ScenePayload) => void;
|
||||
onEditorActivity: () => void;
|
||||
};
|
||||
|
||||
function sceneToInitialData(scene: ScenePayload): ExcalidrawInitialDataState {
|
||||
return scene as ExcalidrawInitialDataState;
|
||||
}
|
||||
|
||||
function sceneFromEditor(
|
||||
elements: readonly unknown[],
|
||||
appState: AppState,
|
||||
files: BinaryFiles,
|
||||
): ScenePayload {
|
||||
return {
|
||||
elements: [...elements],
|
||||
appState: appState as unknown as Record<string, unknown>,
|
||||
files: files as unknown as Record<string, unknown>,
|
||||
};
|
||||
}
|
||||
|
||||
export function EditorCanvas({
|
||||
activeId,
|
||||
scene,
|
||||
loading,
|
||||
error,
|
||||
editorReloadNonce,
|
||||
onSceneChange,
|
||||
onEditorActivity,
|
||||
}: EditorCanvasProps) {
|
||||
if (loading || !scene) {
|
||||
return <div className="editor-loading">{error ?? "Loading..."}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="editor-frame">
|
||||
<Excalidraw
|
||||
key={`${activeId}:${editorReloadNonce}`}
|
||||
initialData={sceneToInitialData(scene)}
|
||||
onChange={(elements, appState, files) => {
|
||||
onEditorActivity();
|
||||
onSceneChange(sceneFromEditor(elements, appState, files));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { DEFAULT_TITLE, type DrawingMeta, type ScenePayload } from "../../core/shared";
|
||||
|
||||
type DrawingResponse = DrawingMeta & ScenePayload;
|
||||
type ApiErrorBody = { ok: false; error?: string; drawing?: DrawingMeta };
|
||||
type UpdateResponse = { ok: true; drawing: DrawingMeta };
|
||||
|
||||
class RequestError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly body: ApiErrorBody,
|
||||
) {
|
||||
super(body.error ?? `Request failed: ${status}`);
|
||||
}
|
||||
}
|
||||
|
||||
function pathToId(pathname = window.location.pathname): string | null {
|
||||
const match = pathname.match(/^\/d\/([^/]+)$/);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
function sortDrawings(drawings: DrawingMeta[]): DrawingMeta[] {
|
||||
return [...drawings].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||
}
|
||||
|
||||
function replaceMeta(drawings: DrawingMeta[], drawing: DrawingMeta): DrawingMeta[] {
|
||||
const filtered = drawings.filter((item) => item.id !== drawing.id);
|
||||
return sortDrawings([drawing, ...filtered]);
|
||||
}
|
||||
|
||||
async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.body ? { "content-type": "application/json" } : {}),
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
|
||||
const body = (await response.json()) as T & ApiErrorBody;
|
||||
if (!response.ok) {
|
||||
throw new RequestError(response.status, body);
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
function fetchDrawingList() {
|
||||
return requestJson<DrawingMeta[]>("/api/drawings", { method: "GET" });
|
||||
}
|
||||
|
||||
function isConflictError(error: unknown): error is RequestError & { body: ApiErrorBody & { drawing: DrawingMeta } } {
|
||||
return error instanceof RequestError && error.status === 409 && error.body.drawing !== undefined;
|
||||
}
|
||||
|
||||
function sceneFromDrawing(drawing: DrawingResponse): ScenePayload {
|
||||
return {
|
||||
elements: drawing.elements,
|
||||
appState: drawing.appState,
|
||||
files: drawing.files,
|
||||
};
|
||||
}
|
||||
|
||||
export function useDrawingSession() {
|
||||
const [drawings, setDrawings] = useState<DrawingMeta[]>([]);
|
||||
const [activeId, setActiveId] = useState<string | null>(pathToId());
|
||||
const [activeTitle, setActiveTitleState] = useState(DEFAULT_TITLE);
|
||||
const [scene, setScene] = useState<ScenePayload | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [toastMessage, setToastMessage] = useState<string | null>(null);
|
||||
const [editorReloadNonce, setEditorReloadNonce] = useState(0);
|
||||
|
||||
const currentIdRef = useRef<string | null>(activeId);
|
||||
const currentTitleRef = useRef(activeTitle);
|
||||
const latestSceneRef = useRef<ScenePayload | null>(null);
|
||||
const ignoreChangeRef = useRef(false);
|
||||
const saveTimeoutRef = useRef<number | null>(null);
|
||||
const toastTimeoutRef = useRef<number | null>(null);
|
||||
const inFlightSaveRef = useRef<Promise<void> | null>(null);
|
||||
const loadVersionRef = useRef(0);
|
||||
const loadedRevisionRef = useRef<number | null>(null);
|
||||
|
||||
const clearPendingSaveTimeout = useCallback(() => {
|
||||
if (saveTimeoutRef.current !== null) {
|
||||
clearTimeout(saveTimeoutRef.current);
|
||||
saveTimeoutRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const showToast = useCallback((message: string | null, timeoutMs?: number) => {
|
||||
if (toastTimeoutRef.current !== null) {
|
||||
clearTimeout(toastTimeoutRef.current);
|
||||
toastTimeoutRef.current = null;
|
||||
}
|
||||
|
||||
setToastMessage(message);
|
||||
if (message !== null && timeoutMs !== undefined) {
|
||||
toastTimeoutRef.current = window.setTimeout(() => setToastMessage(null), timeoutMs);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const refreshList = useCallback(async () => {
|
||||
const list = await fetchDrawingList();
|
||||
setDrawings(sortDrawings(list));
|
||||
return list;
|
||||
}, []);
|
||||
|
||||
const loadDrawing = useCallback(
|
||||
async (drawingId: string) => {
|
||||
const version = ++loadVersionRef.current;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [list, drawing] = await Promise.all([
|
||||
requestJson<DrawingMeta[]>("/api/drawings", { method: "GET" }),
|
||||
requestJson<DrawingResponse>(`/api/drawings/${drawingId}`, { method: "GET" }),
|
||||
]);
|
||||
|
||||
if (version !== loadVersionRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextScene = sceneFromDrawing(drawing);
|
||||
|
||||
ignoreChangeRef.current = true;
|
||||
currentIdRef.current = drawing.id;
|
||||
currentTitleRef.current = drawing.title;
|
||||
latestSceneRef.current = nextScene;
|
||||
loadedRevisionRef.current = drawing.revision;
|
||||
|
||||
setDrawings(replaceMeta(list, drawing));
|
||||
setActiveId(drawing.id);
|
||||
setActiveTitleState(drawing.title);
|
||||
setScene(nextScene);
|
||||
setEditorReloadNonce((current) => current + 1);
|
||||
} catch (loadError) {
|
||||
if (version !== loadVersionRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const list = await fetchDrawingList();
|
||||
if (version !== loadVersionRef.current) {
|
||||
return;
|
||||
}
|
||||
setDrawings(sortDrawings(list));
|
||||
|
||||
if (list.length === 0) {
|
||||
const created = await requestJson<DrawingResponse>("/api/drawings", { method: "POST" });
|
||||
if (version !== loadVersionRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.history.replaceState(null, "", `/d/${created.id}`);
|
||||
await loadDrawing(created.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const fallback = list[0];
|
||||
if (fallback && fallback.id !== drawingId) {
|
||||
window.history.replaceState(null, "", `/d/${fallback.id}`);
|
||||
await loadDrawing(fallback.id);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(loadError instanceof Error ? loadError.message : "Failed to load drawing");
|
||||
} finally {
|
||||
if (version === loadVersionRef.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const saveScene = useCallback(
|
||||
async (isManual = false) => {
|
||||
const drawingId = currentIdRef.current;
|
||||
const nextScene = latestSceneRef.current;
|
||||
const expectedRevision = loadedRevisionRef.current;
|
||||
if (!drawingId || !nextScene) {
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
|
||||
if (isManual) {
|
||||
showToast("Saving...");
|
||||
}
|
||||
|
||||
const promise = requestJson<UpdateResponse>(`/api/drawings/${drawingId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ ...nextScene, expectedRevision }),
|
||||
})
|
||||
.then((body) => {
|
||||
setDrawings((current) => replaceMeta(current, body.drawing));
|
||||
if (currentIdRef.current === drawingId) {
|
||||
loadedRevisionRef.current = body.drawing.revision;
|
||||
}
|
||||
if (isManual) {
|
||||
showToast("Saved", 2000);
|
||||
}
|
||||
})
|
||||
.catch((saveError: unknown) => {
|
||||
if (isConflictError(saveError)) {
|
||||
clearPendingSaveTimeout();
|
||||
setError(null);
|
||||
setDrawings((current) => replaceMeta(current, saveError.body.drawing));
|
||||
if (isManual) {
|
||||
showToast("Reloading latest...");
|
||||
}
|
||||
return loadDrawing(drawingId);
|
||||
}
|
||||
|
||||
setError(saveError instanceof Error ? saveError.message : "Save failed");
|
||||
if (isManual) {
|
||||
showToast("Save failed", 2000);
|
||||
}
|
||||
throw saveError;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightSaveRef.current = null;
|
||||
});
|
||||
|
||||
inFlightSaveRef.current = promise;
|
||||
await promise;
|
||||
},
|
||||
[clearPendingSaveTimeout, loadDrawing, showToast],
|
||||
);
|
||||
|
||||
const flushPendingSave = useCallback(async () => {
|
||||
if (saveTimeoutRef.current !== null) {
|
||||
clearPendingSaveTimeout();
|
||||
await saveScene();
|
||||
return;
|
||||
}
|
||||
|
||||
if (inFlightSaveRef.current) {
|
||||
await inFlightSaveRef.current;
|
||||
}
|
||||
}, [clearPendingSaveTimeout, saveScene]);
|
||||
|
||||
const triggerManualSave = useCallback(async () => {
|
||||
if (saveTimeoutRef.current !== null) {
|
||||
clearPendingSaveTimeout();
|
||||
}
|
||||
if (inFlightSaveRef.current) {
|
||||
await inFlightSaveRef.current;
|
||||
}
|
||||
await saveScene(true);
|
||||
}, [clearPendingSaveTimeout, saveScene]);
|
||||
|
||||
const scheduleSave = useCallback(() => {
|
||||
if (saveTimeoutRef.current !== null) {
|
||||
clearTimeout(saveTimeoutRef.current);
|
||||
}
|
||||
|
||||
saveTimeoutRef.current = window.setTimeout(() => {
|
||||
saveTimeoutRef.current = null;
|
||||
void saveScene();
|
||||
}, 30000);
|
||||
}, [saveScene]);
|
||||
|
||||
const navigateToDrawing = useCallback(
|
||||
async (drawingId: string, options?: { replace?: boolean; flush?: boolean }) => {
|
||||
const replace = options?.replace ?? false;
|
||||
const flush = options?.flush ?? true;
|
||||
|
||||
if (drawingId === currentIdRef.current && latestSceneRef.current) {
|
||||
if (replace) {
|
||||
window.history.replaceState(null, "", `/d/${drawingId}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (flush) {
|
||||
await flushPendingSave();
|
||||
}
|
||||
|
||||
if (replace) {
|
||||
window.history.replaceState(null, "", `/d/${drawingId}`);
|
||||
} else {
|
||||
window.history.pushState(null, "", `/d/${drawingId}`);
|
||||
}
|
||||
|
||||
await loadDrawing(drawingId);
|
||||
},
|
||||
[flushPendingSave, loadDrawing],
|
||||
);
|
||||
|
||||
const createDrawing = useCallback(async () => {
|
||||
await flushPendingSave();
|
||||
const created = await requestJson<DrawingResponse>("/api/drawings", { method: "POST" });
|
||||
await navigateToDrawing(created.id, { flush: false });
|
||||
}, [flushPendingSave, navigateToDrawing]);
|
||||
|
||||
const deleteDrawing = useCallback(
|
||||
async (drawingId: string) => {
|
||||
if (!window.confirm("Delete this drawing?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (drawingId === currentIdRef.current) {
|
||||
await flushPendingSave();
|
||||
}
|
||||
|
||||
const response = await requestJson<{ ok: true; nextId: string | null }>(`/api/drawings/${drawingId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (drawingId === currentIdRef.current && response.nextId) {
|
||||
await navigateToDrawing(response.nextId, { replace: true, flush: false });
|
||||
} else {
|
||||
await refreshList();
|
||||
}
|
||||
},
|
||||
[flushPendingSave, navigateToDrawing, refreshList],
|
||||
);
|
||||
|
||||
const setActiveTitle = useCallback((title: string) => {
|
||||
currentTitleRef.current = title;
|
||||
setActiveTitleState(title);
|
||||
}, []);
|
||||
|
||||
const submitTitle = useCallback(async () => {
|
||||
const drawingId = currentIdRef.current;
|
||||
if (!drawingId) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await requestJson<UpdateResponse>(`/api/drawings/${drawingId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
title: currentTitleRef.current,
|
||||
expectedRevision: loadedRevisionRef.current,
|
||||
}),
|
||||
});
|
||||
|
||||
currentTitleRef.current = body.drawing.title;
|
||||
loadedRevisionRef.current = body.drawing.revision;
|
||||
setActiveTitleState(body.drawing.title);
|
||||
setDrawings((current) => replaceMeta(current, body.drawing));
|
||||
} catch (renameError) {
|
||||
if (isConflictError(renameError)) {
|
||||
clearPendingSaveTimeout();
|
||||
setDrawings((current) => replaceMeta(current, renameError.body.drawing));
|
||||
await loadDrawing(drawingId);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(renameError instanceof Error ? renameError.message : "Rename failed");
|
||||
}
|
||||
}, [clearPendingSaveTimeout, loadDrawing]);
|
||||
|
||||
const handleSceneChange = useCallback(
|
||||
(nextScene: ScenePayload) => {
|
||||
latestSceneRef.current = nextScene;
|
||||
|
||||
if (ignoreChangeRef.current) {
|
||||
ignoreChangeRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleSave();
|
||||
},
|
||||
[scheduleSave],
|
||||
);
|
||||
|
||||
const selectDrawing = useCallback(
|
||||
async (drawingId: string) => {
|
||||
await navigateToDrawing(drawingId);
|
||||
},
|
||||
[navigateToDrawing],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void triggerManualSave();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown, { capture: true });
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown, { capture: true });
|
||||
};
|
||||
}, [triggerManualSave]);
|
||||
|
||||
useEffect(() => {
|
||||
const currentPathId = pathToId();
|
||||
if (currentPathId) {
|
||||
void loadDrawing(currentPathId);
|
||||
} else {
|
||||
window.location.replace("/");
|
||||
}
|
||||
|
||||
const onPopState = () => {
|
||||
const nextId = pathToId();
|
||||
if (nextId) {
|
||||
void navigateToDrawing(nextId, { replace: true, flush: true });
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("popstate", onPopState);
|
||||
return () => {
|
||||
window.removeEventListener("popstate", onPopState);
|
||||
};
|
||||
}, [loadDrawing, navigateToDrawing]);
|
||||
|
||||
useEffect(() => {
|
||||
const checkForExternalChanges = async () => {
|
||||
try {
|
||||
const list = await refreshList();
|
||||
const drawingId = currentIdRef.current;
|
||||
const loadedRevision = loadedRevisionRef.current;
|
||||
const serverDrawing = drawingId ? list.find((drawing) => drawing.id === drawingId) : null;
|
||||
|
||||
if (serverDrawing && loadedRevision !== null && serverDrawing.revision > loadedRevision) {
|
||||
clearPendingSaveTimeout();
|
||||
await loadDrawing(serverDrawing.id);
|
||||
}
|
||||
} catch {
|
||||
// Focus checks only discover external edits; direct save/load requests report failures.
|
||||
}
|
||||
};
|
||||
|
||||
const handleFocus = () => {
|
||||
void checkForExternalChanges();
|
||||
};
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
void checkForExternalChanges();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("focus", handleFocus);
|
||||
document.addEventListener("visibilitychange", handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("focus", handleFocus);
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||||
};
|
||||
}, [clearPendingSaveTimeout, loadDrawing, refreshList]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (saveTimeoutRef.current !== null) {
|
||||
clearTimeout(saveTimeoutRef.current);
|
||||
}
|
||||
if (toastTimeoutRef.current !== null) {
|
||||
clearTimeout(toastTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
drawings,
|
||||
activeId,
|
||||
activeTitle,
|
||||
scene,
|
||||
loading,
|
||||
error,
|
||||
toastMessage,
|
||||
editorReloadNonce,
|
||||
setActiveTitle,
|
||||
submitTitle,
|
||||
handleSceneChange,
|
||||
selectDrawing,
|
||||
createDrawing,
|
||||
deleteDrawing,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useCallback, useEffect, useRef, type RefObject } from "react";
|
||||
|
||||
const EXCALIDRAW_THEME_TOKEN_MAP = [
|
||||
["--island-bg-color", "--app-island-bg"],
|
||||
["--sidebar-bg-color", "--app-sidebar-bg"],
|
||||
["--sidebar-border-color", "--app-sidebar-border"],
|
||||
["--sidebar-shadow", "--app-sidebar-shadow"],
|
||||
["--color-surface-lowest", "--app-surface-lowest"],
|
||||
["--color-surface-low", "--app-surface-low"],
|
||||
["--color-surface-primary-container", "--app-selected-bg"],
|
||||
["--color-on-surface", "--app-text-color"],
|
||||
["--color-on-primary-container", "--app-selected-text-color"],
|
||||
["--color-disabled", "--app-disabled-color"],
|
||||
["--input-bg-color", "--app-input-bg"],
|
||||
["--input-border-color", "--app-input-border"],
|
||||
["--input-label-color", "--app-input-color"],
|
||||
["--default-border-color", "--app-button-border"],
|
||||
["--button-hover-bg", "--app-button-hover-bg"],
|
||||
["--button-active-bg", "--app-button-active-bg"],
|
||||
["--button-active-border", "--app-button-active-border"],
|
||||
["--overlay-bg-color", "--app-overlay-bg"],
|
||||
] as const;
|
||||
|
||||
export function useThemeTokenSync(appShellRef: RefObject<HTMLDivElement | null>) {
|
||||
const themeSyncFrameRef = useRef<number | null>(null);
|
||||
|
||||
const syncThemeTokens = useCallback(() => {
|
||||
const appShell = appShellRef.current;
|
||||
const excalidrawRoot = appShell?.querySelector<HTMLElement>(".excalidraw");
|
||||
if (!appShell || !excalidrawRoot) {
|
||||
return;
|
||||
}
|
||||
|
||||
const computedStyles = window.getComputedStyle(excalidrawRoot);
|
||||
for (const [sourceToken, targetToken] of EXCALIDRAW_THEME_TOKEN_MAP) {
|
||||
const value = computedStyles.getPropertyValue(sourceToken).trim();
|
||||
if (value) {
|
||||
appShell.style.setProperty(targetToken, value);
|
||||
}
|
||||
}
|
||||
}, [appShellRef]);
|
||||
|
||||
const scheduleThemeTokenSync = useCallback(() => {
|
||||
if (themeSyncFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(themeSyncFrameRef.current);
|
||||
}
|
||||
|
||||
themeSyncFrameRef.current = window.requestAnimationFrame(() => {
|
||||
themeSyncFrameRef.current = null;
|
||||
syncThemeTokens();
|
||||
});
|
||||
}, [syncThemeTokens]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (themeSyncFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(themeSyncFrameRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return scheduleThemeTokenSync;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<!-- to resolve the hs and css from root -->
|
||||
<base href="/" />
|
||||
<title>excali-box</title>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App";
|
||||
import "./styles.css";
|
||||
|
||||
const root = document.getElementById("root");
|
||||
|
||||
if (!root) {
|
||||
throw new Error("Root element not found");
|
||||
}
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,313 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
font-family:
|
||||
Inter,
|
||||
ui-sans-serif,
|
||||
system-ui,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
background: #f5f5f4;
|
||||
color: #18181b;
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
height: 100%;
|
||||
color: var(--app-text-color, #18181b);
|
||||
--app-sidebar-font-size: 0.875rem;
|
||||
--app-island-bg: #ffffff;
|
||||
--app-sidebar-bg: #ffffff;
|
||||
--app-sidebar-border: #e4e4e7;
|
||||
--app-sidebar-shadow: 0 24px 80px rgba(24, 24, 27, 0.22);
|
||||
--app-surface-lowest: #ffffff;
|
||||
--app-surface-low: #f4f4f5;
|
||||
--app-selected-bg: #f4f4f5;
|
||||
--app-text-color: #18181b;
|
||||
--app-selected-text-color: #18181b;
|
||||
--app-disabled-color: #a1a1aa;
|
||||
--app-input-bg: #ffffff;
|
||||
--app-input-border: #d4d4d8;
|
||||
--app-input-color: #18181b;
|
||||
--app-button-border: #d4d4d8;
|
||||
--app-button-hover-bg: #f4f4f5;
|
||||
--app-button-active-bg: #e4e4e7;
|
||||
--app-button-active-border: #5b8def;
|
||||
--app-overlay-bg: rgba(255, 255, 255, 0.88);
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
width: min(340px, calc(100vw - 32px));
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--app-sidebar-border);
|
||||
background: var(--app-sidebar-bg);
|
||||
box-shadow: var(--app-sidebar-shadow);
|
||||
transform: translateX(calc(-100% - 24px));
|
||||
transition:
|
||||
transform 180ms ease,
|
||||
box-shadow 180ms ease;
|
||||
}
|
||||
|
||||
.sidebar-open {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
border-bottom: 1px solid var(--app-sidebar-border);
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.sidebar-header h1 {
|
||||
margin: 0;
|
||||
font-size: var(--app-sidebar-font-size);
|
||||
font-weight: 600;
|
||||
color: var(--app-text-color);
|
||||
}
|
||||
|
||||
.sidebar-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.sidebar-actions .primary-button,
|
||||
.sidebar-actions .icon-button {
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
.drawing-list {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.drawing-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border-radius: 8px;
|
||||
padding: 4px 12px;
|
||||
}
|
||||
|
||||
.drawing-item-active {
|
||||
background: var(--app-selected-bg);
|
||||
color: var(--app-selected-text-color);
|
||||
}
|
||||
|
||||
.drawing-link {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
padding: 8px 0;
|
||||
text-align: left;
|
||||
font-size: var(--app-sidebar-font-size);
|
||||
}
|
||||
|
||||
.drawing-title,
|
||||
.title-input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.title-input {
|
||||
border: 1px solid var(--app-input-border);
|
||||
border-radius: 6px;
|
||||
background: var(--app-input-bg);
|
||||
color: var(--app-input-color);
|
||||
font-size: var(--app-sidebar-font-size);
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.editor-shell {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.app-actions {
|
||||
position: fixed;
|
||||
right: max(16px, calc(env(safe-area-inset-right) + 16px));
|
||||
bottom: calc(max(16px, env(safe-area-inset-bottom)) + 48px);
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.app-actions-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: var(--lg-button-size, 2.25rem);
|
||||
height: var(--lg-button-size, 2.25rem);
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--border-radius-lg, 12px);
|
||||
box-shadow: 0 0 0 1px var(--app-surface-lowest);
|
||||
background: var(--app-surface-low);
|
||||
color: var(--app-text-color);
|
||||
}
|
||||
|
||||
.app-actions-toggle svg {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
overflow: visible;
|
||||
transform: translateY(0.5px) scale(1.08);
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
.primary-button,
|
||||
.secondary-button,
|
||||
.icon-button {
|
||||
border: 1px solid var(--app-button-border);
|
||||
border-radius: 8px;
|
||||
background: var(--app-island-bg);
|
||||
color: var(--app-text-color);
|
||||
transition:
|
||||
background-color 120ms ease,
|
||||
border-color 120ms ease,
|
||||
color 120ms ease,
|
||||
box-shadow 120ms ease;
|
||||
}
|
||||
|
||||
.primary-button,
|
||||
.secondary-button {
|
||||
cursor: pointer;
|
||||
font-size: var(--app-sidebar-font-size);
|
||||
font-weight: 500;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.primary-button:hover,
|
||||
.secondary-button:hover,
|
||||
.icon-button:hover {
|
||||
background: var(--app-button-hover-bg);
|
||||
}
|
||||
|
||||
.primary-button:active,
|
||||
.secondary-button:active,
|
||||
.icon-button:active {
|
||||
background: var(--app-button-active-bg);
|
||||
border-color: var(--app-button-active-border);
|
||||
}
|
||||
|
||||
.secondary-button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
color: var(--app-disabled-color);
|
||||
}
|
||||
|
||||
.icon-button {
|
||||
display: inline-flex;
|
||||
flex: 0 0 32px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sidebar-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 30;
|
||||
background: color-mix(in srgb, var(--app-overlay-bg) 72%, #000000);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 180ms ease;
|
||||
}
|
||||
|
||||
.sidebar-backdrop-open {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.toast-overlay {
|
||||
position: fixed;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
z-index: 100;
|
||||
background: var(--app-overlay-bg);
|
||||
backdrop-filter: blur(4px);
|
||||
color: var(--app-text-color);
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
font-size: var(--app-sidebar-font-size);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid var(--app-sidebar-border);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.editor-frame,
|
||||
.editor-loading {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.editor-loading {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--app-text-color);
|
||||
}
|
||||
|
||||
.app-actions-toggle:hover {
|
||||
background: var(--app-button-hover-bg);
|
||||
}
|
||||
|
||||
.app-actions-toggle:active {
|
||||
box-shadow: 0 0 0 1px var(--app-button-active-border);
|
||||
background: var(--app-button-active-bg);
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.sidebar {
|
||||
width: min(300px, calc(100vw - 20px));
|
||||
}
|
||||
|
||||
.app-actions {
|
||||
right: max(16px, calc(env(safe-area-inset-right) + 16px));
|
||||
bottom: calc(max(16px, env(safe-area-inset-bottom)) + 56px);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user