✨ collaborative whiteboard + accent-color backend sync
Browse files at this commit58593cc6febd55be91090c8aaec52e745eae8e21Parent: 1eecf87- feat
- ✨ collaborative whiteboard + accent-color backend sync
26 changed files +1931 -3
- src/api/__tests__/boards/boards.test.ts +124 -0
- src/api/__tests__/users/users.test.ts +24 -0
- src/api/boards/deleteBoardById.ts +6 -0
- src/api/boards/getBoardById.ts +7 -0
- src/api/boards/getBoardEpochs.ts +16 -0
- src/api/boards/getBoardHistory.ts +24 -0
- src/api/boards/getBoardStrokes.ts +16 -0
- src/api/boards/getBoards.ts +8 -0
- src/api/boards/index.ts +11 -0
- src/api/boards/patchBoardById.ts +7 -0
- src/api/boards/postBoard.ts +7 -0
- src/api/boards/postBoardClear.ts +8 -0
- src/api/boards/postBoardClose.ts +8 -0
- src/api/boards/types.ts +49 -0
- src/api/client/types.ts +1 -0
- src/api/users/patchMyPreferences.ts +2 -0
- src/components/layout/nav-items.ts +2 -0
- src/components/whiteboard/whiteboard-canvas.tsx +388 -0
- src/components/whiteboard/whiteboard-room-ws.tsx +295 -0
- src/i18n/messages.ts +105 -0
- src/lib/board-stroke-codec.test.ts +83 -0
- src/lib/board-stroke-codec.ts +172 -0
- src/pages/whiteboard-page.tsx +308 -0
- src/pages/whiteboards-page.tsx +234 -0
- src/routes/router.tsx +16 -0
- src/stores/preferences-context.tsx +10 -3
src/api/__tests__/boards/boards.test.tsadded+124 -0
| @@ -0,0 +1,124 @@ | ||
| 1 | +import { afterEach, describe, expect, it, vi } from "vitest"; | |
| 2 | +import { | |
| 3 | + deleteBoardById, | |
| 4 | + getBoardById, | |
| 5 | + getBoardEpochs, | |
| 6 | + getBoardHistory, | |
| 7 | + getBoardStrokes, | |
| 8 | + getBoards, | |
| 9 | + patchBoardById, | |
| 10 | + postBoard, | |
| 11 | + postBoardClear, | |
| 12 | + postBoardClose, | |
| 13 | +} from "../../boards"; | |
| 14 | +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; | |
| 15 | + | |
| 16 | +describe("boards API", () => { | |
| 17 | + afterEach(() => { | |
| 18 | + vi.restoreAllMocks(); | |
| 19 | + }); | |
| 20 | + | |
| 21 | + it("postBoard calls POST /boards with the body", async () => { | |
| 22 | + mockFetchSuccess({ id: "b1", title: "Math" }); | |
| 23 | + const body = { title: "Math", participants: ["u2", "u3"] }; | |
| 24 | + await postBoard(body); | |
| 25 | + | |
| 26 | + const [url, init] = lastFetchCall(); | |
| 27 | + expect(url).toBe("/api/boards"); | |
| 28 | + expect(init?.method).toBe("POST"); | |
| 29 | + expect(init?.body).toBe(JSON.stringify(body)); | |
| 30 | + }); | |
| 31 | + | |
| 32 | + it("getBoards calls GET /boards with pagination", async () => { | |
| 33 | + const mockPage = { items: [{ id: "b1" }], total: 1 }; | |
| 34 | + mockFetchSuccess(mockPage); | |
| 35 | + const result = await getBoards({ limit: 10, offset: 20 }); | |
| 36 | + expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); | |
| 37 | + | |
| 38 | + const [url, init] = lastFetchCall(); | |
| 39 | + expect(url).toBe("/api/boards?limit=10&offset=20"); | |
| 40 | + expect(init?.method).toBe("GET"); | |
| 41 | + }); | |
| 42 | + | |
| 43 | + it("getBoardById calls GET /boards/:id", async () => { | |
| 44 | + mockFetchSuccess({ id: "b1" }); | |
| 45 | + await getBoardById("b1"); | |
| 46 | + | |
| 47 | + const [url, init] = lastFetchCall(); | |
| 48 | + expect(url).toBe("/api/boards/b1"); | |
| 49 | + expect(init?.method).toBe("GET"); | |
| 50 | + }); | |
| 51 | + | |
| 52 | + it("getBoardStrokes calls GET /boards/:id/strokes", async () => { | |
| 53 | + mockFetchSuccess({ items: [], total: 0 }); | |
| 54 | + await getBoardStrokes("b1", { limit: 200 }); | |
| 55 | + | |
| 56 | + const [url, init] = lastFetchCall(); | |
| 57 | + expect(url).toBe("/api/boards/b1/strokes?limit=200"); | |
| 58 | + expect(init?.method).toBe("GET"); | |
| 59 | + }); | |
| 60 | + | |
| 61 | + it("getBoardHistory calls GET /boards/:id/history with epoch + pagination", async () => { | |
| 62 | + mockFetchSuccess({ items: [], total: 0 }); | |
| 63 | + await getBoardHistory("b1", { epoch: 3, limit: 50 }); | |
| 64 | + | |
| 65 | + const [url, init] = lastFetchCall(); | |
| 66 | + expect(url).toBe("/api/boards/b1/history?epoch=3&limit=50"); | |
| 67 | + expect(init?.method).toBe("GET"); | |
| 68 | + }); | |
| 69 | + | |
| 70 | + it("getBoardHistory omits epoch when not given", async () => { | |
| 71 | + mockFetchSuccess({ items: [], total: 0 }); | |
| 72 | + await getBoardHistory("b1"); | |
| 73 | + | |
| 74 | + const [url] = lastFetchCall(); | |
| 75 | + expect(url).toBe("/api/boards/b1/history"); | |
| 76 | + }); | |
| 77 | + | |
| 78 | + it("getBoardEpochs calls GET /boards/:id/epochs", async () => { | |
| 79 | + mockFetchSuccess({ items: [], total: 0 }); | |
| 80 | + await getBoardEpochs("b1"); | |
| 81 | + | |
| 82 | + const [url, init] = lastFetchCall(); | |
| 83 | + expect(url).toBe("/api/boards/b1/epochs"); | |
| 84 | + expect(init?.method).toBe("GET"); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + it("patchBoardById calls PATCH /boards/:id with the body", async () => { | |
| 88 | + mockFetchSuccess({ id: "b1" }); | |
| 89 | + const body = { locked: true }; | |
| 90 | + await patchBoardById("b1", body); | |
| 91 | + | |
| 92 | + const [url, init] = lastFetchCall(); | |
| 93 | + expect(url).toBe("/api/boards/b1"); | |
| 94 | + expect(init?.method).toBe("PATCH"); | |
| 95 | + expect(init?.body).toBe(JSON.stringify(body)); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + it("postBoardClear calls POST /boards/:id/clear", async () => { | |
| 99 | + mockFetchSuccess({ id: "s1", kind: "clear" }); | |
| 100 | + await postBoardClear("b1"); | |
| 101 | + | |
| 102 | + const [url, init] = lastFetchCall(); | |
| 103 | + expect(url).toBe("/api/boards/b1/clear"); | |
| 104 | + expect(init?.method).toBe("POST"); | |
| 105 | + }); | |
| 106 | + | |
| 107 | + it("postBoardClose calls POST /boards/:id/close", async () => { | |
| 108 | + mockFetchSuccess({ id: "b1", closed_at: 123 }); | |
| 109 | + await postBoardClose("b1"); | |
| 110 | + | |
| 111 | + const [url, init] = lastFetchCall(); | |
| 112 | + expect(url).toBe("/api/boards/b1/close"); | |
| 113 | + expect(init?.method).toBe("POST"); | |
| 114 | + }); | |
| 115 | + | |
| 116 | + it("deleteBoardById calls DELETE /boards/:id", async () => { | |
| 117 | + mockFetch204(); | |
| 118 | + await deleteBoardById("b1"); | |
| 119 | + | |
| 120 | + const [url, init] = lastFetchCall(); | |
| 121 | + expect(url).toBe("/api/boards/b1"); | |
| 122 | + expect(init?.method).toBe("DELETE"); | |
| 123 | + }); | |
| 124 | +}); |
src/api/__tests__/users/users.test.tsmodified+24 -0
| @@ -118,6 +118,30 @@ describe("users API", () => { | ||
| 118 | 118 | expect(init?.body).toBe(JSON.stringify(updates)); |
| 119 | 119 | }); |
| 120 | 120 | |
| 121 | + it("patchMyPreferences sends palette_color to set the accent", async () => { | |
| 122 | + const mockUser = { id: "u1", palette_color: "#fefae0" }; | |
| 123 | + mockFetchSuccess(mockUser); | |
| 124 | + | |
| 125 | + const updates = { palette_color: "#fefae0" }; | |
| 126 | + await patchMyPreferences(updates); | |
| 127 | + | |
| 128 | + const [url, init] = lastFetchCall(); | |
| 129 | + expect(url).toBe("/api/users/me/preferences"); | |
| 130 | + expect(init?.method).toBe("PATCH"); | |
| 131 | + expect(init?.body).toBe(JSON.stringify(updates)); | |
| 132 | + }); | |
| 133 | + | |
| 134 | + it("patchMyPreferences sends empty palette_color to clear the accent", async () => { | |
| 135 | + const mockUser = { id: "u1", palette_color: null }; | |
| 136 | + mockFetchSuccess(mockUser); | |
| 137 | + | |
| 138 | + const updates = { palette_color: "" }; | |
| 139 | + await patchMyPreferences(updates); | |
| 140 | + | |
| 141 | + const [, init] = lastFetchCall(); | |
| 142 | + expect(init?.body).toBe(JSON.stringify({ palette_color: "" })); | |
| 143 | + }); | |
| 144 | + | |
| 121 | 145 | it("patchUserPreferences calls /users/:id/preferences", async () => { |
| 122 | 146 | const mockUser = { id: "u1", language: "tr" }; |
| 123 | 147 | mockFetchSuccess(mockUser); |
src/api/boards/deleteBoardById.tsadded+6 -0
| @@ -0,0 +1,6 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | + | |
| 3 | +// Creator only: delete the board and its whole stroke log; frees a board seat. | |
| 4 | +export function deleteBoardById(id: string): Promise<void> { | |
| 5 | + return client<void>(`/boards/${encodeURIComponent(id)}`, { method: "DELETE" }); | |
| 6 | +} |
src/api/boards/getBoardById.tsadded+7 -0
| @@ -0,0 +1,7 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { Board } from "./types"; | |
| 3 | + | |
| 4 | +// One board — a 404 (never 403) for anyone not on it. | |
| 5 | +export function getBoardById(id: string, signal?: AbortSignal): Promise<Board> { | |
| 6 | + return client<Board>(`/boards/${encodeURIComponent(id)}`, { signal }); | |
| 7 | +} |
src/api/boards/getBoardEpochs.tsadded+16 -0
| @@ -0,0 +1,16 @@ | ||
| 1 | +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; | |
| 2 | +import type { StrokeRow } from "./types"; | |
| 3 | + | |
| 4 | +// The epoch index: every clear marker (each carries the closed epoch + its | |
| 5 | +// final stroke count), oldest first. The open epoch is deliberately absent. | |
| 6 | +export async function getBoardEpochs( | |
| 7 | + id: string, | |
| 8 | + params?: PageParams, | |
| 9 | + signal?: AbortSignal, | |
| 10 | +): Promise<Page<StrokeRow>> { | |
| 11 | + const data = await client<unknown>( | |
| 12 | + `/boards/${encodeURIComponent(id)}/epochs${pageQuery(params)}`, | |
| 13 | + { signal }, | |
| 14 | + ); | |
| 15 | + return normalizePage<StrokeRow>(data); | |
| 16 | +} |
src/api/boards/getBoardHistory.tsadded+24 -0
| @@ -0,0 +1,24 @@ | ||
| 1 | +import { | |
| 2 | + appendPageParams, | |
| 3 | + client, | |
| 4 | + normalizePage, | |
| 5 | + type Page, | |
| 6 | +} from "../client"; | |
| 7 | +import type { BoardHistoryParams, StrokeRow } from "./types"; | |
| 8 | + | |
| 9 | +// The whole append-only log, oldest first, clear markers included. `epoch` | |
| 10 | +// narrows to a single epoch (for session replay); omit for the whole life. | |
| 11 | +export async function getBoardHistory( | |
| 12 | + id: string, | |
| 13 | + params?: BoardHistoryParams, | |
| 14 | + signal?: AbortSignal, | |
| 15 | +): Promise<Page<StrokeRow>> { | |
| 16 | + const query = new URLSearchParams(); | |
| 17 | + if (params?.epoch != null) query.set("epoch", String(params.epoch)); | |
| 18 | + appendPageParams(query, params); | |
| 19 | + const suffix = query.toString() ? `?${query.toString()}` : ""; | |
| 20 | + const data = await client<unknown>(`/boards/${encodeURIComponent(id)}/history${suffix}`, { | |
| 21 | + signal, | |
| 22 | + }); | |
| 23 | + return normalizePage<StrokeRow>(data); | |
| 24 | +} |
src/api/boards/getBoardStrokes.tsadded+16 -0
| @@ -0,0 +1,16 @@ | ||
| 1 | +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; | |
| 2 | +import type { StrokeRow } from "./types"; | |
| 3 | + | |
| 4 | +// The live canvas: the current epoch's strokes, oldest first. REST catch-up | |
| 5 | +// / fallback for the same canvas the socket replays. | |
| 6 | +export async function getBoardStrokes( | |
| 7 | + id: string, | |
| 8 | + params?: PageParams, | |
| 9 | + signal?: AbortSignal, | |
| 10 | +): Promise<Page<StrokeRow>> { | |
| 11 | + const data = await client<unknown>( | |
| 12 | + `/boards/${encodeURIComponent(id)}/strokes${pageQuery(params)}`, | |
| 13 | + { signal }, | |
| 14 | + ); | |
| 15 | + return normalizePage<StrokeRow>(data); | |
| 16 | +} |
src/api/boards/getBoards.tsadded+8 -0
| @@ -0,0 +1,8 @@ | ||
| 1 | +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; | |
| 2 | +import type { Board } from "./types"; | |
| 3 | + | |
| 4 | +// Boards the caller created or was invited to, newest first. | |
| 5 | +export async function getBoards(params?: PageParams, signal?: AbortSignal): Promise<Page<Board>> { | |
| 6 | + const data = await client<unknown>(`/boards${pageQuery(params)}`, { signal }); | |
| 7 | + return normalizePage<Board>(data); | |
| 8 | +} |
src/api/boards/index.tsadded+11 -0
| @@ -0,0 +1,11 @@ | ||
| 1 | +export * from "./types"; | |
| 2 | +export * from "./postBoard"; | |
| 3 | +export * from "./getBoards"; | |
| 4 | +export * from "./getBoardById"; | |
| 5 | +export * from "./getBoardStrokes"; | |
| 6 | +export * from "./getBoardHistory"; | |
| 7 | +export * from "./getBoardEpochs"; | |
| 8 | +export * from "./patchBoardById"; | |
| 9 | +export * from "./postBoardClear"; | |
| 10 | +export * from "./postBoardClose"; | |
| 11 | +export * from "./deleteBoardById"; |
src/api/boards/patchBoardById.tsadded+7 -0
| @@ -0,0 +1,7 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { Board, UpdateBoardBody } from "./types"; | |
| 3 | + | |
| 4 | +// Re-title (any participant); roster + lock are the creator's alone (403). | |
| 5 | +export function patchBoardById(id: string, body: UpdateBoardBody): Promise<Board> { | |
| 6 | + return client<Board>(`/boards/${encodeURIComponent(id)}`, { method: "PATCH", body }); | |
| 7 | +} |
src/api/boards/postBoard.tsadded+7 -0
| @@ -0,0 +1,7 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { Board, CreateBoardBody } from "./types"; | |
| 3 | + | |
| 4 | +// Open a whiteboard; the caller becomes its creator. 409 at max_boards_per_creator. | |
| 5 | +export function postBoard(body: CreateBoardBody): Promise<Board> { | |
| 6 | + return client<Board>("/boards", { method: "POST", body }); | |
| 7 | +} |
src/api/boards/postBoardClear.tsadded+8 -0
| @@ -0,0 +1,8 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { StrokeRow } from "./types"; | |
| 3 | + | |
| 4 | +// Creator only: bump the epoch, blanking the live canvas (nothing deleted). | |
| 5 | +// 409 on a closed board. Returns the clear marker. | |
| 6 | +export function postBoardClear(id: string): Promise<StrokeRow> { | |
| 7 | + return client<StrokeRow>(`/boards/${encodeURIComponent(id)}/clear`, { method: "POST" }); | |
| 8 | +} |
src/api/boards/postBoardClose.tsadded+8 -0
| @@ -0,0 +1,8 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { Board } from "./types"; | |
| 3 | + | |
| 4 | +// Creator only: retire the board — permanently read-only, still fully | |
| 5 | +// readable; idempotent, no reopen. | |
| 6 | +export function postBoardClose(id: string): Promise<Board> { | |
| 7 | + return client<Board>(`/boards/${encodeURIComponent(id)}/close`, { method: "POST" }); | |
| 8 | +} |
src/api/boards/types.tsadded+49 -0
| @@ -0,0 +1,49 @@ | ||
| 1 | +import type { PageParams } from "../client"; | |
| 2 | + | |
| 3 | +// A collaborative whiteboard. `creator` is always a participant but never | |
| 4 | +// appears in `participants`. `epoch` is the live-canvas generation (a clear | |
| 5 | +// bumps it); `closed_at` set => permanently read-only. | |
| 6 | +export type Board = { | |
| 7 | + id: string; | |
| 8 | + title: string; | |
| 9 | + creator: string; | |
| 10 | + participants: string[]; | |
| 11 | + locked: boolean; | |
| 12 | + locked_by: string | null; | |
| 13 | + locked_at: number | null; | |
| 14 | + epoch: number; | |
| 15 | + closed_at: number | null; | |
| 16 | + created_at: number; | |
| 17 | +}; | |
| 18 | + | |
| 19 | +export type BoardStrokeKind = "stroke" | "clear"; | |
| 20 | + | |
| 21 | +// One row of the append-only stroke log. `payload` is the opaque serialized | |
| 22 | +// mark (null on a clear marker); `count` is the closed epoch's final stroke | |
| 23 | +// count, present only on a clear marker. | |
| 24 | +export type StrokeRow = { | |
| 25 | + id: string; | |
| 26 | + author: string; | |
| 27 | + kind: BoardStrokeKind; | |
| 28 | + payload: string | null; | |
| 29 | + count: number | null; | |
| 30 | + epoch: number; | |
| 31 | + created_at: number; | |
| 32 | +}; | |
| 33 | + | |
| 34 | +// POST /boards rejects unknown keys (422) — send only these two fields. | |
| 35 | +export type CreateBoardBody = { | |
| 36 | + title: string; | |
| 37 | + participants?: string[]; | |
| 38 | +}; | |
| 39 | + | |
| 40 | +// PATCH /boards/{id} rejects unknown keys (422). Send only the writable fields | |
| 41 | +// that changed: `title` (any participant), `participants`/`locked` (creator). | |
| 42 | +export type UpdateBoardBody = { | |
| 43 | + title?: string; | |
| 44 | + participants?: string[] | null; | |
| 45 | + locked?: boolean; | |
| 46 | +}; | |
| 47 | + | |
| 48 | +// GET /boards/{id}/history: `epoch` narrows to one epoch; omit for whole life. | |
| 49 | +export type BoardHistoryParams = PageParams & { epoch?: number }; |
src/api/client/types.tsmodified+1 -0
| @@ -23,6 +23,7 @@ export type User = { | ||
| 23 | 23 | birth_date: string | null; |
| 24 | 24 | theme: UserTheme | null; |
| 25 | 25 | language: UserLanguage | null; |
| 26 | + palette_color: string | null; | |
| 26 | 27 | }; |
| 27 | 28 | |
| 28 | 29 | export type ProfileUpdate = { |
src/api/users/patchMyPreferences.tsmodified+2 -0
| @@ -4,6 +4,8 @@ import type { User, UserLanguage, UserTheme } from "../client"; | ||
| 4 | 4 | export type PatchMyPreferencesBody = { |
| 5 | 5 | theme?: UserTheme; |
| 6 | 6 | language?: UserLanguage; |
| 7 | + // Accent color: "#rrggbb" to set, "" to clear back to null, omit to keep. | |
| 8 | + palette_color?: string; | |
| 7 | 9 | }; |
| 8 | 10 | |
| 9 | 11 | export function patchMyPreferences(body: PatchMyPreferencesBody): Promise<User> { |
src/components/layout/nav-items.tsmodified+2 -0
| @@ -17,6 +17,7 @@ import { | ||
| 17 | 17 | IconHomework, |
| 18 | 18 | IconHome, |
| 19 | 19 | IconMessage, |
| 20 | + IconEdit, | |
| 20 | 21 | IconNote, |
| 21 | 22 | IconReportAnalytics, |
| 22 | 23 | IconSchool, |
| @@ -129,6 +130,7 @@ const NAV_GROUPS: NavGroup[] = [ | ||
| 129 | 130 | CALENDAR_ITEM, |
| 130 | 131 | { id: "appointments", to: "/appointments", labelKey: "nav.appointments", Icon: IconClock }, |
| 131 | 132 | { id: "notes", to: "/notes", labelKey: "nav.notes", Icon: IconNote }, |
| 133 | + { id: "whiteboards", to: "/whiteboards", labelKey: "nav.whiteboards", Icon: IconEdit, minRole: "student" }, | |
| 132 | 134 | { id: "marks", to: "/marks", labelKey: "nav.marks", Icon: IconChart, exactRole: "student" }, |
| 133 | 135 | { id: "pomodoro", to: "/pomodoro", labelKey: "nav.pomodoro", Icon: IconClock, exactRole: "student" }, |
| 134 | 136 | ], |
src/components/whiteboard/whiteboard-canvas.tsxadded+388 -0
| @@ -0,0 +1,388 @@ | ||
| 1 | +import { For, Show, createSignal, onCleanup, onMount } from "solid-js"; | |
| 2 | +import { IconEdit, IconEraser, IconMove, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; | |
| 3 | +import { cn } from "@/lib/cn"; | |
| 4 | +import { | |
| 5 | + PAPER_CELL, | |
| 6 | + PAPER_LINE, | |
| 7 | + paintStroke, | |
| 8 | + paintTip, | |
| 9 | + type Point, | |
| 10 | + type Stroke, | |
| 11 | +} from "@/lib/draw-stroke"; | |
| 12 | +import { useT } from "@/stores/preferences-context"; | |
| 13 | + | |
| 14 | +const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; | |
| 15 | +const WIDTHS = [2, 6, 14]; | |
| 16 | +const ZOOM_MIN = 0.25; | |
| 17 | +const ZOOM_MAX = 4; | |
| 18 | +const ZOOM_STEP = 1.25; | |
| 19 | +const OVERLAY_CARD = "absolute z-10 flex gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-xs backdrop-blur-xs"; | |
| 20 | + | |
| 21 | +// Imperative handle the room uses to push server-confirmed marks onto the | |
| 22 | +// canvas without re-rendering the whole component per stroke. | |
| 23 | +export type WhiteboardCanvasController = { | |
| 24 | + /** Paint one server-confirmed stroke or segment (board-space coords). */ | |
| 25 | + applyStroke: (stroke: Stroke) => void; | |
| 26 | + /** Replace the whole canvas (REST catch-up, resync). */ | |
| 27 | + loadStrokes: (strokes: Stroke[]) => void; | |
| 28 | + /** Blank the live canvas (a clear / epoch bump — history is untouched). */ | |
| 29 | + reset: () => void; | |
| 30 | +}; | |
| 31 | + | |
| 32 | +/** | |
| 33 | + * The collaborative whiteboard drawing surface. Unlike {@link DrawCanvas} it | |
| 34 | + * never saves a File: each finished local stroke is emitted through | |
| 35 | + * `props.onStroke` (board-space, device/zoom independent) for the room to send | |
| 36 | + * over the socket, and server-confirmed strokes are pushed back in through the | |
| 37 | + * controller. Strokes are held in a plain array and painted incrementally so a | |
| 38 | + * busy board stays cheap; a full redraw only runs on pan / zoom / resize. | |
| 39 | + */ | |
| 40 | +export function WhiteboardCanvas(props: { | |
| 41 | + disabled?: boolean; | |
| 42 | + onStroke: (stroke: Stroke) => void; | |
| 43 | + controllerRef?: (c: WhiteboardCanvasController) => void; | |
| 44 | + class?: string; | |
| 45 | +}) { | |
| 46 | + const t = useT(); | |
| 47 | + let canvas: HTMLCanvasElement | undefined; | |
| 48 | + let wrap: HTMLDivElement | undefined; | |
| 49 | + let current: Stroke | undefined; | |
| 50 | + let panStart: { x: number; y: number; px: number; py: number } | undefined; | |
| 51 | + // Every committed mark (local + remote), in draw order. Plain array, not a | |
| 52 | + // signal: it can grow into the thousands and only pan/zoom/resize repaints it. | |
| 53 | + const committed: Stroke[] = []; | |
| 54 | + | |
| 55 | + const [color, setColor] = createSignal(COLORS[0]); | |
| 56 | + const [width, setWidth] = createSignal(WIDTHS[1]); | |
| 57 | + const [erasing, setErasing] = createSignal(false); | |
| 58 | + const [hand, setHand] = createSignal(false); | |
| 59 | + const [override, setOverride] = createSignal<null | "pan" | "erase">(null); | |
| 60 | + const [pan, setPan] = createSignal({ x: 0, y: 0 }); | |
| 61 | + const [panning, setPanning] = createSignal(false); | |
| 62 | + const [zoom, setZoom] = createSignal(1); | |
| 63 | + const [empty, setEmpty] = createSignal(true); | |
| 64 | + | |
| 65 | + const ratio = () => window.devicePixelRatio || 1; | |
| 66 | + const context = () => canvas?.getContext("2d") ?? null; | |
| 67 | + | |
| 68 | + const activeTool = (): "pen" | "erase" | "pan" => { | |
| 69 | + const o = override(); | |
| 70 | + if (o) return o; | |
| 71 | + if (hand()) return "pan"; | |
| 72 | + if (erasing()) return "erase"; | |
| 73 | + return "pen"; | |
| 74 | + }; | |
| 75 | + | |
| 76 | + const cursor = () => { | |
| 77 | + const tool = activeTool(); | |
| 78 | + if (tool === "pan") return panning() ? "grabbing" : "grab"; | |
| 79 | + return "crosshair"; | |
| 80 | + }; | |
| 81 | + | |
| 82 | + const redraw = () => { | |
| 83 | + const c = context(); | |
| 84 | + if (!c || !canvas) return; | |
| 85 | + const scale = ratio(); | |
| 86 | + c.setTransform(scale, 0, 0, scale, 0, 0); | |
| 87 | + c.clearRect(0, 0, canvas.width / scale, canvas.height / scale); | |
| 88 | + const p = pan(); | |
| 89 | + const z = zoom(); | |
| 90 | + c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); | |
| 91 | + for (const stroke of committed) paintStroke(c, stroke); | |
| 92 | + if (current) paintStroke(c, current); | |
| 93 | + }; | |
| 94 | + | |
| 95 | + const resize = () => { | |
| 96 | + if (!canvas) return; | |
| 97 | + const rect = canvas.getBoundingClientRect(); | |
| 98 | + if (rect.width === 0 || rect.height === 0) return; | |
| 99 | + const scale = ratio(); | |
| 100 | + canvas.width = Math.round(rect.width * scale); | |
| 101 | + canvas.height = Math.round(rect.height * scale); | |
| 102 | + redraw(); | |
| 103 | + }; | |
| 104 | + | |
| 105 | + // Paint one just-committed stroke on top of the current transform, without a | |
| 106 | + // full redraw. The transform matches redraw()'s so it lands in the same place. | |
| 107 | + const paintOne = (stroke: Stroke) => { | |
| 108 | + const c = context(); | |
| 109 | + if (!c || !canvas) return; | |
| 110 | + const scale = ratio(); | |
| 111 | + const p = pan(); | |
| 112 | + const z = zoom(); | |
| 113 | + c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); | |
| 114 | + paintStroke(c, stroke); | |
| 115 | + }; | |
| 116 | + | |
| 117 | + const controller: WhiteboardCanvasController = { | |
| 118 | + applyStroke: (stroke) => { | |
| 119 | + committed.push(stroke); | |
| 120 | + setEmpty(false); | |
| 121 | + paintOne(stroke); | |
| 122 | + }, | |
| 123 | + loadStrokes: (strokes) => { | |
| 124 | + committed.length = 0; | |
| 125 | + committed.push(...strokes); | |
| 126 | + setEmpty(committed.length === 0); | |
| 127 | + redraw(); | |
| 128 | + }, | |
| 129 | + reset: () => { | |
| 130 | + committed.length = 0; | |
| 131 | + setEmpty(true); | |
| 132 | + redraw(); | |
| 133 | + }, | |
| 134 | + }; | |
| 135 | + | |
| 136 | + onMount(() => { | |
| 137 | + resize(); | |
| 138 | + props.controllerRef?.(controller); | |
| 139 | + const observer = new ResizeObserver(() => resize()); | |
| 140 | + if (wrap) observer.observe(wrap); | |
| 141 | + onCleanup(() => observer.disconnect()); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + const pointAt = (e: PointerEvent): Point => { | |
| 145 | + const rect = canvas!.getBoundingClientRect(); | |
| 146 | + const p = pan(); | |
| 147 | + const z = zoom(); | |
| 148 | + return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z }; | |
| 149 | + }; | |
| 150 | + | |
| 151 | + const zoomBy = (factor: number) => { | |
| 152 | + if (!canvas) return; | |
| 153 | + const rect = canvas.getBoundingClientRect(); | |
| 154 | + const cx = rect.width / 2; | |
| 155 | + const cy = rect.height / 2; | |
| 156 | + const p = pan(); | |
| 157 | + const z0 = zoom(); | |
| 158 | + const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); | |
| 159 | + if (z1 === z0) return; | |
| 160 | + const wx = (cx - p.x) / z0; | |
| 161 | + const wy = (cy - p.y) / z0; | |
| 162 | + setZoom(z1); | |
| 163 | + setPan({ x: cx - wx * z1, y: cy - wy * z1 }); | |
| 164 | + redraw(); | |
| 165 | + }; | |
| 166 | + | |
| 167 | + const resetZoom = () => zoomBy(1 / zoom()); | |
| 168 | + | |
| 169 | + const drawTip = (stroke: Stroke) => { | |
| 170 | + const c = context(); | |
| 171 | + if (c) paintTip(c, stroke); | |
| 172 | + }; | |
| 173 | + | |
| 174 | + const startStroke = (e: PointerEvent) => { | |
| 175 | + if (props.disabled && !(e.button === 1 || hand())) return; | |
| 176 | + e.preventDefault(); | |
| 177 | + canvas?.setPointerCapture(e.pointerId); | |
| 178 | + if (e.button === 1 || (hand() && e.button !== 2)) { | |
| 179 | + if (e.button === 1) setOverride("pan"); | |
| 180 | + const p = pan(); | |
| 181 | + panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y }; | |
| 182 | + setPanning(true); | |
| 183 | + return; | |
| 184 | + } | |
| 185 | + if (props.disabled) return; | |
| 186 | + const eraseNow = erasing() || e.button === 2; | |
| 187 | + if (e.button === 2) setOverride("erase"); | |
| 188 | + current = { | |
| 189 | + color: color(), | |
| 190 | + width: eraseNow ? width() * 2.5 : width(), | |
| 191 | + erase: eraseNow, | |
| 192 | + points: [pointAt(e)], | |
| 193 | + }; | |
| 194 | + drawTip(current); | |
| 195 | + }; | |
| 196 | + | |
| 197 | + const extendStroke = (e: PointerEvent) => { | |
| 198 | + if (panStart) { | |
| 199 | + setPan({ x: panStart.px + (e.clientX - panStart.x), y: panStart.py + (e.clientY - panStart.y) }); | |
| 200 | + redraw(); | |
| 201 | + return; | |
| 202 | + } | |
| 203 | + if (!current) return; | |
| 204 | + current.points.push(pointAt(e)); | |
| 205 | + drawTip(current); | |
| 206 | + }; | |
| 207 | + | |
| 208 | + const endStroke = () => { | |
| 209 | + setOverride(null); | |
| 210 | + if (panStart) { | |
| 211 | + panStart = undefined; | |
| 212 | + setPanning(false); | |
| 213 | + return; | |
| 214 | + } | |
| 215 | + const done = current; | |
| 216 | + current = undefined; | |
| 217 | + if (!done || done.points.length === 0) return; | |
| 218 | + committed.push(done); | |
| 219 | + setEmpty(false); | |
| 220 | + redraw(); // swap the live polyline for its smoothed replay | |
| 221 | + props.onStroke(done); | |
| 222 | + }; | |
| 223 | + | |
| 224 | + const toolClass = (active: boolean) => | |
| 225 | + cn( | |
| 226 | + "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors", | |
| 227 | + active | |
| 228 | + ? "border-primary bg-primary text-primary-foreground shadow-xs" | |
| 229 | + : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground", | |
| 230 | + ); | |
| 231 | + | |
| 232 | + const paperStyle = () => { | |
| 233 | + const cell = PAPER_CELL * zoom(); | |
| 234 | + const p = pan(); | |
| 235 | + return { | |
| 236 | + "background-image": `linear-gradient(to right, ${PAPER_LINE} 1px, transparent 1px), linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`, | |
| 237 | + "background-size": `${cell}px ${cell}px`, | |
| 238 | + "background-position": `${p.x}px ${p.y}px`, | |
| 239 | + }; | |
| 240 | + }; | |
| 241 | + | |
| 242 | + return ( | |
| 243 | + <div class={cn("space-y-3", props.class)}> | |
| 244 | + <div | |
| 245 | + ref={wrap} | |
| 246 | + class="relative h-104 overflow-hidden rounded-lg border bg-white shadow-inner sm:h-[70vh]" | |
| 247 | + style={paperStyle()} | |
| 248 | + > | |
| 249 | + <canvas | |
| 250 | + ref={canvas} | |
| 251 | + class="h-full w-full touch-none" | |
| 252 | + style={{ cursor: cursor() }} | |
| 253 | + onMouseDown={(e) => { | |
| 254 | + if (e.button === 1) e.preventDefault(); | |
| 255 | + }} | |
| 256 | + onContextMenu={(e) => e.preventDefault()} | |
| 257 | + onPointerDown={startStroke} | |
| 258 | + onPointerMove={extendStroke} | |
| 259 | + onPointerUp={endStroke} | |
| 260 | + onPointerCancel={endStroke} | |
| 261 | + onWheel={(e) => { | |
| 262 | + e.preventDefault(); | |
| 263 | + zoomBy(e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP); | |
| 264 | + }} | |
| 265 | + /> | |
| 266 | + <Show when={empty() && !current}> | |
| 267 | + <p class="pointer-events-none absolute inset-0 flex items-center justify-center text-sm text-slate-400"> | |
| 268 | + {t("whiteboard.canvasHint")} | |
| 269 | + </p> | |
| 270 | + </Show> | |
| 271 | + | |
| 272 | + {/* Top-left island — tools */} | |
| 273 | + <div class={cn(OVERLAY_CARD, "left-2 top-2")}> | |
| 274 | + <button | |
| 275 | + type="button" | |
| 276 | + class={toolClass(activeTool() === "pen")} | |
| 277 | + title={t("draw.pen")} | |
| 278 | + onClick={() => { | |
| 279 | + setErasing(false); | |
| 280 | + setHand(false); | |
| 281 | + }} | |
| 282 | + > | |
| 283 | + <IconEdit class="h-5 w-5" /> | |
| 284 | + <span class="sr-only">{t("draw.pen")}</span> | |
| 285 | + </button> | |
| 286 | + <button | |
| 287 | + type="button" | |
| 288 | + class={toolClass(activeTool() === "erase")} | |
| 289 | + title={t("draw.eraser")} | |
| 290 | + onClick={() => { | |
| 291 | + setErasing(true); | |
| 292 | + setHand(false); | |
| 293 | + }} | |
| 294 | + > | |
| 295 | + <IconEraser class="h-5 w-5" /> | |
| 296 | + <span class="sr-only">{t("draw.eraser")}</span> | |
| 297 | + </button> | |
| 298 | + <button | |
| 299 | + type="button" | |
| 300 | + class={toolClass(activeTool() === "pan")} | |
| 301 | + title={t("draw.pan")} | |
| 302 | + onClick={() => setHand(true)} | |
| 303 | + > | |
| 304 | + <IconMove class="h-5 w-5" /> | |
| 305 | + <span class="sr-only">{t("draw.pan")}</span> | |
| 306 | + </button> | |
| 307 | + </div> | |
| 308 | + | |
| 309 | + {/* Top-middle island — colours */} | |
| 310 | + <div | |
| 311 | + class={cn(OVERLAY_CARD, "left-1/2 top-2 -translate-x-1/2 flex-wrap items-center")} | |
| 312 | + role="group" | |
| 313 | + aria-label={t("draw.color")} | |
| 314 | + > | |
| 315 | + <For each={COLORS}> | |
| 316 | + {(swatch) => ( | |
| 317 | + <button | |
| 318 | + type="button" | |
| 319 | + title={t("draw.color")} | |
| 320 | + class={cn( | |
| 321 | + "h-9 w-9 sm:h-11 sm:w-11 rounded-lg border-2 transition-transform", | |
| 322 | + color() === swatch && activeTool() === "pen" | |
| 323 | + ? "border-foreground scale-105" | |
| 324 | + : "border-border/60 hover:scale-105", | |
| 325 | + )} | |
| 326 | + style={{ "background-color": swatch }} | |
| 327 | + onClick={() => { | |
| 328 | + setColor(swatch); | |
| 329 | + setErasing(false); | |
| 330 | + setHand(false); | |
| 331 | + }} | |
| 332 | + > | |
| 333 | + <span class="sr-only">{swatch}</span> | |
| 334 | + </button> | |
| 335 | + )} | |
| 336 | + </For> | |
| 337 | + </div> | |
| 338 | + | |
| 339 | + {/* Top-right island — width */} | |
| 340 | + <div class={cn(OVERLAY_CARD, "right-2 top-2")} role="group" aria-label={t("draw.width")}> | |
| 341 | + <For each={WIDTHS}> | |
| 342 | + {(size) => ( | |
| 343 | + <button | |
| 344 | + type="button" | |
| 345 | + title={t("draw.width")} | |
| 346 | + class={toolClass(width() === size)} | |
| 347 | + onClick={() => setWidth(size)} | |
| 348 | + > | |
| 349 | + <span class="rounded-full bg-current" style={{ width: `${size + 2}px`, height: `${size + 2}px` }} /> | |
| 350 | + <span class="sr-only">{size}</span> | |
| 351 | + </button> | |
| 352 | + )} | |
| 353 | + </For> | |
| 354 | + </div> | |
| 355 | + | |
| 356 | + {/* Bottom-right zoom */} | |
| 357 | + <div class="absolute bottom-2 right-2 z-10 flex flex-col divide-y divide-border overflow-hidden rounded-lg border bg-card/90 shadow-xs backdrop-blur-xs"> | |
| 358 | + <button | |
| 359 | + type="button" | |
| 360 | + class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" | |
| 361 | + title={t("draw.zoomIn")} | |
| 362 | + onClick={() => zoomBy(ZOOM_STEP)} | |
| 363 | + > | |
| 364 | + <IconZoomIn class="h-5 w-5" /> | |
| 365 | + <span class="sr-only">{t("draw.zoomIn")}</span> | |
| 366 | + </button> | |
| 367 | + <button | |
| 368 | + type="button" | |
| 369 | + class="flex h-9 w-9 items-center justify-center font-mono text-xs tabular-nums text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" | |
| 370 | + title={t("draw.resetZoom")} | |
| 371 | + onClick={resetZoom} | |
| 372 | + > | |
| 373 | + {Math.round(zoom() * 100)}% | |
| 374 | + </button> | |
| 375 | + <button | |
| 376 | + type="button" | |
| 377 | + class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" | |
| 378 | + title={t("draw.zoomOut")} | |
| 379 | + onClick={() => zoomBy(1 / ZOOM_STEP)} | |
| 380 | + > | |
| 381 | + <IconZoomOut class="h-5 w-5" /> | |
| 382 | + <span class="sr-only">{t("draw.zoomOut")}</span> | |
| 383 | + </button> | |
| 384 | + </div> | |
| 385 | + </div> | |
| 386 | + </div> | |
| 387 | + ); | |
| 388 | +} |
src/components/whiteboard/whiteboard-room-ws.tsxadded+295 -0
| @@ -0,0 +1,295 @@ | ||
| 1 | +import { Show, createSignal, onCleanup, onMount } from "solid-js"; | |
| 2 | +import { getBoardStrokes, type Board } from "@/api/boards"; | |
| 3 | +import { formatApiErrorMessage } from "@/api/client"; | |
| 4 | +import { IconAlert } from "@/components/ui/icons"; | |
| 5 | +import { encodeStrokeSegments, decodeSegment, segmentToStroke } from "@/lib/board-stroke-codec"; | |
| 6 | +import type { Stroke } from "@/lib/draw-stroke"; | |
| 7 | +import { usePreferences, useT } from "@/stores/preferences-context"; | |
| 8 | +import { WhiteboardCanvas, type WhiteboardCanvasController } from "./whiteboard-canvas"; | |
| 9 | + | |
| 10 | +type WsState = "connecting" | "connected" | "disconnected"; | |
| 11 | + | |
| 12 | +// Live state the room lifts back to the page so its creator controls and roster | |
| 13 | +// reflect what the socket saw (a fanned-out lock/close/roster change). | |
| 14 | +export type BoardLiveState = { | |
| 15 | + locked?: boolean; | |
| 16 | + closed?: boolean; | |
| 17 | + creator?: string; | |
| 18 | + participants?: string[]; | |
| 19 | + epoch?: number; | |
| 20 | +}; | |
| 21 | + | |
| 22 | +type WsIn = | |
| 23 | + | { type: "state"; board: string; epoch: number; locked: boolean; closed_at: number | null; creator: string; participants: string[]; now: number } | |
| 24 | + | { type: "strokes"; epoch: number; strokes: { id: string; author: string; payload: string }[] } | |
| 25 | + | { type: "synced"; epoch: number; cursor: string | null } | |
| 26 | + | { type: "stroke"; id: string; author: string; payload: string; epoch: number } | |
| 27 | + | { type: "saved"; id: string; client_seq?: number } | |
| 28 | + | { type: "pong" } | |
| 29 | + | { type: "cleared"; epoch: number; by: string | null } | |
| 30 | + | { type: "locked"; locked: boolean; by: string } | |
| 31 | + | { type: "closed"; closed_at: number | null } | |
| 32 | + | { type: "participants"; creator: string; participants: string[] } | |
| 33 | + | { type: "deleted" } | |
| 34 | + | { type: "error"; code: string; message: string; client_seq?: number }; | |
| 35 | + | |
| 36 | +const MAX_RECONNECT = 6; | |
| 37 | + | |
| 38 | +export function WhiteboardRoom(props: { | |
| 39 | + board: Board; | |
| 40 | + meId: string; | |
| 41 | + onState?: (patch: BoardLiveState) => void; | |
| 42 | + onDeleted?: () => void; | |
| 43 | +}) { | |
| 44 | + const t = useT(); | |
| 45 | + const { locale } = usePreferences(); | |
| 46 | + | |
| 47 | + const [wsState, setWsState] = createSignal<WsState>("disconnected"); | |
| 48 | + const [locked, setLocked] = createSignal(props.board.locked); | |
| 49 | + const [closed, setClosed] = createSignal(props.board.closed_at != null); | |
| 50 | + const [creator, setCreator] = createSignal(props.board.creator); | |
| 51 | + const [participants, setParticipants] = createSignal<string[]>(props.board.participants); | |
| 52 | + const [notice, setNotice] = createSignal(""); | |
| 53 | + | |
| 54 | + let controller: WhiteboardCanvasController | null = null; | |
| 55 | + let ws: WebSocket | null = null; | |
| 56 | + let epoch: number = props.board.epoch; | |
| 57 | + let cursor: string | null = null; | |
| 58 | + let clientSeq = 0; | |
| 59 | + // Backend stroke row ids already painted, so a resync/replay never double-draws. | |
| 60 | + const seen = new Set<string>(); | |
| 61 | + | |
| 62 | + let reconnectTimer: ReturnType<typeof setTimeout> | null = null; | |
| 63 | + let reconnectAttempts = 0; | |
| 64 | + let closedByUs = false; | |
| 65 | + | |
| 66 | + const isParticipant = () => props.meId === creator() || participants().includes(props.meId); | |
| 67 | + const canDraw = () => wsState() === "connected" && !locked() && !closed() && isParticipant(); | |
| 68 | + | |
| 69 | + const wsUrl = () => { | |
| 70 | + const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; | |
| 71 | + return `${proto}//${window.location.host}/api/boards/${encodeURIComponent(props.board.id)}/ws`; | |
| 72 | + }; | |
| 73 | + | |
| 74 | + const clearReconnect = () => { | |
| 75 | + if (reconnectTimer) { | |
| 76 | + clearTimeout(reconnectTimer); | |
| 77 | + reconnectTimer = null; | |
| 78 | + } | |
| 79 | + }; | |
| 80 | + | |
| 81 | + const scheduleReconnect = () => { | |
| 82 | + if (closedByUs || reconnectTimer) return; | |
| 83 | + if (closed()) return; // a closed board is read-only; the socket will only replay | |
| 84 | + if (reconnectAttempts >= MAX_RECONNECT) return; | |
| 85 | + const delay = Math.min(1000 * 2 ** reconnectAttempts, 15000); | |
| 86 | + reconnectAttempts += 1; | |
| 87 | + reconnectTimer = setTimeout(() => { | |
| 88 | + reconnectTimer = null; | |
| 89 | + connectWs(); | |
| 90 | + }, delay); | |
| 91 | + }; | |
| 92 | + | |
| 93 | + const applyRow = (row: { id: string; payload: string | null }) => { | |
| 94 | + if (seen.has(row.id)) return; | |
| 95 | + seen.add(row.id); | |
| 96 | + const seg = decodeSegment(row.payload); | |
| 97 | + if (seg) controller?.applyStroke(segmentToStroke(seg)); | |
| 98 | + }; | |
| 99 | + | |
| 100 | + const wipe = () => { | |
| 101 | + seen.clear(); | |
| 102 | + controller?.reset(); | |
| 103 | + }; | |
| 104 | + | |
| 105 | + // Reconcile the whole live canvas from REST — used when the server rejects a | |
| 106 | + // draw (locked/full/closed): the database is the authority, so we throw the | |
| 107 | + // optimistic local canvas away and take what is actually stored. | |
| 108 | + const resyncFromRest = async () => { | |
| 109 | + try { | |
| 110 | + const page = await getBoardStrokes(props.board.id, { limit: 500 }); | |
| 111 | + wipe(); | |
| 112 | + for (const row of page.items) applyRow({ id: row.id, payload: row.payload }); | |
| 113 | + } catch { | |
| 114 | + // socket replay will catch us up on the next reconnect | |
| 115 | + } | |
| 116 | + }; | |
| 117 | + | |
| 118 | + const connectWs = () => { | |
| 119 | + clearReconnect(); | |
| 120 | + if (ws) { | |
| 121 | + ws.onclose = null; | |
| 122 | + ws.onerror = null; | |
| 123 | + ws.onmessage = null; | |
| 124 | + ws.close(); | |
| 125 | + } | |
| 126 | + setWsState("connecting"); | |
| 127 | + const socket = new WebSocket(wsUrl()); | |
| 128 | + ws = socket; | |
| 129 | + | |
| 130 | + socket.onopen = () => { | |
| 131 | + reconnectAttempts = 0; | |
| 132 | + setWsState("connected"); | |
| 133 | + // Resume from our cursor; the server replays only what is newer (or the | |
| 134 | + // whole current epoch, preceded by a `cleared`, on a stale/absent cursor). | |
| 135 | + sendWs({ type: "join", after: cursor ?? undefined, epoch }); | |
| 136 | + }; | |
| 137 | + const dropped = () => { | |
| 138 | + setWsState("disconnected"); | |
| 139 | + ws = null; | |
| 140 | + scheduleReconnect(); | |
| 141 | + }; | |
| 142 | + socket.onclose = dropped; | |
| 143 | + socket.onerror = dropped; | |
| 144 | + socket.onmessage = (event) => { | |
| 145 | + try { | |
| 146 | + handle(JSON.parse(event.data) as WsIn); | |
| 147 | + } catch { | |
| 148 | + // ignore malformed frame | |
| 149 | + } | |
| 150 | + }; | |
| 151 | + }; | |
| 152 | + | |
| 153 | + const sendWs = (data: unknown) => { | |
| 154 | + if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(data)); | |
| 155 | + }; | |
| 156 | + | |
| 157 | + const pushState = (patch: BoardLiveState) => props.onState?.(patch); | |
| 158 | + | |
| 159 | + const handle = (msg: WsIn) => { | |
| 160 | + switch (msg.type) { | |
| 161 | + case "state": { | |
| 162 | + epoch = msg.epoch; | |
| 163 | + setLocked(msg.locked); | |
| 164 | + setClosed(msg.closed_at != null); | |
| 165 | + setCreator(msg.creator); | |
| 166 | + setParticipants(msg.participants); | |
| 167 | + pushState({ locked: msg.locked, closed: msg.closed_at != null, creator: msg.creator, participants: msg.participants, epoch: msg.epoch }); | |
| 168 | + break; | |
| 169 | + } | |
| 170 | + case "strokes": { | |
| 171 | + for (const row of msg.strokes) applyRow(row); | |
| 172 | + break; | |
| 173 | + } | |
| 174 | + case "synced": { | |
| 175 | + epoch = msg.epoch; | |
| 176 | + cursor = msg.cursor; | |
| 177 | + break; | |
| 178 | + } | |
| 179 | + case "stroke": { | |
| 180 | + applyRow(msg); | |
| 181 | + break; | |
| 182 | + } | |
| 183 | + case "saved": { | |
| 184 | + break; // our own mark persisted; already painted optimistically | |
| 185 | + } | |
| 186 | + case "cleared": { | |
| 187 | + epoch = msg.epoch; | |
| 188 | + wipe(); | |
| 189 | + pushState({ epoch: msg.epoch }); | |
| 190 | + break; | |
| 191 | + } | |
| 192 | + case "locked": { | |
| 193 | + setLocked(msg.locked); | |
| 194 | + pushState({ locked: msg.locked }); | |
| 195 | + break; | |
| 196 | + } | |
| 197 | + case "closed": { | |
| 198 | + setClosed(true); | |
| 199 | + pushState({ closed: true }); | |
| 200 | + break; | |
| 201 | + } | |
| 202 | + case "participants": { | |
| 203 | + setCreator(msg.creator); | |
| 204 | + setParticipants(msg.participants); | |
| 205 | + pushState({ creator: msg.creator, participants: msg.participants }); | |
| 206 | + break; | |
| 207 | + } | |
| 208 | + case "deleted": { | |
| 209 | + closedByUs = true; | |
| 210 | + props.onDeleted?.(); | |
| 211 | + break; | |
| 212 | + } | |
| 213 | + case "pong": { | |
| 214 | + break; | |
| 215 | + } | |
| 216 | + case "error": { | |
| 217 | + const message = formatApiErrorMessage(msg.message, locale()); | |
| 218 | + setNotice(message); | |
| 219 | + // A rejected draw (locked, full epoch, closed) or a room resync means the | |
| 220 | + // optimistic local canvas is out of step — take the truth from the DB. | |
| 221 | + if (["epoch_full", "board_closed", "locked", "resync", "conflict", "forbidden"].includes(msg.code)) { | |
| 222 | + void resyncFromRest(); | |
| 223 | + } | |
| 224 | + break; | |
| 225 | + } | |
| 226 | + } | |
| 227 | + }; | |
| 228 | + | |
| 229 | + const onLocalStroke = (stroke: Stroke) => { | |
| 230 | + if (!canDraw()) return; | |
| 231 | + const sid = `${props.meId}-${Date.now()}-${(clientSeq += 1)}`; | |
| 232 | + for (const payload of encodeStrokeSegments(stroke, sid)) { | |
| 233 | + sendWs({ type: "stroke", payload, client_seq: (clientSeq += 1) }); | |
| 234 | + } | |
| 235 | + }; | |
| 236 | + | |
| 237 | + onMount(() => { | |
| 238 | + connectWs(); | |
| 239 | + }); | |
| 240 | + | |
| 241 | + onCleanup(() => { | |
| 242 | + closedByUs = true; | |
| 243 | + clearReconnect(); | |
| 244 | + if (ws) ws.close(); | |
| 245 | + }); | |
| 246 | + | |
| 247 | + const wsLabel = () => { | |
| 248 | + if (wsState() === "connecting") return t("ws.connecting"); | |
| 249 | + if (wsState() === "connected") return t("ws.connected"); | |
| 250 | + return t("ws.disconnected"); | |
| 251 | + }; | |
| 252 | + | |
| 253 | + return ( | |
| 254 | + <div class="space-y-3"> | |
| 255 | + <div class="flex flex-wrap items-center gap-3 rounded-lg border bg-card px-3 py-2 text-xs text-muted-foreground"> | |
| 256 | + <span class="inline-flex items-center gap-1.5"> | |
| 257 | + <span class={wsState() === "connected" ? "h-2 w-2 rounded-full bg-success" : "h-2 w-2 rounded-full bg-warning"} /> | |
| 258 | + {wsLabel()} | |
| 259 | + </span> | |
| 260 | + <Show when={closed()}> | |
| 261 | + <span class="rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 font-medium text-amber-600"> | |
| 262 | + {t("whiteboard.closedBadge")} | |
| 263 | + </span> | |
| 264 | + </Show> | |
| 265 | + <Show when={locked() && !closed()}> | |
| 266 | + <span class="rounded-full border border-border bg-muted px-2 py-0.5 font-medium"> | |
| 267 | + {t("whiteboard.lockedBadge")} | |
| 268 | + </span> | |
| 269 | + </Show> | |
| 270 | + <Show when={!isParticipant()}> | |
| 271 | + <span class="rounded-full border border-border bg-muted px-2 py-0.5 font-medium"> | |
| 272 | + {t("whiteboard.readOnlyBadge")} | |
| 273 | + </span> | |
| 274 | + </Show> | |
| 275 | + </div> | |
| 276 | + | |
| 277 | + <Show when={notice()}> | |
| 278 | + {(msg) => ( | |
| 279 | + <div class="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3"> | |
| 280 | + <IconAlert class="mt-0.5 h-5 w-5 shrink-0 text-destructive" /> | |
| 281 | + <p class="min-w-0 text-sm text-destructive">{msg()}</p> | |
| 282 | + </div> | |
| 283 | + )} | |
| 284 | + </Show> | |
| 285 | + | |
| 286 | + <WhiteboardCanvas | |
| 287 | + disabled={!canDraw()} | |
| 288 | + onStroke={onLocalStroke} | |
| 289 | + controllerRef={(c) => { | |
| 290 | + controller = c; | |
| 291 | + }} | |
| 292 | + /> | |
| 293 | + </div> | |
| 294 | + ); | |
| 295 | +} |
src/i18n/messages.tsmodified+105 -0
| @@ -953,6 +953,41 @@ export type MessageKey = | ||
| 953 | 953 | | "meals.priceTry" |
| 954 | 954 | | "nav.payments" |
| 955 | 955 | | "nav.paymentStatement" |
| 956 | + | "nav.whiteboards" | |
| 957 | + | "whiteboard.title" | |
| 958 | + | "whiteboard.subtitle" | |
| 959 | + | "whiteboard.empty" | |
| 960 | + | "whiteboard.create" | |
| 961 | + | "whiteboard.titleLabel" | |
| 962 | + | "whiteboard.participants" | |
| 963 | + | "whiteboard.participantsHint" | |
| 964 | + | "whiteboard.open" | |
| 965 | + | "whiteboard.createdAt" | |
| 966 | + | "whiteboard.limitReached" | |
| 967 | + | "whiteboard.canvasHint" | |
| 968 | + | "whiteboard.closedBadge" | |
| 969 | + | "whiteboard.lockedBadge" | |
| 970 | + | "whiteboard.readOnlyBadge" | |
| 971 | + | "whiteboard.lock" | |
| 972 | + | "whiteboard.unlock" | |
| 973 | + | "whiteboard.clear" | |
| 974 | + | "whiteboard.clearConfirm" | |
| 975 | + | "whiteboard.close" | |
| 976 | + | "whiteboard.closeConfirm" | |
| 977 | + | "whiteboard.delete" | |
| 978 | + | "whiteboard.deleteConfirm" | |
| 979 | + | "whiteboard.creator" | |
| 980 | + | "whiteboard.roster" | |
| 981 | + | "whiteboard.addParticipant" | |
| 982 | + | "whiteboard.removeParticipant" | |
| 983 | + | "whiteboard.history" | |
| 984 | + | "whiteboard.noHistory" | |
| 985 | + | "whiteboard.replaySession" | |
| 986 | + | "whiteboard.play" | |
| 987 | + | "whiteboard.pause" | |
| 988 | + | "whiteboard.restart" | |
| 989 | + | "whiteboard.notFound" | |
| 990 | + | "whiteboard.back" | |
| 956 | 991 | | "payments.title" |
| 957 | 992 | | "payments.subtitle" |
| 958 | 993 | | "payments.empty" |
| @@ -2222,6 +2257,41 @@ const en: Dict = { | ||
| 2222 | 2257 | "meals.priceTry": "Price (TRY)", |
| 2223 | 2258 | "nav.payments": "Fees", |
| 2224 | 2259 | "nav.paymentStatement": "My Fees", |
| 2260 | + "nav.whiteboards": "Whiteboards", | |
| 2261 | + "whiteboard.title": "Whiteboards", | |
| 2262 | + "whiteboard.subtitle": "Live collaborative sketch boards.", | |
| 2263 | + "whiteboard.empty": "No whiteboards yet.", | |
| 2264 | + "whiteboard.create": "New whiteboard", | |
| 2265 | + "whiteboard.titleLabel": "Title", | |
| 2266 | + "whiteboard.participants": "Participants", | |
| 2267 | + "whiteboard.participantsHint": "Invite students and staff who may draw.", | |
| 2268 | + "whiteboard.open": "Open", | |
| 2269 | + "whiteboard.createdAt": "Created", | |
| 2270 | + "whiteboard.limitReached": "You have reached your whiteboard limit.", | |
| 2271 | + "whiteboard.canvasHint": "Draw here — everyone on the board sees it live.", | |
| 2272 | + "whiteboard.closedBadge": "Closed", | |
| 2273 | + "whiteboard.lockedBadge": "Locked", | |
| 2274 | + "whiteboard.readOnlyBadge": "Read-only", | |
| 2275 | + "whiteboard.lock": "Lock", | |
| 2276 | + "whiteboard.unlock": "Unlock", | |
| 2277 | + "whiteboard.clear": "Clear", | |
| 2278 | + "whiteboard.clearConfirm": "Clear the live canvas? The history is kept and stays replayable.", | |
| 2279 | + "whiteboard.close": "Close board", | |
| 2280 | + "whiteboard.closeConfirm": "Close this board? It becomes permanently read-only.", | |
| 2281 | + "whiteboard.delete": "Delete board", | |
| 2282 | + "whiteboard.deleteConfirm": "Delete this board and its whole history? This cannot be undone.", | |
| 2283 | + "whiteboard.creator": "Creator", | |
| 2284 | + "whiteboard.roster": "Participants", | |
| 2285 | + "whiteboard.addParticipant": "Add participant", | |
| 2286 | + "whiteboard.removeParticipant": "Remove", | |
| 2287 | + "whiteboard.history": "History", | |
| 2288 | + "whiteboard.noHistory": "No past sessions yet.", | |
| 2289 | + "whiteboard.replaySession": "Replay session", | |
| 2290 | + "whiteboard.play": "Play", | |
| 2291 | + "whiteboard.pause": "Pause", | |
| 2292 | + "whiteboard.restart": "Restart", | |
| 2293 | + "whiteboard.notFound": "This whiteboard does not exist or you are not on it.", | |
| 2294 | + "whiteboard.back": "Back to whiteboards", | |
| 2225 | 2295 | "payments.title": "School fees", |
| 2226 | 2296 | "payments.subtitle": "Fee plans, assignments, and the payment ledger.", |
| 2227 | 2297 | "payments.empty": "No fee plans yet.", |
| @@ -3417,6 +3487,41 @@ const tr: Dict = { | ||
| 3417 | 3487 | "meals.priceTry": "Fiyat (TRY)", |
| 3418 | 3488 | "nav.payments": "Ücretler", |
| 3419 | 3489 | "nav.paymentStatement": "Ücretlerim", |
| 3490 | + "nav.whiteboards": "Beyaz Tahtalar", | |
| 3491 | + "whiteboard.title": "Beyaz Tahtalar", | |
| 3492 | + "whiteboard.subtitle": "Canlı ortak çizim tahtaları.", | |
| 3493 | + "whiteboard.empty": "Henüz beyaz tahta yok.", | |
| 3494 | + "whiteboard.create": "Yeni tahta", | |
| 3495 | + "whiteboard.titleLabel": "Başlık", | |
| 3496 | + "whiteboard.participants": "Katılımcılar", | |
| 3497 | + "whiteboard.participantsHint": "Çizebilecek öğrenci ve personeli davet edin.", | |
| 3498 | + "whiteboard.open": "Aç", | |
| 3499 | + "whiteboard.createdAt": "Oluşturuldu", | |
| 3500 | + "whiteboard.limitReached": "Beyaz tahta sınırına ulaştınız.", | |
| 3501 | + "whiteboard.canvasHint": "Buraya çizin — tahtadaki herkes anlık görür.", | |
| 3502 | + "whiteboard.closedBadge": "Kapalı", | |
| 3503 | + "whiteboard.lockedBadge": "Kilitli", | |
| 3504 | + "whiteboard.readOnlyBadge": "Salt okunur", | |
| 3505 | + "whiteboard.lock": "Kilitle", | |
| 3506 | + "whiteboard.unlock": "Kilidi aç", | |
| 3507 | + "whiteboard.clear": "Temizle", | |
| 3508 | + "whiteboard.clearConfirm": "Canlı tuval temizlensin mi? Geçmiş korunur ve tekrar oynatılabilir.", | |
| 3509 | + "whiteboard.close": "Tahtayı kapat", | |
| 3510 | + "whiteboard.closeConfirm": "Bu tahta kapatılsın mı? Kalıcı olarak salt okunur olur.", | |
| 3511 | + "whiteboard.delete": "Tahtayı sil", | |
| 3512 | + "whiteboard.deleteConfirm": "Bu tahta ve tüm geçmişi silinsin mi? Geri alınamaz.", | |
| 3513 | + "whiteboard.creator": "Oluşturan", | |
| 3514 | + "whiteboard.roster": "Katılımcılar", | |
| 3515 | + "whiteboard.addParticipant": "Katılımcı ekle", | |
| 3516 | + "whiteboard.removeParticipant": "Çıkar", | |
| 3517 | + "whiteboard.history": "Geçmiş", | |
| 3518 | + "whiteboard.noHistory": "Henüz geçmiş oturum yok.", | |
| 3519 | + "whiteboard.replaySession": "Oturumu oynat", | |
| 3520 | + "whiteboard.play": "Oynat", | |
| 3521 | + "whiteboard.pause": "Duraklat", | |
| 3522 | + "whiteboard.restart": "Baştan", | |
| 3523 | + "whiteboard.notFound": "Bu beyaz tahta yok ya da üzerinde değilsiniz.", | |
| 3524 | + "whiteboard.back": "Beyaz tahtalara dön", | |
| 3420 | 3525 | "payments.title": "Okul ücretleri", |
| 3421 | 3526 | "payments.subtitle": "Ücret planları, atamalar ve ödeme hareketleri.", |
| 3422 | 3527 | "payments.empty": "Henüz ücret planı yok.", |
src/lib/board-stroke-codec.test.tsadded+83 -0
| @@ -0,0 +1,83 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + decodeSegment, | |
| 4 | + encodeStrokeSegments, | |
| 5 | + reassembleStrokes, | |
| 6 | + segmentToStroke, | |
| 7 | +} from "./board-stroke-codec"; | |
| 8 | +import type { Stroke } from "./draw-stroke"; | |
| 9 | + | |
| 10 | +function makeStroke(pointCount: number): Stroke { | |
| 11 | + const points = Array.from({ length: pointCount }, (_, i) => ({ x: i * 1.234, y: i * 5.678 })); | |
| 12 | + return { color: "#ff0000", width: 3, erase: false, points }; | |
| 13 | +} | |
| 14 | + | |
| 15 | +describe("board-stroke-codec", () => { | |
| 16 | + it("encodes a short stroke into a single segment", () => { | |
| 17 | + const payloads = encodeStrokeSegments(makeStroke(5), "s1"); | |
| 18 | + expect(payloads).toHaveLength(1); | |
| 19 | + const seg = decodeSegment(payloads[0]); | |
| 20 | + expect(seg).not.toBeNull(); | |
| 21 | + expect(seg?.sid).toBe("s1"); | |
| 22 | + expect(seg?.seg).toBe(0); | |
| 23 | + expect(seg?.last).toBe(true); | |
| 24 | + expect(seg?.pts).toHaveLength(5); | |
| 25 | + }); | |
| 26 | + | |
| 27 | + it("returns no segments for an empty stroke", () => { | |
| 28 | + expect(encodeStrokeSegments(makeStroke(0), "s1")).toEqual([]); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + it("splits a long stroke into multiple capped segments", () => { | |
| 32 | + const payloads = encodeStrokeSegments(makeStroke(2000), "s2", 512); | |
| 33 | + expect(payloads.length).toBeGreaterThan(1); | |
| 34 | + for (const p of payloads) { | |
| 35 | + expect(new TextEncoder().encode(p).length).toBeLessThanOrEqual(512); | |
| 36 | + } | |
| 37 | + // exactly one final segment | |
| 38 | + const lasts = payloads.map((p) => decodeSegment(p)!.last).filter(Boolean); | |
| 39 | + expect(lasts).toHaveLength(1); | |
| 40 | + expect(decodeSegment(payloads[payloads.length - 1])!.last).toBe(true); | |
| 41 | + }); | |
| 42 | + | |
| 43 | + it("reassembles segments back into the original stroke (no duplicate overlap points)", () => { | |
| 44 | + const original = makeStroke(2000); | |
| 45 | + const payloads = encodeStrokeSegments(original, "s3", 512); | |
| 46 | + const [rebuilt] = reassembleStrokes(payloads); | |
| 47 | + expect(rebuilt.points).toHaveLength(original.points.length); | |
| 48 | + expect(rebuilt.color).toBe(original.color); | |
| 49 | + expect(rebuilt.width).toBe(original.width); | |
| 50 | + // rounded to 2dp, so compare with tolerance | |
| 51 | + expect(rebuilt.points[0].x).toBeCloseTo(original.points[0].x, 2); | |
| 52 | + expect(rebuilt.points[1999].y).toBeCloseTo(original.points[1999].y, 2); | |
| 53 | + }); | |
| 54 | + | |
| 55 | + it("keeps distinct sids as distinct strokes, in order", () => { | |
| 56 | + const a = encodeStrokeSegments({ ...makeStroke(3), color: "#111111" }, "a"); | |
| 57 | + const b = encodeStrokeSegments({ ...makeStroke(3), color: "#222222" }, "b"); | |
| 58 | + const strokes = reassembleStrokes([...a, ...b]); | |
| 59 | + expect(strokes).toHaveLength(2); | |
| 60 | + expect(strokes[0].color).toBe("#111111"); | |
| 61 | + expect(strokes[1].color).toBe("#222222"); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("segmentToStroke paints a single segment's own points", () => { | |
| 65 | + const [payload] = encodeStrokeSegments(makeStroke(4), "s4"); | |
| 66 | + const stroke = segmentToStroke(decodeSegment(payload)!); | |
| 67 | + expect(stroke.points).toHaveLength(4); | |
| 68 | + expect(stroke.erase).toBe(false); | |
| 69 | + }); | |
| 70 | + | |
| 71 | + it("decodeSegment rejects malformed payloads", () => { | |
| 72 | + expect(decodeSegment(null)).toBeNull(); | |
| 73 | + expect(decodeSegment("not json")).toBeNull(); | |
| 74 | + expect(decodeSegment(JSON.stringify({ v: 2, sid: "x" }))).toBeNull(); | |
| 75 | + expect(decodeSegment(JSON.stringify({ v: 1, sid: "x", seg: 0, last: true, color: "#000000", width: 1, erase: false, pts: [[1]] }))).toBeNull(); | |
| 76 | + }); | |
| 77 | + | |
| 78 | + it("skips non-stroke rows during reassembly", () => { | |
| 79 | + const good = encodeStrokeSegments(makeStroke(2), "g"); | |
| 80 | + const strokes = reassembleStrokes([null, "garbage", ...good]); | |
| 81 | + expect(strokes).toHaveLength(1); | |
| 82 | + }); | |
| 83 | +}); |
src/lib/board-stroke-codec.tsadded+172 -0
| @@ -0,0 +1,172 @@ | ||
| 1 | +import type { Point, Stroke } from "./draw-stroke"; | |
| 2 | + | |
| 3 | +// The whiteboard backend caps each stroke `payload` at 4096 bytes | |
| 4 | +// (board.max_stroke_payload_len, published at GET /limits). A long freehand | |
| 5 | +// stroke is split into several segment frames that share one `sid`; the | |
| 6 | +// receiver paints each segment as it arrives (consecutive segments overlap by | |
| 7 | +// one point so the line stays continuous) and can reassemble the full stroke | |
| 8 | +// for history replay. | |
| 9 | +export const MAX_STROKE_PAYLOAD_BYTES = 4096; | |
| 10 | + | |
| 11 | +// A little headroom under the hard cap so we never sit exactly on the byte | |
| 12 | +// boundary the server rejects. | |
| 13 | +const DEFAULT_MAX_BYTES = MAX_STROKE_PAYLOAD_BYTES - 64; | |
| 14 | + | |
| 15 | +// Wire envelope for one segment of a logical stroke. Coordinates are | |
| 16 | +// board-space (device/zoom independent); points travel as [x, y] tuples to | |
| 17 | +// keep the payload small. | |
| 18 | +export type StrokeSegment = { | |
| 19 | + v: 1; | |
| 20 | + sid: string; | |
| 21 | + seg: number; | |
| 22 | + last: boolean; | |
| 23 | + color: string; | |
| 24 | + width: number; | |
| 25 | + erase: boolean; | |
| 26 | + pts: [number, number][]; | |
| 27 | +}; | |
| 28 | + | |
| 29 | +const encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null; | |
| 30 | + | |
| 31 | +function byteLength(text: string): number { | |
| 32 | + return encoder ? encoder.encode(text).length : text.length; | |
| 33 | +} | |
| 34 | + | |
| 35 | +// Board-space may be fractional; two decimals is plenty of fidelity and keeps | |
| 36 | +// the payload compact. | |
| 37 | +function round2(n: number): number { | |
| 38 | + return Math.round(n * 100) / 100; | |
| 39 | +} | |
| 40 | + | |
| 41 | +function segmentString( | |
| 42 | + sid: string, | |
| 43 | + seg: number, | |
| 44 | + last: boolean, | |
| 45 | + stroke: Pick<Stroke, "color" | "width" | "erase">, | |
| 46 | + pts: [number, number][], | |
| 47 | +): string { | |
| 48 | + const envelope: StrokeSegment = { | |
| 49 | + v: 1, | |
| 50 | + sid, | |
| 51 | + seg, | |
| 52 | + last, | |
| 53 | + color: stroke.color, | |
| 54 | + width: stroke.width, | |
| 55 | + erase: stroke.erase, | |
| 56 | + pts, | |
| 57 | + }; | |
| 58 | + return JSON.stringify(envelope); | |
| 59 | +} | |
| 60 | + | |
| 61 | +/** | |
| 62 | + * Serialize one logical stroke into one or more segment payloads, each under | |
| 63 | + * `maxBytes`. Consecutive segments repeat the previous segment's last point as | |
| 64 | + * their first, so painting them in order leaves no gap. A single point whose | |
| 65 | + * envelope already exceeds the cap is still emitted (a point can't be split). | |
| 66 | + */ | |
| 67 | +export function encodeStrokeSegments( | |
| 68 | + stroke: Stroke, | |
| 69 | + sid: string, | |
| 70 | + maxBytes: number = DEFAULT_MAX_BYTES, | |
| 71 | +): string[] { | |
| 72 | + const tuples: [number, number][] = stroke.points.map((p) => [round2(p.x), round2(p.y)]); | |
| 73 | + if (tuples.length === 0) return []; | |
| 74 | + | |
| 75 | + const segments: [number, number][][] = []; | |
| 76 | + let current: [number, number][] = []; | |
| 77 | + | |
| 78 | + for (const pt of tuples) { | |
| 79 | + const candidate = [...current, pt]; | |
| 80 | + // Not the last segment yet (last flag unknown here), so measure with | |
| 81 | + // last:false — the final re-encode below stamps the real flags. | |
| 82 | + const fits = byteLength(segmentString(sid, segments.length, false, stroke, candidate)) <= maxBytes; | |
| 83 | + if (fits || current.length === 0) { | |
| 84 | + current = candidate; | |
| 85 | + } else { | |
| 86 | + segments.push(current); | |
| 87 | + // Overlap one point for continuity across the segment boundary. | |
| 88 | + current = [current[current.length - 1], pt]; | |
| 89 | + } | |
| 90 | + } | |
| 91 | + if (current.length > 0) segments.push(current); | |
| 92 | + | |
| 93 | + return segments.map((pts, i) => | |
| 94 | + segmentString(sid, i, i === segments.length - 1, stroke, pts), | |
| 95 | + ); | |
| 96 | +} | |
| 97 | + | |
| 98 | +function isTuple(v: unknown): v is [number, number] { | |
| 99 | + return ( | |
| 100 | + Array.isArray(v) && | |
| 101 | + v.length === 2 && | |
| 102 | + typeof v[0] === "number" && | |
| 103 | + typeof v[1] === "number" && | |
| 104 | + Number.isFinite(v[0]) && | |
| 105 | + Number.isFinite(v[1]) | |
| 106 | + ); | |
| 107 | +} | |
| 108 | + | |
| 109 | +/** Parse one segment payload, or null on anything malformed (payloads are untrusted). */ | |
| 110 | +export function decodeSegment(payload: string | null): StrokeSegment | null { | |
| 111 | + if (!payload) return null; | |
| 112 | + let data: unknown; | |
| 113 | + try { | |
| 114 | + data = JSON.parse(payload); | |
| 115 | + } catch { | |
| 116 | + return null; | |
| 117 | + } | |
| 118 | + if (!data || typeof data !== "object") return null; | |
| 119 | + const s = data as StrokeSegment; | |
| 120 | + if ( | |
| 121 | + s.v !== 1 || | |
| 122 | + typeof s.sid !== "string" || | |
| 123 | + typeof s.seg !== "number" || | |
| 124 | + typeof s.last !== "boolean" || | |
| 125 | + typeof s.color !== "string" || | |
| 126 | + typeof s.width !== "number" || | |
| 127 | + typeof s.erase !== "boolean" || | |
| 128 | + !Array.isArray(s.pts) || | |
| 129 | + !s.pts.every(isTuple) | |
| 130 | + ) { | |
| 131 | + return null; | |
| 132 | + } | |
| 133 | + return s; | |
| 134 | +} | |
| 135 | + | |
| 136 | +/** One decoded segment as a paintable Stroke (its own points only). */ | |
| 137 | +export function segmentToStroke(seg: StrokeSegment): Stroke { | |
| 138 | + return { | |
| 139 | + color: seg.color, | |
| 140 | + width: seg.width, | |
| 141 | + erase: seg.erase, | |
| 142 | + points: seg.pts.map(([x, y]) => ({ x, y }) as Point), | |
| 143 | + }; | |
| 144 | +} | |
| 145 | + | |
| 146 | +/** | |
| 147 | + * Reassemble full strokes from an ordered list of stroke payloads (e.g. a | |
| 148 | + * history/epoch page). Segments are grouped by `sid` in arrival order; the | |
| 149 | + * overlap point each later segment repeats is dropped so the joined stroke has | |
| 150 | + * no duplicate vertex. Non-stroke rows (null payloads, clear markers) are | |
| 151 | + * skipped by the caller passing only stroke payloads. | |
| 152 | + */ | |
| 153 | +export function reassembleStrokes(payloads: (string | null)[]): Stroke[] { | |
| 154 | + const order: string[] = []; | |
| 155 | + const bySid = new Map<string, Stroke>(); | |
| 156 | + | |
| 157 | + for (const payload of payloads) { | |
| 158 | + const seg = decodeSegment(payload); | |
| 159 | + if (!seg) continue; | |
| 160 | + const pts = seg.pts.map(([x, y]) => ({ x, y }) as Point); | |
| 161 | + const existing = bySid.get(seg.sid); | |
| 162 | + if (!existing) { | |
| 163 | + order.push(seg.sid); | |
| 164 | + bySid.set(seg.sid, { color: seg.color, width: seg.width, erase: seg.erase, points: pts }); | |
| 165 | + } else { | |
| 166 | + // Drop the leading overlap point that duplicates the previous last point. | |
| 167 | + existing.points.push(...(seg.seg > 0 ? pts.slice(1) : pts)); | |
| 168 | + } | |
| 169 | + } | |
| 170 | + | |
| 171 | + return order.map((sid) => bySid.get(sid)!); | |
| 172 | +} |
src/pages/whiteboard-page.tsxadded+308 -0
| @@ -0,0 +1,308 @@ | ||
| 1 | +import { useLocation, useNavigate } from "@tanstack/solid-router"; | |
| 2 | +import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js"; | |
| 3 | +import { | |
| 4 | + deleteBoardById, | |
| 5 | + getBoardEpochs, | |
| 6 | + getBoardHistory, | |
| 7 | + getBoardById, | |
| 8 | + patchBoardById, | |
| 9 | + postBoardClear, | |
| 10 | + postBoardClose, | |
| 11 | +} from "@/api/boards"; | |
| 12 | +import { getUsers } from "@/api/users"; | |
| 13 | +import { formatApiError } from "@/api/client"; | |
| 14 | +import { WhiteboardRoom, type BoardLiveState } from "@/components/whiteboard/whiteboard-room-ws"; | |
| 15 | +import { RouteGuard } from "@/components/layout/route-guard"; | |
| 16 | +import { PageHeader } from "@/components/layout/page-header"; | |
| 17 | +import { Alert } from "@/components/ui/alert"; | |
| 18 | +import { Badge } from "@/components/ui/badge"; | |
| 19 | +import { Button } from "@/components/ui/button"; | |
| 20 | +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | |
| 21 | +import { DrawingPlayback } from "@/components/ui/drawing-playback"; | |
| 22 | +import { IconChevronLeft, IconTrash } from "@/components/ui/icons"; | |
| 23 | +import { PageSpinner } from "@/components/ui/page-spinner"; | |
| 24 | +import { SidePanel } from "@/components/ui/side-panel"; | |
| 25 | +import { reassembleStrokes } from "@/lib/board-stroke-codec"; | |
| 26 | +import { strokesBounds, type DrawScene } from "@/lib/draw-stroke"; | |
| 27 | +import { formatDateTime } from "@/lib/format"; | |
| 28 | +import { useAuth } from "@/stores/auth-context"; | |
| 29 | +import { usePreferences, useT } from "@/stores/preferences-context"; | |
| 30 | + | |
| 31 | +export default function WhiteboardPage() { | |
| 32 | + return ( | |
| 33 | + <RouteGuard minRole="student"> | |
| 34 | + <WhiteboardContent /> | |
| 35 | + </RouteGuard> | |
| 36 | + ); | |
| 37 | +} | |
| 38 | + | |
| 39 | +const EXPORT_MARGIN = 8; | |
| 40 | + | |
| 41 | +// Build a replayable scene from a set of reassembled strokes (an epoch's marks), | |
| 42 | +// shifted into a tight box like the drawing export pipeline. | |
| 43 | +function strokesToScene(strokes: DrawScene["strokes"]): DrawScene | null { | |
| 44 | + const b = strokesBounds(strokes); | |
| 45 | + if (!b) return null; | |
| 46 | + const w = Math.ceil(b.w + EXPORT_MARGIN * 2); | |
| 47 | + const h = Math.ceil(b.h + EXPORT_MARGIN * 2); | |
| 48 | + const dx = EXPORT_MARGIN - b.x; | |
| 49 | + const dy = EXPORT_MARGIN - b.y; | |
| 50 | + const shifted = strokes.map((s) => ({ ...s, points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })) })); | |
| 51 | + return { v: 1, w, h, strokes: shifted, bg: "grid" }; | |
| 52 | +} | |
| 53 | + | |
| 54 | +function WhiteboardContent() { | |
| 55 | + const t = useT(); | |
| 56 | + const { locale } = usePreferences(); | |
| 57 | + const auth = useAuth(); | |
| 58 | + const navigate = useNavigate(); | |
| 59 | + const location = useLocation(); | |
| 60 | + | |
| 61 | + const id = createMemo((prev: string) => { | |
| 62 | + const match = /^\/whiteboards\/([^/]+)$/.exec(location().pathname); | |
| 63 | + return match ? decodeURIComponent(match[1]) : prev; | |
| 64 | + }, ""); | |
| 65 | + | |
| 66 | + const [board] = createResource(id, (boardId) => getBoardById(boardId)); | |
| 67 | + const [users] = createResource(async () => { | |
| 68 | + try { | |
| 69 | + return (await getUsers({ limit: 500 })).items; | |
| 70 | + } catch { | |
| 71 | + return []; | |
| 72 | + } | |
| 73 | + }); | |
| 74 | + | |
| 75 | + // Live board state, seeded from the REST read and updated by the room's socket. | |
| 76 | + const [live, setLive] = createSignal<BoardLiveState>({}); | |
| 77 | + createEffect(() => { | |
| 78 | + const b = board(); | |
| 79 | + if (b) { | |
| 80 | + setLive({ | |
| 81 | + locked: b.locked, | |
| 82 | + closed: b.closed_at != null, | |
| 83 | + creator: b.creator, | |
| 84 | + participants: b.participants, | |
| 85 | + epoch: b.epoch, | |
| 86 | + }); | |
| 87 | + } | |
| 88 | + }); | |
| 89 | + const mergeLive = (patch: BoardLiveState) => setLive((prev) => ({ ...prev, ...patch })); | |
| 90 | + | |
| 91 | + const meId = () => auth.user()?.id ?? ""; | |
| 92 | + const isCreator = () => live().creator === meId(); | |
| 93 | + const locked = () => live().locked ?? false; | |
| 94 | + const closed = () => live().closed ?? false; | |
| 95 | + | |
| 96 | + const nameOf = (userId: string) => { | |
| 97 | + const u = (users() ?? []).find((x) => x.id === userId); | |
| 98 | + if (!u) return userId; | |
| 99 | + return [u.name, u.surname].filter(Boolean).join(" ") || u.username; | |
| 100 | + }; | |
| 101 | + const roster = () => { | |
| 102 | + const creator = live().creator; | |
| 103 | + const parts = live().participants ?? []; | |
| 104 | + return creator ? [creator, ...parts] : parts; | |
| 105 | + }; | |
| 106 | + | |
| 107 | + const [error, setError] = createSignal(""); | |
| 108 | + const [busy, setBusy] = createSignal(false); | |
| 109 | + const [clearOpen, setClearOpen] = createSignal(false); | |
| 110 | + const [closeOpen, setCloseOpen] = createSignal(false); | |
| 111 | + const [deleteOpen, setDeleteOpen] = createSignal(false); | |
| 112 | + const [historyOpen, setHistoryOpen] = createSignal(false); | |
| 113 | + | |
| 114 | + const run = async (fn: () => Promise<void>) => { | |
| 115 | + setBusy(true); | |
| 116 | + setError(""); | |
| 117 | + try { | |
| 118 | + await fn(); | |
| 119 | + } catch (err) { | |
| 120 | + setError(formatApiError(err, locale())); | |
| 121 | + } finally { | |
| 122 | + setBusy(false); | |
| 123 | + } | |
| 124 | + }; | |
| 125 | + | |
| 126 | + const toggleLock = () => | |
| 127 | + run(async () => { | |
| 128 | + const next = !locked(); | |
| 129 | + await patchBoardById(id(), { locked: next }); | |
| 130 | + mergeLive({ locked: next }); | |
| 131 | + }); | |
| 132 | + const doClear = () => run(async () => void (await postBoardClear(id()))); | |
| 133 | + const doClose = () => | |
| 134 | + run(async () => { | |
| 135 | + await postBoardClose(id()); | |
| 136 | + mergeLive({ closed: true }); | |
| 137 | + }); | |
| 138 | + const doDelete = () => | |
| 139 | + run(async () => { | |
| 140 | + await deleteBoardById(id()); | |
| 141 | + navigate({ to: "/whiteboards" }); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + return ( | |
| 145 | + <Suspense fallback={<PageSpinner />}> | |
| 146 | + <Show | |
| 147 | + when={board()?.id === id() ? board() : undefined} | |
| 148 | + fallback={ | |
| 149 | + <Show when={board.error} fallback={<PageSpinner />}> | |
| 150 | + <Alert variant="destructive">{t("whiteboard.notFound")}</Alert> | |
| 151 | + </Show> | |
| 152 | + } | |
| 153 | + > | |
| 154 | + {(b) => ( | |
| 155 | + <div class="space-y-4"> | |
| 156 | + <PageHeader | |
| 157 | + compact | |
| 158 | + title={b().title} | |
| 159 | + actions={ | |
| 160 | + <div class="flex flex-wrap items-center gap-1.5"> | |
| 161 | + <Button type="button" variant="ghost" size="sm" onClick={() => navigate({ to: "/whiteboards" })}> | |
| 162 | + <IconChevronLeft class="h-4 w-4" /> | |
| 163 | + {t("common.back")} | |
| 164 | + </Button> | |
| 165 | + <Button type="button" variant="outline" size="sm" onClick={() => setHistoryOpen(true)}> | |
| 166 | + {t("whiteboard.history")} | |
| 167 | + </Button> | |
| 168 | + <Show when={isCreator() && !closed()}> | |
| 169 | + <Button type="button" variant="outline" size="sm" disabled={busy()} onClick={() => void toggleLock()}> | |
| 170 | + {locked() ? t("whiteboard.unlock") : t("whiteboard.lock")} | |
| 171 | + </Button> | |
| 172 | + <Button type="button" variant="outline" size="sm" disabled={busy()} onClick={() => setClearOpen(true)}> | |
| 173 | + {t("whiteboard.clear")} | |
| 174 | + </Button> | |
| 175 | + <Button type="button" variant="outline" size="sm" disabled={busy()} onClick={() => setCloseOpen(true)}> | |
| 176 | + {t("whiteboard.close")} | |
| 177 | + </Button> | |
| 178 | + </Show> | |
| 179 | + <Show when={isCreator()}> | |
| 180 | + <Button type="button" variant="outline" size="sm" class="text-destructive" disabled={busy()} onClick={() => setDeleteOpen(true)}> | |
| 181 | + <IconTrash class="h-4 w-4" /> | |
| 182 | + {t("whiteboard.delete")} | |
| 183 | + </Button> | |
| 184 | + </Show> | |
| 185 | + </div> | |
| 186 | + } | |
| 187 | + /> | |
| 188 | + | |
| 189 | + <Show when={error()}> | |
| 190 | + <Alert variant="destructive">{error()}</Alert> | |
| 191 | + </Show> | |
| 192 | + | |
| 193 | + <div class="grid gap-4 lg:grid-cols-[minmax(0,1fr)_15rem]"> | |
| 194 | + <WhiteboardRoom | |
| 195 | + board={b()} | |
| 196 | + meId={meId()} | |
| 197 | + onState={mergeLive} | |
| 198 | + onDeleted={() => navigate({ to: "/whiteboards" })} | |
| 199 | + /> | |
| 200 | + <aside class="space-y-2 rounded-xl border bg-card p-3"> | |
| 201 | + <h3 class="text-sm font-semibold">{t("whiteboard.roster")}</h3> | |
| 202 | + <ul class="space-y-1"> | |
| 203 | + <For each={roster()}> | |
| 204 | + {(userId) => ( | |
| 205 | + <li class="flex items-center justify-between gap-2 text-sm"> | |
| 206 | + <span class="min-w-0 truncate">{nameOf(userId)}</span> | |
| 207 | + <Show when={userId === live().creator}> | |
| 208 | + <Badge variant="outline" class="rounded-full text-xs">{t("whiteboard.creator")}</Badge> | |
| 209 | + </Show> | |
| 210 | + </li> | |
| 211 | + )} | |
| 212 | + </For> | |
| 213 | + </ul> | |
| 214 | + </aside> | |
| 215 | + </div> | |
| 216 | + | |
| 217 | + <HistoryPanel open={historyOpen()} onOpenChange={setHistoryOpen} boardId={id()} /> | |
| 218 | + | |
| 219 | + <ConfirmDialog | |
| 220 | + open={clearOpen()} | |
| 221 | + onOpenChange={setClearOpen} | |
| 222 | + title={t("whiteboard.clear")} | |
| 223 | + description={t("whiteboard.clearConfirm")} | |
| 224 | + summary={b().title} | |
| 225 | + onConfirm={doClear} | |
| 226 | + /> | |
| 227 | + <ConfirmDialog | |
| 228 | + open={closeOpen()} | |
| 229 | + onOpenChange={setCloseOpen} | |
| 230 | + variant="destructive" | |
| 231 | + title={t("whiteboard.close")} | |
| 232 | + description={t("whiteboard.closeConfirm")} | |
| 233 | + summary={b().title} | |
| 234 | + onConfirm={doClose} | |
| 235 | + /> | |
| 236 | + <ConfirmDialog | |
| 237 | + open={deleteOpen()} | |
| 238 | + onOpenChange={setDeleteOpen} | |
| 239 | + variant="destructive" | |
| 240 | + title={t("whiteboard.delete")} | |
| 241 | + description={t("whiteboard.deleteConfirm")} | |
| 242 | + summary={b().title} | |
| 243 | + onConfirm={doDelete} | |
| 244 | + /> | |
| 245 | + </div> | |
| 246 | + )} | |
| 247 | + </Show> | |
| 248 | + </Suspense> | |
| 249 | + ); | |
| 250 | +} | |
| 251 | + | |
| 252 | +function HistoryPanel(props: { open: boolean; onOpenChange: (open: boolean) => void; boardId: string }) { | |
| 253 | + const t = useT(); | |
| 254 | + const { locale } = usePreferences(); | |
| 255 | + const [selectedEpoch, setSelectedEpoch] = createSignal<number | null>(null); | |
| 256 | + | |
| 257 | + // Only fetch the epoch index while the panel is open. | |
| 258 | + const [epochs] = createResource( | |
| 259 | + () => (props.open ? props.boardId : null), | |
| 260 | + async (boardId) => (await getBoardEpochs(boardId, { limit: 100 })).items, | |
| 261 | + ); | |
| 262 | + | |
| 263 | + const [scene] = createResource( | |
| 264 | + () => (selectedEpoch() != null ? { boardId: props.boardId, epoch: selectedEpoch()! } : null), | |
| 265 | + async (arg) => { | |
| 266 | + const page = await getBoardHistory(arg.boardId, { epoch: arg.epoch, limit: 500 }); | |
| 267 | + const strokes = reassembleStrokes(page.items.filter((r) => r.kind === "stroke").map((r) => r.payload)); | |
| 268 | + return strokesToScene(strokes); | |
| 269 | + }, | |
| 270 | + ); | |
| 271 | + | |
| 272 | + return ( | |
| 273 | + <SidePanel open={props.open} onOpenChange={props.onOpenChange} title={t("whiteboard.history")} size="wide"> | |
| 274 | + <div class="space-y-4"> | |
| 275 | + <Suspense fallback={<PageSpinner />}> | |
| 276 | + <Show | |
| 277 | + when={(epochs() ?? []).length > 0} | |
| 278 | + fallback={<p class="text-sm text-muted-foreground">{t("whiteboard.noHistory")}</p>} | |
| 279 | + > | |
| 280 | + <div class="flex flex-wrap gap-2"> | |
| 281 | + <For each={epochs()}> | |
| 282 | + {(marker) => ( | |
| 283 | + <Button | |
| 284 | + type="button" | |
| 285 | + variant={selectedEpoch() === marker.epoch ? "default" : "outline"} | |
| 286 | + size="sm" | |
| 287 | + onClick={() => setSelectedEpoch(marker.epoch)} | |
| 288 | + > | |
| 289 | + {t("whiteboard.replaySession")} {marker.epoch} | |
| 290 | + <span class="ml-1 text-xs text-muted-foreground">· {formatDateTime(marker.created_at, locale())}</span> | |
| 291 | + </Button> | |
| 292 | + )} | |
| 293 | + </For> | |
| 294 | + </div> | |
| 295 | + </Show> | |
| 296 | + </Suspense> | |
| 297 | + | |
| 298 | + <Show when={selectedEpoch() != null}> | |
| 299 | + <Suspense fallback={<PageSpinner />}> | |
| 300 | + <Show when={scene()} fallback={<p class="text-sm text-muted-foreground">{t("whiteboard.noHistory")}</p>}> | |
| 301 | + {(s) => <DrawingPlayback scene={s()} />} | |
| 302 | + </Show> | |
| 303 | + </Suspense> | |
| 304 | + </Show> | |
| 305 | + </div> | |
| 306 | + </SidePanel> | |
| 307 | + ); | |
| 308 | +} |
src/pages/whiteboards-page.tsxadded+234 -0
| @@ -0,0 +1,234 @@ | ||
| 1 | +import { useNavigate } from "@tanstack/solid-router"; | |
| 2 | +import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js"; | |
| 3 | +import { getBoards, postBoard, type Board } from "@/api/boards"; | |
| 4 | +import { getUsers } from "@/api/users"; | |
| 5 | +import { formatApiError, type User } from "@/api/client"; | |
| 6 | +import { RouteGuard } from "@/components/layout/route-guard"; | |
| 7 | +import { PageHeader } from "@/components/layout/page-header"; | |
| 8 | +import { Badge } from "@/components/ui/badge"; | |
| 9 | +import { Button } from "@/components/ui/button"; | |
| 10 | +import { EmptyState } from "@/components/ui/empty-state"; | |
| 11 | +import { ErrorAlert } from "@/components/ui/error-alert"; | |
| 12 | +import { IconPlus, IconX } from "@/components/ui/icons"; | |
| 13 | +import { Input } from "@/components/ui/input"; | |
| 14 | +import { Label } from "@/components/ui/label"; | |
| 15 | +import { PageSpinner } from "@/components/ui/page-spinner"; | |
| 16 | +import { SidePanel } from "@/components/ui/side-panel"; | |
| 17 | +import { formatDate } from "@/lib/format"; | |
| 18 | +import { useAuth } from "@/stores/auth-context"; | |
| 19 | +import { usePreferences, useT } from "@/stores/preferences-context"; | |
| 20 | + | |
| 21 | +export default function WhiteboardsPage() { | |
| 22 | + return ( | |
| 23 | + <RouteGuard minRole="student"> | |
| 24 | + <WhiteboardsContent /> | |
| 25 | + </RouteGuard> | |
| 26 | + ); | |
| 27 | +} | |
| 28 | + | |
| 29 | +function WhiteboardsContent() { | |
| 30 | + const t = useT(); | |
| 31 | + const { locale } = usePreferences(); | |
| 32 | + const auth = useAuth(); | |
| 33 | + const navigate = useNavigate(); | |
| 34 | + | |
| 35 | + const [boards, { refetch }] = createResource(async () => (await getBoards({ limit: 200 })).items); | |
| 36 | + const [createOpen, setCreateOpen] = createSignal(false); | |
| 37 | + | |
| 38 | + const meId = () => auth.user()?.id ?? ""; | |
| 39 | + | |
| 40 | + return ( | |
| 41 | + <div class="space-y-5"> | |
| 42 | + <PageHeader | |
| 43 | + title={t("whiteboard.title")} | |
| 44 | + description={t("whiteboard.subtitle")} | |
| 45 | + actions={ | |
| 46 | + <Button type="button" onClick={() => setCreateOpen(true)}> | |
| 47 | + <IconPlus class="h-4 w-4" /> | |
| 48 | + {t("whiteboard.create")} | |
| 49 | + </Button> | |
| 50 | + } | |
| 51 | + /> | |
| 52 | + | |
| 53 | + <Suspense fallback={<PageSpinner />}> | |
| 54 | + <Show when={boards.error}> | |
| 55 | + <ErrorAlert message={formatApiError(boards.error, locale())} /> | |
| 56 | + </Show> | |
| 57 | + <Show | |
| 58 | + when={(boards() ?? []).length > 0} | |
| 59 | + fallback={<EmptyState title={t("whiteboard.empty")} description={t("whiteboard.subtitle")} />} | |
| 60 | + > | |
| 61 | + <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3"> | |
| 62 | + <For each={boards()}> | |
| 63 | + {(board) => ( | |
| 64 | + <BoardCard | |
| 65 | + board={board} | |
| 66 | + isCreator={board.creator === meId()} | |
| 67 | + onOpen={() => navigate({ to: "/whiteboards/$id", params: { id: board.id } })} | |
| 68 | + createdLabel={formatDate(board.created_at, locale())} | |
| 69 | + /> | |
| 70 | + )} | |
| 71 | + </For> | |
| 72 | + </div> | |
| 73 | + </Show> | |
| 74 | + </Suspense> | |
| 75 | + | |
| 76 | + <CreateBoardPanel | |
| 77 | + open={createOpen()} | |
| 78 | + onOpenChange={setCreateOpen} | |
| 79 | + onCreated={(board) => { | |
| 80 | + setCreateOpen(false); | |
| 81 | + void refetch(); | |
| 82 | + navigate({ to: "/whiteboards/$id", params: { id: board.id } }); | |
| 83 | + }} | |
| 84 | + /> | |
| 85 | + </div> | |
| 86 | + ); | |
| 87 | +} | |
| 88 | + | |
| 89 | +function BoardCard(props: { board: Board; isCreator: boolean; onOpen: () => void; createdLabel: string }) { | |
| 90 | + const t = useT(); | |
| 91 | + return ( | |
| 92 | + <div class="flex flex-col gap-3 rounded-xl border bg-card p-4 shadow-xs"> | |
| 93 | + <div class="flex items-start justify-between gap-2"> | |
| 94 | + <h3 class="min-w-0 truncate font-semibold">{props.board.title}</h3> | |
| 95 | + <div class="flex shrink-0 gap-1"> | |
| 96 | + <Show when={props.board.closed_at != null}> | |
| 97 | + <Badge variant="outline" class="rounded-full text-amber-600">{t("whiteboard.closedBadge")}</Badge> | |
| 98 | + </Show> | |
| 99 | + <Show when={props.board.locked && props.board.closed_at == null}> | |
| 100 | + <Badge variant="outline" class="rounded-full">{t("whiteboard.lockedBadge")}</Badge> | |
| 101 | + </Show> | |
| 102 | + <Show when={props.isCreator}> | |
| 103 | + <Badge variant="outline" class="rounded-full">{t("whiteboard.creator")}</Badge> | |
| 104 | + </Show> | |
| 105 | + </div> | |
| 106 | + </div> | |
| 107 | + <p class="text-xs text-muted-foreground"> | |
| 108 | + {t("whiteboard.createdAt")}: {props.createdLabel} · {props.board.participants.length + 1} {t("whiteboard.participants").toLowerCase()} | |
| 109 | + </p> | |
| 110 | + <Button type="button" variant="outline" size="sm" class="mt-auto w-full" onClick={props.onOpen}> | |
| 111 | + {t("whiteboard.open")} | |
| 112 | + </Button> | |
| 113 | + </div> | |
| 114 | + ); | |
| 115 | +} | |
| 116 | + | |
| 117 | +function CreateBoardPanel(props: { | |
| 118 | + open: boolean; | |
| 119 | + onOpenChange: (open: boolean) => void; | |
| 120 | + onCreated: (board: Board) => void; | |
| 121 | +}) { | |
| 122 | + const t = useT(); | |
| 123 | + const { locale } = usePreferences(); | |
| 124 | + const [title, setTitle] = createSignal(""); | |
| 125 | + const [query, setQuery] = createSignal(""); | |
| 126 | + const [selected, setSelected] = createSignal<User[]>([]); | |
| 127 | + const [pending, setPending] = createSignal(false); | |
| 128 | + const [error, setError] = createSignal(""); | |
| 129 | + | |
| 130 | + // Parents can never be on a roster (backend 400s them), so they are filtered out. | |
| 131 | + const [candidates] = createResource(async () => | |
| 132 | + (await getUsers({ limit: 500 })).items.filter((u) => u.role !== "parent"), | |
| 133 | + ); | |
| 134 | + | |
| 135 | + const selectedIds = createMemo(() => new Set(selected().map((u) => u.id))); | |
| 136 | + const filtered = createMemo(() => { | |
| 137 | + const q = query().trim().toLowerCase(); | |
| 138 | + const me = undefined; | |
| 139 | + return (candidates() ?? []) | |
| 140 | + .filter((u) => u !== me && !selectedIds().has(u.id)) | |
| 141 | + .filter((u) => !q || u.username.toLowerCase().includes(q) || (u.name ?? "").toLowerCase().includes(q)) | |
| 142 | + .slice(0, 8); | |
| 143 | + }); | |
| 144 | + | |
| 145 | + const label = (u: User) => [u.name, u.surname].filter(Boolean).join(" ") || u.username; | |
| 146 | + | |
| 147 | + const submit = async () => { | |
| 148 | + if (!title().trim()) return; | |
| 149 | + setPending(true); | |
| 150 | + setError(""); | |
| 151 | + try { | |
| 152 | + const board = await postBoard({ | |
| 153 | + title: title().trim(), | |
| 154 | + participants: selected().map((u) => u.id), | |
| 155 | + }); | |
| 156 | + setTitle(""); | |
| 157 | + setSelected([]); | |
| 158 | + setQuery(""); | |
| 159 | + props.onCreated(board); | |
| 160 | + } catch (err) { | |
| 161 | + setError(formatApiError(err, locale())); | |
| 162 | + } finally { | |
| 163 | + setPending(false); | |
| 164 | + } | |
| 165 | + }; | |
| 166 | + | |
| 167 | + return ( | |
| 168 | + <SidePanel open={props.open} onOpenChange={props.onOpenChange} title={t("whiteboard.create")}> | |
| 169 | + <div class="space-y-4"> | |
| 170 | + <Show when={error()}> | |
| 171 | + <ErrorAlert message={error()} /> | |
| 172 | + </Show> | |
| 173 | + <div class="space-y-1.5"> | |
| 174 | + <Label>{t("whiteboard.titleLabel")}</Label> | |
| 175 | + <Input value={title()} maxlength={200} onInput={(e) => setTitle(e.currentTarget.value)} /> | |
| 176 | + </div> | |
| 177 | + | |
| 178 | + <div class="space-y-1.5"> | |
| 179 | + <Label>{t("whiteboard.participants")}</Label> | |
| 180 | + <p class="text-xs text-muted-foreground">{t("whiteboard.participantsHint")}</p> | |
| 181 | + <Show when={selected().length > 0}> | |
| 182 | + <div class="flex flex-wrap gap-1.5"> | |
| 183 | + <For each={selected()}> | |
| 184 | + {(u) => ( | |
| 185 | + <button | |
| 186 | + type="button" | |
| 187 | + class="inline-flex items-center gap-1 rounded-full border bg-muted px-2 py-0.5 text-xs" | |
| 188 | + onClick={() => setSelected((prev) => prev.filter((x) => x.id !== u.id))} | |
| 189 | + > | |
| 190 | + {label(u)} | |
| 191 | + <IconX class="h-3 w-3" /> | |
| 192 | + </button> | |
| 193 | + )} | |
| 194 | + </For> | |
| 195 | + </div> | |
| 196 | + </Show> | |
| 197 | + <Input | |
| 198 | + placeholder={t("whiteboard.addParticipant")} | |
| 199 | + value={query()} | |
| 200 | + onInput={(e) => setQuery(e.currentTarget.value)} | |
| 201 | + /> | |
| 202 | + <Show when={query().trim() && filtered().length > 0}> | |
| 203 | + <div class="rounded-lg border"> | |
| 204 | + <For each={filtered()}> | |
| 205 | + {(u) => ( | |
| 206 | + <button | |
| 207 | + type="button" | |
| 208 | + class="flex w-full items-center justify-between px-3 py-2 text-left text-sm hover:bg-accent" | |
| 209 | + onClick={() => { | |
| 210 | + setSelected((prev) => [...prev, u]); | |
| 211 | + setQuery(""); | |
| 212 | + }} | |
| 213 | + > | |
| 214 | + <span class="truncate">{label(u)}</span> | |
| 215 | + <span class="text-xs text-muted-foreground">{u.role}</span> | |
| 216 | + </button> | |
| 217 | + )} | |
| 218 | + </For> | |
| 219 | + </div> | |
| 220 | + </Show> | |
| 221 | + </div> | |
| 222 | + | |
| 223 | + <div class="flex justify-end gap-2 pt-2"> | |
| 224 | + <Button type="button" variant="outline" onClick={() => props.onOpenChange(false)}> | |
| 225 | + {t("common.cancel")} | |
| 226 | + </Button> | |
| 227 | + <Button type="button" disabled={pending() || !title().trim()} onClick={() => void submit()}> | |
| 228 | + {t("whiteboard.create")} | |
| 229 | + </Button> | |
| 230 | + </div> | |
| 231 | + </div> | |
| 232 | + </SidePanel> | |
| 233 | + ); | |
| 234 | +} |
src/routes/router.tsxmodified+16 -0
| @@ -61,6 +61,8 @@ const MealsPage = lazyRoute(() => import("@/pages/meals-page")); | ||
| 61 | 61 | const MealDetailPage = lazyRoute(() => import("@/pages/meal-detail-page")); |
| 62 | 62 | const PaymentsPage = lazyRoute(() => import("@/pages/payments-page")); |
| 63 | 63 | const PaymentStatementPage = lazyRoute(() => import("@/pages/payment-statement-page")); |
| 64 | +const WhiteboardsPage = lazyRoute(() => import("@/pages/whiteboards-page")); | |
| 65 | +const WhiteboardPage = lazyRoute(() => import("@/pages/whiteboard-page")); | |
| 64 | 66 | |
| 65 | 67 | function RootComponent() { |
| 66 | 68 | return ( |
| @@ -357,6 +359,18 @@ const paymentStatementRoute = createRoute({ | ||
| 357 | 359 | component: PaymentStatementPage, |
| 358 | 360 | }); |
| 359 | 361 | |
| 362 | +const whiteboardsRoute = createRoute({ | |
| 363 | + getParentRoute: () => rootRoute, | |
| 364 | + path: "/whiteboards", | |
| 365 | + component: WhiteboardsPage, | |
| 366 | +}); | |
| 367 | + | |
| 368 | +const whiteboardRoute = createRoute({ | |
| 369 | + getParentRoute: () => rootRoute, | |
| 370 | + path: "/whiteboards/$id", | |
| 371 | + component: WhiteboardPage, | |
| 372 | +}); | |
| 373 | + | |
| 360 | 374 | const routeTree = rootRoute.addChildren([ |
| 361 | 375 | indexRoute, |
| 362 | 376 | loginRoute, |
| @@ -401,6 +415,8 @@ const routeTree = rootRoute.addChildren([ | ||
| 401 | 415 | paymentsRoute, |
| 402 | 416 | managedPaymentDetailRoute, |
| 403 | 417 | paymentStatementRoute, |
| 418 | + whiteboardsRoute, | |
| 419 | + whiteboardRoute, | |
| 404 | 420 | ]); |
| 405 | 421 | |
| 406 | 422 | function RouterPending() { |
src/stores/preferences-context.tsxmodified+10 -3
| @@ -20,7 +20,7 @@ type PreferencesContextValue = { | ||
| 20 | 20 | paletteColor: Accessor<string | null>; |
| 21 | 21 | setPaletteColor: (color: string | null) => void; |
| 22 | 22 | toggleTheme: () => void; |
| 23 | - hydratePreferences: (user: Pick<User, "theme" | "language">) => void; | |
| 23 | + hydratePreferences: (user: Pick<User, "theme" | "language" | "palette_color">) => void; | |
| 24 | 24 | sidebarCollapsed: Accessor<boolean>; |
| 25 | 25 | setSidebarCollapsed: (collapsed: boolean) => void; |
| 26 | 26 | toggleSidebar: () => void; |
| @@ -182,15 +182,22 @@ export function PreferencesProvider(props: ParentProps) { | ||
| 182 | 182 | persistPreferences({ theme: th }); |
| 183 | 183 | }; |
| 184 | 184 | const setPaletteColor = (color: string | null) => { |
| 185 | - setPaletteColorSignal(color && HEX_COLOR.test(color) ? color.toLowerCase() : null); | |
| 185 | + const next = color && HEX_COLOR.test(color) ? color.toLowerCase() : null; | |
| 186 | + setPaletteColorSignal(next); | |
| 187 | + // Empty string clears the accent back to "never chose" on the backend; a | |
| 188 | + // valid hex sets it. Mirrors the theme/language sync. | |
| 189 | + persistPreferences({ palette_color: next ?? "" }); | |
| 186 | 190 | }; |
| 187 | 191 | const toggleTheme = () => { |
| 188 | 192 | const next = theme() === "dark" ? "light" : "dark"; |
| 189 | 193 | setTheme(next); |
| 190 | 194 | }; |
| 191 | - const hydratePreferences = (user: Pick<User, "theme" | "language">) => { | |
| 195 | + const hydratePreferences = (user: Pick<User, "theme" | "language" | "palette_color">) => { | |
| 192 | 196 | if (user.language === "en" || user.language === "tr") setLocaleSignal(user.language); |
| 193 | 197 | if (user.theme === "light" || user.theme === "dark") setThemeSignal(user.theme); |
| 198 | + if (user.palette_color && HEX_COLOR.test(user.palette_color)) { | |
| 199 | + setPaletteColorSignal(user.palette_color.toLowerCase()); | |
| 200 | + } | |
| 194 | 201 | }; |
| 195 | 202 | const setSidebarCollapsed = (v: boolean) => setSidebarCollapsedSignal(v); |
| 196 | 203 | const toggleSidebar = () => setSidebarCollapsedSignal((v) => !v); |