diff --git a/src/api/__tests__/boards/boards.test.ts b/src/api/__tests__/boards/boards.test.ts new file mode 100644 index 0000000..4bd7edc --- /dev/null +++ b/src/api/__tests__/boards/boards.test.ts @@ -0,0 +1,124 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + deleteBoardById, + getBoardById, + getBoardEpochs, + getBoardHistory, + getBoardStrokes, + getBoards, + patchBoardById, + postBoard, + postBoardClear, + postBoardClose, +} from "../../boards"; +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; + +describe("boards API", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("postBoard calls POST /boards with the body", async () => { + mockFetchSuccess({ id: "b1", title: "Math" }); + const body = { title: "Math", participants: ["u2", "u3"] }; + await postBoard(body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("getBoards calls GET /boards with pagination", async () => { + const mockPage = { items: [{ id: "b1" }], total: 1 }; + mockFetchSuccess(mockPage); + const result = await getBoards({ limit: 10, offset: 20 }); + expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards?limit=10&offset=20"); + expect(init?.method).toBe("GET"); + }); + + it("getBoardById calls GET /boards/:id", async () => { + mockFetchSuccess({ id: "b1" }); + await getBoardById("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1"); + expect(init?.method).toBe("GET"); + }); + + it("getBoardStrokes calls GET /boards/:id/strokes", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getBoardStrokes("b1", { limit: 200 }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1/strokes?limit=200"); + expect(init?.method).toBe("GET"); + }); + + it("getBoardHistory calls GET /boards/:id/history with epoch + pagination", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getBoardHistory("b1", { epoch: 3, limit: 50 }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1/history?epoch=3&limit=50"); + expect(init?.method).toBe("GET"); + }); + + it("getBoardHistory omits epoch when not given", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getBoardHistory("b1"); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/boards/b1/history"); + }); + + it("getBoardEpochs calls GET /boards/:id/epochs", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getBoardEpochs("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1/epochs"); + expect(init?.method).toBe("GET"); + }); + + it("patchBoardById calls PATCH /boards/:id with the body", async () => { + mockFetchSuccess({ id: "b1" }); + const body = { locked: true }; + await patchBoardById("b1", body); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify(body)); + }); + + it("postBoardClear calls POST /boards/:id/clear", async () => { + mockFetchSuccess({ id: "s1", kind: "clear" }); + await postBoardClear("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1/clear"); + expect(init?.method).toBe("POST"); + }); + + it("postBoardClose calls POST /boards/:id/close", async () => { + mockFetchSuccess({ id: "b1", closed_at: 123 }); + await postBoardClose("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1/close"); + expect(init?.method).toBe("POST"); + }); + + it("deleteBoardById calls DELETE /boards/:id", async () => { + mockFetch204(); + await deleteBoardById("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/boards/b1"); + expect(init?.method).toBe("DELETE"); + }); +}); diff --git a/src/api/__tests__/users/users.test.ts b/src/api/__tests__/users/users.test.ts index 773d432..d7b9c38 100644 --- a/src/api/__tests__/users/users.test.ts +++ b/src/api/__tests__/users/users.test.ts @@ -118,6 +118,30 @@ describe("users API", () => { expect(init?.body).toBe(JSON.stringify(updates)); }); + it("patchMyPreferences sends palette_color to set the accent", async () => { + const mockUser = { id: "u1", palette_color: "#fefae0" }; + mockFetchSuccess(mockUser); + + const updates = { palette_color: "#fefae0" }; + await patchMyPreferences(updates); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/users/me/preferences"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify(updates)); + }); + + it("patchMyPreferences sends empty palette_color to clear the accent", async () => { + const mockUser = { id: "u1", palette_color: null }; + mockFetchSuccess(mockUser); + + const updates = { palette_color: "" }; + await patchMyPreferences(updates); + + const [, init] = lastFetchCall(); + expect(init?.body).toBe(JSON.stringify({ palette_color: "" })); + }); + it("patchUserPreferences calls /users/:id/preferences", async () => { const mockUser = { id: "u1", language: "tr" }; mockFetchSuccess(mockUser); diff --git a/src/api/boards/deleteBoardById.ts b/src/api/boards/deleteBoardById.ts new file mode 100644 index 0000000..9e2974a --- /dev/null +++ b/src/api/boards/deleteBoardById.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; + +// Creator only: delete the board and its whole stroke log; frees a board seat. +export function deleteBoardById(id: string): Promise { + return client(`/boards/${encodeURIComponent(id)}`, { method: "DELETE" }); +} diff --git a/src/api/boards/getBoardById.ts b/src/api/boards/getBoardById.ts new file mode 100644 index 0000000..42c5b78 --- /dev/null +++ b/src/api/boards/getBoardById.ts @@ -0,0 +1,7 @@ +import { client } from "../client"; +import type { Board } from "./types"; + +// One board — a 404 (never 403) for anyone not on it. +export function getBoardById(id: string, signal?: AbortSignal): Promise { + return client(`/boards/${encodeURIComponent(id)}`, { signal }); +} diff --git a/src/api/boards/getBoardEpochs.ts b/src/api/boards/getBoardEpochs.ts new file mode 100644 index 0000000..3bfeaed --- /dev/null +++ b/src/api/boards/getBoardEpochs.ts @@ -0,0 +1,16 @@ +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { StrokeRow } from "./types"; + +// The epoch index: every clear marker (each carries the closed epoch + its +// final stroke count), oldest first. The open epoch is deliberately absent. +export async function getBoardEpochs( + id: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client( + `/boards/${encodeURIComponent(id)}/epochs${pageQuery(params)}`, + { signal }, + ); + return normalizePage(data); +} diff --git a/src/api/boards/getBoardHistory.ts b/src/api/boards/getBoardHistory.ts new file mode 100644 index 0000000..ce2131b --- /dev/null +++ b/src/api/boards/getBoardHistory.ts @@ -0,0 +1,24 @@ +import { + appendPageParams, + client, + normalizePage, + type Page, +} from "../client"; +import type { BoardHistoryParams, StrokeRow } from "./types"; + +// The whole append-only log, oldest first, clear markers included. `epoch` +// narrows to a single epoch (for session replay); omit for the whole life. +export async function getBoardHistory( + id: string, + params?: BoardHistoryParams, + signal?: AbortSignal, +): Promise> { + const query = new URLSearchParams(); + if (params?.epoch != null) query.set("epoch", String(params.epoch)); + appendPageParams(query, params); + const suffix = query.toString() ? `?${query.toString()}` : ""; + const data = await client(`/boards/${encodeURIComponent(id)}/history${suffix}`, { + signal, + }); + return normalizePage(data); +} diff --git a/src/api/boards/getBoardStrokes.ts b/src/api/boards/getBoardStrokes.ts new file mode 100644 index 0000000..a6f01c5 --- /dev/null +++ b/src/api/boards/getBoardStrokes.ts @@ -0,0 +1,16 @@ +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { StrokeRow } from "./types"; + +// The live canvas: the current epoch's strokes, oldest first. REST catch-up +// / fallback for the same canvas the socket replays. +export async function getBoardStrokes( + id: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client( + `/boards/${encodeURIComponent(id)}/strokes${pageQuery(params)}`, + { signal }, + ); + return normalizePage(data); +} diff --git a/src/api/boards/getBoards.ts b/src/api/boards/getBoards.ts new file mode 100644 index 0000000..e64d0f6 --- /dev/null +++ b/src/api/boards/getBoards.ts @@ -0,0 +1,8 @@ +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { Board } from "./types"; + +// Boards the caller created or was invited to, newest first. +export async function getBoards(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/boards${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/boards/index.ts b/src/api/boards/index.ts new file mode 100644 index 0000000..ae3c659 --- /dev/null +++ b/src/api/boards/index.ts @@ -0,0 +1,11 @@ +export * from "./types"; +export * from "./postBoard"; +export * from "./getBoards"; +export * from "./getBoardById"; +export * from "./getBoardStrokes"; +export * from "./getBoardHistory"; +export * from "./getBoardEpochs"; +export * from "./patchBoardById"; +export * from "./postBoardClear"; +export * from "./postBoardClose"; +export * from "./deleteBoardById"; diff --git a/src/api/boards/patchBoardById.ts b/src/api/boards/patchBoardById.ts new file mode 100644 index 0000000..be78709 --- /dev/null +++ b/src/api/boards/patchBoardById.ts @@ -0,0 +1,7 @@ +import { client } from "../client"; +import type { Board, UpdateBoardBody } from "./types"; + +// Re-title (any participant); roster + lock are the creator's alone (403). +export function patchBoardById(id: string, body: UpdateBoardBody): Promise { + return client(`/boards/${encodeURIComponent(id)}`, { method: "PATCH", body }); +} diff --git a/src/api/boards/postBoard.ts b/src/api/boards/postBoard.ts new file mode 100644 index 0000000..f727d0b --- /dev/null +++ b/src/api/boards/postBoard.ts @@ -0,0 +1,7 @@ +import { client } from "../client"; +import type { Board, CreateBoardBody } from "./types"; + +// Open a whiteboard; the caller becomes its creator. 409 at max_boards_per_creator. +export function postBoard(body: CreateBoardBody): Promise { + return client("/boards", { method: "POST", body }); +} diff --git a/src/api/boards/postBoardClear.ts b/src/api/boards/postBoardClear.ts new file mode 100644 index 0000000..5f8529d --- /dev/null +++ b/src/api/boards/postBoardClear.ts @@ -0,0 +1,8 @@ +import { client } from "../client"; +import type { StrokeRow } from "./types"; + +// Creator only: bump the epoch, blanking the live canvas (nothing deleted). +// 409 on a closed board. Returns the clear marker. +export function postBoardClear(id: string): Promise { + return client(`/boards/${encodeURIComponent(id)}/clear`, { method: "POST" }); +} diff --git a/src/api/boards/postBoardClose.ts b/src/api/boards/postBoardClose.ts new file mode 100644 index 0000000..0a5806e --- /dev/null +++ b/src/api/boards/postBoardClose.ts @@ -0,0 +1,8 @@ +import { client } from "../client"; +import type { Board } from "./types"; + +// Creator only: retire the board — permanently read-only, still fully +// readable; idempotent, no reopen. +export function postBoardClose(id: string): Promise { + return client(`/boards/${encodeURIComponent(id)}/close`, { method: "POST" }); +} diff --git a/src/api/boards/types.ts b/src/api/boards/types.ts new file mode 100644 index 0000000..2cc5f08 --- /dev/null +++ b/src/api/boards/types.ts @@ -0,0 +1,49 @@ +import type { PageParams } from "../client"; + +// A collaborative whiteboard. `creator` is always a participant but never +// appears in `participants`. `epoch` is the live-canvas generation (a clear +// bumps it); `closed_at` set => permanently read-only. +export type Board = { + id: string; + title: string; + creator: string; + participants: string[]; + locked: boolean; + locked_by: string | null; + locked_at: number | null; + epoch: number; + closed_at: number | null; + created_at: number; +}; + +export type BoardStrokeKind = "stroke" | "clear"; + +// One row of the append-only stroke log. `payload` is the opaque serialized +// mark (null on a clear marker); `count` is the closed epoch's final stroke +// count, present only on a clear marker. +export type StrokeRow = { + id: string; + author: string; + kind: BoardStrokeKind; + payload: string | null; + count: number | null; + epoch: number; + created_at: number; +}; + +// POST /boards rejects unknown keys (422) — send only these two fields. +export type CreateBoardBody = { + title: string; + participants?: string[]; +}; + +// PATCH /boards/{id} rejects unknown keys (422). Send only the writable fields +// that changed: `title` (any participant), `participants`/`locked` (creator). +export type UpdateBoardBody = { + title?: string; + participants?: string[] | null; + locked?: boolean; +}; + +// GET /boards/{id}/history: `epoch` narrows to one epoch; omit for whole life. +export type BoardHistoryParams = PageParams & { epoch?: number }; diff --git a/src/api/client/types.ts b/src/api/client/types.ts index 2af4ecf..5fea0d6 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -23,6 +23,7 @@ export type User = { birth_date: string | null; theme: UserTheme | null; language: UserLanguage | null; + palette_color: string | null; }; export type ProfileUpdate = { diff --git a/src/api/users/patchMyPreferences.ts b/src/api/users/patchMyPreferences.ts index fe568a8..af4ac51 100644 --- a/src/api/users/patchMyPreferences.ts +++ b/src/api/users/patchMyPreferences.ts @@ -4,6 +4,8 @@ import type { User, UserLanguage, UserTheme } from "../client"; export type PatchMyPreferencesBody = { theme?: UserTheme; language?: UserLanguage; + // Accent color: "#rrggbb" to set, "" to clear back to null, omit to keep. + palette_color?: string; }; export function patchMyPreferences(body: PatchMyPreferencesBody): Promise { diff --git a/src/components/layout/nav-items.ts b/src/components/layout/nav-items.ts index 62ea6fe..f58ecf9 100644 --- a/src/components/layout/nav-items.ts +++ b/src/components/layout/nav-items.ts @@ -17,6 +17,7 @@ import { IconHomework, IconHome, IconMessage, + IconEdit, IconNote, IconReportAnalytics, IconSchool, @@ -129,6 +130,7 @@ const NAV_GROUPS: NavGroup[] = [ CALENDAR_ITEM, { id: "appointments", to: "/appointments", labelKey: "nav.appointments", Icon: IconClock }, { id: "notes", to: "/notes", labelKey: "nav.notes", Icon: IconNote }, + { id: "whiteboards", to: "/whiteboards", labelKey: "nav.whiteboards", Icon: IconEdit, minRole: "student" }, { id: "marks", to: "/marks", labelKey: "nav.marks", Icon: IconChart, exactRole: "student" }, { id: "pomodoro", to: "/pomodoro", labelKey: "nav.pomodoro", Icon: IconClock, exactRole: "student" }, ], diff --git a/src/components/whiteboard/whiteboard-canvas.tsx b/src/components/whiteboard/whiteboard-canvas.tsx new file mode 100644 index 0000000..e977f7c --- /dev/null +++ b/src/components/whiteboard/whiteboard-canvas.tsx @@ -0,0 +1,388 @@ +import { For, Show, createSignal, onCleanup, onMount } from "solid-js"; +import { IconEdit, IconEraser, IconMove, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; +import { cn } from "@/lib/cn"; +import { + PAPER_CELL, + PAPER_LINE, + paintStroke, + paintTip, + type Point, + type Stroke, +} from "@/lib/draw-stroke"; +import { useT } from "@/stores/preferences-context"; + +const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; +const WIDTHS = [2, 6, 14]; +const ZOOM_MIN = 0.25; +const ZOOM_MAX = 4; +const ZOOM_STEP = 1.25; +const OVERLAY_CARD = "absolute z-10 flex gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-xs backdrop-blur-xs"; + +// Imperative handle the room uses to push server-confirmed marks onto the +// canvas without re-rendering the whole component per stroke. +export type WhiteboardCanvasController = { + /** Paint one server-confirmed stroke or segment (board-space coords). */ + applyStroke: (stroke: Stroke) => void; + /** Replace the whole canvas (REST catch-up, resync). */ + loadStrokes: (strokes: Stroke[]) => void; + /** Blank the live canvas (a clear / epoch bump — history is untouched). */ + reset: () => void; +}; + +/** + * The collaborative whiteboard drawing surface. Unlike {@link DrawCanvas} it + * never saves a File: each finished local stroke is emitted through + * `props.onStroke` (board-space, device/zoom independent) for the room to send + * over the socket, and server-confirmed strokes are pushed back in through the + * controller. Strokes are held in a plain array and painted incrementally so a + * busy board stays cheap; a full redraw only runs on pan / zoom / resize. + */ +export function WhiteboardCanvas(props: { + disabled?: boolean; + onStroke: (stroke: Stroke) => void; + controllerRef?: (c: WhiteboardCanvasController) => void; + class?: string; +}) { + const t = useT(); + let canvas: HTMLCanvasElement | undefined; + let wrap: HTMLDivElement | undefined; + let current: Stroke | undefined; + let panStart: { x: number; y: number; px: number; py: number } | undefined; + // Every committed mark (local + remote), in draw order. Plain array, not a + // signal: it can grow into the thousands and only pan/zoom/resize repaints it. + const committed: Stroke[] = []; + + const [color, setColor] = createSignal(COLORS[0]); + const [width, setWidth] = createSignal(WIDTHS[1]); + const [erasing, setErasing] = createSignal(false); + const [hand, setHand] = createSignal(false); + const [override, setOverride] = createSignal(null); + const [pan, setPan] = createSignal({ x: 0, y: 0 }); + const [panning, setPanning] = createSignal(false); + const [zoom, setZoom] = createSignal(1); + const [empty, setEmpty] = createSignal(true); + + const ratio = () => window.devicePixelRatio || 1; + const context = () => canvas?.getContext("2d") ?? null; + + const activeTool = (): "pen" | "erase" | "pan" => { + const o = override(); + if (o) return o; + if (hand()) return "pan"; + if (erasing()) return "erase"; + return "pen"; + }; + + const cursor = () => { + const tool = activeTool(); + if (tool === "pan") return panning() ? "grabbing" : "grab"; + return "crosshair"; + }; + + const redraw = () => { + const c = context(); + if (!c || !canvas) return; + const scale = ratio(); + c.setTransform(scale, 0, 0, scale, 0, 0); + c.clearRect(0, 0, canvas.width / scale, canvas.height / scale); + const p = pan(); + const z = zoom(); + c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); + for (const stroke of committed) paintStroke(c, stroke); + if (current) paintStroke(c, current); + }; + + const resize = () => { + if (!canvas) return; + const rect = canvas.getBoundingClientRect(); + if (rect.width === 0 || rect.height === 0) return; + const scale = ratio(); + canvas.width = Math.round(rect.width * scale); + canvas.height = Math.round(rect.height * scale); + redraw(); + }; + + // Paint one just-committed stroke on top of the current transform, without a + // full redraw. The transform matches redraw()'s so it lands in the same place. + const paintOne = (stroke: Stroke) => { + const c = context(); + if (!c || !canvas) return; + const scale = ratio(); + const p = pan(); + const z = zoom(); + c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); + paintStroke(c, stroke); + }; + + const controller: WhiteboardCanvasController = { + applyStroke: (stroke) => { + committed.push(stroke); + setEmpty(false); + paintOne(stroke); + }, + loadStrokes: (strokes) => { + committed.length = 0; + committed.push(...strokes); + setEmpty(committed.length === 0); + redraw(); + }, + reset: () => { + committed.length = 0; + setEmpty(true); + redraw(); + }, + }; + + onMount(() => { + resize(); + props.controllerRef?.(controller); + const observer = new ResizeObserver(() => resize()); + if (wrap) observer.observe(wrap); + onCleanup(() => observer.disconnect()); + }); + + const pointAt = (e: PointerEvent): Point => { + const rect = canvas!.getBoundingClientRect(); + const p = pan(); + const z = zoom(); + return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z }; + }; + + const zoomBy = (factor: number) => { + if (!canvas) return; + const rect = canvas.getBoundingClientRect(); + const cx = rect.width / 2; + const cy = rect.height / 2; + const p = pan(); + const z0 = zoom(); + const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); + if (z1 === z0) return; + const wx = (cx - p.x) / z0; + const wy = (cy - p.y) / z0; + setZoom(z1); + setPan({ x: cx - wx * z1, y: cy - wy * z1 }); + redraw(); + }; + + const resetZoom = () => zoomBy(1 / zoom()); + + const drawTip = (stroke: Stroke) => { + const c = context(); + if (c) paintTip(c, stroke); + }; + + const startStroke = (e: PointerEvent) => { + if (props.disabled && !(e.button === 1 || hand())) return; + e.preventDefault(); + canvas?.setPointerCapture(e.pointerId); + if (e.button === 1 || (hand() && e.button !== 2)) { + if (e.button === 1) setOverride("pan"); + const p = pan(); + panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y }; + setPanning(true); + return; + } + if (props.disabled) return; + const eraseNow = erasing() || e.button === 2; + if (e.button === 2) setOverride("erase"); + current = { + color: color(), + width: eraseNow ? width() * 2.5 : width(), + erase: eraseNow, + points: [pointAt(e)], + }; + drawTip(current); + }; + + const extendStroke = (e: PointerEvent) => { + if (panStart) { + setPan({ x: panStart.px + (e.clientX - panStart.x), y: panStart.py + (e.clientY - panStart.y) }); + redraw(); + return; + } + if (!current) return; + current.points.push(pointAt(e)); + drawTip(current); + }; + + const endStroke = () => { + setOverride(null); + if (panStart) { + panStart = undefined; + setPanning(false); + return; + } + const done = current; + current = undefined; + if (!done || done.points.length === 0) return; + committed.push(done); + setEmpty(false); + redraw(); // swap the live polyline for its smoothed replay + props.onStroke(done); + }; + + const toolClass = (active: boolean) => + cn( + "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors", + active + ? "border-primary bg-primary text-primary-foreground shadow-xs" + : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground", + ); + + const paperStyle = () => { + const cell = PAPER_CELL * zoom(); + const p = pan(); + return { + "background-image": `linear-gradient(to right, ${PAPER_LINE} 1px, transparent 1px), linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`, + "background-size": `${cell}px ${cell}px`, + "background-position": `${p.x}px ${p.y}px`, + }; + }; + + return ( +
+
+ { + if (e.button === 1) e.preventDefault(); + }} + onContextMenu={(e) => e.preventDefault()} + onPointerDown={startStroke} + onPointerMove={extendStroke} + onPointerUp={endStroke} + onPointerCancel={endStroke} + onWheel={(e) => { + e.preventDefault(); + zoomBy(e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP); + }} + /> + +

+ {t("whiteboard.canvasHint")} +

+
+ + {/* Top-left island — tools */} +
+ + + +
+ + {/* Top-middle island — colours */} +
+ + {(swatch) => ( + + )} + +
+ + {/* Top-right island — width */} +
+ + {(size) => ( + + )} + +
+ + {/* Bottom-right zoom */} +
+ + + +
+
+
+ ); +} diff --git a/src/components/whiteboard/whiteboard-room-ws.tsx b/src/components/whiteboard/whiteboard-room-ws.tsx new file mode 100644 index 0000000..8d6992e --- /dev/null +++ b/src/components/whiteboard/whiteboard-room-ws.tsx @@ -0,0 +1,295 @@ +import { Show, createSignal, onCleanup, onMount } from "solid-js"; +import { getBoardStrokes, type Board } from "@/api/boards"; +import { formatApiErrorMessage } from "@/api/client"; +import { IconAlert } from "@/components/ui/icons"; +import { encodeStrokeSegments, decodeSegment, segmentToStroke } from "@/lib/board-stroke-codec"; +import type { Stroke } from "@/lib/draw-stroke"; +import { usePreferences, useT } from "@/stores/preferences-context"; +import { WhiteboardCanvas, type WhiteboardCanvasController } from "./whiteboard-canvas"; + +type WsState = "connecting" | "connected" | "disconnected"; + +// Live state the room lifts back to the page so its creator controls and roster +// reflect what the socket saw (a fanned-out lock/close/roster change). +export type BoardLiveState = { + locked?: boolean; + closed?: boolean; + creator?: string; + participants?: string[]; + epoch?: number; +}; + +type WsIn = + | { type: "state"; board: string; epoch: number; locked: boolean; closed_at: number | null; creator: string; participants: string[]; now: number } + | { type: "strokes"; epoch: number; strokes: { id: string; author: string; payload: string }[] } + | { type: "synced"; epoch: number; cursor: string | null } + | { type: "stroke"; id: string; author: string; payload: string; epoch: number } + | { type: "saved"; id: string; client_seq?: number } + | { type: "pong" } + | { type: "cleared"; epoch: number; by: string | null } + | { type: "locked"; locked: boolean; by: string } + | { type: "closed"; closed_at: number | null } + | { type: "participants"; creator: string; participants: string[] } + | { type: "deleted" } + | { type: "error"; code: string; message: string; client_seq?: number }; + +const MAX_RECONNECT = 6; + +export function WhiteboardRoom(props: { + board: Board; + meId: string; + onState?: (patch: BoardLiveState) => void; + onDeleted?: () => void; +}) { + const t = useT(); + const { locale } = usePreferences(); + + const [wsState, setWsState] = createSignal("disconnected"); + const [locked, setLocked] = createSignal(props.board.locked); + const [closed, setClosed] = createSignal(props.board.closed_at != null); + const [creator, setCreator] = createSignal(props.board.creator); + const [participants, setParticipants] = createSignal(props.board.participants); + const [notice, setNotice] = createSignal(""); + + let controller: WhiteboardCanvasController | null = null; + let ws: WebSocket | null = null; + let epoch: number = props.board.epoch; + let cursor: string | null = null; + let clientSeq = 0; + // Backend stroke row ids already painted, so a resync/replay never double-draws. + const seen = new Set(); + + let reconnectTimer: ReturnType | null = null; + let reconnectAttempts = 0; + let closedByUs = false; + + const isParticipant = () => props.meId === creator() || participants().includes(props.meId); + const canDraw = () => wsState() === "connected" && !locked() && !closed() && isParticipant(); + + const wsUrl = () => { + const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; + return `${proto}//${window.location.host}/api/boards/${encodeURIComponent(props.board.id)}/ws`; + }; + + const clearReconnect = () => { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + }; + + const scheduleReconnect = () => { + if (closedByUs || reconnectTimer) return; + if (closed()) return; // a closed board is read-only; the socket will only replay + if (reconnectAttempts >= MAX_RECONNECT) return; + const delay = Math.min(1000 * 2 ** reconnectAttempts, 15000); + reconnectAttempts += 1; + reconnectTimer = setTimeout(() => { + reconnectTimer = null; + connectWs(); + }, delay); + }; + + const applyRow = (row: { id: string; payload: string | null }) => { + if (seen.has(row.id)) return; + seen.add(row.id); + const seg = decodeSegment(row.payload); + if (seg) controller?.applyStroke(segmentToStroke(seg)); + }; + + const wipe = () => { + seen.clear(); + controller?.reset(); + }; + + // Reconcile the whole live canvas from REST — used when the server rejects a + // draw (locked/full/closed): the database is the authority, so we throw the + // optimistic local canvas away and take what is actually stored. + const resyncFromRest = async () => { + try { + const page = await getBoardStrokes(props.board.id, { limit: 500 }); + wipe(); + for (const row of page.items) applyRow({ id: row.id, payload: row.payload }); + } catch { + // socket replay will catch us up on the next reconnect + } + }; + + const connectWs = () => { + clearReconnect(); + if (ws) { + ws.onclose = null; + ws.onerror = null; + ws.onmessage = null; + ws.close(); + } + setWsState("connecting"); + const socket = new WebSocket(wsUrl()); + ws = socket; + + socket.onopen = () => { + reconnectAttempts = 0; + setWsState("connected"); + // Resume from our cursor; the server replays only what is newer (or the + // whole current epoch, preceded by a `cleared`, on a stale/absent cursor). + sendWs({ type: "join", after: cursor ?? undefined, epoch }); + }; + const dropped = () => { + setWsState("disconnected"); + ws = null; + scheduleReconnect(); + }; + socket.onclose = dropped; + socket.onerror = dropped; + socket.onmessage = (event) => { + try { + handle(JSON.parse(event.data) as WsIn); + } catch { + // ignore malformed frame + } + }; + }; + + const sendWs = (data: unknown) => { + if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(data)); + }; + + const pushState = (patch: BoardLiveState) => props.onState?.(patch); + + const handle = (msg: WsIn) => { + switch (msg.type) { + case "state": { + epoch = msg.epoch; + setLocked(msg.locked); + setClosed(msg.closed_at != null); + setCreator(msg.creator); + setParticipants(msg.participants); + pushState({ locked: msg.locked, closed: msg.closed_at != null, creator: msg.creator, participants: msg.participants, epoch: msg.epoch }); + break; + } + case "strokes": { + for (const row of msg.strokes) applyRow(row); + break; + } + case "synced": { + epoch = msg.epoch; + cursor = msg.cursor; + break; + } + case "stroke": { + applyRow(msg); + break; + } + case "saved": { + break; // our own mark persisted; already painted optimistically + } + case "cleared": { + epoch = msg.epoch; + wipe(); + pushState({ epoch: msg.epoch }); + break; + } + case "locked": { + setLocked(msg.locked); + pushState({ locked: msg.locked }); + break; + } + case "closed": { + setClosed(true); + pushState({ closed: true }); + break; + } + case "participants": { + setCreator(msg.creator); + setParticipants(msg.participants); + pushState({ creator: msg.creator, participants: msg.participants }); + break; + } + case "deleted": { + closedByUs = true; + props.onDeleted?.(); + break; + } + case "pong": { + break; + } + case "error": { + const message = formatApiErrorMessage(msg.message, locale()); + setNotice(message); + // A rejected draw (locked, full epoch, closed) or a room resync means the + // optimistic local canvas is out of step — take the truth from the DB. + if (["epoch_full", "board_closed", "locked", "resync", "conflict", "forbidden"].includes(msg.code)) { + void resyncFromRest(); + } + break; + } + } + }; + + const onLocalStroke = (stroke: Stroke) => { + if (!canDraw()) return; + const sid = `${props.meId}-${Date.now()}-${(clientSeq += 1)}`; + for (const payload of encodeStrokeSegments(stroke, sid)) { + sendWs({ type: "stroke", payload, client_seq: (clientSeq += 1) }); + } + }; + + onMount(() => { + connectWs(); + }); + + onCleanup(() => { + closedByUs = true; + clearReconnect(); + if (ws) ws.close(); + }); + + const wsLabel = () => { + if (wsState() === "connecting") return t("ws.connecting"); + if (wsState() === "connected") return t("ws.connected"); + return t("ws.disconnected"); + }; + + return ( +
+
+ + + {wsLabel()} + + + + {t("whiteboard.closedBadge")} + + + + + {t("whiteboard.lockedBadge")} + + + + + {t("whiteboard.readOnlyBadge")} + + +
+ + + {(msg) => ( +
+ +

{msg()}

+
+ )} +
+ + { + controller = c; + }} + /> +
+ ); +} diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index fec0b9e..5bfb385 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -953,6 +953,41 @@ export type MessageKey = | "meals.priceTry" | "nav.payments" | "nav.paymentStatement" + | "nav.whiteboards" + | "whiteboard.title" + | "whiteboard.subtitle" + | "whiteboard.empty" + | "whiteboard.create" + | "whiteboard.titleLabel" + | "whiteboard.participants" + | "whiteboard.participantsHint" + | "whiteboard.open" + | "whiteboard.createdAt" + | "whiteboard.limitReached" + | "whiteboard.canvasHint" + | "whiteboard.closedBadge" + | "whiteboard.lockedBadge" + | "whiteboard.readOnlyBadge" + | "whiteboard.lock" + | "whiteboard.unlock" + | "whiteboard.clear" + | "whiteboard.clearConfirm" + | "whiteboard.close" + | "whiteboard.closeConfirm" + | "whiteboard.delete" + | "whiteboard.deleteConfirm" + | "whiteboard.creator" + | "whiteboard.roster" + | "whiteboard.addParticipant" + | "whiteboard.removeParticipant" + | "whiteboard.history" + | "whiteboard.noHistory" + | "whiteboard.replaySession" + | "whiteboard.play" + | "whiteboard.pause" + | "whiteboard.restart" + | "whiteboard.notFound" + | "whiteboard.back" | "payments.title" | "payments.subtitle" | "payments.empty" @@ -2222,6 +2257,41 @@ const en: Dict = { "meals.priceTry": "Price (TRY)", "nav.payments": "Fees", "nav.paymentStatement": "My Fees", + "nav.whiteboards": "Whiteboards", + "whiteboard.title": "Whiteboards", + "whiteboard.subtitle": "Live collaborative sketch boards.", + "whiteboard.empty": "No whiteboards yet.", + "whiteboard.create": "New whiteboard", + "whiteboard.titleLabel": "Title", + "whiteboard.participants": "Participants", + "whiteboard.participantsHint": "Invite students and staff who may draw.", + "whiteboard.open": "Open", + "whiteboard.createdAt": "Created", + "whiteboard.limitReached": "You have reached your whiteboard limit.", + "whiteboard.canvasHint": "Draw here — everyone on the board sees it live.", + "whiteboard.closedBadge": "Closed", + "whiteboard.lockedBadge": "Locked", + "whiteboard.readOnlyBadge": "Read-only", + "whiteboard.lock": "Lock", + "whiteboard.unlock": "Unlock", + "whiteboard.clear": "Clear", + "whiteboard.clearConfirm": "Clear the live canvas? The history is kept and stays replayable.", + "whiteboard.close": "Close board", + "whiteboard.closeConfirm": "Close this board? It becomes permanently read-only.", + "whiteboard.delete": "Delete board", + "whiteboard.deleteConfirm": "Delete this board and its whole history? This cannot be undone.", + "whiteboard.creator": "Creator", + "whiteboard.roster": "Participants", + "whiteboard.addParticipant": "Add participant", + "whiteboard.removeParticipant": "Remove", + "whiteboard.history": "History", + "whiteboard.noHistory": "No past sessions yet.", + "whiteboard.replaySession": "Replay session", + "whiteboard.play": "Play", + "whiteboard.pause": "Pause", + "whiteboard.restart": "Restart", + "whiteboard.notFound": "This whiteboard does not exist or you are not on it.", + "whiteboard.back": "Back to whiteboards", "payments.title": "School fees", "payments.subtitle": "Fee plans, assignments, and the payment ledger.", "payments.empty": "No fee plans yet.", @@ -3417,6 +3487,41 @@ const tr: Dict = { "meals.priceTry": "Fiyat (TRY)", "nav.payments": "Ücretler", "nav.paymentStatement": "Ücretlerim", + "nav.whiteboards": "Beyaz Tahtalar", + "whiteboard.title": "Beyaz Tahtalar", + "whiteboard.subtitle": "Canlı ortak çizim tahtaları.", + "whiteboard.empty": "Henüz beyaz tahta yok.", + "whiteboard.create": "Yeni tahta", + "whiteboard.titleLabel": "Başlık", + "whiteboard.participants": "Katılımcılar", + "whiteboard.participantsHint": "Çizebilecek öğrenci ve personeli davet edin.", + "whiteboard.open": "Aç", + "whiteboard.createdAt": "Oluşturuldu", + "whiteboard.limitReached": "Beyaz tahta sınırına ulaştınız.", + "whiteboard.canvasHint": "Buraya çizin — tahtadaki herkes anlık görür.", + "whiteboard.closedBadge": "Kapalı", + "whiteboard.lockedBadge": "Kilitli", + "whiteboard.readOnlyBadge": "Salt okunur", + "whiteboard.lock": "Kilitle", + "whiteboard.unlock": "Kilidi aç", + "whiteboard.clear": "Temizle", + "whiteboard.clearConfirm": "Canlı tuval temizlensin mi? Geçmiş korunur ve tekrar oynatılabilir.", + "whiteboard.close": "Tahtayı kapat", + "whiteboard.closeConfirm": "Bu tahta kapatılsın mı? Kalıcı olarak salt okunur olur.", + "whiteboard.delete": "Tahtayı sil", + "whiteboard.deleteConfirm": "Bu tahta ve tüm geçmişi silinsin mi? Geri alınamaz.", + "whiteboard.creator": "Oluşturan", + "whiteboard.roster": "Katılımcılar", + "whiteboard.addParticipant": "Katılımcı ekle", + "whiteboard.removeParticipant": "Çıkar", + "whiteboard.history": "Geçmiş", + "whiteboard.noHistory": "Henüz geçmiş oturum yok.", + "whiteboard.replaySession": "Oturumu oynat", + "whiteboard.play": "Oynat", + "whiteboard.pause": "Duraklat", + "whiteboard.restart": "Baştan", + "whiteboard.notFound": "Bu beyaz tahta yok ya da üzerinde değilsiniz.", + "whiteboard.back": "Beyaz tahtalara dön", "payments.title": "Okul ücretleri", "payments.subtitle": "Ücret planları, atamalar ve ödeme hareketleri.", "payments.empty": "Henüz ücret planı yok.", diff --git a/src/lib/board-stroke-codec.test.ts b/src/lib/board-stroke-codec.test.ts new file mode 100644 index 0000000..eb751f0 --- /dev/null +++ b/src/lib/board-stroke-codec.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from "vitest"; +import { + decodeSegment, + encodeStrokeSegments, + reassembleStrokes, + segmentToStroke, +} from "./board-stroke-codec"; +import type { Stroke } from "./draw-stroke"; + +function makeStroke(pointCount: number): Stroke { + const points = Array.from({ length: pointCount }, (_, i) => ({ x: i * 1.234, y: i * 5.678 })); + return { color: "#ff0000", width: 3, erase: false, points }; +} + +describe("board-stroke-codec", () => { + it("encodes a short stroke into a single segment", () => { + const payloads = encodeStrokeSegments(makeStroke(5), "s1"); + expect(payloads).toHaveLength(1); + const seg = decodeSegment(payloads[0]); + expect(seg).not.toBeNull(); + expect(seg?.sid).toBe("s1"); + expect(seg?.seg).toBe(0); + expect(seg?.last).toBe(true); + expect(seg?.pts).toHaveLength(5); + }); + + it("returns no segments for an empty stroke", () => { + expect(encodeStrokeSegments(makeStroke(0), "s1")).toEqual([]); + }); + + it("splits a long stroke into multiple capped segments", () => { + const payloads = encodeStrokeSegments(makeStroke(2000), "s2", 512); + expect(payloads.length).toBeGreaterThan(1); + for (const p of payloads) { + expect(new TextEncoder().encode(p).length).toBeLessThanOrEqual(512); + } + // exactly one final segment + const lasts = payloads.map((p) => decodeSegment(p)!.last).filter(Boolean); + expect(lasts).toHaveLength(1); + expect(decodeSegment(payloads[payloads.length - 1])!.last).toBe(true); + }); + + it("reassembles segments back into the original stroke (no duplicate overlap points)", () => { + const original = makeStroke(2000); + const payloads = encodeStrokeSegments(original, "s3", 512); + const [rebuilt] = reassembleStrokes(payloads); + expect(rebuilt.points).toHaveLength(original.points.length); + expect(rebuilt.color).toBe(original.color); + expect(rebuilt.width).toBe(original.width); + // rounded to 2dp, so compare with tolerance + expect(rebuilt.points[0].x).toBeCloseTo(original.points[0].x, 2); + expect(rebuilt.points[1999].y).toBeCloseTo(original.points[1999].y, 2); + }); + + it("keeps distinct sids as distinct strokes, in order", () => { + const a = encodeStrokeSegments({ ...makeStroke(3), color: "#111111" }, "a"); + const b = encodeStrokeSegments({ ...makeStroke(3), color: "#222222" }, "b"); + const strokes = reassembleStrokes([...a, ...b]); + expect(strokes).toHaveLength(2); + expect(strokes[0].color).toBe("#111111"); + expect(strokes[1].color).toBe("#222222"); + }); + + it("segmentToStroke paints a single segment's own points", () => { + const [payload] = encodeStrokeSegments(makeStroke(4), "s4"); + const stroke = segmentToStroke(decodeSegment(payload)!); + expect(stroke.points).toHaveLength(4); + expect(stroke.erase).toBe(false); + }); + + it("decodeSegment rejects malformed payloads", () => { + expect(decodeSegment(null)).toBeNull(); + expect(decodeSegment("not json")).toBeNull(); + expect(decodeSegment(JSON.stringify({ v: 2, sid: "x" }))).toBeNull(); + expect(decodeSegment(JSON.stringify({ v: 1, sid: "x", seg: 0, last: true, color: "#000000", width: 1, erase: false, pts: [[1]] }))).toBeNull(); + }); + + it("skips non-stroke rows during reassembly", () => { + const good = encodeStrokeSegments(makeStroke(2), "g"); + const strokes = reassembleStrokes([null, "garbage", ...good]); + expect(strokes).toHaveLength(1); + }); +}); diff --git a/src/lib/board-stroke-codec.ts b/src/lib/board-stroke-codec.ts new file mode 100644 index 0000000..a0fc6cf --- /dev/null +++ b/src/lib/board-stroke-codec.ts @@ -0,0 +1,172 @@ +import type { Point, Stroke } from "./draw-stroke"; + +// The whiteboard backend caps each stroke `payload` at 4096 bytes +// (board.max_stroke_payload_len, published at GET /limits). A long freehand +// stroke is split into several segment frames that share one `sid`; the +// receiver paints each segment as it arrives (consecutive segments overlap by +// one point so the line stays continuous) and can reassemble the full stroke +// for history replay. +export const MAX_STROKE_PAYLOAD_BYTES = 4096; + +// A little headroom under the hard cap so we never sit exactly on the byte +// boundary the server rejects. +const DEFAULT_MAX_BYTES = MAX_STROKE_PAYLOAD_BYTES - 64; + +// Wire envelope for one segment of a logical stroke. Coordinates are +// board-space (device/zoom independent); points travel as [x, y] tuples to +// keep the payload small. +export type StrokeSegment = { + v: 1; + sid: string; + seg: number; + last: boolean; + color: string; + width: number; + erase: boolean; + pts: [number, number][]; +}; + +const encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null; + +function byteLength(text: string): number { + return encoder ? encoder.encode(text).length : text.length; +} + +// Board-space may be fractional; two decimals is plenty of fidelity and keeps +// the payload compact. +function round2(n: number): number { + return Math.round(n * 100) / 100; +} + +function segmentString( + sid: string, + seg: number, + last: boolean, + stroke: Pick, + pts: [number, number][], +): string { + const envelope: StrokeSegment = { + v: 1, + sid, + seg, + last, + color: stroke.color, + width: stroke.width, + erase: stroke.erase, + pts, + }; + return JSON.stringify(envelope); +} + +/** + * Serialize one logical stroke into one or more segment payloads, each under + * `maxBytes`. Consecutive segments repeat the previous segment's last point as + * their first, so painting them in order leaves no gap. A single point whose + * envelope already exceeds the cap is still emitted (a point can't be split). + */ +export function encodeStrokeSegments( + stroke: Stroke, + sid: string, + maxBytes: number = DEFAULT_MAX_BYTES, +): string[] { + const tuples: [number, number][] = stroke.points.map((p) => [round2(p.x), round2(p.y)]); + if (tuples.length === 0) return []; + + const segments: [number, number][][] = []; + let current: [number, number][] = []; + + for (const pt of tuples) { + const candidate = [...current, pt]; + // Not the last segment yet (last flag unknown here), so measure with + // last:false — the final re-encode below stamps the real flags. + const fits = byteLength(segmentString(sid, segments.length, false, stroke, candidate)) <= maxBytes; + if (fits || current.length === 0) { + current = candidate; + } else { + segments.push(current); + // Overlap one point for continuity across the segment boundary. + current = [current[current.length - 1], pt]; + } + } + if (current.length > 0) segments.push(current); + + return segments.map((pts, i) => + segmentString(sid, i, i === segments.length - 1, stroke, pts), + ); +} + +function isTuple(v: unknown): v is [number, number] { + return ( + Array.isArray(v) && + v.length === 2 && + typeof v[0] === "number" && + typeof v[1] === "number" && + Number.isFinite(v[0]) && + Number.isFinite(v[1]) + ); +} + +/** Parse one segment payload, or null on anything malformed (payloads are untrusted). */ +export function decodeSegment(payload: string | null): StrokeSegment | null { + if (!payload) return null; + let data: unknown; + try { + data = JSON.parse(payload); + } catch { + return null; + } + if (!data || typeof data !== "object") return null; + const s = data as StrokeSegment; + if ( + s.v !== 1 || + typeof s.sid !== "string" || + typeof s.seg !== "number" || + typeof s.last !== "boolean" || + typeof s.color !== "string" || + typeof s.width !== "number" || + typeof s.erase !== "boolean" || + !Array.isArray(s.pts) || + !s.pts.every(isTuple) + ) { + return null; + } + return s; +} + +/** One decoded segment as a paintable Stroke (its own points only). */ +export function segmentToStroke(seg: StrokeSegment): Stroke { + return { + color: seg.color, + width: seg.width, + erase: seg.erase, + points: seg.pts.map(([x, y]) => ({ x, y }) as Point), + }; +} + +/** + * Reassemble full strokes from an ordered list of stroke payloads (e.g. a + * history/epoch page). Segments are grouped by `sid` in arrival order; the + * overlap point each later segment repeats is dropped so the joined stroke has + * no duplicate vertex. Non-stroke rows (null payloads, clear markers) are + * skipped by the caller passing only stroke payloads. + */ +export function reassembleStrokes(payloads: (string | null)[]): Stroke[] { + const order: string[] = []; + const bySid = new Map(); + + for (const payload of payloads) { + const seg = decodeSegment(payload); + if (!seg) continue; + const pts = seg.pts.map(([x, y]) => ({ x, y }) as Point); + const existing = bySid.get(seg.sid); + if (!existing) { + order.push(seg.sid); + bySid.set(seg.sid, { color: seg.color, width: seg.width, erase: seg.erase, points: pts }); + } else { + // Drop the leading overlap point that duplicates the previous last point. + existing.points.push(...(seg.seg > 0 ? pts.slice(1) : pts)); + } + } + + return order.map((sid) => bySid.get(sid)!); +} diff --git a/src/pages/whiteboard-page.tsx b/src/pages/whiteboard-page.tsx new file mode 100644 index 0000000..a602a07 --- /dev/null +++ b/src/pages/whiteboard-page.tsx @@ -0,0 +1,308 @@ +import { useLocation, useNavigate } from "@tanstack/solid-router"; +import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js"; +import { + deleteBoardById, + getBoardEpochs, + getBoardHistory, + getBoardById, + patchBoardById, + postBoardClear, + postBoardClose, +} from "@/api/boards"; +import { getUsers } from "@/api/users"; +import { formatApiError } from "@/api/client"; +import { WhiteboardRoom, type BoardLiveState } from "@/components/whiteboard/whiteboard-room-ws"; +import { RouteGuard } from "@/components/layout/route-guard"; +import { PageHeader } from "@/components/layout/page-header"; +import { Alert } from "@/components/ui/alert"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { DrawingPlayback } from "@/components/ui/drawing-playback"; +import { IconChevronLeft, IconTrash } from "@/components/ui/icons"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { SidePanel } from "@/components/ui/side-panel"; +import { reassembleStrokes } from "@/lib/board-stroke-codec"; +import { strokesBounds, type DrawScene } from "@/lib/draw-stroke"; +import { formatDateTime } from "@/lib/format"; +import { useAuth } from "@/stores/auth-context"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +export default function WhiteboardPage() { + return ( + + + + ); +} + +const EXPORT_MARGIN = 8; + +// Build a replayable scene from a set of reassembled strokes (an epoch's marks), +// shifted into a tight box like the drawing export pipeline. +function strokesToScene(strokes: DrawScene["strokes"]): DrawScene | null { + const b = strokesBounds(strokes); + if (!b) return null; + const w = Math.ceil(b.w + EXPORT_MARGIN * 2); + const h = Math.ceil(b.h + EXPORT_MARGIN * 2); + const dx = EXPORT_MARGIN - b.x; + const dy = EXPORT_MARGIN - b.y; + const shifted = strokes.map((s) => ({ ...s, points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })) })); + return { v: 1, w, h, strokes: shifted, bg: "grid" }; +} + +function WhiteboardContent() { + const t = useT(); + const { locale } = usePreferences(); + const auth = useAuth(); + const navigate = useNavigate(); + const location = useLocation(); + + const id = createMemo((prev: string) => { + const match = /^\/whiteboards\/([^/]+)$/.exec(location().pathname); + return match ? decodeURIComponent(match[1]) : prev; + }, ""); + + const [board] = createResource(id, (boardId) => getBoardById(boardId)); + const [users] = createResource(async () => { + try { + return (await getUsers({ limit: 500 })).items; + } catch { + return []; + } + }); + + // Live board state, seeded from the REST read and updated by the room's socket. + const [live, setLive] = createSignal({}); + createEffect(() => { + const b = board(); + if (b) { + setLive({ + locked: b.locked, + closed: b.closed_at != null, + creator: b.creator, + participants: b.participants, + epoch: b.epoch, + }); + } + }); + const mergeLive = (patch: BoardLiveState) => setLive((prev) => ({ ...prev, ...patch })); + + const meId = () => auth.user()?.id ?? ""; + const isCreator = () => live().creator === meId(); + const locked = () => live().locked ?? false; + const closed = () => live().closed ?? false; + + const nameOf = (userId: string) => { + const u = (users() ?? []).find((x) => x.id === userId); + if (!u) return userId; + return [u.name, u.surname].filter(Boolean).join(" ") || u.username; + }; + const roster = () => { + const creator = live().creator; + const parts = live().participants ?? []; + return creator ? [creator, ...parts] : parts; + }; + + const [error, setError] = createSignal(""); + const [busy, setBusy] = createSignal(false); + const [clearOpen, setClearOpen] = createSignal(false); + const [closeOpen, setCloseOpen] = createSignal(false); + const [deleteOpen, setDeleteOpen] = createSignal(false); + const [historyOpen, setHistoryOpen] = createSignal(false); + + const run = async (fn: () => Promise) => { + setBusy(true); + setError(""); + try { + await fn(); + } catch (err) { + setError(formatApiError(err, locale())); + } finally { + setBusy(false); + } + }; + + const toggleLock = () => + run(async () => { + const next = !locked(); + await patchBoardById(id(), { locked: next }); + mergeLive({ locked: next }); + }); + const doClear = () => run(async () => void (await postBoardClear(id()))); + const doClose = () => + run(async () => { + await postBoardClose(id()); + mergeLive({ closed: true }); + }); + const doDelete = () => + run(async () => { + await deleteBoardById(id()); + navigate({ to: "/whiteboards" }); + }); + + return ( + }> + }> + {t("whiteboard.notFound")} + + } + > + {(b) => ( +
+ + + + + + + + + + + +
+ } + /> + + + {error()} + + +
+ navigate({ to: "/whiteboards" })} + /> + +
+ + + + + + + + )} + +
+ ); +} + +function HistoryPanel(props: { open: boolean; onOpenChange: (open: boolean) => void; boardId: string }) { + const t = useT(); + const { locale } = usePreferences(); + const [selectedEpoch, setSelectedEpoch] = createSignal(null); + + // Only fetch the epoch index while the panel is open. + const [epochs] = createResource( + () => (props.open ? props.boardId : null), + async (boardId) => (await getBoardEpochs(boardId, { limit: 100 })).items, + ); + + const [scene] = createResource( + () => (selectedEpoch() != null ? { boardId: props.boardId, epoch: selectedEpoch()! } : null), + async (arg) => { + const page = await getBoardHistory(arg.boardId, { epoch: arg.epoch, limit: 500 }); + const strokes = reassembleStrokes(page.items.filter((r) => r.kind === "stroke").map((r) => r.payload)); + return strokesToScene(strokes); + }, + ); + + return ( + +
+ }> + 0} + fallback={

{t("whiteboard.noHistory")}

} + > +
+ + {(marker) => ( + + )} + +
+
+
+ + + }> + {t("whiteboard.noHistory")}

}> + {(s) => } +
+
+
+
+
+ ); +} diff --git a/src/pages/whiteboards-page.tsx b/src/pages/whiteboards-page.tsx new file mode 100644 index 0000000..ca5218a --- /dev/null +++ b/src/pages/whiteboards-page.tsx @@ -0,0 +1,234 @@ +import { useNavigate } from "@tanstack/solid-router"; +import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js"; +import { getBoards, postBoard, type Board } from "@/api/boards"; +import { getUsers } from "@/api/users"; +import { formatApiError, type User } from "@/api/client"; +import { RouteGuard } from "@/components/layout/route-guard"; +import { PageHeader } from "@/components/layout/page-header"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { EmptyState } from "@/components/ui/empty-state"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconPlus, IconX } from "@/components/ui/icons"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { SidePanel } from "@/components/ui/side-panel"; +import { formatDate } from "@/lib/format"; +import { useAuth } from "@/stores/auth-context"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +export default function WhiteboardsPage() { + return ( + + + + ); +} + +function WhiteboardsContent() { + const t = useT(); + const { locale } = usePreferences(); + const auth = useAuth(); + const navigate = useNavigate(); + + const [boards, { refetch }] = createResource(async () => (await getBoards({ limit: 200 })).items); + const [createOpen, setCreateOpen] = createSignal(false); + + const meId = () => auth.user()?.id ?? ""; + + return ( +
+ setCreateOpen(true)}> + + {t("whiteboard.create")} + + } + /> + + }> + + + + 0} + fallback={} + > +
+ + {(board) => ( + navigate({ to: "/whiteboards/$id", params: { id: board.id } })} + createdLabel={formatDate(board.created_at, locale())} + /> + )} + +
+
+
+ + { + setCreateOpen(false); + void refetch(); + navigate({ to: "/whiteboards/$id", params: { id: board.id } }); + }} + /> +
+ ); +} + +function BoardCard(props: { board: Board; isCreator: boolean; onOpen: () => void; createdLabel: string }) { + const t = useT(); + return ( +
+
+

{props.board.title}

+
+ + {t("whiteboard.closedBadge")} + + + {t("whiteboard.lockedBadge")} + + + {t("whiteboard.creator")} + +
+
+

+ {t("whiteboard.createdAt")}: {props.createdLabel} · {props.board.participants.length + 1} {t("whiteboard.participants").toLowerCase()} +

+ +
+ ); +} + +function CreateBoardPanel(props: { + open: boolean; + onOpenChange: (open: boolean) => void; + onCreated: (board: Board) => void; +}) { + const t = useT(); + const { locale } = usePreferences(); + const [title, setTitle] = createSignal(""); + const [query, setQuery] = createSignal(""); + const [selected, setSelected] = createSignal([]); + const [pending, setPending] = createSignal(false); + const [error, setError] = createSignal(""); + + // Parents can never be on a roster (backend 400s them), so they are filtered out. + const [candidates] = createResource(async () => + (await getUsers({ limit: 500 })).items.filter((u) => u.role !== "parent"), + ); + + const selectedIds = createMemo(() => new Set(selected().map((u) => u.id))); + const filtered = createMemo(() => { + const q = query().trim().toLowerCase(); + const me = undefined; + return (candidates() ?? []) + .filter((u) => u !== me && !selectedIds().has(u.id)) + .filter((u) => !q || u.username.toLowerCase().includes(q) || (u.name ?? "").toLowerCase().includes(q)) + .slice(0, 8); + }); + + const label = (u: User) => [u.name, u.surname].filter(Boolean).join(" ") || u.username; + + const submit = async () => { + if (!title().trim()) return; + setPending(true); + setError(""); + try { + const board = await postBoard({ + title: title().trim(), + participants: selected().map((u) => u.id), + }); + setTitle(""); + setSelected([]); + setQuery(""); + props.onCreated(board); + } catch (err) { + setError(formatApiError(err, locale())); + } finally { + setPending(false); + } + }; + + return ( + +
+ + + +
+ + setTitle(e.currentTarget.value)} /> +
+ +
+ +

