Compare commits

...

12 Commits

Author SHA1 Message Date
ruinivist b3e79d839e fix: style guide 2026-05-31 18:14:41 +00:00
ruinivist 0d9dd742b2 feat: add a styles guide 2026-05-31 14:54:46 +00:00
ruinivist acce5ed05c docs: add tl;dr section 2026-05-31 14:54:38 +00:00
ruinivist 6e3d18ce94 refactor: remove drawing load fallback handling 2026-05-31 14:41:41 +00:00
ruinivist b4a540214b feat: add optional styles guide resource 2026-05-31 14:36:51 +00:00
ruinivist 25bf171f6b refactor: reorganize src structure 2026-05-31 12:46:21 +00:00
ruinivist f349617427 fix: skip no-op scene revision bumps 2026-05-31 12:35:57 +00:00
ruinivist d7a0a5d076 test: remove negative legacy cases 2026-05-31 12:31:34 +00:00
ruinivist 83191055bd refactor: drop legacy db and scene fallback 2026-05-31 12:29:58 +00:00
ruinivist ab786a7861 refactor: split app shell 2026-05-31 12:17:18 +00:00
ruinivist 6911033c1a fix: prevent stale drawing saves 2026-05-31 11:47:20 +00:00
ruinivist c13c137e24 feat: handle 499 cases as no throw on server
* fix(api): gracefully handle aborted requests

When a client closes a connection early (e.g. while `await request.text()` is parsing), it throws a `DOMException` with `name: "AbortError"`. Previously, this hit our catch block, was logged as an unhandled exception to the console via `console.error`, and returned a `500` status. This resulted in an alarming error message which looked like a server crash, but the server actually stayed up.

This commit updates `errorResponse` in `src/api.ts` to intercept `AbortError` and handle it properly. If we detect an `AbortError`, we now log a simple `400 Bad Request` instead, without writing out the `DOMException` stack trace.

* fix(api): gracefully handle aborted requests

When a client closes a connection early (e.g. while `await request.text()` is parsing), it throws a `DOMException` with `name: "AbortError"`. Previously, this hit our catch block, was logged as an unhandled exception to the console via `console.error`, and returned a `500` status. This resulted in an alarming error message which looked like a server crash, but the server actually stayed up.

This commit updates `errorResponse` in `src/api.ts` to intercept `AbortError` and handle it properly. If we detect an `AbortError`, we now log a simple `499 Client Closed Request` instead, without writing out the `DOMException` stack trace.

---------

