From 6f21fd4b5dc6d737e0705a99f8bf77335abc370c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:18:25 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=A8=20Excalidraw-style=20white?= =?UTF-8?q?boards=20-=20board=20page=20fills=20the=20content=20column=20ed?= =?UTF-8?q?ge=20to=20edge:=20board=20menu=20top-left=20=20=20(back,=20hist?= =?UTF-8?q?ory,=20edit,=20lock,=20clear,=20close,=20delete),=20roster=20av?= =?UTF-8?q?atars=20with=20=20=20a=20popover,=20one-click=20lock=20and=20in?= =?UTF-8?q?vite=20top-right,=20status=20banner=20under=20=20=20the=20tools?= =?UTF-8?q?;=20the=20old=20header=20and=20roster=20aside=20are=20gone=20-?= =?UTF-8?q?=20tool=20island=20top-centre=20with=20H/P/R/D/O/A/L/E=20shortc?= =?UTF-8?q?uts;=20style=20island=20=20=20with=20Excalidraw's=20palette,=20?= =?UTF-8?q?three=20widths,=20solid/dashed/dotted=20and=20=20=20architect/a?= =?UTF-8?q?rtist/cartoonist=20sloppiness;=20zoom=20and=20grid=20bottom-lef?= =?UTF-8?q?t=20-=20rectangle,=20diamond,=20ellipse,=20line=20and=20arrow?= =?UTF-8?q?=20are=20baked=20into=20ordinary=20=20=20strokes=20(lib/board-s?= =?UTF-8?q?hapes),=20Shift=20squares=20boxes=20and=20snaps=20lines=20to=20?= =?UTF-8?q?45=C2=B0=20-=20object=20eraser:=20swept=20strokes=20fade=20and?= =?UTF-8?q?=20are=20removed=20whole=20on=20release,=20=20=20logged=20as=20?= =?UTF-8?q?an=20append-only=20marker=20listing=20the=20removed=20sids;=20l?= =?UTF-8?q?ive=20=20=20clients=20and=20history=20replay=20drop=20them=20-?= =?UTF-8?q?=20optional=20`dash`=20field=20on=20strokes=20and=20segments;?= =?UTF-8?q?=20solid=20payloads=20unchanged=20-=20wheel=20pans,=20Ctrl+whee?= =?UTF-8?q?l/pinch=20zooms=20to=20the=20pointer,=20Space-drag=20pans,=20?= =?UTF-8?q?=20=20Ctrl=20+/-/0=20zoom;=20the=20dark=20theme=20inverts=20the?= =?UTF-8?q?=20canvas=20like=20Excalidraw=20-=20closing=20is=20final=20by?= =?UTF-8?q?=20backend=20design,=20so=20the=20close=20confirmation=20says?= =?UTF-8?q?=20so=20=20=20and=20points=20to=20lock=20for=20a=20pause?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/skills/ui-conventions/SKILL.md | 1 + src/components/ui/icons.tsx | 30 + .../whiteboard/whiteboard-canvas.tsx | 830 +++++++++++++----- .../whiteboard/whiteboard-room-ws.tsx | 78 +- src/i18n/locales/en.ts | 32 +- src/i18n/locales/tr.ts | 32 +- src/i18n/messages.ts | 28 + src/lib/board-hit.test.ts | 48 + src/lib/board-hit.ts | 72 ++ src/lib/board-shapes.test.ts | 65 ++ src/lib/board-shapes.ts | 194 ++++ src/lib/board-stroke-codec.test.ts | 43 + src/lib/board-stroke-codec.ts | 57 +- src/lib/draw-stroke.test.ts | 20 + src/lib/draw-stroke.ts | 16 +- src/pages/whiteboard-page.tsx | 317 ++++--- 16 files changed, 1466 insertions(+), 397 deletions(-) create mode 100644 src/lib/board-hit.test.ts create mode 100644 src/lib/board-hit.ts create mode 100644 src/lib/board-shapes.test.ts create mode 100644 src/lib/board-shapes.ts diff --git a/.claude/skills/ui-conventions/SKILL.md b/.claude/skills/ui-conventions/SKILL.md index 6de0328..16ad056 100644 --- a/.claude/skills/ui-conventions/SKILL.md +++ b/.claude/skills/ui-conventions/SKILL.md @@ -79,3 +79,4 @@ Active project reference docs (read the relevant one before changing that area): - **Notes editor:** Personal notes open as full pages — `/notes/new` and `/notes/$id` (`NoteDocument`) — not side panels. Bodies are HTML written by `NoteRichEditor` (contentEditable, sticky toolbar, ⌘S save, ⌘K link, unsaved-changes blocker); course notes use the same editor inside `NoteForm`. Stored Markdown-ish bodies (imports, older notes) load through `toRichTextHtml`. - **Rendering stored HTML:** anything a user wrote that reaches `innerHTML` (notes, messages, homework submissions) goes through `sanitizeRichText` / `toRichTextHtml` from `src/lib/rich-text.ts`. Card excerpts use `richTextExcerpt` (plain text), never `innerHTML`. - **Drawing Canvas (`DrawCanvas`):** Freehand drawings saved as `.hzdraw.png` with embedded scene JSON metadata. Live drawing effects must guard `initialScene` against re-initializing during active strokes. +- **Whiteboard (`WhiteboardCanvas`):** Excalidraw-style, edge to edge on `/whiteboards/$id` — top-centre tool island (H/P/R/D/O/A/L/E shortcuts), left style island, board menu top-left (history, edit, lock/clear/close, delete), roster avatars + lock + invite top-right, status banner under the tools, zoom bottom-left; Space/scroll pans, Ctrl+scroll zooms. The board backend stores only an append-only log of opaque stroke payloads: shapes are baked into ordinary strokes (`src/lib/board-shapes.ts`), and the object eraser logs a marker payload whose `del` lists the removed sids (`encodeEraseMarkers`) — markers count toward the epoch stroke cap. A closed board cannot be reopened (backend by design); lock is the reversible pause. Never add a shape/text wire kind without a backend contract for it. diff --git a/src/components/ui/icons.tsx b/src/components/ui/icons.tsx index 48c894b..a3c571f 100644 --- a/src/components/ui/icons.tsx +++ b/src/components/ui/icons.tsx @@ -41,6 +41,12 @@ import magnifyingGlassUrl from "@phosphor-icons/core/regular/magnifying-glass.sv import packageUrl from "@phosphor-icons/core/regular/package.svg?url"; import paperPlaneTiltUrl from "@phosphor-icons/core/regular/paper-plane-tilt.svg?url"; import pencilSimpleUrl from "@phosphor-icons/core/regular/pencil-simple.svg?url"; +import handUrl from "@phosphor-icons/core/regular/hand.svg?url"; +import squareUrl from "@phosphor-icons/core/regular/square.svg?url"; +import diamondUrl from "@phosphor-icons/core/regular/diamond.svg?url"; +import circleUrl from "@phosphor-icons/core/regular/circle.svg?url"; +import arrowRightUrl from "@phosphor-icons/core/regular/arrow-right.svg?url"; +import lineSegmentUrl from "@phosphor-icons/core/regular/line-segment.svg?url"; import plusUrl from "@phosphor-icons/core/regular/plus.svg?url"; import questionUrl from "@phosphor-icons/core/regular/question.svg?url"; import scanUrl from "@phosphor-icons/core/regular/scan.svg?url"; @@ -209,6 +215,30 @@ export function IconEdit(props: IconProps) { return ; } +export function IconHand(props: IconProps) { + return ; +} + +export function IconSquare(props: IconProps) { + return ; +} + +export function IconDiamond(props: IconProps) { + return ; +} + +export function IconCircle(props: IconProps) { + return ; +} + +export function IconArrowRight(props: IconProps) { + return ; +} + +export function IconLineSegment(props: IconProps) { + return ; +} + export function IconEraser(props: IconProps) { return ( diff --git a/src/components/whiteboard/whiteboard-canvas.tsx b/src/components/whiteboard/whiteboard-canvas.tsx index 8dfb994..0012ca7 100644 --- a/src/components/whiteboard/whiteboard-canvas.tsx +++ b/src/components/whiteboard/whiteboard-canvas.tsx @@ -1,41 +1,104 @@ -import { For, Show, createSignal, onCleanup, onMount } from "solid-js"; +import { For, Show, createSignal, onCleanup, onMount, type JSX } from "solid-js"; import { FullscreenToggle } from "@/components/ui/fullscreen-toggle"; -import { IconEdit, IconEraser, IconMove, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; +import { + IconArrowRight, + IconCircle, + IconDiamond, + IconEdit, + IconEraser, + IconGrid, + IconHand, + IconLineSegment, + IconSquare, +} from "@/components/ui/icons"; import { cn } from "@/lib/cn"; import { FULLSCREEN_ROOT_CLASS, createFullscreen } from "@/lib/fullscreen"; +import { constrainEnd, shapeStrokes, type ShapeKind, type Sloppiness } from "@/lib/board-shapes"; +import { strokeHit } from "@/lib/board-hit"; +import type { BoardStroke } from "@/lib/board-stroke-codec"; import { PAPER_CELL, PAPER_LINE, paintStroke, - paintTip, type Point, type Stroke, + type StrokeDash, } from "@/lib/draw-stroke"; import type { MessageKey } from "@/i18n/messages"; import { useT } from "@/stores/preferences-context"; -const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; +// Layout and vocabulary follow Excalidraw: a tool island top-centre with a +// single-letter shortcut on every tool, a style island on the left while a +// drawing tool is active, zoom bottom-left, the hand tool on Space / scroll. + +type Tool = "hand" | "pen" | ShapeKind | "eraser"; + +const TOOLS: { tool: Tool; key: string; label: MessageKey; icon: (p: { class?: string }) => JSX.Element }[] = [ + { tool: "hand", key: "H", label: "draw.pan", icon: IconHand }, + { tool: "pen", key: "P", label: "draw.pen", icon: IconEdit }, + { tool: "rectangle", key: "R", label: "draw.rectangle", icon: IconSquare }, + { tool: "diamond", key: "D", label: "draw.diamond", icon: IconDiamond }, + { tool: "ellipse", key: "O", label: "draw.ellipse", icon: IconCircle }, + { tool: "arrow", key: "A", label: "draw.arrow", icon: IconArrowRight }, + { tool: "line", key: "L", label: "draw.line", icon: IconLineSegment }, + { tool: "eraser", key: "E", label: "draw.eraser", icon: IconEraser }, +]; +const TOOL_BY_KEY = new Map(TOOLS.map((entry) => [entry.key.toLowerCase(), entry.tool])); +const SHAPES = new Set(["rectangle", "diamond", "ellipse", "arrow", "line"]); +const isShape = (tool: Tool): tool is ShapeKind => SHAPES.has(tool); + +// Excalidraw's default stroke palette. +const COLORS = ["#1e1e1e", "#e03131", "#2f9e44", "#1971c2", "#f08c00"]; /** Spoken name of each swatch — a hex code is no accessible name. */ const COLOR_NAMES: Record = { - "#1f2937": "draw.colorName.black", - "#dc2626": "draw.colorName.red", - "#2563eb": "draw.colorName.blue", - "#16a34a": "draw.colorName.green", - "#ca8a04": "draw.colorName.yellow", + "#1e1e1e": "draw.colorName.black", + "#e03131": "draw.colorName.red", + "#2f9e44": "draw.colorName.green", + "#1971c2": "draw.colorName.blue", + "#f08c00": "draw.colorName.orange", }; -const WIDTHS = [2, 6, 14]; +const WIDTHS: { size: number; label: MessageKey }[] = [ + { size: 2, label: "draw.widthThin" }, + { size: 4, label: "draw.widthBold" }, + { size: 8, label: "draw.widthExtraBold" }, +]; +const DASHES: { dash: StrokeDash | undefined; label: MessageKey; pattern?: string }[] = [ + { dash: undefined, label: "draw.styleSolid" }, + { dash: "dashed", label: "draw.styleDashed", pattern: "4 3" }, + { dash: "dotted", label: "draw.styleDotted", pattern: "0.5 3" }, +]; +const SLOPPINESS: { slop: Sloppiness; label: MessageKey; path: string }[] = [ + { slop: 0, label: "draw.slopArchitect", path: "M2 12 C6 12 8 6 12 6 S18 12 22 12" }, + { slop: 1, label: "draw.slopArtist", path: "M2 13 C5 11 7 6 10 7 S13 14 16 12 S20 7 22 9" }, + { slop: 2, label: "draw.slopCartoonist", path: "M2 13 C5 10 7 5 10 7 S13 15 16 12 S20 6 22 9 M3 11 C6 9 8 7 11 8 S14 13 17 11 S20 8 22 11" }, +]; +/** How far the eraser reaches, in screen px (divided by zoom for board-space). */ +const ERASER_REACH = 6; +/** Opacity of strokes the eraser has touched but not yet removed. */ +const ERASE_PENDING_ALPHA = 0.2; +const ERASER_CURSOR = `url("data:image/svg+xml,${encodeURIComponent( + '', +)}") 8 8, crosshair`; const ZOOM_MIN = 0.25; const ZOOM_MAX = 4; const ZOOM_STEP = 1.25; -const OVERLAY_CARD = "absolute z-10 gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-xs backdrop-blur-xs"; +// Dark theme flips the ink the way Excalidraw does rather than re-colouring +// strokes: stored colours stay the same for everyone, only the view inverts. +const DARK_INK = "dark:[filter:invert(93%)_hue-rotate(180deg)]"; +const ISLAND = "rounded-lg border border-border/70 bg-card shadow-[0_1px_4px_rgb(0_0_0/0.08)]"; + +const isTypingTarget = (target: EventTarget | null) => + target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)); // Imperative handle the room uses to push server-confirmed marks onto the // canvas without re-rendering the whole component per stroke. export type WhiteboardCanvasController = { /** Paint one server-confirmed stroke or segment (board-space coords). */ - applyStroke: (stroke: Stroke) => void; + applyStroke: (stroke: BoardStroke) => void; /** Replace the whole canvas (REST catch-up, resync). */ - loadStrokes: (strokes: Stroke[]) => void; + loadStrokes: (strokes: BoardStroke[]) => void; + /** Drop the strokes with these ids (an erase marker, local or remote). */ + removeStrokes: (ids: string[]) => void; /** Blank the live canvas (a clear / epoch bump — history is untouched). */ reset: () => void; }; @@ -45,118 +108,250 @@ export type WhiteboardCanvasController = { * never saves a File: each finished local stroke is emitted through * `props.onStroke` (board-space, device/zoom independent) for the room to send * over the socket, and server-confirmed strokes are pushed back in through the - * controller. Strokes are held in a plain array and painted incrementally so a - * busy board stays cheap; a full redraw only runs on pan / zoom / resize. + * controller. Shapes are baked into plain strokes (see lib/board-shapes), so + * the wire and the history replay only ever see strokes. Committed strokes are + * held in a plain array and painted incrementally; the mark being drawn lives + * on a separate preview canvas so a shape can be re-drawn on every move. */ export function WhiteboardCanvas(props: { disabled?: boolean; - onStroke: (stroke: Stroke) => void; + /** A finished local stroke; its `id` is the sid it must travel under. */ + onStroke: (stroke: BoardStroke) => void; + /** The eraser removed these strokes locally; the room logs the removal. */ + onErase: (ids: string[]) => void; + /** Board-level controls docked top-right, beside the tool island. */ + topRight?: JSX.Element; + /** Board-level controls docked top-left (the board menu). */ + topLeft?: JSX.Element; + /** A status line under the tool island (locked, closed, an error). */ + banner?: string; + bannerTone?: "info" | "error"; + /** Fill the parent edge to edge, the way Excalidraw owns the viewport. */ + fill?: boolean; controllerRef?: (c: WhiteboardCanvasController) => void; class?: string; }) { const t = useT(); let canvas: HTMLCanvasElement | undefined; + let preview: HTMLCanvasElement | undefined; let wrap: HTMLDivElement | undefined; let root: HTMLDivElement | undefined; - let current: Stroke | undefined; + let current: BoardStroke | undefined; + // Excalidraw's eraser: strokes swept over fade while the button is held and + // are removed on release, whole — never cut into pieces. + let erasing: { ids: Set; trail: Point[] } | undefined; + let shape: { kind: ShapeKind; start: Point; seed: number; strokes: Stroke[] } | undefined; // The ResizeObserver on `wrap` re-sizes the backing store on enter/exit and // redraw() repaints `committed`, so no stroke is lost. const fullscreen = createFullscreen(() => root); let panStart: { x: number; y: number; px: number; py: number } | undefined; // Every committed mark (local + remote), in draw order. Plain array, not a // signal: it can grow into the thousands and only pan/zoom/resize repaints it. - const committed: Stroke[] = []; + const committed: BoardStroke[] = []; + // Ids already erased, so a late segment of a removed stroke never reappears. + const removed = new Set(); + let idSeq = 0; + const newId = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}-${(idSeq += 1)}`; const [color, setColor] = createSignal(COLORS[0]); - const [width, setWidth] = createSignal(WIDTHS[1]); - const [erasing, setErasing] = createSignal(false); + const [width, setWidth] = createSignal(WIDTHS[1].size); + const [dash, setDash] = createSignal(undefined); + const [slop, setSlop] = createSignal(1); // The board opens on the hand tool: it is a shared live canvas, so a stray - // tap or scroll must not leave a mark for everyone — drawing starts only - // once the pen (or a colour) is picked. - const [hand, setHand] = createSignal(true); - const [override, setOverride] = createSignal(null); + // tap must not leave a mark for everyone — drawing starts once a tool is picked. + const [tool, setTool] = createSignal("hand"); + // A middle-drag pans and a right-drag erases for as long as the button is held. + const [override, setOverride] = createSignal(null); + const [spaceHeld, setSpaceHeld] = createSignal(false); const [pan, setPan] = createSignal({ x: 0, y: 0 }); const [panning, setPanning] = createSignal(false); const [zoom, setZoom] = createSignal(1); const [empty, setEmpty] = createSignal(true); + const [grid, setGrid] = createSignal(false); + // Phones have no room for the style island next to the canvas, so there it + // opens on demand from the swatch button bottom-left. + const [styleOpen, setStyleOpen] = createSignal(false); + // Below this width the tool island no longer fits between the corner + // controls, so it drops to a second row. + const [wide, setWide] = createSignal(true); + const hasCorners = () => Boolean(props.topLeft || props.topRight); + const toolbarRow2 = () => hasCorners() && !wide() && !fullscreen.active(); + const showsStyle = () => activeTool() !== "hand" && activeTool() !== "eraser"; const ratio = () => window.devicePixelRatio || 1; const context = () => canvas?.getContext("2d") ?? null; - const activeTool = (): "pen" | "erase" | "pan" => { - const o = override(); - if (o) return o; - if (hand()) return "pan"; - if (erasing()) return "erase"; - return "pen"; - }; + const activeTool = (): Tool => override() ?? (spaceHeld() ? "hand" : tool()); const cursor = () => { - const tool = activeTool(); - if (tool === "pan") return panning() ? "grabbing" : "grab"; + const active = activeTool(); + if (active === "hand") return panning() ? "grabbing" : "grab"; + if (active === "eraser") return ERASER_CURSOR; return "crosshair"; }; - const redraw = () => { - const c = context(); - if (!c || !canvas) return; + const worldTransform = (c: CanvasRenderingContext2D) => { const scale = ratio(); - c.setTransform(scale, 0, 0, scale, 0, 0); - c.clearRect(0, 0, canvas.width / scale, canvas.height / scale); const p = pan(); const z = zoom(); c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); - for (const stroke of committed) paintStroke(c, stroke); - if (current) paintStroke(c, current); + }; + + const clearCanvas = (target: HTMLCanvasElement | undefined) => { + const c = target?.getContext("2d"); + if (!c || !target) return null; + const scale = ratio(); + c.setTransform(scale, 0, 0, scale, 0, 0); + c.clearRect(0, 0, target.width / scale, target.height / scale); + return c; + }; + + const redraw = () => { + const c = clearCanvas(canvas); + if (!c) return; + worldTransform(c); + const pending = erasing?.ids; + for (const stroke of committed) { + const fading = pending !== undefined && stroke.id !== undefined && pending.has(stroke.id); + if (fading) c.globalAlpha = ERASE_PENDING_ALPHA; + paintStroke(c, stroke); + if (fading) c.globalAlpha = 1; + } + }; + + /** Repaint the in-progress pen line or shape on the preview layer. */ + const paintPreview = (strokes: Stroke[]) => { + const c = clearCanvas(preview); + if (!c) return; + worldTransform(c); + for (const stroke of strokes) paintStroke(c, stroke); }; const resize = () => { - if (!canvas) return; + if (!canvas || !preview) return; const rect = canvas.getBoundingClientRect(); if (rect.width === 0 || rect.height === 0) return; + setWide(rect.width >= 1000); const scale = ratio(); - canvas.width = Math.round(rect.width * scale); - canvas.height = Math.round(rect.height * scale); + for (const target of [canvas, preview]) { + target.width = Math.round(rect.width * scale); + target.height = Math.round(rect.height * scale); + } redraw(); }; // Paint one just-committed stroke on top of the current transform, without a // full redraw. The transform matches redraw()'s so it lands in the same place. - const paintOne = (stroke: Stroke) => { + const paintOne = (stroke: BoardStroke) => { const c = context(); - if (!c || !canvas) return; - const scale = ratio(); - const p = pan(); - const z = zoom(); - c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); + if (!c) return; + worldTransform(c); paintStroke(c, stroke); }; + const removeLocal = (ids: Iterable) => { + for (const id of ids) removed.add(id); + const kept = committed.filter((stroke) => !(stroke.id && removed.has(stroke.id))); + if (kept.length === committed.length) return; + committed.length = 0; + committed.push(...kept); + setEmpty(committed.length === 0); + redraw(); + }; + const controller: WhiteboardCanvasController = { applyStroke: (stroke) => { + if (stroke.id && removed.has(stroke.id)) return; committed.push(stroke); setEmpty(false); paintOne(stroke); }, loadStrokes: (strokes) => { + removed.clear(); committed.length = 0; committed.push(...strokes); setEmpty(committed.length === 0); redraw(); }, + removeStrokes: (ids) => removeLocal(ids), reset: () => { + removed.clear(); committed.length = 0; setEmpty(true); redraw(); }, }; + const zoomAt = (cx: number, cy: number, factor: number) => { + const p = pan(); + const z0 = zoom(); + const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); + if (z1 === z0) return; + const wx = (cx - p.x) / z0; + const wy = (cy - p.y) / z0; + setZoom(z1); + setPan({ x: cx - wx * z1, y: cy - wy * z1 }); + redraw(); + }; + + const zoomBy = (factor: number) => { + if (!canvas) return; + const rect = canvas.getBoundingClientRect(); + zoomAt(rect.width / 2, rect.height / 2, factor); + }; + + const resetZoom = () => zoomBy(1 / zoom()); + + const pickTool = (next: Tool) => { + setTool(next); + if (next === "hand") setStyleOpen(false); + }; + + const onKeyDown = (e: KeyboardEvent) => { + if (e.defaultPrevented || isTypingTarget(e.target)) return; + // A side panel or confirm dialog above the board owns the keyboard. + if (e.target instanceof Element && e.target.closest("[role='dialog']")) return; + if (e.code === "Space") { + // A focused button keeps Space as its own activation key. + if (e.target instanceof HTMLButtonElement) return; + e.preventDefault(); + if (!e.repeat) setSpaceHeld(true); + return; + } + if (e.ctrlKey || e.metaKey) { + if (e.key === "=" || e.key === "+") zoomBy(ZOOM_STEP); + else if (e.key === "-") zoomBy(1 / ZOOM_STEP); + else if (e.key === "0") resetZoom(); + else return; + e.preventDefault(); + return; + } + if (e.altKey || e.repeat) return; + const next = TOOL_BY_KEY.get(e.key.toLowerCase()); + if (next) { + e.preventDefault(); + pickTool(next); + } + }; + const onKeyUp = (e: KeyboardEvent) => { + if (e.code === "Space") setSpaceHeld(false); + }; + const onBlur = () => setSpaceHeld(false); + onMount(() => { resize(); props.controllerRef?.(controller); const observer = new ResizeObserver(() => resize()); if (wrap) observer.observe(wrap); - onCleanup(() => observer.disconnect()); + window.addEventListener("keydown", onKeyDown); + window.addEventListener("keyup", onKeyUp); + window.addEventListener("blur", onBlur); + onCleanup(() => { + observer.disconnect(); + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("keyup", onKeyUp); + window.removeEventListener("blur", onBlur); + }); }); const pointAt = (e: PointerEvent): Point => { @@ -166,50 +361,58 @@ export function WhiteboardCanvas(props: { return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z }; }; - const zoomBy = (factor: number) => { - if (!canvas) return; - const rect = canvas.getBoundingClientRect(); - const cx = rect.width / 2; - const cy = rect.height / 2; - const p = pan(); - const z0 = zoom(); - const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); - if (z1 === z0) return; - const wx = (cx - p.x) / z0; - const wy = (cy - p.y) / z0; - setZoom(z1); - setPan({ x: cx - wx * z1, y: cy - wy * z1 }); - redraw(); + /** Mark every stroke the eraser's latest move touched; true when any is new. */ + const sweep = (a: Point, b: Point) => { + if (!erasing) return false; + const reach = ERASER_REACH / zoom(); + let hit = false; + for (const stroke of committed) { + if (!stroke.id || erasing.ids.has(stroke.id)) continue; + if (strokeHit(stroke, a, b, reach)) { + erasing.ids.add(stroke.id); + hit = true; + } + } + return hit; }; - const resetZoom = () => zoomBy(1 / zoom()); - - const drawTip = (stroke: Stroke) => { - const c = context(); - if (c) paintTip(c, stroke); + /** A short fading grey trail behind the eraser, on the preview layer. */ + const paintTrail = (trail: Point[]) => { + const c = clearCanvas(preview); + if (!c) return; + worldTransform(c); + const tail = trail.slice(-12); + paintStroke(c, { color: "rgba(120, 120, 120, 0.35)", width: 5 / zoom(), erase: false, points: tail }); }; + const strokeStyle = () => ({ color: color(), width: width(), ...(dash() ? { dash: dash() } : {}) }); + const startStroke = (e: PointerEvent) => { - if (props.disabled && !(e.button === 1 || hand())) return; + const panNow = e.button === 1 || (activeTool() === "hand" && e.button !== 2); + if (props.disabled && !panNow) return; e.preventDefault(); canvas?.setPointerCapture(e.pointerId); - if (e.button === 1 || (hand() && e.button !== 2)) { - if (e.button === 1) setOverride("pan"); + if (panNow) { + if (e.button === 1) setOverride("hand"); const p = pan(); panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y }; setPanning(true); return; } - if (props.disabled) return; - const eraseNow = erasing() || e.button === 2; - if (e.button === 2) setOverride("erase"); - current = { - color: color(), - width: eraseNow ? width() * 2.5 : width(), - erase: eraseNow, - points: [pointAt(e)], - }; - drawTip(current); + const point = pointAt(e); + if (e.button === 2 || activeTool() === "eraser") { + if (e.button === 2) setOverride("eraser"); + erasing = { ids: new Set(), trail: [point] }; + if (sweep(point, point)) redraw(); + return; + } + const active = activeTool(); + if (isShape(active)) { + shape = { kind: active, start: point, seed: Math.floor(Math.random() * 2 ** 31), strokes: [] }; + return; + } + current = { ...strokeStyle(), erase: false, id: newId(), points: [point] }; + paintPreview([current]); }; const extendStroke = (e: PointerEvent) => { @@ -218,9 +421,30 @@ export function WhiteboardCanvas(props: { redraw(); return; } + if (shape) { + const point = pointAt(e); + const end = e.shiftKey ? constrainEnd(shape.kind, shape.start, point) : point; + shape.strokes = shapeStrokes(shape.kind, shape.start, end, strokeStyle(), slop(), shape.seed); + paintPreview(shape.strokes); + return; + } + if (erasing) { + const point = pointAt(e); + const prev = erasing.trail[erasing.trail.length - 1]; + erasing.trail.push(point); + if (sweep(prev, point)) redraw(); + paintTrail(erasing.trail); + return; + } if (!current) return; current.points.push(pointAt(e)); - drawTip(current); + paintPreview([current]); + }; + + const commit = (stroke: BoardStroke) => { + committed.push(stroke); + setEmpty(false); + props.onStroke(stroke); }; const endStroke = () => { @@ -230,110 +454,60 @@ export function WhiteboardCanvas(props: { setPanning(false); return; } + clearCanvas(preview); + if (erasing) { + const ids = [...erasing.ids]; + erasing = undefined; + if (ids.length === 0) return; + removeLocal(ids); + props.onErase(ids); + return; + } + if (shape) { + const strokes = shape.strokes; + shape = undefined; + for (const bare of strokes) { + const stroke: BoardStroke = { ...bare, id: newId() }; + paintOne(stroke); + commit(stroke); + } + return; + } const done = current; current = undefined; if (!done || done.points.length === 0) return; - committed.push(done); - setEmpty(false); - redraw(); // swap the live polyline for its smoothed replay - props.onStroke(done); + paintOne(done); + commit(done); }; - const toolClass = (active: boolean) => - cn( - "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors", - active - ? "border-primary bg-primary text-primary-foreground shadow-xs" - : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground", - ); - - // Shared button groups rendered twice: once inside the mobile wrapping bar, - // once inside the three desktop corner islands. Each instance mounts its own - // reactive scope over the same signals above, so both stay in sync. - const ToolButtons = () => ( - <> - {t("draw.pen")} - - - - - ); - - const ColorSwatches = () => ( - - {(swatch) => ( - - )} - - ); + const hint = () => { + const active = activeTool(); + if (props.disabled) return active === "hand" ? t("whiteboard.panHint") : ""; + if (isShape(active)) return t("whiteboard.shapeHint"); + if (active === "eraser") return t("whiteboard.eraserHint"); + if (active === "hand" || active === "pen") return t("whiteboard.panHint"); + return ""; + }; const paperStyle = () => { + if (!grid()) return {}; const cell = PAPER_CELL * zoom(); const p = pan(); return { @@ -343,19 +517,36 @@ export function WhiteboardCanvas(props: { }; }; + const optionClass = (active: boolean) => + cn( + "flex h-8 w-8 items-center justify-center rounded-md transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring", + active ? "bg-primary/15 text-primary-text ring-1 ring-primary/40" : "bg-muted/60 text-foreground/80 hover:bg-muted", + ); + + const plainButton = + "flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"; + + const Section = (sectionProps: { label: string; children: JSX.Element }) => ( +
+