{t("whiteboard.participantsHint")}

+ 0}> +
+ + {(u) => ( + + )} + +
+
+ setQuery(e.currentTarget.value)} + /> + 0}> +
+ + {(u) => ( + + )} + +
+
+
+ +
+ + +
+
+
+ ); +} diff --git a/src/routes/router.tsx b/src/routes/router.tsx index 5e71e80..bb593cf 100644 --- a/src/routes/router.tsx +++ b/src/routes/router.tsx @@ -61,6 +61,8 @@ const MealsPage = lazyRoute(() => import("@/pages/meals-page")); const MealDetailPage = lazyRoute(() => import("@/pages/meal-detail-page")); const PaymentsPage = lazyRoute(() => import("@/pages/payments-page")); const PaymentStatementPage = lazyRoute(() => import("@/pages/payment-statement-page")); +const WhiteboardsPage = lazyRoute(() => import("@/pages/whiteboards-page")); +const WhiteboardPage = lazyRoute(() => import("@/pages/whiteboard-page")); function RootComponent() { return ( @@ -357,6 +359,18 @@ const paymentStatementRoute = createRoute({ component: PaymentStatementPage, }); +const whiteboardsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/whiteboards", + component: WhiteboardsPage, +}); + +const whiteboardRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/whiteboards/$id", + component: WhiteboardPage, +}); + const routeTree = rootRoute.addChildren([ indexRoute, loginRoute, @@ -401,6 +415,8 @@ const routeTree = rootRoute.addChildren([ paymentsRoute, managedPaymentDetailRoute, paymentStatementRoute, + whiteboardsRoute, + whiteboardRoute, ]); function RouterPending() { diff --git a/src/stores/preferences-context.tsx b/src/stores/preferences-context.tsx index 7457244..493aca7 100644 --- a/src/stores/preferences-context.tsx +++ b/src/stores/preferences-context.tsx @@ -20,7 +20,7 @@ type PreferencesContextValue = { paletteColor: Accessor; setPaletteColor: (color: string | null) => void; toggleTheme: () => void; - hydratePreferences: (user: Pick) => void; + hydratePreferences: (user: Pick) => void; sidebarCollapsed: Accessor; setSidebarCollapsed: (collapsed: boolean) => void; toggleSidebar: () => void; @@ -182,15 +182,22 @@ export function PreferencesProvider(props: ParentProps) { persistPreferences({ theme: th }); }; const setPaletteColor = (color: string | null) => { - setPaletteColorSignal(color && HEX_COLOR.test(color) ? color.toLowerCase() : null); + const next = color && HEX_COLOR.test(color) ? color.toLowerCase() : null; + setPaletteColorSignal(next); + // Empty string clears the accent back to "never chose" on the backend; a + // valid hex sets it. Mirrors the theme/language sync. + persistPreferences({ palette_color: next ?? "" }); }; const toggleTheme = () => { const next = theme() === "dark" ? "light" : "dark"; setTheme(next); }; - const hydratePreferences = (user: Pick) => { + const hydratePreferences = (user: Pick) => { if (user.language === "en" || user.language === "tr") setLocaleSignal(user.language); if (user.theme === "light" || user.theme === "dark") setThemeSignal(user.theme); + if (user.palette_color && HEX_COLOR.test(user.palette_color)) { + setPaletteColorSignal(user.palette_color.toLowerCase()); + } }; const setSidebarCollapsed = (v: boolean) => setSidebarCollapsedSignal(v); const toggleSidebar = () => setSidebarCollapsedSignal((v) => !v);