Co-authored-by: ruinivist <179396038+ruinivist@users.noreply.github.com>
2026-05-31 16:48:02 +05:30
27 changed files with 1857 additions and 888 deletions
+40
View File
@@ -7,6 +7,30 @@ No auth to keep things simple - you either run in a private network or put it be
> GPT 5.5 generated
## Tl;dr
When building the image yourself
```
docker run --rm \
-p 127.0.0.1:3000:80 \
-e PUBLIC_BASE_URL=http://localhost:3000 \
-v "$PWD/excali-box-data:/data" \
-v "$PWD/STYLES_GUIDE.md:/config/styles-guide.md:ro" \
excali
```
When pulling from GHCR ( you would want to change the `PUBLIC_BASE_URL` )
```
docker run --rm \
-p 127.0.0.1:3000:80 \
-e PUBLIC_BASE_URL=http://localhost:3000 \
-v "$PWD/excali-box-data:/data" \
-v "$PWD/STYLES_GUIDE.md:/config/styles-guide.md:ro" \
ghcr.io/ruinivist/excalidraw-box:latest
```
## Pull from GHCR and run
Images are published to:
@@ -42,3 +66,19 @@ docker run --rm -p 127.0.0.1:3000:80 -e PUBLIC_BASE_URL=http://localhost:3000 -v
```
This will make the data persistent in the `excali-box-data` folder in the current directory, with Caddy serving the browser build on `localhost:3000`. `PUBLIC_BASE_URL` is required so MCP tools can return drawing URLs with the public browser origin. You would want it to be the same url you use to access the app in the browser - in case you reverse proxy or use a tailscale alias etc.
## Optional MCP styles guide resource
The MCP server can optionally expose one extra read-only resource at `excali://styles-guide`. This file is then
discoverable as an MCP resource.
```bash
docker run --rm \
-p 127.0.0.1:3000:80 \
-e PUBLIC_BASE_URL=http://localhost:3000 \
-v "$PWD/excali-box-data:/data" \
-v "$PWD/STYLES_GUIDE.md:/config/styles-guide.md:ro" \
ghcr.io/ruinivist/excalidraw-box:latest
```
Repo-root `STYLES_GUIDE.md` which is what I wrote for myself is not used at all unless you explicitly mount it to `/config/styles-guide.md`.
+212
View File
@@ -0,0 +1,212 @@
# Styles Guide
Use this guide when generating or modifying Excalidraw scenes.
## Author intent (must follow)
- Excalidraw is for free-flow visual thinking: nodes, arrows, curves, boundaries, and hanging labels.
- Treat this as a diagramming task, not a document-writing task.
- Prefer visual relationships over long prose.
- If content starts becoming paragraph-heavy, split it into smaller nodes and explicit connectors.
- Prioritize flow clarity over text density.
## Core intent
- Always set `scene.appState.theme` to `"dark"`.
- Always use light-style element colors.
- Optimize for clarity, technical precision, and fast visual parsing.
- Tailor structure to the problem. Do not default to generic flowcharts.
- Prefer diagrams that look like working engineering notes, not slides.
## Theme
- Use a light canvas and light containers by default.
- Keep contrast high enough for comfortable reading.
- Use vibrant accent colors with strong readability on light surfaces.
- Keep color mapping stable: the same logical component/flow must keep the same color across node, connector, and connector label.
- For subtypes within a flow, use close shades of the same family instead of unrelated hues.
### Default palette
- Canvas / background: `#f8fafc`
- Surface: `#ffffff`
- Muted surface: `#f1f5f9`
- Text: `#212529`
- Muted text: `#343a40`
- Green: `#099268`
- Pink: `#c2255c`
- Red: `#ff5d73`
- Purple: `#6741d9`
- Blue: `#1971c2`
- Teal: `#0c8599`
- Border / connector: `#868e96`
### Extended accent set
- Mint: `#12b886`
- Cyan: `#1098ad`
- Indigo: `#364fc7`
- Violet: `#5f3dc4`
- Magenta: `#a61e4d`
- Rose: `#e64980`
- Slate dark: `#212529`
- Slate mid: `#495057`
- Slate light: `#868e96`
## Layout
- Keep the layout spacious.
- Use consistent alignment and clear grouping.
- Maintain obvious reading order (usually left-to-right or top-to-bottom).
- Separate major groups with generous whitespace.
- Avoid dense clusters and unclear crossings.
### Spacing defaults
- Between major groups: `160-240px`
- Between related nodes: `72-120px`
- Container padding: `48-72px`
- Keep connector crossings rare. Re-route instead of stacking lines through central content.
### Connector label placement
- Do not place connector labels directly on top of arrow/line strokes.
- Offset connector labels from the path by at least `16-24px` on the normal axis.
- Prefer labels slightly to the side of the connector midpoint, not centered on the stroke.
- If lines still reduce readability, move the label further away.
- Connector labels must remain clearly associated with their connector.
- Connector endpoints should stop with a visible gap before node/container borders: `8-16px`.
- Prefer slight natural curves for connectors (gentle 3-point bends) instead of rigid perfectly straight arrows.
- Keep curvature subtle; avoid dramatic arcs unless the route needs explicit detouring.
- Use straight connectors only when they are materially clearer than curved ones.
### Container nesting
- Default to one container level.
- Maximum nesting depth is two.
- Use second-level nesting only when needed.
- Avoid box-within-box-within-box structures unless explicitly required.
## Text fit and sizing
Use explicit sizing so text fits without clipping or cramped boxes.
### Typography defaults
- Body/node text: `20px` Excalidraw monospace (`fontFamily: 3`)
- Section labels: `24px`
- Auxiliary notes: `20px` minimum
- Line height multiplier: `1.25`
### Text length and wrapping
- Target max line length: `22-28` characters.
- If label text exceeds `28` characters, insert line breaks at phrase boundaries.
- Keep most labels to `1-2` lines.
- Hard cap: `3` lines for standard nodes, `4` lines for large containers.
### Box size contract
- Horizontal text padding: `32px` per side (`64px` total)
- Vertical text padding: `24px` per side (`48px` total)
- Minimum node size: `260x120`
- Recommended width bands:
- Short labels (`<=18` chars): `260-320px`
- Medium labels (`19-40` chars): `340-460px`
- Long labels (wrapped): `480-680px`
### Overflow guardrails
- Text must remain fully inside its box at `zoom: 1`.
- Keep at least `28px` interior clearance from text to borders after render.
- If text would overflow: increase width first, then height, then split content into multiple nodes.
- No label overlap is allowed.
- Bias toward extra whitespace over dense packing.
## Structural guidance
Pick the structure that matches the content.
- Flows/lifecycles: sequence or pipeline layouts
- Layered systems: stacked layers with strict boundaries
- Ownership/containment: nested containers
- Stateful behavior: state-machine style
- Dependencies: directional graphs grouped by subsystem
- Comparisons/migrations: side-by-side layouts
Do not force every task into boxes with arrows when a better structure exists.
## Logical coherence
- Every element must have a reason to exist.
- Group by real system boundaries, not visual symmetry alone.
- Make relationships explicit: data flow, control flow, ownership, lifecycle, dependency.
- Minimize ambiguous arrows.
- If a connection has specific meaning, label it briefly.
- Prefer fewer, clearer elements over exhaustive clutter.
## Language
- Use terse, technical labels.
- Use short phrases, not full sentences.
- Assume the reader is a senior engineer.
- Prefer concrete nouns/verbs.
- Use concrete system terms: API, worker, queue, WAL, cache, AST, token, retry loop, reconciliation pass.
### Avoid
- Business speak
- Marketing language
- Vague labels like `Platform`, `Service Layer`, `System`, `Magic`
- Ambiguous shorthand like `edge`, `core`, `backend`, `worker` without qualifiers
- Filler phrases like `leverages`, `enables`, `streamlines`, `orchestrates`
### Naming specificity
- Prefer concrete component names over abstract layer names.
- Label the actual technology/runtime boundary when known.
- Example: use `caddy router` or `reverse proxy (caddy :80)` instead of `edge`.
- Example: use `bun http api (:3000)` instead of `backend`.
## Visual style
- Use subtle emphasis, not decoration.
- Reserve accent colors for meaning, not aesthetics alone.
- Keep color mapping stable for each logical subsystem/flow.
- Use container fills and border weight to show hierarchy.
- Keep shapes simple and consistent unless variation materially helps.
## Creativity rule
Be creative in structure, not flashy in styling.
- Adapt composition to the specific problem.
- Use framing, grouping, and flow intentionally.
- Make the diagram feel specific to the task.
## Dark mode persistence
- Treat dark mode as a persisted app-state requirement only.
- At create/update time, `scene.appState.theme` must be `"dark"`.
- Do not rely on UI defaults or post-hoc toggles.
- Theme and element colors are separate controls:
- `theme: "dark"` is required.
- Keep element colors in a light-style palette.
- Do not manually invert colors.
- Do not use dark canvas/surface colors for theme compliance.
## Hard constraints
- Always set `scene.appState.theme` to `"dark"`.
- Always use light-mode element colors.
- No manual color inversion.
- Default to one container level; max two unless explicitly needed.
- No tight text boxes.
- No cluttered layouts.
- No overlapping labels.
- No label text with connector strokes running through glyphs.
- No connector endpoint flush against a box border; keep a visible gap.
- No inconsistent color mapping for the same logical subsystem/flow.
- No decorative noise.
- No business/management tone.
- No generic one-size-fits-all flowchart when a better structure is appropriate.
+4 -4
View File
@@ -3,11 +3,11 @@
"type": "module",
"private": true,
"scripts": {
"dev": "bun --hot src/dev-server.tsx",
"dev": "bun --hot src/server/dev-server.tsx",
"build": "rm -rf dist && bun run build:client && bun run build:server && bun run build:mcp",
"build:client": "bun build --target=browser --production --outdir ./dist/public ./src/index.html",
"build:server": "mkdir -p ./dist/server && bun build --target=bun --production --outfile ./dist/server/server.js ./src/server.tsx",
"build:mcp": "mkdir -p ./dist/mcp && bun build --target=bun --production --outfile ./dist/mcp/mcp-server.js ./src/mcp-server.ts",
"build:client": "bun build --target=browser --production --outdir ./dist/public ./src/client/index.html",
"build:server": "mkdir -p ./dist/server && bun build --target=bun --production --outfile ./dist/server/server.js ./src/server/http-server.tsx",
"build:mcp": "mkdir -p ./dist/mcp && bun build --target=bun --production --outfile ./dist/mcp/mcp-server.js ./src/mcp/server.ts",
"start": "DATABASE_PATH=./data/excalidraw.sqlite bun ./dist/server/server.js",
"test": "bun test",
"typecheck": "tsc --noEmit"
-566
View File
@@ -1,566 +0,0 @@
import "../node_modules/@excalidraw/excalidraw/dist/prod/index.css";
import { Excalidraw } from "@excalidraw/excalidraw";
import type {
AppState,
BinaryFiles,
ExcalidrawInitialDataState,
} from "@excalidraw/excalidraw/types";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { DEFAULT_TITLE, type DrawingMeta, type ScenePayload } from "./shared";
type DrawingResponse = DrawingMeta & ScenePayload;
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;
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]);
}
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>,
};
}
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 & { error?: string };
if (!response.ok) {
throw new Error(body.error ?? `Request failed: ${response.status}`);
}
return body;
}
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 App() {
const [drawings, setDrawings] = useState<DrawingMeta[]>([]);
const [activeId, setActiveId] = useState<string | null>(pathToId());
const [activeTitle, setActiveTitle] = useState(DEFAULT_TITLE);
const [scene, setScene] = useState<ScenePayload | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [toastMessage, setToastMessage] = useState<string | null>(null);
const currentIdRef = useRef<string | null>(activeId);
const currentTitleRef = useRef(activeTitle);
const latestSceneRef = useRef<ScenePayload | null>(null);
const ignoreChangeRef = useRef(false);
const appShellRef = useRef<HTMLDivElement | null>(null);
const timeoutRef = useRef<number | null>(null);
const inFlightSaveRef = useRef<Promise<void> | null>(null);
const loadVersionRef = useRef(0);
const themeSyncFrameRef = useRef<number | null>(null);
const toastTimeoutRef = useRef<number | null>(null);
const activeDrawing = useMemo(
() => drawings.find((drawing) => drawing.id === activeId) ?? null,
[activeId, drawings],
);
const refreshList = useCallback(async () => {
const list = await requestJson<DrawingMeta[]>("/api/drawings", { method: "GET" });
setDrawings(sortDrawings(list));
return list;
}, []);
const saveScene = useCallback(async (isManual = false) => {
const drawingId = currentIdRef.current;
const nextScene = latestSceneRef.current;
if (!drawingId || !nextScene) {
return;
}
setError(null);
if (isManual) {
setToastMessage("Saving...");
if (toastTimeoutRef.current !== null) {
clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
}
const promise = requestJson<{ ok: true; drawing: DrawingMeta }>(`/api/drawings/${drawingId}`, {
method: "PUT",
body: JSON.stringify(nextScene),
})
.then((body) => {
setDrawings((current) => replaceMeta(current, body.drawing));
if (isManual) {
setToastMessage("Saved");
if (toastTimeoutRef.current !== null) {
clearTimeout(toastTimeoutRef.current);
}
toastTimeoutRef.current = window.setTimeout(() => setToastMessage(null), 2000);
}
})
.catch((saveError: unknown) => {
setError(saveError instanceof Error ? saveError.message : "Save failed");
if (isManual) {
setToastMessage("Save failed");
if (toastTimeoutRef.current !== null) {
clearTimeout(toastTimeoutRef.current);
}
toastTimeoutRef.current = window.setTimeout(() => setToastMessage(null), 2000);
}
throw saveError;
})
.finally(() => {
inFlightSaveRef.current = null;
});
inFlightSaveRef.current = promise;
await promise;
}, []);
const flushPendingSave = useCallback(async () => {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
await saveScene();
return;
}
if (inFlightSaveRef.current) {
await inFlightSaveRef.current;
}
}, [saveScene]);
const triggerManualSave = useCallback(async () => {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
if (inFlightSaveRef.current) {
await inFlightSaveRef.current;
}
await saveScene(true);
}, [saveScene]);
const scheduleSave = useCallback(() => {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = window.setTimeout(() => {
timeoutRef.current = null;
void saveScene();
}, 30000);
}, [saveScene]);
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 = {
elements: drawing.elements,
appState: drawing.appState,
files: drawing.files,
};
ignoreChangeRef.current = true;
currentIdRef.current = drawing.id;
currentTitleRef.current = drawing.title;
latestSceneRef.current = nextScene;
setDrawings(sortDrawings(list));
setActiveId(drawing.id);
setActiveTitle(drawing.title);
setScene(nextScene);
} catch (loadError) {
const list = await refreshList();
if (list.length === 0) {
const created = await requestJson<DrawingResponse>("/api/drawings", { method: "POST" });
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);
}
}
},
[refreshList],
);
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 handleTitleSubmit = useCallback(async () => {
const drawingId = currentIdRef.current;
if (!drawingId) {
return;
}
try {
const body = await requestJson<{ ok: true; drawing: DrawingMeta }>(`/api/drawings/${drawingId}`, {
method: "PUT",
body: JSON.stringify({ title: currentTitleRef.current }),
});
currentTitleRef.current = body.drawing.title;
setActiveTitle(body.drawing.title);
setDrawings((current) => replaceMeta(current, body.drawing));
} catch (renameError) {
setError(renameError instanceof Error ? renameError.message : "Rename failed");
}
}, []);
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);
}
}
}, []);
const scheduleThemeTokenSync = useCallback(() => {
if (themeSyncFrameRef.current !== null) {
window.cancelAnimationFrame(themeSyncFrameRef.current);
}
themeSyncFrameRef.current = window.requestAnimationFrame(() => {
themeSyncFrameRef.current = null;
syncThemeTokens();
});
}, [syncThemeTokens]);
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(() => {
return () => {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
}
if (themeSyncFrameRef.current !== null) {
window.cancelAnimationFrame(themeSyncFrameRef.current);
}
};
}, []);
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(
async (drawingId: string) => {
setIsSidebarOpen(false);
await navigateToDrawing(drawingId);
},
[navigateToDrawing],
);
const handleCreateDrawing = useCallback(async () => {
setIsSidebarOpen(false);
await 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">
<button
type="button"
className="secondary-button app-actions-toggle"
onClick={openSidebar}
aria-label="Open drawings"
>
<DrawerIcon />
<span className="sr-only">Open drawings</span>
</button>
</div>
{loading || !scene ? (
<div className="editor-loading">{error ?? "Loading..."}</div>
) : (
<div className="editor-frame">
<Excalidraw
key={activeDrawing?.id ?? activeId}
initialData={sceneToInitialData(scene)}
onChange={(elements, appState, files) => {
const nextScene = sceneFromEditor(elements, appState, files);
latestSceneRef.current = nextScene;
scheduleThemeTokenSync();
if (ignoreChangeRef.current) {
ignoreChangeRef.current = false;
return;
}
scheduleSave();
}}
/>
</div>
)}
</main>
<div
className={isSidebarOpen ? "sidebar-backdrop sidebar-backdrop-open" : "sidebar-backdrop"}
onClick={closeSidebar}
aria-hidden={!isSidebarOpen}
/>
<aside className={isSidebarOpen ? "sidebar sidebar-open" : "sidebar"} aria-hidden={!isSidebarOpen}>
<div className="sidebar-header">
<h1>excali-box</h1>
<div className="sidebar-actions">
<button type="button" className="primary-button" onClick={() => void handleCreateDrawing()}>
New
</button>
<button type="button" className="icon-button" onClick={closeSidebar} 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) => {
currentTitleRef.current = event.target.value;
setActiveTitle(event.target.value);
}}
onBlur={() => void handleTitleSubmit()}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.currentTarget.blur();
}
}}
/>
</div>
) : (
<button
type="button"
className="drawing-link"
onClick={() => void handleSelectDrawing(drawing.id)}
>
<span className="drawing-title">{drawing.title}</span>
</button>
)}
<button
type="button"
className="icon-button"
onClick={() => void deleteDrawing(drawing.id)}
aria-label={`Delete ${drawing.title}`}
>
×
</button>
</div>
))}
</div>
</aside>
</div>
);
}
-82
View File
@@ -1,82 +0,0 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createApi } from "./api";
import { createDrawingStore } from "./db";
function withApi() {
const dir = mkdtempSync(join(tmpdir(), "excali-api-"));
const store = createDrawingStore(join(dir, "test.sqlite"));
const api = createApi(store);
return {
api,
cleanup() {
store.close();
rmSync(dir, { recursive: true, force: true });
},
};
}
describe("api", () => {
test("creates a drawing with dark theme by default", async () => {
const { api, cleanup } = withApi();
const created = await api.createDrawing().json();
expect(created.appState.theme).toBe("dark");
cleanup();
});
test("returns 400 for invalid JSON", async () => {
const { api, cleanup } = withApi();
const drawing = await api.createDrawing().json();
const response = await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${drawing.id}`, {
method: "PUT",
body: "{",
}),
{ params: { id: drawing.id } },
),
);
expect(response.status).toBe(400);
cleanup();
});
test("returns 404 for missing drawing", () => {
const { api, cleanup } = withApi();
const response = api.getDrawing(
Object.assign(new Request("http://local/api/drawings/missing"), { params: { id: "missing" } }),
);
expect(response.status).toBe(404);
cleanup();
});
test("updates a drawing scene", async () => {
const { api, cleanup } = withApi();
const created = await api.createDrawing().json();
const response = await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${created.id}`, {
method: "PUT",
body: JSON.stringify({
elements: [{ id: "shape" }],
appState: {},
files: {},
}),
}),
{ params: { id: created.id } },
),
);
expect(response.status).toBe(200);
cleanup();
});
});
+110
View File
@@ -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>
);
}
+110
View File
@@ -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>
</>
);
}
+61
View File
@@ -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>
);
}
+451
View File
@@ -0,0 +1,451 @@
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;
}
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,
};
}
+63
View File
@@ -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;
}
+1 -1
View File
@@ -6,7 +6,7 @@
<!-- to resolve the hs and css from root -->
<base href="/" />
<title>excali-box</title>
<script type="module" src="./client.tsx"></script>
<script type="module" src="./main.tsx"></script>
</head>
<body>
<div id="root"></div>
-8
View File
@@ -87,11 +87,3 @@ export function parseJsonBody<T = unknown>(text: string): T {
export function parseSceneText(text: string): ScenePayload {
return normalizeScene(parseJsonBody(text));
}
export function coerceStoredScene(input: unknown): ScenePayload {
try {
return normalizeScene(input);
} catch {
return emptyScene();
}
}
+1
View File
@@ -9,6 +9,7 @@ export type DrawingMeta = {
title: string;
createdAt: string;
updatedAt: string;
revision: number;
};
export type DrawingRecord = DrawingMeta & {
-50
View File
@@ -1,50 +0,0 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createDrawingStore } from "./db";
const cleanup: string[] = [];
afterEach(() => {
while (cleanup.length > 0) {
const dir = cleanup.pop();
if (dir) {
rmSync(dir, { recursive: true, force: true });
}
}
});
function createTempStore() {
const dir = mkdtempSync(join(tmpdir(), "excali-"));
cleanup.push(dir);
return createDrawingStore(join(dir, "test.sqlite"));
}
describe("drawing store", () => {
test("creates, updates, lists, and deletes drawings", () => {
const store = createTempStore();
const created = store.createDrawing();
expect(created.title).toBe("Untitled");
expect(created.scene.appState.theme).toBe("dark");
expect(store.listDrawings()).toHaveLength(1);
const updated = store.updateDrawing(created.id, {
title: "Flow",
scene: {
elements: [{ id: "one" }],
appState: { gridSize: 20 },
files: {},
},
});
expect(updated?.title).toBe("Flow");
expect(updated?.scene.elements).toHaveLength(1);
const removed = store.deleteDrawing(created.id);
expect(removed.deleted).toBe(true);
expect(store.listDrawings()).toHaveLength(1);
expect(removed.next?.id).not.toBe(created.id);
});
});
-119
View File
@@ -1,119 +0,0 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createDrawingStore, type DrawingStore } from "./db";
import { createMcpToolHandlers, resolvePublicBaseUrl } from "./mcp-server";
import { type ScenePayload } from "./shared";
const cleanup: Array<{ dir: string; store: DrawingStore }> = [];
afterEach(() => {
while (cleanup.length > 0) {
const item = cleanup.pop();
if (item) {
item.store.close();
rmSync(item.dir, { recursive: true, force: true });
}
}
});
function createTempTools() {
const dir = mkdtempSync(join(tmpdir(), "excali-mcp-"));
const store = createDrawingStore(join(dir, "test.sqlite"));
cleanup.push({ dir, store });
return {
store,
tools: createMcpToolHandlers(store, "http://example.test"),
};
}
function testScene(): ScenePayload {
return {
elements: [
{ id: "one", type: "rectangle", x: 10, y: 20 },
{ id: "two", type: "text", text: "hello" },
],
appState: { theme: "dark" },
files: {},
};
}
describe("mcp tool handlers", () => {
test("PUBLIC_BASE_URL is required", () => {
expect(() => resolvePublicBaseUrl("")).toThrow("PUBLIC_BASE_URL is required");
});
test("create_drawing writes an explicit scene to a temp SQLite DB", () => {
const { store, tools } = createTempTools();
const scene = testScene();
const result = tools.create_drawing({ title: "explicit", scene });
const drawing = store.getDrawing(result.id);
expect(result).toEqual({
id: result.id,
title: "explicit",
url: `http://example.test/d/${result.id}`,
});
expect(drawing?.scene).toEqual(scene);
});
test("get_drawing returns raw scene plus URL", () => {
const { tools } = createTempTools();
const scene = testScene();
const result = tools.create_drawing({ title: "read", scene });
const drawing = tools.get_drawing({ id: result.id });
expect(drawing).toMatchObject({
id: result.id,
title: "read",
url: `http://example.test/d/${result.id}`,
scene,
});
});
test("replace_drawing updates the existing drawing", () => {
const { store, tools } = createTempTools();
const result = tools.create_drawing({ title: "replace", scene: testScene() });
const nextScene: ScenePayload = {
elements: [{ id: "manual", type: "rectangle" }],
appState: { theme: "dark" },
files: {},
};
tools.replace_drawing({ id: result.id, title: "replaced", scene: nextScene });
expect(store.listDrawings()).toHaveLength(1);
expect(store.getDrawing(result.id)?.title).toBe("replaced");
expect(store.getDrawing(result.id)?.scene).toEqual(nextScene);
});
test("patch_drawing replaces an element property and removes an element", () => {
const { store, tools } = createTempTools();
const result = tools.create_drawing({ title: "patch", scene: testScene() });
tools.patch_drawing({
id: result.id,
patch: [
{ op: "replace", path: "/elements/0/x", value: 42 },
{ op: "remove", path: "/elements/1" },
],
});
expect(store.getDrawing(result.id)?.scene.elements).toEqual([{ id: "one", type: "rectangle", x: 42, y: 20 }]);
});
test("missing drawing IDs return tool errors", () => {
const { tools } = createTempTools();
expect(() => tools.get_drawing({ id: "missing" })).toThrow("Drawing not found: missing");
expect(() =>
tools.replace_drawing({
id: "missing",
scene: testScene(),
}),
).toThrow("Drawing not found: missing");
});
});
+210
View File
@@ -0,0 +1,210 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { type ScenePayload } from "../core/shared";
import { createDrawingStore, type DrawingStore } from "../server/db";
import {
DEFAULT_STYLES_GUIDE_PATH,
createExcaliMcpHandler,
createMcpToolHandlers,
resolvePublicBaseUrl,
resolveStylesGuidePath,
} from "./server";
const cleanup: Array<{ dir: string; store?: DrawingStore; client?: Client }> = [];
afterEach(async () => {
while (cleanup.length > 0) {
const item = cleanup.pop();
if (item) {
await item.client?.close().catch(() => undefined);
item.store?.close();
rmSync(item.dir, { recursive: true, force: true });
}
}
});
function createTempTools() {
const dir = mkdtempSync(join(tmpdir(), "excali-mcp-"));
const store = createDrawingStore(join(dir, "test.sqlite"));
cleanup.push({ dir, store });
return {
store,
tools: createMcpToolHandlers(store, "http://example.test"),
};
}
function createTempStylesGuidePath(content?: string) {
const dir = mkdtempSync(join(tmpdir(), "excali-mcp-"));
const path = join(dir, DEFAULT_STYLES_GUIDE_PATH.slice(1));
mkdirSync(dirname(path), { recursive: true });
if (content !== undefined) {
writeFileSync(path, content);
}
cleanup.push({ dir });
return path;
}
async function createTempClient(stylesGuidePath?: string) {
const dir = mkdtempSync(join(tmpdir(), "excali-mcp-"));
const store = createDrawingStore(join(dir, "test.sqlite"));
const handler = createExcaliMcpHandler(
store,
"http://example.test",
stylesGuidePath ? resolveStylesGuidePath(stylesGuidePath) : undefined,
);
const transport = new StreamableHTTPClientTransport(new URL("http://localhost/mcp"), {
fetch: async (input, init) => handler(new Request(input, init)),
});
const client = new Client({ name: "excali-test", version: "1.0.0" });
await client.connect(transport);
cleanup.push({ dir, store, client });
return { client, store };
}
function testScene(): ScenePayload {
return {
elements: [
{ id: "one", type: "rectangle", x: 10, y: 20 },
{ id: "two", type: "text", text: "hello" },
],
appState: { theme: "dark" },
files: {},
};
}
describe("mcp tool handlers", () => {
test("PUBLIC_BASE_URL is required", () => {
expect(() => resolvePublicBaseUrl("")).toThrow("PUBLIC_BASE_URL is required");
});
test("missing fixed styles-guide path exposes no styles-guide resource", async () => {
const stylesGuidePath = createTempStylesGuidePath();
expect(resolveStylesGuidePath(stylesGuidePath)).toBeUndefined();
const { client } = await createTempClient(stylesGuidePath);
expect(client.getServerCapabilities()?.resources).toBeUndefined();
});
test("valid fixed styles-guide path registers the styles-guide resource", async () => {
const contents = "# Scene style\n\nKeep labels terse.\n";
const stylesGuidePath = createTempStylesGuidePath(contents);
const resolved = resolveStylesGuidePath(stylesGuidePath);
const { client } = await createTempClient(stylesGuidePath);
const resources = await client.listResources();
const readResult = await client.readResource({ uri: "excali://styles-guide" });
expect(resolved).toEqual({ path: stylesGuidePath });
expect(resources.resources).toContainEqual({
name: "styles-guide",
uri: "excali://styles-guide",
title: "Styles Guide",
description: "User-provided drawing styles guide for scene generation",
mimeType: "text/markdown",
});
expect(readResult.contents).toEqual([
{
uri: "excali://styles-guide",
mimeType: "text/markdown",
text: contents,
},
]);
});
test("create_drawing writes an explicit scene to a temp SQLite DB", () => {
const { store, tools } = createTempTools();
const scene = testScene();
const result = tools.create_drawing({ title: "explicit", scene });
const drawing = store.getDrawing(result.id);
expect(result).toEqual({
id: result.id,
title: "explicit",
revision: 1,
url: `http://example.test/d/${result.id}`,
});
expect(drawing?.revision).toBe(1);
expect(drawing?.scene).toEqual(scene);
});
test("get_drawing returns raw scene plus URL", () => {
const { tools } = createTempTools();
const scene = testScene();
const result = tools.create_drawing({ title: "read", scene });
const drawing = tools.get_drawing({ id: result.id });
expect(drawing).toMatchObject({
id: result.id,
title: "read",
revision: 1,
url: `http://example.test/d/${result.id}`,
scene,
});
});
test("replace_drawing updates the existing drawing", () => {
const { store, tools } = createTempTools();
const result = tools.create_drawing({ title: "replace", scene: testScene() });
const nextScene: ScenePayload = {
elements: [{ id: "manual", type: "rectangle" }],
appState: { theme: "dark" },
files: {},
};
const replaced = tools.replace_drawing({ id: result.id, title: "replaced", scene: nextScene });
expect(store.listDrawings()).toHaveLength(1);
expect(replaced.revision).toBe(2);
expect(store.getDrawing(result.id)?.title).toBe("replaced");
expect(store.getDrawing(result.id)?.revision).toBe(2);
expect(store.getDrawing(result.id)?.scene).toEqual(nextScene);
});
test("replace_drawing keeps the revision when the scene is already stored", () => {
const { store, tools } = createTempTools();
const scene = testScene();
const result = tools.create_drawing({ title: "replace noop", scene });
const replaced = tools.replace_drawing({ id: result.id, scene });
expect(replaced.revision).toBe(1);
expect(store.getDrawing(result.id)?.revision).toBe(1);
expect(store.getDrawing(result.id)?.scene).toEqual(scene);
});
test("patch_drawing replaces an element property and removes an element", () => {
const { store, tools } = createTempTools();
const result = tools.create_drawing({ title: "patch", scene: testScene() });
const patched = tools.patch_drawing({
id: result.id,
patch: [
{ op: "replace", path: "/elements/0/x", value: 42 },
{ op: "remove", path: "/elements/1" },
],
});
expect(patched.revision).toBe(2);
expect(store.getDrawing(result.id)?.revision).toBe(2);
expect(store.getDrawing(result.id)?.scene.elements).toEqual([{ id: "one", type: "rectangle", x: 42, y: 20 }]);
});
test("missing drawing IDs return tool errors", () => {
const { tools } = createTempTools();
expect(() => tools.get_drawing({ id: "missing" })).toThrow("Drawing not found: missing");
expect(() =>
tools.replace_drawing({
id: "missing",
scene: testScene(),
}),
).toThrow("Drawing not found: missing");
});
});
+91 -8
View File
@@ -1,9 +1,11 @@
import { applyPatch, type Operation } from "fast-json-patch";
import { accessSync, constants, readFileSync, statSync } from "node:fs";
import { extname, isAbsolute } from "node:path";
import { createMcpHandler } from "mcp-handler";
import { z } from "zod";
import { createDrawingStore, type DrawingStore } from "./db";
import { normalizeScene, normalizeTitle } from "./scene";
import { type ScenePayload } from "./shared";
import { normalizeScene, normalizeTitle } from "../core/scene";
import { type ScenePayload } from "../core/shared";
import { createDrawingStore, type DrawingStore } from "../server/db";
const sceneSchema = z.object({
elements: z.array(z.unknown()),
@@ -35,6 +37,12 @@ type ToolResult = {
content: Array<{ type: "text"; text: string }>;
};
type StylesGuideResource = {
path: string;
};
export const DEFAULT_STYLES_GUIDE_PATH = "/config/styles-guide.md";
function trimTrailingSlash(url: string): string {
return url.replace(/\/+$/, "");
}
@@ -56,6 +64,50 @@ export function resolvePublicBaseUrl(raw = process.env.PUBLIC_BASE_URL): string
throw new Error("PUBLIC_BASE_URL must be an absolute http(s) URL");
}
export function resolveStylesGuidePath(raw = DEFAULT_STYLES_GUIDE_PATH): StylesGuideResource | undefined {
const value = raw.trim();
if (!isAbsolute(value)) {
throw new Error("Styles guide path must be an absolute filesystem path");
}
let stats;
try {
stats = statSync(value);
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
return undefined;
}
throw new Error(
error instanceof Error
? `Styles guide path could not be checked: ${error.message}`
: "Styles guide path could not be checked",
);
}
const extension = extname(value).toLowerCase();
if (extension !== ".md" && extension !== ".markdown") {
throw new Error("Styles guide path must point to a Markdown file (.md or .markdown)");
}
if (!stats.isFile()) {
throw new Error("Styles guide path must point to a regular file");
}
try {
accessSync(value, constants.R_OK);
} catch (error) {
throw new Error(
error instanceof Error
? `Styles guide path must point to a readable file: ${error.message}`
: "Styles guide path must point to a readable file",
);
}
return { path: value };
}
function drawingUrl(baseUrl: string, id: string): string {
return `${trimTrailingSlash(baseUrl)}/d/${id}`;
}
@@ -75,10 +127,11 @@ function notFound(id: string): never {
throw new Error(`Drawing not found: ${id}`);
}
function mutationResult(publicBaseUrl: string, drawing: { id: string; title: string }) {
function mutationResult(publicBaseUrl: string, drawing: { id: string; title: string; revision: number }) {
return {
id: drawing.id,
title: drawing.title,
revision: drawing.revision,
url: drawingUrl(publicBaseUrl, drawing.id),
};
}
@@ -88,8 +141,12 @@ function updateExistingDrawing(
id: string,
update: { scene?: ScenePayload; title?: string },
) {
const updated = store.updateDrawing(id, update);
return updated ?? notFound(id);
const result = store.updateDrawing(id, update);
if (!result.ok) {
return notFound(id);
}
return result.drawing;
}
function applyScenePatch(scene: ScenePayload, patch: Operation[]): ScenePayload {
@@ -115,6 +172,7 @@ export function createMcpToolHandlers(store: DrawingStore, publicBaseUrl: string
title: drawing.title,
createdAt: drawing.createdAt,
updatedAt: drawing.updatedAt,
revision: drawing.revision,
url: drawingUrl(publicBaseUrl, drawing.id),
scene: drawing.scene,
};
@@ -151,11 +209,36 @@ export function createMcpToolHandlers(store: DrawingStore, publicBaseUrl: string
};
}
export function createExcaliMcpHandler(store: DrawingStore, publicBaseUrl: string) {
export function createExcaliMcpHandler(
store: DrawingStore,
publicBaseUrl: string,
stylesGuide?: StylesGuideResource,
) {
const tools = createMcpToolHandlers(store, publicBaseUrl);
return createMcpHandler(
(server) => {
if (stylesGuide) {
server.registerResource(
"styles-guide",
"excali://styles-guide",
{
title: "Styles Guide",
description: "User-provided drawing styles guide for scene generation",
mimeType: "text/markdown",
},
async (uri) => ({
contents: [
{
uri: uri.toString(),
mimeType: "text/markdown",
text: readFileSync(stylesGuide.path, "utf8"),
},
],
}),
);
}
server.registerTool(
"list_drawings",
{
@@ -221,7 +304,7 @@ export function createExcaliMcpHandler(store: DrawingStore, publicBaseUrl: strin
export function createMcpServer() {
const store = createDrawingStore(process.env.DATABASE_PATH);
const handler = createExcaliMcpHandler(store, resolvePublicBaseUrl());
const handler = createExcaliMcpHandler(store, resolvePublicBaseUrl(), resolveStylesGuidePath());
return {
port: Number(process.env.MCP_PORT ?? "3001"),
+208
View File
@@ -0,0 +1,208 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createApi } from "./api";
import { createDrawingStore } from "./db";
function withApi() {
const dir = mkdtempSync(join(tmpdir(), "excali-api-"));
const store = createDrawingStore(join(dir, "test.sqlite"));
const api = createApi(store);
return {
api,
cleanup() {
store.close();
rmSync(dir, { recursive: true, force: true });
},
};
}
describe("api", () => {
test("creates a drawing with dark theme by default", async () => {
const { api, cleanup } = withApi();
const created = await api.createDrawing().json();
expect(created.appState.theme).toBe("dark");
expect(created.revision).toBe(0);
cleanup();
});
test("returns 400 for invalid JSON", async () => {
const { api, cleanup } = withApi();
const drawing = await api.createDrawing().json();
const response = await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${drawing.id}`, {
method: "PUT",
body: "{",
}),
{ params: { id: drawing.id } },
),
);
expect(response.status).toBe(400);
cleanup();
});
test("returns 404 for missing drawing", () => {
const { api, cleanup } = withApi();
const response = api.getDrawing(
Object.assign(new Request("http://local/api/drawings/missing"), { params: { id: "missing" } }),
);
expect(response.status).toBe(404);
cleanup();
});
test("updates a drawing scene", async () => {
const { api, cleanup } = withApi();
const created = await api.createDrawing().json();
const response = await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${created.id}`, {
method: "PUT",
body: JSON.stringify({
elements: [{ id: "shape" }],
appState: {},
files: {},
expectedRevision: created.revision,
}),
}),
{ params: { id: created.id } },
),
);
expect(response.status).toBe(200);
const body = await response.json();
expect(body.drawing.revision).toBe(1);
cleanup();
});
test("does not increment revisions for equivalent normalized scenes", async () => {
const { api, cleanup } = withApi();
const created = await api.createDrawing().json();
await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${created.id}`, {
method: "PUT",
body: JSON.stringify({
elements: [{ id: "shape" }],
appState: { gridSize: 20 },
files: {},
expectedRevision: 0,
}),
}),
{ params: { id: created.id } },
),
);
const response = await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${created.id}`, {
method: "PUT",
body: JSON.stringify({
elements: [{ id: "shape" }],
appState: { gridSize: 20, selectedElementIds: { shape: true } },
files: {},
expectedRevision: 0,
}),
}),
{ params: { id: created.id } },
),
);
expect(response.status).toBe(200);
const body = await response.json();
expect(body.drawing.revision).toBe(1);
cleanup();
});
test("updates scene and title with a matching expected revision", async () => {
const { api, cleanup } = withApi();
const created = await api.createDrawing().json();
const response = await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${created.id}`, {
method: "PUT",
body: JSON.stringify({
title: "Synced",
elements: [{ id: "shape" }],
appState: {},
files: {},
expectedRevision: 0,
}),
}),
{ params: { id: created.id } },
),
);
expect(response.status).toBe(200);
const body = await response.json();
expect(body.drawing.title).toBe("Synced");
expect(body.drawing.revision).toBe(1);
cleanup();
});
test("returns 409 for stale expected revisions without overwriting", async () => {
const { api, cleanup } = withApi();
const created = await api.createDrawing().json();
await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${created.id}`, {
method: "PUT",
body: JSON.stringify({
elements: [{ id: "server" }],
appState: {},
files: {},
expectedRevision: 0,
}),
}),
{ params: { id: created.id } },
),
);
const conflict = await api.updateDrawing(
Object.assign(
new Request(`http://local/api/drawings/${created.id}`, {
method: "PUT",
body: JSON.stringify({
elements: [{ id: "stale" }],
appState: {},
files: {},
expectedRevision: 0,
}),
}),
{ params: { id: created.id } },
),
);
expect(conflict.status).toBe(409);
const body = await conflict.json();
expect(body).toEqual({
ok: false,
error: "Drawing changed externally",
drawing: {
id: created.id,
title: created.title,
createdAt: body.drawing.createdAt,
updatedAt: body.drawing.updatedAt,
revision: 1,
},
});
const stored = await api.getDrawing(
Object.assign(new Request(`http://local/api/drawings/${created.id}`), { params: { id: created.id } }),
).json();
expect(stored.elements).toEqual([{ id: "server" }]);
cleanup();
});
});
+60 -25
View File
@@ -1,5 +1,6 @@
import { type DrawingStore } from "./db";
import { HttpError, normalizeTitle, parseJsonBody, parseSceneText } from "./scene";
import { type DrawingMeta } from "../core/shared";
import { HttpError, normalizeTitle, parseJsonBody, parseSceneText } from "../core/scene";
type RouteRequest = Request & {
params?: Record<string, string>;
@@ -14,10 +15,37 @@ function errorResponse(error: unknown): Response {
return json({ ok: false, error: error.message }, { status: error.status });
}
if (error instanceof Error && error.name === "AbortError") {
return json({ ok: false, error: "Request aborted" }, { status: 499 });
}
console.error(error);
return json({ ok: false, error: "Internal server error" }, { status: 500 });
}
function toMeta(drawing: DrawingMeta): DrawingMeta {
return {
id: drawing.id,
title: drawing.title,
createdAt: drawing.createdAt,
updatedAt: drawing.updatedAt,
revision: drawing.revision,
};
}
function parseExpectedRevision(raw: Record<string, unknown>): number | undefined {
if (!Object.hasOwn(raw, "expectedRevision")) {
return undefined;
}
const value = raw.expectedRevision;
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
throw new HttpError(400, "expectedRevision must be a non-negative integer");
}
return value;
}
export function createApi(store: DrawingStore) {
return {
health() {
@@ -32,10 +60,7 @@ export function createApi(store: DrawingStore) {
const drawing = store.createDrawing();
return json(
{
id: drawing.id,
title: drawing.title,
createdAt: drawing.createdAt,
updatedAt: drawing.updatedAt,
...toMeta(drawing),
...drawing.scene,
},
{ status: 201 },
@@ -43,20 +68,21 @@ export function createApi(store: DrawingStore) {
},
getDrawing(request: RouteRequest) {
const id = request.params?.id;
const drawing = id ? store.getDrawing(id) : null;
try {
const id = request.params?.id;
const drawing = id ? store.getDrawing(id) : null;
if (!drawing) {
return json({ ok: false, error: "Drawing not found" }, { status: 404 });
if (!drawing) {
return json({ ok: false, error: "Drawing not found" }, { status: 404 });
}
return json({
...toMeta(drawing),
...drawing.scene,
});
} catch (error) {
return errorResponse(error);
}
return json({
id: drawing.id,
title: drawing.title,
createdAt: drawing.createdAt,
updatedAt: drawing.updatedAt,
...drawing.scene,
});
},
async updateDrawing(request: RouteRequest) {
@@ -73,29 +99,38 @@ export function createApi(store: DrawingStore) {
Object.hasOwn(raw, "elements") ||
Object.hasOwn(raw, "appState") ||
Object.hasOwn(raw, "files");
const expectedRevision = parseExpectedRevision(raw);
if (!hasTitle && !hasScene) {
throw new HttpError(400, "Nothing to update");
}
const scene = hasScene ? parseSceneText(text) : undefined;
const updated = store.updateDrawing(id, {
const result = store.updateDrawing(id, {
scene,
title: hasTitle ? normalizeTitle(raw.title) : undefined,
expectedRevision,
});
if (!updated) {
if (!result.ok && result.reason === "not_found") {
return json({ ok: false, error: "Drawing not found" }, { status: 404 });
}
if (!result.ok && result.reason === "conflict") {
return json(
{
ok: false,
error: "Drawing changed externally",
drawing: toMeta(result.drawing),
},
{ status: 409 },
);
}
const updated = result.drawing;
return json({
ok: true,
drawing: {
id: updated.id,
title: updated.title,
createdAt: updated.createdAt,
updatedAt: updated.updatedAt,
},
drawing: toMeta(updated),
});
} catch (error) {
return errorResponse(error);
+138
View File
@@ -0,0 +1,138 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createDrawingStore } from "./db";
const cleanup: string[] = [];
afterEach(() => {
while (cleanup.length > 0) {
const dir = cleanup.pop();
if (dir) {
rmSync(dir, { recursive: true, force: true });
}
}
});
function createTempStore() {
const dir = mkdtempSync(join(tmpdir(), "excali-"));
cleanup.push(dir);
return createDrawingStore(join(dir, "test.sqlite"));
}
describe("drawing store", () => {
test("creates, updates, lists, and deletes drawings", () => {
const store = createTempStore();
const created = store.createDrawing();
expect(created.title).toBe("Untitled");
expect(created.revision).toBe(0);
expect(created.scene.appState.theme).toBe("dark");
expect(store.listDrawings()).toHaveLength(1);
expect(store.listDrawings()[0]?.revision).toBe(0);
const updated = store.updateDrawing(created.id, {
title: "Flow",
scene: {
elements: [{ id: "one" }],
appState: { gridSize: 20 },
files: {},
},
});
expect(updated.ok).toBe(true);
expect(updated.ok ? updated.drawing.title : null).toBe("Flow");
expect(updated.ok ? updated.drawing.revision : null).toBe(1);
expect(updated.ok ? updated.drawing.scene.elements : []).toHaveLength(1);
const removed = store.deleteDrawing(created.id);
expect(removed.deleted).toBe(true);
expect(store.listDrawings()).toHaveLength(1);
expect(removed.next?.id).not.toBe(created.id);
});
test("rejects stale expected revisions without overwriting the scene", () => {
const store = createTempStore();
const created = store.createDrawing();
const first = store.updateDrawing(created.id, {
expectedRevision: 0,
scene: {
elements: [{ id: "first" }],
appState: {},
files: {},
},
});
expect(first.ok).toBe(true);
const stale = store.updateDrawing(created.id, {
expectedRevision: 0,
scene: {
elements: [{ id: "stale" }],
appState: {},
files: {},
},
});
expect(stale.ok).toBe(false);
expect(stale.ok ? null : stale.reason).toBe("conflict");
expect(store.getDrawing(created.id)?.revision).toBe(1);
expect(store.getDrawing(created.id)?.scene.elements).toEqual([{ id: "first" }]);
});
test("keeps the revision unchanged when the scene is already stored", () => {
const store = createTempStore();
const created = store.createDrawing();
const scene = {
elements: [{ id: "same" }],
appState: {},
files: {},
};
const first = store.updateDrawing(created.id, { scene });
expect(first.ok ? first.drawing.revision : null).toBe(1);
const repeated = store.updateDrawing(created.id, { scene });
expect(repeated.ok).toBe(true);
expect(repeated.ok ? repeated.drawing.revision : null).toBe(1);
expect(store.getDrawing(created.id)?.revision).toBe(1);
});
test("accepts stale expected revisions when the scene is already stored", () => {
const store = createTempStore();
const created = store.createDrawing();
const scene = {
elements: [{ id: "same" }],
appState: {},
files: {},
};
const first = store.updateDrawing(created.id, { expectedRevision: 0, scene });
expect(first.ok ? first.drawing.revision : null).toBe(1);
const repeated = store.updateDrawing(created.id, { expectedRevision: 0, scene });
expect(repeated.ok).toBe(true);
expect(repeated.ok ? repeated.drawing.revision : null).toBe(1);
expect(store.getDrawing(created.id)?.scene.elements).toEqual([{ id: "same" }]);
});
test("increments the revision when the title changes but the scene does not", () => {
const store = createTempStore();
const created = store.createDrawing();
const scene = {
elements: [{ id: "same" }],
appState: {},
files: {},
};
const first = store.updateDrawing(created.id, { expectedRevision: 0, scene });
expect(first.ok ? first.drawing.revision : null).toBe(1);
const renamed = store.updateDrawing(created.id, { expectedRevision: 1, title: "Renamed", scene });
expect(renamed.ok).toBe(true);
expect(renamed.ok ? renamed.drawing.title : null).toBe("Renamed");
expect(renamed.ok ? renamed.drawing.revision : null).toBe(2);
});
});
+94 -22
View File
@@ -2,8 +2,8 @@ import { Database } from "bun:sqlite";
import { randomUUID } from "node:crypto";
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { DEFAULT_TITLE, type DrawingMeta, type DrawingRecord, type ScenePayload } from "./shared";
import { coerceStoredScene, emptyScene, normalizeTitle } from "./scene";
import { DEFAULT_TITLE, type DrawingMeta, type DrawingRecord, type ScenePayload } from "../core/shared";
import { emptyScene, normalizeScene, normalizeTitle } from "../core/scene";
type DrawingRow = {
id: string;
@@ -11,10 +11,16 @@ type DrawingRow = {
data: string;
createdAt: string;
updatedAt: string;
revision: number;
};
type DrawingMetaRow = Omit<DrawingRow, "data">;
export type DrawingUpdateResult =
| { ok: true; drawing: DrawingRecord }
| { ok: false; reason: "not_found" }
| { ok: false; reason: "conflict"; drawing: DrawingRecord };
export type DrawingStore = ReturnType<typeof createDrawingStore>;
function createId(): string {
@@ -44,6 +50,7 @@ function readMeta(row: DrawingMetaRow | null | undefined): DrawingMeta | null {
title: row.title,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
revision: row.revision,
};
}
@@ -52,9 +59,17 @@ function readRow(row: DrawingRow | null | undefined): DrawingRecord | null {
return null;
}
let scene: ScenePayload;
try {
scene = normalizeScene(JSON.parse(row.data));
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown scene parsing error";
throw new Error(`Invalid stored scene for drawing ${row.id}: ${message}`);
}
return {
...readMeta(row)!,
scene: coerceStoredScene(JSON.parse(row.data)),
scene,
};
}
@@ -70,7 +85,8 @@ export function createDrawingStore(databasePath = resolveDatabasePath()) {
title TEXT NOT NULL,
data TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
revision INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS drawings_updated_at_idx
@@ -82,7 +98,8 @@ export function createDrawingStore(databasePath = resolveDatabasePath()) {
id,
title,
created_at AS createdAt,
updated_at AS updatedAt
updated_at AS updatedAt,
revision
FROM drawings
ORDER BY updated_at DESC, created_at DESC
`);
@@ -93,7 +110,8 @@ export function createDrawingStore(databasePath = resolveDatabasePath()) {
title,
data,
created_at AS createdAt,
updated_at AS updatedAt
updated_at AS updatedAt,
revision
FROM drawings
WHERE id = ?1
`);
@@ -105,22 +123,40 @@ export function createDrawingStore(databasePath = resolveDatabasePath()) {
const updateSceneQuery = db.query(`
UPDATE drawings
SET data = ?2, updated_at = CURRENT_TIMESTAMP
SET data = ?2, updated_at = CURRENT_TIMESTAMP, revision = revision + 1
WHERE id = ?1
`);
const updateTitleQuery = db.query(`
UPDATE drawings
SET title = ?2, updated_at = CURRENT_TIMESTAMP
SET title = ?2, updated_at = CURRENT_TIMESTAMP, revision = revision + 1
WHERE id = ?1
`);
const updateBothQuery = db.query(`
UPDATE drawings
SET title = ?2, data = ?3, updated_at = CURRENT_TIMESTAMP
SET title = ?2, data = ?3, updated_at = CURRENT_TIMESTAMP, revision = revision + 1
WHERE id = ?1
`);
const updateSceneExpectedQuery = db.query(`
UPDATE drawings
SET data = ?2, updated_at = CURRENT_TIMESTAMP, revision = revision + 1
WHERE id = ?1 AND revision = ?3
`);
const updateTitleExpectedQuery = db.query(`
UPDATE drawings
SET title = ?2, updated_at = CURRENT_TIMESTAMP, revision = revision + 1
WHERE id = ?1 AND revision = ?3
`);
const updateBothExpectedQuery = db.query(`
UPDATE drawings
SET title = ?2, data = ?3, updated_at = CURRENT_TIMESTAMP, revision = revision + 1
WHERE id = ?1 AND revision = ?4
`);
const deleteQuery = db.query(`
DELETE FROM drawings
WHERE id = ?1
@@ -148,28 +184,64 @@ export function createDrawingStore(databasePath = resolveDatabasePath()) {
return getLatestDrawing() ?? createDrawing();
}
function updateDrawing(id: string, update: { scene?: ScenePayload; title?: string }): DrawingRecord | null {
const existing = getDrawing(id);
if (!existing) {
return null;
}
function updateDrawing(
id: string,
update: { scene?: ScenePayload; title?: string; expectedRevision?: number },
): DrawingUpdateResult {
const hasScene = update.scene !== undefined;
const hasTitle = update.title !== undefined;
const existingRow = getQuery.get(id) as DrawingRow | null | undefined;
if (!existingRow) {
return { ok: false, reason: "not_found" };
}
const existing = readRow(existingRow)!;
if (!hasScene && !hasTitle) {
return existing;
return { ok: true, drawing: existing };
}
if (hasScene && hasTitle) {
updateBothQuery.run(id, normalizeTitle(update.title), JSON.stringify(update.scene));
} else if (hasScene) {
updateSceneQuery.run(id, JSON.stringify(update.scene));
const nextTitle = hasTitle ? normalizeTitle(update.title) : existingRow.title;
const nextScene = hasScene ? JSON.stringify(update.scene) : existingRow.data;
const titleChanged = nextTitle !== existingRow.title;
const sceneChanged = nextScene !== existingRow.data;
if (!titleChanged && !sceneChanged) {
return { ok: true, drawing: existing };
}
if (update.expectedRevision !== undefined && update.expectedRevision !== existingRow.revision) {
return { ok: false, reason: "conflict", drawing: existing };
}
let changes: number;
if (sceneChanged && titleChanged) {
changes =
update.expectedRevision === undefined
? Number(updateBothQuery.run(id, nextTitle, nextScene).changes)
: Number(updateBothExpectedQuery.run(id, nextTitle, nextScene, update.expectedRevision).changes);
} else if (sceneChanged) {
changes =
update.expectedRevision === undefined
? Number(updateSceneQuery.run(id, nextScene).changes)
: Number(updateSceneExpectedQuery.run(id, nextScene, update.expectedRevision).changes);
} else {
updateTitleQuery.run(id, normalizeTitle(update.title));
changes =
update.expectedRevision === undefined
? Number(updateTitleQuery.run(id, nextTitle).changes)
: Number(updateTitleExpectedQuery.run(id, nextTitle, update.expectedRevision).changes);
}
return getDrawing(id);
const drawing = getDrawing(id);
if (changes > 0 && drawing) {
return { ok: true, drawing };
}
if (!drawing) {
return { ok: false, reason: "not_found" };
}
return { ok: false, reason: "conflict", drawing };
}
function deleteDrawing(id: string): { deleted: boolean; next: DrawingMeta | null } {
@@ -1,5 +1,5 @@
import index from "./index.html";
import { createServer } from "./server";
import index from "../client/index.html";
import { createServer } from "./http-server";
export function createDevServer() {
const server = createServer();
@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createDrawingStore, type DrawingStore } from "./db";
import { createServer } from "./server";
import { createServer } from "./http-server";
const cleanup: string[] = [];
const stores: DrawingStore[] = [];