{sectionProps.label}

+
{sectionProps.children}
+
+ ); + return ( -
+
{ if (e.button === 1) e.preventDefault(); @@ -365,80 +556,231 @@ export function WhiteboardCanvas(props: { onPointerMove={extendStroke} onPointerUp={endStroke} onPointerCancel={endStroke} - onWheel={(e) => { - e.preventDefault(); - zoomBy(e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP); - }} + onWheel={onWheel} /> - -

- {activeTool() === "pan" && !props.disabled ? t("whiteboard.canvasHintPickPen") : t("whiteboard.canvasHint")} +

+ {activeTool() === "hand" && !props.disabled ? t("whiteboard.canvasHintPickPen") : t("whiteboard.canvasHint")}

- {/* Mobile: the three corner islands below overlap each other under ~640px - (they need ~520px combined), so under sm they collapse into one - wrapping bar instead; desktop keeps the original three corners. */} -
-
- -
-
- -
-
- -
-
- - {/* Top-left island — tools */} - + {/* Corner controls the host docks beside the tools. Hidden in full + screen: their menus portal to , which full screen covers. */} + +
{props.topLeft}
+
+ +
{props.topRight}
+
- {/* Top-middle island — colours */} + {/* Top-centre tool island, with the active tool's hint (or the host's + status banner) under it. */} - {/* Top-right island — width */} - diff --git a/src/components/whiteboard/whiteboard-room-ws.tsx b/src/components/whiteboard/whiteboard-room-ws.tsx index 7525e28..2dec0bc 100644 --- a/src/components/whiteboard/whiteboard-room-ws.tsx +++ b/src/components/whiteboard/whiteboard-room-ws.tsx @@ -1,9 +1,13 @@ -import { Show, createEffect, createSignal, onCleanup, onMount } from "solid-js"; +import { createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js"; import { getBoardStrokes, type Board } from "@/api/boards"; import { formatApiErrorMessage } from "@/api/client"; -import { IconAlert } from "@/components/ui/icons"; -import { encodeStrokeSegments, decodeSegment, segmentToStroke } from "@/lib/board-stroke-codec"; -import type { Stroke } from "@/lib/draw-stroke"; +import { + decodeSegment, + encodeEraseMarkers, + encodeStrokeSegments, + segmentToStroke, + type BoardStroke, +} from "@/lib/board-stroke-codec"; import { parseBoardWsMessage, type BoardWsMessage } from "@/lib/websocket-messages"; import { usePreferences } from "@/stores/preferences-context"; import { WhiteboardCanvas, type WhiteboardCanvasController } from "./whiteboard-canvas"; @@ -21,6 +25,8 @@ export type BoardLiveState = { }; const MAX_RECONNECT = 6; +/** A socket error stays on the canvas banner this long. */ +const NOTICE_MS = 6000; export function WhiteboardRoom(props: { board: Board; @@ -28,6 +34,12 @@ export function WhiteboardRoom(props: { onState?: (patch: BoardLiveState) => void; onConnectionChange?: (state: WsState) => void; onDeleted?: () => void; + /** Passed through to the canvas corners and banner. */ + topLeft?: JSX.Element; + topRight?: JSX.Element; + banner?: string; + bannerTone?: "info" | "error"; + class?: string; }) { const { locale } = usePreferences(); @@ -47,6 +59,7 @@ export function WhiteboardRoom(props: { const seen = new Set(); let reconnectTimer: ReturnType | null = null; + let noticeTimer: ReturnType | undefined; let reconnectAttempts = 0; let closedByUs = false; @@ -81,7 +94,9 @@ export function WhiteboardRoom(props: { if (seen.has(row.id)) return; seen.add(row.id); const seg = decodeSegment(row.payload); - if (seg) controller?.applyStroke(segmentToStroke(seg)); + if (!seg) return; + if (seg.del) controller?.removeStrokes(seg.del); + else controller?.applyStroke({ ...segmentToStroke(seg), id: seg.sid }); }; const wipe = () => { @@ -204,6 +219,8 @@ export function WhiteboardRoom(props: { case "error": { const message = formatApiErrorMessage(msg.message, locale()); setNotice(message); + if (noticeTimer) clearTimeout(noticeTimer); + noticeTimer = setTimeout(() => setNotice(""), NOTICE_MS); // A rejected draw (locked, full epoch, closed) or a room resync means the // optimistic local canvas is out of step — take the truth from the DB. if (["epoch_full", "board_closed", "locked", "resync", "conflict", "forbidden"].includes(msg.code)) { @@ -214,10 +231,22 @@ export function WhiteboardRoom(props: { } }; - const onLocalStroke = (stroke: Stroke) => { + const nextSid = () => `${props.meId}-${Date.now()}-${(clientSeq += 1)}`; + + // The canvas tags every local stroke with an id; it is the sid on the wire, + // so a later erase — ours or anyone's — can name it. + const onLocalStroke = (stroke: BoardStroke) => { if (!canDraw()) return; - const sid = `${props.meId}-${Date.now()}-${(clientSeq += 1)}`; - for (const payload of encodeStrokeSegments(stroke, sid)) { + for (const payload of encodeStrokeSegments(stroke, stroke.id ?? nextSid())) { + sendWs({ type: "stroke", payload, client_seq: (clientSeq += 1) }); + } + }; + + // The log is append-only, so an erase is logged as a marker naming the + // removed sids; every client (and the history replay) drops them. + const onLocalErase = (ids: string[]) => { + if (!canDraw()) return; + for (const payload of encodeEraseMarkers(ids, nextSid())) { sendWs({ type: "stroke", payload, client_seq: (clientSeq += 1) }); } }; @@ -229,29 +258,26 @@ export function WhiteboardRoom(props: { onCleanup(() => { closedByUs = true; clearReconnect(); + if (noticeTimer) clearTimeout(noticeTimer); if (ws) ws.close(); }); createEffect(() => props.onConnectionChange?.(wsState())); return ( -
- - {(msg) => ( -
- -

{msg()}

-
- )} -
- - { - controller = c; - }} - /> -
+ { + controller = c; + }} + /> ); } diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index c74fa97..cc3e646 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -1266,7 +1266,35 @@ export const en: Dict = { "draw.colorName.blue": "Blue", "draw.colorName.green": "Green", "draw.colorName.yellow": "Yellow", - "whiteboard.canvasHintPickPen": "Pick the pen to draw — everyone on the board sees it live.", + "whiteboard.canvasHintPickPen": "Pick a tool above to draw — everyone on the board sees it live.", + "draw.tools": "Tools", + "draw.rectangle": "Rectangle", + "draw.diamond": "Diamond", + "draw.ellipse": "Ellipse", + "draw.arrow": "Arrow", + "draw.line": "Line", + "draw.colorName.orange": "Orange", + "draw.style": "Style", + "draw.widthThin": "Thin", + "draw.widthBold": "Bold", + "draw.widthExtraBold": "Extra bold", + "draw.strokeStyle": "Stroke style", + "draw.styleSolid": "Solid", + "draw.styleDashed": "Dashed", + "draw.styleDotted": "Dotted", + "draw.sloppiness": "Sloppiness", + "draw.slopArchitect": "Architect", + "draw.slopArtist": "Artist", + "draw.slopCartoonist": "Cartoonist", + "draw.showGrid": "Show grid", + "whiteboard.panHint": "To move the canvas, scroll or hold Space while dragging; Ctrl + scroll zooms.", + "whiteboard.shapeHint": "Hold Shift for a square, a circle or a 45° line.", + "whiteboard.eraserHint": "Sweep over the strokes to erase; they go when you let go.", + "whiteboard.menu": "Board menu", + "whiteboard.lockedBanner": "Board locked — drawing is paused.", + "whiteboard.closedBanner": "Board closed: read-only for good, it can't be reopened.", + "whiteboard.readOnlyBanner": "You're not on this board — you can only watch.", + "whiteboard.you": "You", "exams.publishOnCreateWarning": "Not a draft: the exam opens to students before any question is added.", "exams.publishEmptyTitle": "Publish without questions?", "exams.publishEmptyWarning": "This exam has no questions. If you publish it, students will see an empty exam.", @@ -2199,7 +2227,7 @@ export const en: Dict = { "whiteboard.clear": "Clear", "whiteboard.clearConfirm": "Clear the live canvas? The history is kept and stays replayable.", "whiteboard.close": "Close board", - "whiteboard.closeConfirm": "Close this board? It becomes permanently read-only.", + "whiteboard.closeConfirm": "Close this board? It becomes read-only for good and cannot be reopened — lock it for a short pause instead.", "whiteboard.delete": "Delete board", "whiteboard.deleteConfirm": "Delete this board and its whole history? This cannot be undone.", "whiteboard.creator": "Creator", diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index c112038..34bfd41 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -1262,7 +1262,35 @@ export const tr: Dict = { "draw.colorName.blue": "Mavi", "draw.colorName.green": "Yeşil", "draw.colorName.yellow": "Sarı", - "whiteboard.canvasHintPickPen": "Çizmek için kalemi seç — tahtadaki herkes anlık görür.", + "whiteboard.canvasHintPickPen": "Çizmek için yukarıdan bir araç seç — tahtadaki herkes anlık görür.", + "draw.tools": "Araçlar", + "draw.rectangle": "Dikdörtgen", + "draw.diamond": "Elmas", + "draw.ellipse": "Elips", + "draw.arrow": "Ok", + "draw.line": "Çizgi", + "draw.colorName.orange": "Turuncu", + "draw.style": "Stil", + "draw.widthThin": "İnce", + "draw.widthBold": "Kalın", + "draw.widthExtraBold": "Çok kalın", + "draw.strokeStyle": "Çizgi stili", + "draw.styleSolid": "Düz", + "draw.styleDashed": "Kesikli", + "draw.styleDotted": "Noktalı", + "draw.sloppiness": "Özensizlik", + "draw.slopArchitect": "Mimar", + "draw.slopArtist": "Sanatçı", + "draw.slopCartoonist": "Karikatürist", + "draw.showGrid": "Izgarayı göster", + "whiteboard.panHint": "Tuvali kaydırmak için tekerleği kullan ya da Boşluk tuşuna basılı tutup sürükle; yakınlaştırmak için Ctrl + tekerlek.", + "whiteboard.shapeHint": "Kare, daire ya da 45° çizgi için Shift'e basılı tut.", + "whiteboard.eraserHint": "Silmek istediğin çizgilerin üzerinden geç; bırakınca silinir.", + "whiteboard.menu": "Tahta menüsü", + "whiteboard.lockedBanner": "Tahta kilitli — çizim duraklatıldı.", + "whiteboard.closedBanner": "Tahta kapatıldı: kalıcı olarak salt okunur, yeniden açılamaz.", + "whiteboard.readOnlyBanner": "Bu tahtada katılımcı değilsin; yalnızca izleyebilirsin.", + "whiteboard.you": "Sen", "exams.publishOnCreateWarning": "Taslak işaretli değil: sınav, soru eklenmeden öğrencilere açılır.", "exams.publishEmptyTitle": "Soru olmadan yayınlansın mı?", "exams.publishEmptyWarning": "Bu sınavda hiç soru yok. Yayınlarsan öğrenciler boş bir sınav görür.", @@ -2195,7 +2223,7 @@ export const tr: Dict = { "whiteboard.clear": "Temizle", "whiteboard.clearConfirm": "Canlı tuval temizlensin mi? Geçmiş korunur ve tekrar oynatılabilir.", "whiteboard.close": "Tahtayı kapat", - "whiteboard.closeConfirm": "Bu tahta kapatılsın mı? Kalıcı olarak salt okunur olur.", + "whiteboard.closeConfirm": "Bu tahta kapatılsın mı? Kalıcı olarak salt okunur olur ve yeniden açılamaz; kısa bir ara için kilitlemeyi kullan.", "whiteboard.delete": "Tahtayı sil", "whiteboard.deleteConfirm": "Bu tahta ve tüm geçmişi silinsin mi? Geri alınamaz.", "whiteboard.creator": "Oluşturan", diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 7c1d017..5146740 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -1254,6 +1254,34 @@ export type MessageKey = | "draw.colorName.green" | "draw.colorName.yellow" | "whiteboard.canvasHintPickPen" + | "draw.tools" + | "draw.rectangle" + | "draw.diamond" + | "draw.ellipse" + | "draw.arrow" + | "draw.line" + | "draw.colorName.orange" + | "draw.style" + | "draw.widthThin" + | "draw.widthBold" + | "draw.widthExtraBold" + | "draw.strokeStyle" + | "draw.styleSolid" + | "draw.styleDashed" + | "draw.styleDotted" + | "draw.sloppiness" + | "draw.slopArchitect" + | "draw.slopArtist" + | "draw.slopCartoonist" + | "draw.showGrid" + | "whiteboard.panHint" + | "whiteboard.shapeHint" + | "whiteboard.eraserHint" + | "whiteboard.menu" + | "whiteboard.lockedBanner" + | "whiteboard.closedBanner" + | "whiteboard.readOnlyBanner" + | "whiteboard.you" | "exams.publishOnCreateWarning" | "exams.publishEmptyTitle" | "exams.publishEmptyWarning" diff --git a/src/lib/board-hit.test.ts b/src/lib/board-hit.test.ts new file mode 100644 index 0000000..a1c5972 --- /dev/null +++ b/src/lib/board-hit.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; +import { segmentDist, strokeHit } from "./board-hit"; +import type { Stroke } from "./draw-stroke"; + +const line = (over: Partial = {}): Stroke => ({ + color: "#000", + width: 4, + erase: false, + points: [ + { x: 0, y: 0 }, + { x: 100, y: 0 }, + ], + ...over, +}); + +describe("segmentDist", () => { + it("is zero for crossing segments", () => { + expect(segmentDist({ x: 0, y: -5 }, { x: 0, y: 5 }, { x: -5, y: 0 }, { x: 5, y: 0 })).toBe(0); + }); + + it("measures the gap between parallel segments", () => { + expect(segmentDist({ x: 0, y: 3 }, { x: 10, y: 3 }, { x: 0, y: 0 }, { x: 10, y: 0 })).toBeCloseTo(3); + }); +}); + +describe("strokeHit", () => { + it("hits when the eraser crosses the line", () => { + expect(strokeHit(line(), { x: 50, y: -20 }, { x: 50, y: 20 }, 2)).toBe(true); + }); + + it("hits within half the stroke width plus the eraser reach", () => { + expect(strokeHit(line(), { x: 50, y: 5 }, { x: 60, y: 5 }, 3)).toBe(true); + expect(strokeHit(line(), { x: 50, y: 6 }, { x: 60, y: 6 }, 3)).toBe(false); + }); + + it("misses a stroke far outside its box", () => { + expect(strokeHit(line(), { x: 500, y: 500 }, { x: 510, y: 510 }, 4)).toBe(false); + }); + + it("hits a single-point dot", () => { + expect(strokeHit(line({ points: [{ x: 10, y: 10 }] }), { x: 0, y: 12 }, { x: 20, y: 12 }, 1)).toBe(true); + }); + + it("never targets a pixel-eraser stroke or an empty one", () => { + expect(strokeHit(line({ erase: true }), { x: 50, y: -20 }, { x: 50, y: 20 }, 2)).toBe(false); + expect(strokeHit(line({ points: [] }), { x: 50, y: -20 }, { x: 50, y: 20 }, 2)).toBe(false); + }); +}); diff --git a/src/lib/board-hit.ts b/src/lib/board-hit.ts new file mode 100644 index 0000000..faffdfc --- /dev/null +++ b/src/lib/board-hit.ts @@ -0,0 +1,72 @@ +import type { Point, Stroke } from "./draw-stroke"; + +// Hit testing for the whiteboard's object eraser: a drag of the eraser is a +// chain of short segments, and a stroke is hit when any of them passes within +// the stroke's half-width (plus the eraser's own reach) of its polyline. + +type Box = { x0: number; y0: number; x1: number; y1: number }; + +// Stroke points never change once committed, so the box is computed once. +const boxes = new WeakMap(); + +function boxOf(stroke: Stroke): Box { + let box = boxes.get(stroke); + if (!box) { + box = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity }; + for (const p of stroke.points) { + box.x0 = Math.min(box.x0, p.x); + box.y0 = Math.min(box.y0, p.y); + box.x1 = Math.max(box.x1, p.x); + box.y1 = Math.max(box.y1, p.y); + } + boxes.set(stroke, box); + } + return box; +} + +function pointSegmentDist(p: Point, a: Point, b: Point): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len2 = dx * dx + dy * dy; + const t = len2 === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2)); + return Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t)); +} + +function cross(o: Point, a: Point, b: Point): number { + return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); +} + +/** Shortest distance between segments ab and cd (0 when they cross). */ +export function segmentDist(a: Point, b: Point, c: Point, d: Point): number { + const d1 = cross(c, d, a); + const d2 = cross(c, d, b); + const d3 = cross(a, b, c); + const d4 = cross(a, b, d); + if (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) return 0; + return Math.min(pointSegmentDist(a, c, d), pointSegmentDist(b, c, d), pointSegmentDist(c, a, b), pointSegmentDist(d, a, b)); +} + +/** + * Does the eraser move from `a` to `b` touch `stroke`? `radius` is the eraser's + * reach in board-space. Pixel-eraser strokes (older boards) are never targets: + * they carry no ink of their own. + */ +export function strokeHit(stroke: Stroke, a: Point, b: Point, radius: number): boolean { + const pts = stroke.points; + if (stroke.erase || pts.length === 0) return false; + const reach = stroke.width / 2 + radius; + const box = boxOf(stroke); + if ( + Math.max(a.x, b.x) < box.x0 - reach || + Math.min(a.x, b.x) > box.x1 + reach || + Math.max(a.y, b.y) < box.y0 - reach || + Math.min(a.y, b.y) > box.y1 + reach + ) { + return false; + } + if (pts.length === 1) return pointSegmentDist(pts[0], a, b) <= reach; + for (let i = 1; i < pts.length; i += 1) { + if (segmentDist(a, b, pts[i - 1], pts[i]) <= reach) return true; + } + return false; +} diff --git a/src/lib/board-shapes.test.ts b/src/lib/board-shapes.test.ts new file mode 100644 index 0000000..450edf3 --- /dev/null +++ b/src/lib/board-shapes.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import { constrainEnd, shapeStrokes, type ShapeKind } from "./board-shapes"; +import { strokesBounds } from "./draw-stroke"; + +const style = { color: "#1e1e1e", width: 2 }; +const a = { x: 10, y: 20 }; +const b = { x: 210, y: 120 }; + +describe("board-shapes", () => { + it("returns nothing for a click that never became a shape", () => { + for (const kind of ["rectangle", "diamond", "ellipse", "line", "arrow"] as ShapeKind[]) { + expect(shapeStrokes(kind, a, { x: 11, y: 20.5 }, style, 1, 7)).toEqual([]); + } + }); + + it("keeps a clean rectangle inside its dragged box", () => { + const strokes = shapeStrokes("rectangle", a, b, style, 0, 1); + expect(strokes).toHaveLength(1); + const box = strokesBounds(strokes)!; + expect(box.x).toBeCloseTo(a.x - 1, 5); + expect(box.y).toBeCloseTo(a.y - 1, 5); + expect(box.w).toBeCloseTo(b.x - a.x + 2, 5); + expect(box.h).toBeCloseTo(b.y - a.y + 2, 5); + }); + + it("draws a sloppy shape close to, not exactly on, its box", () => { + const box = strokesBounds(shapeStrokes("diamond", a, b, style, 1, 3))!; + expect(Math.abs(box.x - (a.x - 1))).toBeLessThan(6); + expect(Math.abs(box.w - (b.x - a.x + 2))).toBeLessThan(12); + }); + + it("is deterministic for a seed and varies across seeds", () => { + const one = shapeStrokes("ellipse", a, b, style, 1, 42); + expect(shapeStrokes("ellipse", a, b, style, 1, 42)).toEqual(one); + expect(shapeStrokes("ellipse", a, b, style, 1, 43)).not.toEqual(one); + }); + + it("splits an arrow into shaft and head, and doubles a cartoonist pass", () => { + expect(shapeStrokes("arrow", a, b, style, 0, 1)).toHaveLength(2); + expect(shapeStrokes("arrow", a, b, style, 2, 1)).toHaveLength(4); + expect(shapeStrokes("rectangle", a, b, style, 2, 1)).toHaveLength(2); + }); + + it("ends a clean arrow's shaft and head on the tip", () => { + const [shaft, head] = shapeStrokes("arrow", a, b, style, 0, 1); + expect(shaft.points[0]).toEqual(a); + expect(shaft.points[shaft.points.length - 1]).toEqual(b); + expect(head.points).toContainEqual(b); + }); + + it("carries the dash pattern onto every stroke", () => { + for (const s of shapeStrokes("arrow", a, b, { ...style, dash: "dotted" }, 1, 1)) { + expect(s.dash).toBe("dotted"); + expect(s.erase).toBe(false); + } + expect("dash" in shapeStrokes("line", a, b, style, 0, 1)[0]).toBe(false); + }); + + it("constrains a box to a square and a line to 45° steps", () => { + expect(constrainEnd("rectangle", { x: 0, y: 0 }, { x: -30, y: 10 })).toEqual({ x: -30, y: 30 }); + const end = constrainEnd("line", { x: 0, y: 0 }, { x: 100, y: 10 }); + expect(end.x).toBeCloseTo(Math.hypot(100, 10), 5); + expect(end.y).toBeCloseTo(0, 5); + }); +}); diff --git a/src/lib/board-shapes.ts b/src/lib/board-shapes.ts new file mode 100644 index 0000000..023a4a1 --- /dev/null +++ b/src/lib/board-shapes.ts @@ -0,0 +1,194 @@ +import type { Point, Stroke } from "./draw-stroke"; + +// Whiteboard shapes (Excalidraw-style rectangle, diamond, ellipse, line and +// arrow) are baked into ordinary freehand strokes before they leave the +// client. The board backend only stores stroke payloads, so a shape travels, +// persists and replays exactly like a pen line — no new wire kind, and every +// history replay draws it without knowing it was ever a shape. + +export type ShapeKind = "rectangle" | "diamond" | "ellipse" | "line" | "arrow"; +/** 0 architect (clean), 1 artist (a gentle hand wobble), 2 cartoonist (two loose passes). */ +export type Sloppiness = 0 | 1 | 2; +export type ShapeStyle = Pick; + +/** Below this drag distance (world px) a shape is a stray click, not a shape. */ +const MIN_SIZE = 2; +/** Distance of the guard points placed beside every sharp corner. */ +const CORNER_GUARD = 1.5; +const ELLIPSE_SEGMENTS = 72; + +/** Small deterministic PRNG (mulberry32) so a seed always yields the same wobble. */ +function random(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** Shift-drag: equal sides for boxes, a 45° snap for lines and arrows. */ +export function constrainEnd(kind: ShapeKind, a: Point, b: Point): Point { + const dx = b.x - a.x; + const dy = b.y - a.y; + if (kind === "line" || kind === "arrow") { + const step = Math.PI / 4; + const angle = Math.round(Math.atan2(dy, dx) / step) * step; + const len = Math.hypot(dx, dy); + return { x: a.x + Math.cos(angle) * len, y: a.y + Math.sin(angle) * len }; + } + const side = Math.max(Math.abs(dx), Math.abs(dy)); + return { x: a.x + (dx < 0 ? -side : side), y: a.y + (dy < 0 ? -side : side) }; +} + +/** + * Points from `a` (inclusive) toward `b` (exclusive). The renderer smooths a + * polyline with midpoint quadratics, which would cut a bare corner to the + * midpoints of its edges — so a guard point sits just inside each end and the + * corner only rounds by a pixel. A sloppy edge bows sideways along a half sine. + */ +function edge(a: Point, b: Point, bow: number, rand: () => number, jitter: number): Point[] { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len = Math.hypot(dx, dy); + if (len === 0) return [a]; + const nx = -dy / len; + const ny = dx / len; + const guard = Math.min(CORNER_GUARD, len / 4) / len; + const inner = bow === 0 ? 0 : Math.min(16, Math.max(2, Math.ceil(len / 24))); + const ts = [0, guard]; + for (let i = 1; i < inner; i += 1) ts.push(i / inner); + ts.push(1 - guard); + const out: Point[] = []; + for (const t of ts) { + const off = Math.sin(Math.PI * t) * bow + (t === 0 ? (rand() * 2 - 1) * jitter : 0); + out.push({ x: a.x + dx * t + nx * off, y: a.y + dy * t + ny * off }); + } + return out; +} + +/** One closed or open pass through `vertices`, each edge bowed by the sloppiness. */ +function polygonPass(vertices: Point[], closed: boolean, slop: Sloppiness, rand: () => number): Point[] { + const last = closed ? vertices.length : vertices.length - 1; + const out: Point[] = []; + for (let i = 0; i < last; i += 1) { + const a = vertices[i]; + const b = vertices[(i + 1) % vertices.length]; + const len = Math.hypot(b.x - a.x, b.y - a.y); + const bow = slop === 0 ? 0 : (rand() * 2 - 1) * Math.min(len * 0.015 * slop, 1.6 * slop); + out.push(...edge(a, b, bow, rand, slop * 0.6)); + } + const end = closed ? vertices[0] : vertices[vertices.length - 1]; + out.push(end); + // A loose hand overshoots where a closed outline meets itself. + if (closed && slop > 0 && out.length > 2) { + const next = out[1]; + const f = 0.35 + rand() * 0.25; + out.push({ x: end.x + (next.x - end.x) * f * slop, y: end.y + (next.y - end.y) * f * slop }); + } + return out; +} + +/** Rounded-corner rectangle (Excalidraw's default edges) as one outline pass. */ +function rectanglePass(x0: number, y0: number, x1: number, y1: number, width: number, slop: Sloppiness, rand: () => number): Point[] { + const w = x1 - x0; + const h = y1 - y0; + const r = Math.min(32, Math.min(w, h) * 0.25); + if (r < 2) return polygonPass([{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }], true, slop, rand); + const corners = [ + { cx: x1 - r, cy: y0 + r, from: -Math.PI / 2 }, + { cx: x1 - r, cy: y1 - r, from: 0 }, + { cx: x0 + r, cy: y1 - r, from: Math.PI / 2 }, + { cx: x0 + r, cy: y0 + r, from: Math.PI }, + ]; + const arcSteps = Math.max(4, Math.ceil(r / 3)); + const out: Point[] = []; + let prev: Point = { x: x0 + r, y: y0 }; + for (const c of corners) { + const start = { x: c.cx + Math.cos(c.from) * r, y: c.cy + Math.sin(c.from) * r }; + const len = Math.hypot(start.x - prev.x, start.y - prev.y); + const bow = slop === 0 ? 0 : (rand() * 2 - 1) * Math.min(len * 0.012 * slop, 1.4 * slop); + out.push(...edge(prev, start, bow, rand, slop * 0.5)); + for (let i = 0; i < arcSteps; i += 1) { + const a = c.from + (Math.PI / 2) * (i / arcSteps); + out.push({ x: c.cx + Math.cos(a) * r, y: c.cy + Math.sin(a) * r }); + } + prev = { x: c.cx + Math.cos(c.from + Math.PI / 2) * r, y: c.cy + Math.sin(c.from + Math.PI / 2) * r }; + } + out.push(prev); + if (slop > 0) { + const reach = Math.min(w - 2 * r, 6 + width * 2) * (0.4 + rand() * 0.4) * slop; + out.push({ x: prev.x + Math.max(0, reach), y: prev.y + (rand() * 2 - 1) * slop }); + } + return out; +} + +function ellipsePass(cx: number, cy: number, rx: number, ry: number, slop: Sloppiness, rand: () => number): Point[] { + const start = slop === 0 ? -Math.PI / 2 : rand() * Math.PI * 2; + // The wobble is a slow radial wave, so the outline stays smooth, and a loose + // pass runs a little past its start instead of closing exactly. + const amp = 0.012 * slop; + const phase = rand() * Math.PI * 2; + const sweep = Math.PI * 2 * (1 + 0.04 * slop); + const steps = Math.ceil(ELLIPSE_SEGMENTS * (1 + 0.04 * slop)); + const out: Point[] = []; + for (let i = 0; i <= steps; i += 1) { + const a = start + (sweep * i) / steps; + const k = 1 + amp * Math.sin(2 * a + phase); + out.push({ x: cx + Math.cos(a) * rx * k, y: cy + Math.sin(a) * ry * k }); + } + return out; +} + +function onePass(kind: ShapeKind, a: Point, b: Point, width: number, slop: Sloppiness, rand: () => number): Point[][] { + const x0 = Math.min(a.x, b.x); + const y0 = Math.min(a.y, b.y); + const x1 = Math.max(a.x, b.x); + const y1 = Math.max(a.y, b.y); + switch (kind) { + case "rectangle": + return [rectanglePass(x0, y0, x1, y1, width, slop, rand)]; + case "diamond": { + const mx = (x0 + x1) / 2; + const my = (y0 + y1) / 2; + return [polygonPass([{ x: mx, y: y0 }, { x: x1, y: my }, { x: mx, y: y1 }, { x: x0, y: my }], true, slop, rand)]; + } + case "ellipse": + return [ellipsePass((x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, slop, rand)]; + case "line": + return [polygonPass([a, b], false, slop, rand)]; + case "arrow": { + const len = Math.hypot(b.x - a.x, b.y - a.y); + const angle = Math.atan2(b.y - a.y, b.x - a.x); + const head = Math.min(len / 2.5, 14 + width * 2.5); + const spread = Math.PI / 7; + const left = { x: b.x - Math.cos(angle - spread) * head, y: b.y - Math.sin(angle - spread) * head }; + const right = { x: b.x - Math.cos(angle + spread) * head, y: b.y - Math.sin(angle + spread) * head }; + return [polygonPass([a, b], false, slop, rand), polygonPass([left, b, right], false, slop, rand)]; + } + } +} + +/** + * Bake a dragged shape from `a` to `b` (board-space) into strokes ready to send. + * An arrow is two strokes (shaft, head); a cartoonist shape is drawn twice with + * a fresh wobble. `seed` fixes the wobble so the live preview and the committed + * shape match. Returns [] for a click that never became a shape. + */ +export function shapeStrokes(kind: ShapeKind, a: Point, b: Point, style: ShapeStyle, slop: Sloppiness, seed: number): Stroke[] { + const dx = Math.abs(b.x - a.x); + const dy = Math.abs(b.y - a.y); + const tooSmall = kind === "line" || kind === "arrow" ? Math.hypot(dx, dy) < MIN_SIZE : dx < MIN_SIZE || dy < MIN_SIZE; + if (tooSmall) return []; + const rand = random(seed); + const passes = slop === 2 ? 2 : 1; + const out: Stroke[] = []; + for (let p = 0; p < passes; p += 1) { + for (const points of onePass(kind, a, b, style.width, slop, rand)) { + out.push({ color: style.color, width: style.width, erase: false, ...(style.dash ? { dash: style.dash } : {}), points }); + } + } + return out; +} diff --git a/src/lib/board-stroke-codec.test.ts b/src/lib/board-stroke-codec.test.ts index eb751f0..39b05c2 100644 --- a/src/lib/board-stroke-codec.test.ts +++ b/src/lib/board-stroke-codec.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { decodeSegment, + encodeEraseMarkers, encodeStrokeSegments, reassembleStrokes, segmentToStroke, @@ -80,4 +81,46 @@ describe("board-stroke-codec", () => { const strokes = reassembleStrokes([null, "garbage", ...good]); expect(strokes).toHaveLength(1); }); + + it("round-trips a dash pattern and leaves a solid payload without one", () => { + const dashed = { ...makeStroke(300), dash: "dashed" as const }; + const payloads = encodeStrokeSegments(dashed, "d", 512); + expect(payloads.length).toBeGreaterThan(1); + expect(payloads.every((p) => decodeSegment(p)?.dash === "dashed")).toBe(true); + expect(reassembleStrokes(payloads)[0].dash).toBe("dashed"); + expect(segmentToStroke(decodeSegment(payloads[0])!).dash).toBe("dashed"); + expect(encodeStrokeSegments(makeStroke(2), "s")[0]).not.toContain("dash"); + }); + + it("rejects an unknown dash pattern", () => { + const payload = JSON.parse(encodeStrokeSegments(makeStroke(2), "x")[0]); + expect(decodeSegment(JSON.stringify({ ...payload, dash: "wavy" }))).toBeNull(); + }); + + it("encodes an erase as ink-free markers split under the cap", () => { + const ids = Array.from({ length: 60 }, (_, i) => `user-${i}-1700000000000-${i}`); + const payloads = encodeEraseMarkers(ids, "e", 512); + expect(payloads.length).toBeGreaterThan(1); + const all: string[] = []; + for (const p of payloads) { + expect(new TextEncoder().encode(p).length).toBeLessThanOrEqual(512); + const seg = decodeSegment(p)!; + expect(seg.pts).toEqual([]); + all.push(...seg.del!); + } + expect(all).toEqual(ids); + }); + + it("drops erased strokes from a reassembled history", () => { + const keep = encodeStrokeSegments(makeStroke(3), "keep"); + const gone = encodeStrokeSegments(makeStroke(300), "gone", 512); + const strokes = reassembleStrokes([...gone, ...keep, ...encodeEraseMarkers(["gone"], "e")]); + expect(strokes).toHaveLength(1); + expect(strokes[0].points).toHaveLength(3); + }); + + it("rejects a marker whose del list is not strings", () => { + const payload = JSON.parse(encodeEraseMarkers(["a"], "e")[0]); + expect(decodeSegment(JSON.stringify({ ...payload, del: [1] }))).toBeNull(); + }); }); diff --git a/src/lib/board-stroke-codec.ts b/src/lib/board-stroke-codec.ts index a0fc6cf..b2e4dd5 100644 --- a/src/lib/board-stroke-codec.ts +++ b/src/lib/board-stroke-codec.ts @@ -1,4 +1,4 @@ -import type { Point, Stroke } from "./draw-stroke"; +import { isDash, type Point, type Stroke, type StrokeDash } from "./draw-stroke"; // The whiteboard backend caps each stroke `payload` at 4096 bytes // (board.max_stroke_payload_len, published at GET /limits). A long freehand @@ -12,6 +12,9 @@ export const MAX_STROKE_PAYLOAD_BYTES = 4096; // boundary the server rejects. const DEFAULT_MAX_BYTES = MAX_STROKE_PAYLOAD_BYTES - 64; +/** A stroke on the live board, tagged with the `sid` it travelled under. */ +export type BoardStroke = Stroke & { id?: string }; + // Wire envelope for one segment of a logical stroke. Coordinates are // board-space (device/zoom independent); points travel as [x, y] tuples to // keep the payload small. @@ -23,6 +26,14 @@ export type StrokeSegment = { color: string; width: number; erase: boolean; + /** Absent for a solid line, so a solid stroke's payload is unchanged. */ + dash?: StrokeDash; + /** + * Erase marker: the sids of earlier strokes this entry removes (Excalidraw's + * object eraser). The stroke log is append-only, so a deletion is itself a + * logged entry; a marker carries no ink (`pts` is empty). + */ + del?: string[]; pts: [number, number][]; }; @@ -42,7 +53,7 @@ function segmentString( sid: string, seg: number, last: boolean, - stroke: Pick, + stroke: Pick, pts: [number, number][], ): string { const envelope: StrokeSegment = { @@ -53,6 +64,7 @@ function segmentString( color: stroke.color, width: stroke.width, erase: stroke.erase, + ...(stroke.dash ? { dash: stroke.dash } : {}), pts, }; return JSON.stringify(envelope); @@ -106,6 +118,26 @@ function isTuple(v: unknown): v is [number, number] { ); } +/** + * Serialize an erase of the strokes `ids` into marker payloads, each under + * `maxBytes` (a long sweep can remove more sids than fit in one payload). + */ +export function encodeEraseMarkers(ids: string[], sid: string, maxBytes: number = DEFAULT_MAX_BYTES): string[] { + const out: string[] = []; + const marker = (del: string[], n: number) => + JSON.stringify({ v: 1, sid: `${sid}-${n}`, seg: 0, last: true, color: "", width: 0, erase: true, del, pts: [] } satisfies StrokeSegment); + let batch: string[] = []; + for (const id of ids) { + if (batch.length > 0 && byteLength(marker([...batch, id], out.length)) > maxBytes) { + out.push(marker(batch, out.length)); + batch = []; + } + batch.push(id); + } + if (batch.length > 0) out.push(marker(batch, out.length)); + return out; +} + /** Parse one segment payload, or null on anything malformed (payloads are untrusted). */ export function decodeSegment(payload: string | null): StrokeSegment | null { if (!payload) return null; @@ -125,6 +157,8 @@ export function decodeSegment(payload: string | null): StrokeSegment | null { typeof s.color !== "string" || typeof s.width !== "number" || typeof s.erase !== "boolean" || + (s.dash !== undefined && !isDash(s.dash)) || + (s.del !== undefined && !(Array.isArray(s.del) && s.del.every((id) => typeof id === "string"))) || !Array.isArray(s.pts) || !s.pts.every(isTuple) ) { @@ -139,6 +173,7 @@ export function segmentToStroke(seg: StrokeSegment): Stroke { color: seg.color, width: seg.width, erase: seg.erase, + ...(seg.dash ? { dash: seg.dash } : {}), points: seg.pts.map(([x, y]) => ({ x, y }) as Point), }; } @@ -147,26 +182,38 @@ export function segmentToStroke(seg: StrokeSegment): Stroke { * Reassemble full strokes from an ordered list of stroke payloads (e.g. a * history/epoch page). Segments are grouped by `sid` in arrival order; the * overlap point each later segment repeats is dropped so the joined stroke has - * no duplicate vertex. Non-stroke rows (null payloads, clear markers) are + * no duplicate vertex. Strokes removed by a later erase marker are dropped, + * so a replay ends on what the board actually showed. Non-stroke rows (null payloads, clear markers) are * skipped by the caller passing only stroke payloads. */ export function reassembleStrokes(payloads: (string | null)[]): Stroke[] { const order: string[] = []; const bySid = new Map(); + const deleted = new Set(); for (const payload of payloads) { const seg = decodeSegment(payload); if (!seg) continue; + if (seg.del) { + for (const id of seg.del) deleted.add(id); + continue; + } const pts = seg.pts.map(([x, y]) => ({ x, y }) as Point); const existing = bySid.get(seg.sid); if (!existing) { order.push(seg.sid); - bySid.set(seg.sid, { color: seg.color, width: seg.width, erase: seg.erase, points: pts }); + bySid.set(seg.sid, { + color: seg.color, + width: seg.width, + erase: seg.erase, + ...(seg.dash ? { dash: seg.dash } : {}), + points: pts, + }); } else { // Drop the leading overlap point that duplicates the previous last point. existing.points.push(...(seg.seg > 0 ? pts.slice(1) : pts)); } } - return order.map((sid) => bySid.get(sid)!); + return order.filter((sid) => !deleted.has(sid)).map((sid) => bySid.get(sid)!); } diff --git a/src/lib/draw-stroke.test.ts b/src/lib/draw-stroke.test.ts index efe00dc..b4568d7 100644 --- a/src/lib/draw-stroke.test.ts +++ b/src/lib/draw-stroke.test.ts @@ -20,6 +20,10 @@ function stubContext() { arc: record("arc"), fill: record("fill"), stroke: record("stroke"), + // a style setter, not geometry — kept out of `calls` like the other styles + setLineDash: (segments: number[]) => { + props.lineDash = segments; + }, }; // trap the style assignments so composite mode / width can be asserted too return new Proxy(c, { @@ -81,6 +85,16 @@ describe("paintStroke", () => { expect(c.props.globalCompositeOperation).toBe("destination-out"); }); + it("draws a solid line unless the stroke carries a dash pattern", () => { + const c = stubContext(); + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }])); + expect(c.props.lineDash).toEqual([]); + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { dash: "dashed" })); + expect(c.props.lineDash).toEqual([16, 12]); + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { dash: "dotted" })); + expect((c.props.lineDash as number[])[0]).toBe(0); + }); + it("paints over the layer when not erasing", () => { const c = stubContext(); paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }])); @@ -116,6 +130,12 @@ describe("parseScene", () => { expect(parseScene(JSON.stringify(scene))).toEqual(scene); }); + it("keeps a known dash pattern and rejects an unknown one", () => { + const dashed = { ...scene, strokes: [{ ...scene.strokes[0], dash: "dotted" }] }; + expect(parseScene(JSON.stringify(dashed))).toEqual(dashed); + expect(parseScene(JSON.stringify({ ...scene, strokes: [{ ...scene.strokes[0], dash: "wavy" }] }))).toBeNull(); + }); + it("rejects a wrong version", () => { expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull(); }); diff --git a/src/lib/draw-stroke.ts b/src/lib/draw-stroke.ts index 10f1885..ae5dffc 100644 --- a/src/lib/draw-stroke.ts +++ b/src/lib/draw-stroke.ts @@ -1,5 +1,7 @@ export type Point = { x: number; y: number }; -export type Stroke = { color: string; width: number; erase: boolean; points: Point[] }; +/** Line pattern of a stroke; absent means solid (every older stroke). */ +export type StrokeDash = "dashed" | "dotted"; +export type Stroke = { color: string; width: number; erase: boolean; points: Point[]; dash?: StrokeDash }; export type BgKind = "none" | "lines" | "grid"; /** `w`/`h` are DPR-free world px; `dpr` is the device ratio the PNG beside them was baked at. */ export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind; dpr?: number }; @@ -25,6 +27,10 @@ function isSide(n: unknown): n is number { return typeof n === "number" && n > 0 && n <= MAX_SIDE; // NaN/Infinity fail the comparisons } +export function isDash(d: unknown): d is StrokeDash { + return d === "dashed" || d === "dotted"; +} + function isStroke(s: unknown): s is Stroke { if (!s || typeof s !== "object") return false; const st = s as Stroke; @@ -33,7 +39,8 @@ function isStroke(s: unknown): s is Stroke { typeof st.width === "number" && typeof st.erase === "boolean" && Array.isArray(st.points) && - st.points.every(isPoint) + st.points.every(isPoint) && + (st.dash === undefined || isDash(st.dash)) ); } @@ -143,6 +150,11 @@ function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) { c.lineWidth = stroke.width; c.lineCap = "round"; c.lineJoin = "round"; + // A zero-length dash with a round cap paints a dot; gaps scale with the width + // so a thick dashed line keeps the same rhythm as a thin one. + if (stroke.dash === "dashed") c.setLineDash([stroke.width * 4, stroke.width * 3]); + else if (stroke.dash === "dotted") c.setLineDash([0, stroke.width * 2.2]); + else c.setLineDash([]); } /** Replay a finished stroke. Midpoint quadratics so a fast drag reads as a curve, not a polygon. */ diff --git a/src/pages/whiteboard-page.tsx b/src/pages/whiteboard-page.tsx index ef75b74..78916dc 100644 --- a/src/pages/whiteboard-page.tsx +++ b/src/pages/whiteboard-page.tsx @@ -16,19 +16,28 @@ import type { MessageKey } from "@/i18n/messages"; import { WhiteboardRoom, type BoardLiveState } from "@/components/whiteboard/whiteboard-room-ws"; import { BoardSettingsPanel } from "@/components/whiteboard/board-settings-panel"; import { RouteGuard } from "@/components/layout/route-guard"; -import { PageHeader } from "@/components/layout/page-header"; -import { Breadcrumbs } from "@/components/layout/breadcrumbs"; import { Alert } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { DrawingPlayback } from "@/components/ui/drawing-playback"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; -import { IconDotsVertical, IconEraser, IconLock, IconTrash, IconX } from "@/components/ui/icons"; +import { + IconChevronLeft, + IconEraser, + IconLock, + IconMenu, + IconRotateCcw, + IconSettings, + IconTrash, + IconX, +} from "@/components/ui/icons"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { PageSpinner } from "@/components/ui/page-spinner"; import { SidePanel } from "@/components/ui/side-panel"; import { reassembleStrokes } from "@/lib/board-stroke-codec"; import { strokesBounds, type DrawScene } from "@/lib/draw-stroke"; +import { cn } from "@/lib/cn"; import { formatDateTime } from "@/lib/format"; import { hasMinRole } from "@/lib/roles"; import { useAuth } from "@/stores/auth-context"; @@ -43,6 +52,20 @@ export default function WhiteboardPage() { } const EXPORT_MARGIN = 8; +// Same island look as the canvas's own tool island. +const CORNER_ISLAND = "rounded-lg border border-border/70 bg-card shadow-[0_1px_4px_rgb(0_0_0/0.08)]"; +const CORNER_BUTTON = cn( + CORNER_ISLAND, + "inline-flex h-10 w-10 items-center justify-center text-foreground/80 outline-hidden transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 data-expanded:bg-primary/15 data-expanded:text-primary-text", +); + +/** A soft per-person colour, stable for an id, like Excalidraw's collaborator chips. */ +function avatarStyle(userId: string) { + let hash = 0; + for (let i = 0; i < userId.length; i += 1) hash = (hash * 31 + userId.charCodeAt(i)) | 0; + const hue = Math.abs(hash) % 360; + return { "background-color": `hsl(${hue} 70% 86%)`, color: `hsl(${hue} 45% 26%)` }; +} // Build a replayable scene from a set of reassembled strokes (an epoch's marks), // shifted into a tight box like the drawing export pipeline. @@ -207,6 +230,165 @@ function WhiteboardContent() { } }; + // One status line on the canvas, most important first; an action error + // outranks all of them. + const banner = () => { + if (error()) return error(); + if (closed()) return t("whiteboard.closedBanner"); + if (locked()) return t("whiteboard.lockedBanner"); + if (!isParticipant()) return t("whiteboard.readOnlyBanner"); + if (connection() === "disconnected") return t("ws.disconnected"); + return ""; + }; + + const initialOf = (userId: string) => nameOf(userId).slice(0, 1).toLocaleUpperCase(locale()); + + const BoardMenu = () => ( + <> + + + + + + navigate({ to: "/whiteboards" })}> + + {t("whiteboard.back")} + + + setTimeout(() => setHistoryOpen(true), 0)}> + + {t("whiteboard.history")} + + setTimeout(() => setSettingsOpen(true), 0)}> + + {t("whiteboard.edit")} + + + + void toggleLock()}> + + {locked() ? t("whiteboard.unlock") : t("whiteboard.lock")} + + setTimeout(() => setClearOpen(true), 0)}> + + {t("whiteboard.clear")} + + setTimeout(() => setCloseOpen(true), 0)} + > + + {t("whiteboard.close")} + + + + + setTimeout(() => setDeleteOpen(true), 0)}> + + {t("whiteboard.delete")} + + + + + + + ); + + const BoardPresence = () => ( + <> + + + + + {(userId) => ( + + )} + + + 3}> + +{roster().length - 3} + + + +
+

{t("whiteboard.roster")}

+ + + {connection() === "connected" ? t("ws.connected") : connection() === "connecting" ? t("ws.connecting") : t("ws.disconnected")} + +
+
    + + {(userId) => ( +
  • + + {initialOf(userId)} + + + + {nameOf(userId)} + + ({t("whiteboard.you")}) + + + {t("whiteboard.creator")} + + + {roleOf(userId) || userId} + + + + +
  • + )} +
    +
+
+
+ + + + + + ); + return ( }> {(b) => ( -
- - - - - - - - - - - - void toggleLock()}> - - {locked() ? t("whiteboard.unlock") : t("whiteboard.lock")} - - setTimeout(() => setClearOpen(true), 0)}> - - {t("whiteboard.clear")} - - - setTimeout(() => setCloseOpen(true), 0)}> - - {t("whiteboard.close")} - - - - setTimeout(() => setDeleteOpen(true), 0)}> - - {t("whiteboard.delete")} - - - - -
- } + // Edge to edge over the content column's padding, like Excalidraw + // owning the viewport; the height leaves room for the shell header + // (desktop) or the tab bar (phone). +
+

{boardTitle()}

+ } + topRight={} + banner={banner()} + bannerTone={error() ? "error" : "info"} + onState={mergeLive} + onConnectionChange={setConnection} + onDeleted={() => navigate({ to: "/whiteboards" })} /> - - {error()} - - -
- navigate({ to: "/whiteboards" })} - /> - -
-