This commit is contained in:
2026-05-24 15:32:36 +00:00
commit 1eb5350d09
20 changed files with 2852 additions and 0 deletions
+477
View File
@@ -0,0 +1,477 @@
import "../node_modules/@excalidraw/excalidraw/dist/prod/index.css";
import {
Excalidraw,
exportToBlob,
serializeAsJSON,
} 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 SaveStatus = "saved" | "saving" | "failed";
type DrawingResponse = DrawingMeta & ScenePayload;
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>,
};
}
function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
}
function filenameBase(title: string): string {
const safeTitle = title
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
const now = new Date();
const stamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(
now.getDate(),
).padStart(2, "0")}-${String(now.getHours()).padStart(2, "0")}${String(
now.getMinutes(),
).padStart(2, "0")}`;
return `${safeTitle || "drawing"}-${stamp}`;
}
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;
}
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 [saveStatus, setSaveStatus] = useState<SaveStatus>("saved");
const [error, setError] = 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 timeoutRef = useRef<number | null>(null);
const inFlightSaveRef = useRef<Promise<void> | null>(null);
const loadVersionRef = useRef(0);
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 () => {
const drawingId = currentIdRef.current;
const nextScene = latestSceneRef.current;
if (!drawingId || !nextScene) {
return;
}
setSaveStatus("saving");
setError(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));
setSaveStatus("saved");
})
.catch((saveError: unknown) => {
setSaveStatus("failed");
setError(saveError instanceof Error ? saveError.message : "Save failed");
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 scheduleSave = useCallback(() => {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
}
setSaveStatus("saving");
timeoutRef.current = window.setTimeout(() => {
timeoutRef.current = null;
void saveScene();
}, 1500);
}, [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);
setSaveStatus("saved");
} 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 exportPng = useCallback(async () => {
const latest = latestSceneRef.current;
if (!latest) {
return;
}
const blob = await exportToBlob({
elements: latest.elements as never[],
appState: {
...(latest.appState as unknown as AppState),
exportBackground: true,
},
files: latest.files as BinaryFiles,
mimeType: "image/png",
getDimensions: (width: number, height: number) => ({
width,
height,
scale: 2,
}),
});
downloadBlob(blob, `${filenameBase(currentTitleRef.current)}.png`);
}, []);
const exportExcalidraw = useCallback(() => {
const latest = latestSceneRef.current;
if (!latest) {
return;
}
const json = serializeAsJSON(
latest.elements as never[],
latest.appState as Partial<AppState>,
latest.files as BinaryFiles,
"local",
);
downloadBlob(
new Blob([json], { type: "application/json" }),
`${filenameBase(currentTitleRef.current)}.excalidraw`,
);
}, []);
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);
}
};
}, []);
return (
<div className="app-shell">
<aside className="sidebar">
<div className="sidebar-header">
<h1>excali</h1>
<button type="button" className="primary-button" onClick={() => void createDrawing()}>
New
</button>
</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 navigateToDrawing(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>
<main className="editor-shell">
<div className="toolbar">
<span className={`status-badge status-${saveStatus}`}>
{saveStatus === "saving" ? "Saving..." : saveStatus === "failed" ? "Save failed" : "Saved"}
</span>
<button type="button" className="secondary-button" onClick={() => void exportPng()} disabled={!scene}>
Export PNG
</button>
<button
type="button"
className="secondary-button"
onClick={exportExcalidraw}
disabled={!scene}
>
Export .excalidraw
</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) => {
latestSceneRef.current = sceneFromEditor(elements, appState, files);
if (ignoreChangeRef.current) {
ignoreChangeRef.current = false;
return;
}
scheduleSave();
}}
/>
</div>
)}
</main>
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
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("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();
});
});
+119
View File
@@ -0,0 +1,119 @@
import { type DrawingStore } from "./db";
import { HttpError, normalizeTitle, parseJsonBody, parseSceneText } from "./scene";
type RouteRequest = Request & {
params?: Record<string, string>;
};
function json(data: unknown, init?: ResponseInit): Response {
return Response.json(data, init);
}
function errorResponse(error: unknown): Response {
if (error instanceof HttpError) {
return json({ ok: false, error: error.message }, { status: error.status });
}
console.error(error);
return json({ ok: false, error: "Internal server error" }, { status: 500 });
}
export function createApi(store: DrawingStore) {
return {
health() {
return json({ ok: true });
},
listDrawings() {
return json(store.listDrawings());
},
createDrawing() {
const drawing = store.createDrawing();
return json(
{
id: drawing.id,
title: drawing.title,
createdAt: drawing.createdAt,
updatedAt: drawing.updatedAt,
...drawing.scene,
},
{ status: 201 },
);
},
getDrawing(request: RouteRequest) {
const id = request.params?.id;
const drawing = id ? store.getDrawing(id) : null;
if (!drawing) {
return json({ ok: false, error: "Drawing not found" }, { status: 404 });
}
return json({
id: drawing.id,
title: drawing.title,
createdAt: drawing.createdAt,
updatedAt: drawing.updatedAt,
...drawing.scene,
});
},
async updateDrawing(request: RouteRequest) {
try {
const id = request.params?.id;
if (!id) {
throw new HttpError(400, "Missing drawing id");
}
const text = await request.text();
const raw = parseJsonBody<Record<string, unknown>>(text);
const hasTitle = Object.hasOwn(raw, "title");
const hasScene =
Object.hasOwn(raw, "elements") ||
Object.hasOwn(raw, "appState") ||
Object.hasOwn(raw, "files");
if (!hasTitle && !hasScene) {
throw new HttpError(400, "Nothing to update");
}
const scene = hasScene ? parseSceneText(text) : undefined;
const updated = store.updateDrawing(id, {
scene,
title: hasTitle ? normalizeTitle(raw.title) : undefined,
});
if (!updated) {
return json({ ok: false, error: "Drawing not found" }, { status: 404 });
}
return json({
ok: true,
drawing: {
id: updated.id,
title: updated.title,
createdAt: updated.createdAt,
updatedAt: updated.updatedAt,
},
});
} catch (error) {
return errorResponse(error);
}
},
deleteDrawing(request: RouteRequest) {
const id = request.params?.id;
if (!id) {
return json({ ok: false, error: "Missing drawing id" }, { status: 400 });
}
const { deleted, next } = store.deleteDrawing(id);
if (!deleted) {
return json({ ok: false, error: "Drawing not found" }, { status: 404 });
}
return json({ ok: true, nextId: next?.id ?? null });
},
};
}
+16
View File
@@ -0,0 +1,16 @@
import React 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(
<React.StrictMode>
<App />
</React.StrictMode>,
);
+49
View File
@@ -0,0 +1,49 @@
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(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);
});
});
+209
View File
@@ -0,0 +1,209 @@
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";
type DrawingRow = {
id: string;
title: string;
data: string;
createdAt: string;
updatedAt: string;
};
type DrawingMetaRow = Omit<DrawingRow, "data">;
export type DrawingStore = ReturnType<typeof createDrawingStore>;
function createId(): string {
return randomUUID().replaceAll("-", "").slice(0, 12);
}
function resolveDatabasePath(): string {
if (process.env.DATABASE_PATH) {
return process.env.DATABASE_PATH;
}
try {
mkdirSync("/data", { recursive: true });
return "/data/excalidraw.sqlite";
} catch {
return `${process.cwd()}/data/excalidraw.sqlite`;
}
}
function readMeta(row: DrawingMetaRow | null | undefined): DrawingMeta | null {
if (!row) {
return null;
}
return {
id: row.id,
title: row.title,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
};
}
function readRow(row: DrawingRow | null | undefined): DrawingRecord | null {
if (!row) {
return null;
}
return {
...readMeta(row)!,
scene: coerceStoredScene(JSON.parse(row.data)),
};
}
export function createDrawingStore(databasePath = resolveDatabasePath()) {
mkdirSync(dirname(databasePath), { recursive: true });
const db = new Database(databasePath, { create: true, strict: true });
db.exec(`
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS drawings (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
data TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS drawings_updated_at_idx
ON drawings(updated_at DESC, created_at DESC);
`);
const listQuery = db.query(`
SELECT
id,
title,
created_at AS createdAt,
updated_at AS updatedAt
FROM drawings
ORDER BY updated_at DESC, created_at DESC
`);
const getQuery = db.query(`
SELECT
id,
title,
data,
created_at AS createdAt,
updated_at AS updatedAt
FROM drawings
WHERE id = ?1
`);
const createQuery = db.query(`
INSERT INTO drawings (id, title, data)
VALUES (?1, ?2, ?3)
`);
const updateSceneQuery = db.query(`
UPDATE drawings
SET data = ?2, updated_at = CURRENT_TIMESTAMP
WHERE id = ?1
`);
const updateTitleQuery = db.query(`
UPDATE drawings
SET title = ?2, updated_at = CURRENT_TIMESTAMP
WHERE id = ?1
`);
const updateBothQuery = db.query(`
UPDATE drawings
SET title = ?2, data = ?3, updated_at = CURRENT_TIMESTAMP
WHERE id = ?1
`);
const deleteQuery = db.query(`
DELETE FROM drawings
WHERE id = ?1
`);
function listDrawings(): DrawingMeta[] {
return (listQuery.all() as DrawingMetaRow[]).map((row) => readMeta(row)!);
}
function getDrawing(id: string): DrawingRecord | null {
return readRow(getQuery.get(id) as DrawingRow | null | undefined);
}
function createDrawing(title = DEFAULT_TITLE): DrawingRecord {
const id = createId();
createQuery.run(id, normalizeTitle(title), JSON.stringify(emptyScene()));
return getDrawing(id)!;
}
function getLatestDrawing(): DrawingMeta | null {
return listDrawings()[0] ?? null;
}
function ensureInitialDrawing(): DrawingMeta {
return getLatestDrawing() ?? createDrawing();
}
function updateDrawing(id: string, update: { scene?: ScenePayload; title?: string }): DrawingRecord | null {
const existing = getDrawing(id);
if (!existing) {
return null;
}
const hasScene = update.scene !== undefined;
const hasTitle = update.title !== undefined;
if (!hasScene && !hasTitle) {
return existing;
}
if (hasScene && hasTitle) {
updateBothQuery.run(id, normalizeTitle(update.title), JSON.stringify(update.scene));
} else if (hasScene) {
updateSceneQuery.run(id, JSON.stringify(update.scene));
} else {
updateTitleQuery.run(id, normalizeTitle(update.title));
}
return getDrawing(id);
}
function deleteDrawing(id: string): { deleted: boolean; next: DrawingMeta | null } {
const changes = Number(deleteQuery.run(id).changes);
if (changes === 0) {
return { deleted: false, next: null };
}
return {
deleted: true,
next: ensureInitialDrawing(),
};
}
function close() {
db.close(false);
}
return {
databasePath,
close,
listDrawings,
getDrawing,
createDrawing,
getLatestDrawing,
ensureInitialDrawing,
updateDrawing,
deleteDrawing,
};
}
let defaultStore: DrawingStore | null = null;
export function getDefaultDrawingStore(): DrawingStore {
defaultStore ??= createDrawingStore();
return defaultStore;
}
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>excali</title>
<script type="module" src="./client.tsx"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, test } from "bun:test";
import { HttpError, MAX_SCENE_BYTES, normalizeScene, parseJsonBody } from "./scene";
describe("scene helpers", () => {
test("normalizes volatile app state fields", () => {
const scene = normalizeScene({
elements: [],
appState: {
selectedElementIds: { one: true },
viewModeEnabled: false,
},
files: {},
});
expect(scene.appState.selectedElementIds).toBeUndefined();
expect(scene.appState.viewModeEnabled).toBe(false);
});
test("rejects oversized payloads", () => {
const text = "x".repeat(MAX_SCENE_BYTES + 1);
expect(() => parseJsonBody(text)).toThrow(HttpError);
expect(() => parseJsonBody(text)).toThrow("Payload too large");
});
});
+97
View File
@@ -0,0 +1,97 @@
import { DEFAULT_TITLE, type ScenePayload } from "./shared";
export const MAX_SCENE_BYTES = 25 * 1024 * 1024;
export class HttpError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
}
}
const VOLATILE_APP_STATE_KEYS = new Set([
"collaborators",
"selectedElementIds",
"selectedGroupIds",
"editingElement",
"editingLinearElement",
"openMenu",
"openSidebar",
"contextMenu",
"toast",
]);
export function emptyScene(): ScenePayload {
return {
elements: [],
appState: {},
files: {},
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function normalizeTitle(input: unknown): string {
if (typeof input !== "string") {
return DEFAULT_TITLE;
}
const trimmed = input.trim();
return trimmed.length > 0 ? trimmed : DEFAULT_TITLE;
}
export function normalizeScene(input: unknown): ScenePayload {
if (!isRecord(input)) {
throw new HttpError(400, "Body must be an object");
}
if (!Array.isArray(input.elements)) {
throw new HttpError(400, "elements must be an array");
}
if (!isRecord(input.appState)) {
throw new HttpError(400, "appState must be an object");
}
if (!isRecord(input.files)) {
throw new HttpError(400, "files must be an object");
}
const appState = Object.fromEntries(
Object.entries(input.appState).filter(([key]) => !VOLATILE_APP_STATE_KEYS.has(key)),
);
return {
elements: input.elements,
appState,
files: input.files,
};
}
export function parseJsonBody<T = unknown>(text: string): T {
if (new TextEncoder().encode(text).byteLength > MAX_SCENE_BYTES) {
throw new HttpError(413, "Payload too large");
}
try {
return JSON.parse(text) as T;
} catch {
throw new HttpError(400, "Invalid JSON");
}
}
export function parseSceneText(text: string): ScenePayload {
return normalizeScene(parseJsonBody(text));
}
export function coerceStoredScene(input: unknown): ScenePayload {
try {
return normalizeScene(input);
} catch {
return emptyScene();
}
}
+40
View File
@@ -0,0 +1,40 @@
import index from "./index.html";
import { createApi } from "./api";
import { getDefaultDrawingStore } from "./db";
export function createServer() {
const drawingStore = getDefaultDrawingStore();
const api = createApi(drawingStore);
return {
port: Number(process.env.PORT ?? "3000"),
hostname: process.env.HOST ?? "0.0.0.0",
routes: {
"/": (request: Request) => {
const drawing = drawingStore.ensureInitialDrawing();
return Response.redirect(new URL(`/d/${drawing.id}`, request.url), 302);
},
"/d/:id": index,
"/api/health": {
GET: () => api.health(),
},
"/api/drawings": {
GET: () => api.listDrawings(),
POST: () => api.createDrawing(),
},
"/api/drawings/:id": {
GET: (request: Request & { params: Record<string, string> }) => api.getDrawing(request),
PUT: (request: Request & { params: Record<string, string> }) => api.updateDrawing(request),
DELETE: (request: Request & { params: Record<string, string> }) => api.deleteDrawing(request),
},
},
fetch() {
return Response.json({ ok: false, error: "Not found" }, { status: 404 });
},
} satisfies Parameters<typeof Bun.serve>[0];
}
if (import.meta.main) {
const server = Bun.serve(createServer());
console.log(`Listening on http://${server.hostname}:${server.port}`);
}
+18
View File
@@ -0,0 +1,18 @@
export type ScenePayload = {
elements: unknown[];
appState: Record<string, unknown>;
files: Record<string, unknown>;
};
export type DrawingMeta = {
id: string;
title: string;
createdAt: string;
updatedAt: string;
};
export type DrawingRecord = DrawingMeta & {
scene: ScenePayload;
};
export const DEFAULT_TITLE = "Untitled";
+187
View File
@@ -0,0 +1,187 @@
: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 {
display: flex;
height: 100%;
}
.sidebar {
display: flex;
width: 260px;
min-width: 260px;
flex-direction: column;
border-right: 1px solid #e4e4e7;
background: #ffffff;
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
border-bottom: 1px solid #e4e4e7;
padding: 16px;
}
.sidebar-header h1 {
margin: 0;
font-size: 16px;
font-weight: 600;
}
.drawing-list {
overflow: auto;
padding: 8px;
}
.drawing-item {
display: grid;
grid-template-columns: minmax(0, 1fr) 32px;
align-items: center;
gap: 8px;
border-radius: 8px;
padding: 4px;
}
.drawing-item-active {
background: #f4f4f5;
}
.drawing-link {
min-width: 0;
border: 0;
background: transparent;
padding: 8px;
text-align: left;
}
.drawing-title,
.title-input {
display: block;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.title-input {
border: 1px solid #d4d4d8;
border-radius: 6px;
background: #ffffff;
padding: 6px 8px;
}
.editor-shell {
position: relative;
min-width: 0;
flex: 1;
}
.toolbar {
position: absolute;
top: 16px;
right: 16px;
z-index: 20;
display: flex;
align-items: center;
gap: 8px;
}
.status-badge,
.primary-button,
.secondary-button,
.icon-button {
border: 1px solid #d4d4d8;
border-radius: 8px;
background: #ffffff;
}
.status-badge {
padding: 8px 10px;
font-size: 13px;
}
.status-saving {
color: #1d4ed8;
}
.status-failed {
color: #b91c1c;
}
.status-saved {
color: #166534;
}
.primary-button,
.secondary-button {
cursor: pointer;
padding: 8px 12px;
}
.secondary-button:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.icon-button {
width: 32px;
height: 32px;
cursor: pointer;
}
.editor-frame,
.editor-loading {
height: 100%;
}
.editor-loading {
display: grid;
place-items: center;
color: #52525b;
}
@media (max-width: 900px) {
.sidebar {
width: 220px;
min-width: 220px;
}
.toolbar {
left: 12px;
right: 12px;
flex-wrap: wrap;
justify-content: flex-end;
}
}