🎨 Excalidraw-style whiteboards
Browse files at this commit6f21fd4b5dc6d737e0705a99f8bf77335abc370cParent: 23e3aaa- feat
- 🎨 Excalidraw-style whiteboards
16 changed files +1466 -397
- .claude/skills/ui-conventions/SKILL.md +1 -0
- src/components/ui/icons.tsx +30 -0
- src/components/whiteboard/whiteboard-canvas.tsx +586 -244
- src/components/whiteboard/whiteboard-room-ws.tsx +52 -26
- src/i18n/locales/en.ts +30 -2
- src/i18n/locales/tr.ts +30 -2
- src/i18n/messages.ts +28 -0
- src/lib/board-hit.test.ts +48 -0
- src/lib/board-hit.ts +72 -0
- src/lib/board-shapes.test.ts +65 -0
- src/lib/board-shapes.ts +194 -0
- src/lib/board-stroke-codec.test.ts +43 -0
- src/lib/board-stroke-codec.ts +52 -5
- src/lib/draw-stroke.test.ts +20 -0
- src/lib/draw-stroke.ts +14 -2
- src/pages/whiteboard-page.tsx +201 -116
.claude/skills/ui-conventions/SKILL.mdmodified+1 -0
| @@ -79,3 +79,4 @@ Active project reference docs (read the relevant one before changing that area): | |||
| 79 | - **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`. | 79 | - **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`. |
| 80 | - **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`. | 80 | - **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`. |
| 81 | - **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. | 81 | - **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. |
| 82 | +- **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. | ||
src/components/ui/icons.tsxmodified+30 -0
| @@ -41,6 +41,12 @@ import magnifyingGlassUrl from "@phosphor-icons/core/regular/magnifying-glass.sv | |||
| 41 | import packageUrl from "@phosphor-icons/core/regular/package.svg?url"; | 41 | import packageUrl from "@phosphor-icons/core/regular/package.svg?url"; |
| 42 | import paperPlaneTiltUrl from "@phosphor-icons/core/regular/paper-plane-tilt.svg?url"; | 42 | import paperPlaneTiltUrl from "@phosphor-icons/core/regular/paper-plane-tilt.svg?url"; |
| 43 | import pencilSimpleUrl from "@phosphor-icons/core/regular/pencil-simple.svg?url"; | 43 | import pencilSimpleUrl from "@phosphor-icons/core/regular/pencil-simple.svg?url"; |
| 44 | +import handUrl from "@phosphor-icons/core/regular/hand.svg?url"; | ||
| 45 | +import squareUrl from "@phosphor-icons/core/regular/square.svg?url"; | ||
| 46 | +import diamondUrl from "@phosphor-icons/core/regular/diamond.svg?url"; | ||
| 47 | +import circleUrl from "@phosphor-icons/core/regular/circle.svg?url"; | ||
| 48 | +import arrowRightUrl from "@phosphor-icons/core/regular/arrow-right.svg?url"; | ||
| 49 | +import lineSegmentUrl from "@phosphor-icons/core/regular/line-segment.svg?url"; | ||
| 44 | import plusUrl from "@phosphor-icons/core/regular/plus.svg?url"; | 50 | import plusUrl from "@phosphor-icons/core/regular/plus.svg?url"; |
| 45 | import questionUrl from "@phosphor-icons/core/regular/question.svg?url"; | 51 | import questionUrl from "@phosphor-icons/core/regular/question.svg?url"; |
| 46 | import scanUrl from "@phosphor-icons/core/regular/scan.svg?url"; | 52 | import scanUrl from "@phosphor-icons/core/regular/scan.svg?url"; |
| @@ -209,6 +215,30 @@ export function IconEdit(props: IconProps) { | |||
| 209 | return <PhosphorIcon {...props} src={pencilSimpleUrl} />; | 215 | return <PhosphorIcon {...props} src={pencilSimpleUrl} />; |
| 210 | } | 216 | } |
| 211 | 217 | ||
| 218 | +export function IconHand(props: IconProps) { | ||
| 219 | + return <PhosphorIcon {...props} src={handUrl} />; | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +export function IconSquare(props: IconProps) { | ||
| 223 | + return <PhosphorIcon {...props} src={squareUrl} />; | ||
| 224 | +} | ||
| 225 | + | ||
| 226 | +export function IconDiamond(props: IconProps) { | ||
| 227 | + return <PhosphorIcon {...props} src={diamondUrl} />; | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +export function IconCircle(props: IconProps) { | ||
| 231 | + return <PhosphorIcon {...props} src={circleUrl} />; | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +export function IconArrowRight(props: IconProps) { | ||
| 235 | + return <PhosphorIcon {...props} src={arrowRightUrl} />; | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +export function IconLineSegment(props: IconProps) { | ||
| 239 | + return <PhosphorIcon {...props} src={lineSegmentUrl} />; | ||
| 240 | +} | ||
| 241 | + | ||
| 212 | export function IconEraser(props: IconProps) { | 242 | export function IconEraser(props: IconProps) { |
| 213 | return ( | 243 | return ( |
| 214 | <Svg {...props}> | 244 | <Svg {...props}> |
src/components/whiteboard/whiteboard-canvas.tsxmodified+586 -244
| @@ -1,41 +1,104 @@ | |||
| 1 | -import { For, Show, createSignal, onCleanup, onMount } from "solid-js"; | 1 | +import { For, Show, createSignal, onCleanup, onMount, type JSX } from "solid-js"; |
| 2 | import { FullscreenToggle } from "@/components/ui/fullscreen-toggle"; | 2 | import { FullscreenToggle } from "@/components/ui/fullscreen-toggle"; |
| 3 | -import { IconEdit, IconEraser, IconMove, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; | 3 | +import { |
| 4 | + IconArrowRight, | ||
| 5 | + IconCircle, | ||
| 6 | + IconDiamond, | ||
| 7 | + IconEdit, | ||
| 8 | + IconEraser, | ||
| 9 | + IconGrid, | ||
| 10 | + IconHand, | ||
| 11 | + IconLineSegment, | ||
| 12 | + IconSquare, | ||
| 13 | +} from "@/components/ui/icons"; | ||
| 4 | import { cn } from "@/lib/cn"; | 14 | import { cn } from "@/lib/cn"; |
| 5 | import { FULLSCREEN_ROOT_CLASS, createFullscreen } from "@/lib/fullscreen"; | 15 | import { FULLSCREEN_ROOT_CLASS, createFullscreen } from "@/lib/fullscreen"; |
| 16 | +import { constrainEnd, shapeStrokes, type ShapeKind, type Sloppiness } from "@/lib/board-shapes"; | ||
| 17 | +import { strokeHit } from "@/lib/board-hit"; | ||
| 18 | +import type { BoardStroke } from "@/lib/board-stroke-codec"; | ||
| 6 | import { | 19 | import { |
| 7 | PAPER_CELL, | 20 | PAPER_CELL, |
| 8 | PAPER_LINE, | 21 | PAPER_LINE, |
| 9 | paintStroke, | 22 | paintStroke, |
| 10 | - paintTip, | ||
| 11 | type Point, | 23 | type Point, |
| 12 | type Stroke, | 24 | type Stroke, |
| 25 | + type StrokeDash, | ||
| 13 | } from "@/lib/draw-stroke"; | 26 | } from "@/lib/draw-stroke"; |
| 14 | import type { MessageKey } from "@/i18n/messages"; | 27 | import type { MessageKey } from "@/i18n/messages"; |
| 15 | import { useT } from "@/stores/preferences-context"; | 28 | import { useT } from "@/stores/preferences-context"; |
| 16 | 29 | ||
| 17 | -const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; | 30 | +// Layout and vocabulary follow Excalidraw: a tool island top-centre with a |
| 31 | +// single-letter shortcut on every tool, a style island on the left while a | ||
| 32 | +// drawing tool is active, zoom bottom-left, the hand tool on Space / scroll. | ||
| 33 | + | ||
| 34 | +type Tool = "hand" | "pen" | ShapeKind | "eraser"; | ||
| 35 | + | ||
| 36 | +const TOOLS: { tool: Tool; key: string; label: MessageKey; icon: (p: { class?: string }) => JSX.Element }[] = [ | ||
| 37 | + { tool: "hand", key: "H", label: "draw.pan", icon: IconHand }, | ||
| 38 | + { tool: "pen", key: "P", label: "draw.pen", icon: IconEdit }, | ||
| 39 | + { tool: "rectangle", key: "R", label: "draw.rectangle", icon: IconSquare }, | ||
| 40 | + { tool: "diamond", key: "D", label: "draw.diamond", icon: IconDiamond }, | ||
| 41 | + { tool: "ellipse", key: "O", label: "draw.ellipse", icon: IconCircle }, | ||
| 42 | + { tool: "arrow", key: "A", label: "draw.arrow", icon: IconArrowRight }, | ||
| 43 | + { tool: "line", key: "L", label: "draw.line", icon: IconLineSegment }, | ||
| 44 | + { tool: "eraser", key: "E", label: "draw.eraser", icon: IconEraser }, | ||
| 45 | +]; | ||
| 46 | +const TOOL_BY_KEY = new Map(TOOLS.map((entry) => [entry.key.toLowerCase(), entry.tool])); | ||
| 47 | +const SHAPES = new Set<Tool>(["rectangle", "diamond", "ellipse", "arrow", "line"]); | ||
| 48 | +const isShape = (tool: Tool): tool is ShapeKind => SHAPES.has(tool); | ||
| 49 | + | ||
| 50 | +// Excalidraw's default stroke palette. | ||
| 51 | +const COLORS = ["#1e1e1e", "#e03131", "#2f9e44", "#1971c2", "#f08c00"]; | ||
| 18 | /** Spoken name of each swatch — a hex code is no accessible name. */ | 52 | /** Spoken name of each swatch — a hex code is no accessible name. */ |
| 19 | const COLOR_NAMES: Record<string, MessageKey> = { | 53 | const COLOR_NAMES: Record<string, MessageKey> = { |
| 20 | - "#1f2937": "draw.colorName.black", | 54 | + "#1e1e1e": "draw.colorName.black", |
| 21 | - "#dc2626": "draw.colorName.red", | 55 | + "#e03131": "draw.colorName.red", |
| 22 | - "#2563eb": "draw.colorName.blue", | 56 | + "#2f9e44": "draw.colorName.green", |
| 23 | - "#16a34a": "draw.colorName.green", | 57 | + "#1971c2": "draw.colorName.blue", |
| 24 | - "#ca8a04": "draw.colorName.yellow", | 58 | + "#f08c00": "draw.colorName.orange", |
| 25 | }; | 59 | }; |
| 26 | -const WIDTHS = [2, 6, 14]; | 60 | +const WIDTHS: { size: number; label: MessageKey }[] = [ |
| 61 | + { size: 2, label: "draw.widthThin" }, | ||
| 62 | + { size: 4, label: "draw.widthBold" }, | ||
| 63 | + { size: 8, label: "draw.widthExtraBold" }, | ||
| 64 | +]; | ||
| 65 | +const DASHES: { dash: StrokeDash | undefined; label: MessageKey; pattern?: string }[] = [ | ||
| 66 | + { dash: undefined, label: "draw.styleSolid" }, | ||
| 67 | + { dash: "dashed", label: "draw.styleDashed", pattern: "4 3" }, | ||
| 68 | + { dash: "dotted", label: "draw.styleDotted", pattern: "0.5 3" }, | ||
| 69 | +]; | ||
| 70 | +const SLOPPINESS: { slop: Sloppiness; label: MessageKey; path: string }[] = [ | ||
| 71 | + { slop: 0, label: "draw.slopArchitect", path: "M2 12 C6 12 8 6 12 6 S18 12 22 12" }, | ||
| 72 | + { slop: 1, label: "draw.slopArtist", path: "M2 13 C5 11 7 6 10 7 S13 14 16 12 S20 7 22 9" }, | ||
| 73 | + { 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" }, | ||
| 74 | +]; | ||
| 75 | +/** How far the eraser reaches, in screen px (divided by zoom for board-space). */ | ||
| 76 | +const ERASER_REACH = 6; | ||
| 77 | +/** Opacity of strokes the eraser has touched but not yet removed. */ | ||
| 78 | +const ERASE_PENDING_ALPHA = 0.2; | ||
| 79 | +const ERASER_CURSOR = `url("data:image/svg+xml,${encodeURIComponent( | ||
| 80 | + '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><circle cx="8" cy="8" r="6" fill="white" stroke="black" stroke-width="1.2"/></svg>', | ||
| 81 | +)}") 8 8, crosshair`; | ||
| 27 | const ZOOM_MIN = 0.25; | 82 | const ZOOM_MIN = 0.25; |
| 28 | const ZOOM_MAX = 4; | 83 | const ZOOM_MAX = 4; |
| 29 | const ZOOM_STEP = 1.25; | 84 | const ZOOM_STEP = 1.25; |
| 30 | -const OVERLAY_CARD = "absolute z-10 gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-xs backdrop-blur-xs"; | 85 | +// Dark theme flips the ink the way Excalidraw does rather than re-colouring |
| 86 | +// strokes: stored colours stay the same for everyone, only the view inverts. | ||
| 87 | +const DARK_INK = "dark:[filter:invert(93%)_hue-rotate(180deg)]"; | ||
| 88 | +const ISLAND = "rounded-lg border border-border/70 bg-card shadow-[0_1px_4px_rgb(0_0_0/0.08)]"; | ||
| 89 | + | ||
| 90 | +const isTypingTarget = (target: EventTarget | null) => | ||
| 91 | + target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)); | ||
| 31 | 92 | ||
| 32 | // Imperative handle the room uses to push server-confirmed marks onto the | 93 | // Imperative handle the room uses to push server-confirmed marks onto the |
| 33 | // canvas without re-rendering the whole component per stroke. | 94 | // canvas without re-rendering the whole component per stroke. |
| 34 | export type WhiteboardCanvasController = { | 95 | export type WhiteboardCanvasController = { |
| 35 | /** Paint one server-confirmed stroke or segment (board-space coords). */ | 96 | /** Paint one server-confirmed stroke or segment (board-space coords). */ |
| 36 | - applyStroke: (stroke: Stroke) => void; | 97 | + applyStroke: (stroke: BoardStroke) => void; |
| 37 | /** Replace the whole canvas (REST catch-up, resync). */ | 98 | /** Replace the whole canvas (REST catch-up, resync). */ |
| 38 | - loadStrokes: (strokes: Stroke[]) => void; | 99 | + loadStrokes: (strokes: BoardStroke[]) => void; |
| 100 | + /** Drop the strokes with these ids (an erase marker, local or remote). */ | ||
| 101 | + removeStrokes: (ids: string[]) => void; | ||
| 39 | /** Blank the live canvas (a clear / epoch bump — history is untouched). */ | 102 | /** Blank the live canvas (a clear / epoch bump — history is untouched). */ |
| 40 | reset: () => void; | 103 | reset: () => void; |
| 41 | }; | 104 | }; |
| @@ -45,118 +108,250 @@ export type WhiteboardCanvasController = { | |||
| 45 | * never saves a File: each finished local stroke is emitted through | 108 | * never saves a File: each finished local stroke is emitted through |
| 46 | * `props.onStroke` (board-space, device/zoom independent) for the room to send | 109 | * `props.onStroke` (board-space, device/zoom independent) for the room to send |
| 47 | * over the socket, and server-confirmed strokes are pushed back in through the | 110 | * over the socket, and server-confirmed strokes are pushed back in through the |
| 48 | - * controller. Strokes are held in a plain array and painted incrementally so a | 111 | + * controller. Shapes are baked into plain strokes (see lib/board-shapes), so |
| 49 | - * busy board stays cheap; a full redraw only runs on pan / zoom / resize. | 112 | + * the wire and the history replay only ever see strokes. Committed strokes are |
| 113 | + * held in a plain array and painted incrementally; the mark being drawn lives | ||
| 114 | + * on a separate preview canvas so a shape can be re-drawn on every move. | ||
| 50 | */ | 115 | */ |
| 51 | export function WhiteboardCanvas(props: { | 116 | export function WhiteboardCanvas(props: { |
| 52 | disabled?: boolean; | 117 | disabled?: boolean; |
| 53 | - onStroke: (stroke: Stroke) => void; | 118 | + /** A finished local stroke; its `id` is the sid it must travel under. */ |
| 119 | + onStroke: (stroke: BoardStroke) => void; | ||
| 120 | + /** The eraser removed these strokes locally; the room logs the removal. */ | ||
| 121 | + onErase: (ids: string[]) => void; | ||
| 122 | + /** Board-level controls docked top-right, beside the tool island. */ | ||
| 123 | + topRight?: JSX.Element; | ||
| 124 | + /** Board-level controls docked top-left (the board menu). */ | ||
| 125 | + topLeft?: JSX.Element; | ||
| 126 | + /** A status line under the tool island (locked, closed, an error). */ | ||
| 127 | + banner?: string; | ||
| 128 | + bannerTone?: "info" | "error"; | ||
| 129 | + /** Fill the parent edge to edge, the way Excalidraw owns the viewport. */ | ||
| 130 | + fill?: boolean; | ||
| 54 | controllerRef?: (c: WhiteboardCanvasController) => void; | 131 | controllerRef?: (c: WhiteboardCanvasController) => void; |
| 55 | class?: string; | 132 | class?: string; |
| 56 | }) { | 133 | }) { |
| 57 | const t = useT(); | 134 | const t = useT(); |
| 58 | let canvas: HTMLCanvasElement | undefined; | 135 | let canvas: HTMLCanvasElement | undefined; |
| 136 | + let preview: HTMLCanvasElement | undefined; | ||
| 59 | let wrap: HTMLDivElement | undefined; | 137 | let wrap: HTMLDivElement | undefined; |
| 60 | let root: HTMLDivElement | undefined; | 138 | let root: HTMLDivElement | undefined; |
| 61 | - let current: Stroke | undefined; | 139 | + let current: BoardStroke | undefined; |
| 140 | + // Excalidraw's eraser: strokes swept over fade while the button is held and | ||
| 141 | + // are removed on release, whole — never cut into pieces. | ||
| 142 | + let erasing: { ids: Set<string>; trail: Point[] } | undefined; | ||
| 143 | + let shape: { kind: ShapeKind; start: Point; seed: number; strokes: Stroke[] } | undefined; | ||
| 62 | // The ResizeObserver on `wrap` re-sizes the backing store on enter/exit and | 144 | // The ResizeObserver on `wrap` re-sizes the backing store on enter/exit and |
| 63 | // redraw() repaints `committed`, so no stroke is lost. | 145 | // redraw() repaints `committed`, so no stroke is lost. |
| 64 | const fullscreen = createFullscreen(() => root); | 146 | const fullscreen = createFullscreen(() => root); |
| 65 | let panStart: { x: number; y: number; px: number; py: number } | undefined; | 147 | let panStart: { x: number; y: number; px: number; py: number } | undefined; |
| 66 | // Every committed mark (local + remote), in draw order. Plain array, not a | 148 | // Every committed mark (local + remote), in draw order. Plain array, not a |
| 67 | // signal: it can grow into the thousands and only pan/zoom/resize repaints it. | 149 | // signal: it can grow into the thousands and only pan/zoom/resize repaints it. |
| 68 | - const committed: Stroke[] = []; | 150 | + const committed: BoardStroke[] = []; |
| 151 | + // Ids already erased, so a late segment of a removed stroke never reappears. | ||
| 152 | + const removed = new Set<string>(); | ||
| 153 | + let idSeq = 0; | ||
| 154 | + const newId = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}-${(idSeq += 1)}`; | ||
| 69 | 155 | ||
| 70 | const [color, setColor] = createSignal(COLORS[0]); | 156 | const [color, setColor] = createSignal(COLORS[0]); |
| 71 | - const [width, setWidth] = createSignal(WIDTHS[1]); | 157 | + const [width, setWidth] = createSignal(WIDTHS[1].size); |
| 72 | - const [erasing, setErasing] = createSignal(false); | 158 | + const [dash, setDash] = createSignal<StrokeDash | undefined>(undefined); |
| 159 | + const [slop, setSlop] = createSignal<Sloppiness>(1); | ||
| 73 | // The board opens on the hand tool: it is a shared live canvas, so a stray | 160 | // The board opens on the hand tool: it is a shared live canvas, so a stray |
| 74 | - // tap or scroll must not leave a mark for everyone — drawing starts only | 161 | + // tap must not leave a mark for everyone — drawing starts once a tool is picked. |
| 75 | - // once the pen (or a colour) is picked. | 162 | + const [tool, setTool] = createSignal<Tool>("hand"); |
| 76 | - const [hand, setHand] = createSignal(true); | 163 | + // A middle-drag pans and a right-drag erases for as long as the button is held. |
| 77 | - const [override, setOverride] = createSignal<null | "pan" | "erase">(null); | 164 | + const [override, setOverride] = createSignal<null | "hand" | "eraser">(null); |
| 165 | + const [spaceHeld, setSpaceHeld] = createSignal(false); | ||
| 78 | const [pan, setPan] = createSignal({ x: 0, y: 0 }); | 166 | const [pan, setPan] = createSignal({ x: 0, y: 0 }); |
| 79 | const [panning, setPanning] = createSignal(false); | 167 | const [panning, setPanning] = createSignal(false); |
| 80 | const [zoom, setZoom] = createSignal(1); | 168 | const [zoom, setZoom] = createSignal(1); |
| 81 | const [empty, setEmpty] = createSignal(true); | 169 | const [empty, setEmpty] = createSignal(true); |
| 170 | + const [grid, setGrid] = createSignal(false); | ||
| 171 | + // Phones have no room for the style island next to the canvas, so there it | ||
| 172 | + // opens on demand from the swatch button bottom-left. | ||
| 173 | + const [styleOpen, setStyleOpen] = createSignal(false); | ||
| 174 | + // Below this width the tool island no longer fits between the corner | ||
| 175 | + // controls, so it drops to a second row. | ||
| 176 | + const [wide, setWide] = createSignal(true); | ||
| 177 | + const hasCorners = () => Boolean(props.topLeft || props.topRight); | ||
| 178 | + const toolbarRow2 = () => hasCorners() && !wide() && !fullscreen.active(); | ||
| 179 | + const showsStyle = () => activeTool() !== "hand" && activeTool() !== "eraser"; | ||
| 82 | 180 | ||
| 83 | const ratio = () => window.devicePixelRatio || 1; | 181 | const ratio = () => window.devicePixelRatio || 1; |
| 84 | const context = () => canvas?.getContext("2d") ?? null; | 182 | const context = () => canvas?.getContext("2d") ?? null; |
| 85 | 183 | ||
| 86 | - const activeTool = (): "pen" | "erase" | "pan" => { | 184 | + const activeTool = (): Tool => override() ?? (spaceHeld() ? "hand" : tool()); |
| 87 | - const o = override(); | ||
| 88 | - if (o) return o; | ||
| 89 | - if (hand()) return "pan"; | ||
| 90 | - if (erasing()) return "erase"; | ||
| 91 | - return "pen"; | ||
| 92 | - }; | ||
| 93 | 185 | ||
| 94 | const cursor = () => { | 186 | const cursor = () => { |
| 95 | - const tool = activeTool(); | 187 | + const active = activeTool(); |
| 96 | - if (tool === "pan") return panning() ? "grabbing" : "grab"; | 188 | + if (active === "hand") return panning() ? "grabbing" : "grab"; |
| 189 | + if (active === "eraser") return ERASER_CURSOR; | ||
| 97 | return "crosshair"; | 190 | return "crosshair"; |
| 98 | }; | 191 | }; |
| 99 | 192 | ||
| 100 | - const redraw = () => { | 193 | + const worldTransform = (c: CanvasRenderingContext2D) => { |
| 101 | - const c = context(); | ||
| 102 | - if (!c || !canvas) return; | ||
| 103 | const scale = ratio(); | 194 | const scale = ratio(); |
| 104 | - c.setTransform(scale, 0, 0, scale, 0, 0); | ||
| 105 | - c.clearRect(0, 0, canvas.width / scale, canvas.height / scale); | ||
| 106 | const p = pan(); | 195 | const p = pan(); |
| 107 | const z = zoom(); | 196 | const z = zoom(); |
| 108 | c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); | 197 | c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); |
| 109 | - for (const stroke of committed) paintStroke(c, stroke); | 198 | + }; |
| 110 | - if (current) paintStroke(c, current); | 199 | + |
| 200 | + const clearCanvas = (target: HTMLCanvasElement | undefined) => { | ||
| 201 | + const c = target?.getContext("2d"); | ||
| 202 | + if (!c || !target) return null; | ||
| 203 | + const scale = ratio(); | ||
| 204 | + c.setTransform(scale, 0, 0, scale, 0, 0); | ||
| 205 | + c.clearRect(0, 0, target.width / scale, target.height / scale); | ||
| 206 | + return c; | ||
| 207 | + }; | ||
| 208 | + | ||
| 209 | + const redraw = () => { | ||
| 210 | + const c = clearCanvas(canvas); | ||
| 211 | + if (!c) return; | ||
| 212 | + worldTransform(c); | ||
| 213 | + const pending = erasing?.ids; | ||
| 214 | + for (const stroke of committed) { | ||
| 215 | + const fading = pending !== undefined && stroke.id !== undefined && pending.has(stroke.id); | ||
| 216 | + if (fading) c.globalAlpha = ERASE_PENDING_ALPHA; | ||
| 217 | + paintStroke(c, stroke); | ||
| 218 | + if (fading) c.globalAlpha = 1; | ||
| 219 | + } | ||
| 220 | + }; | ||
| 221 | + | ||
| 222 | + /** Repaint the in-progress pen line or shape on the preview layer. */ | ||
| 223 | + const paintPreview = (strokes: Stroke[]) => { | ||
| 224 | + const c = clearCanvas(preview); | ||
| 225 | + if (!c) return; | ||
| 226 | + worldTransform(c); | ||
| 227 | + for (const stroke of strokes) paintStroke(c, stroke); | ||
| 111 | }; | 228 | }; |
| 112 | 229 | ||
| 113 | const resize = () => { | 230 | const resize = () => { |
| 114 | - if (!canvas) return; | 231 | + if (!canvas || !preview) return; |
| 115 | const rect = canvas.getBoundingClientRect(); | 232 | const rect = canvas.getBoundingClientRect(); |
| 116 | if (rect.width === 0 || rect.height === 0) return; | 233 | if (rect.width === 0 || rect.height === 0) return; |
| 234 | + setWide(rect.width >= 1000); | ||
| 117 | const scale = ratio(); | 235 | const scale = ratio(); |
| 118 | - canvas.width = Math.round(rect.width * scale); | 236 | + for (const target of [canvas, preview]) { |
| 119 | - canvas.height = Math.round(rect.height * scale); | 237 | + target.width = Math.round(rect.width * scale); |
| 238 | + target.height = Math.round(rect.height * scale); | ||
| 239 | + } | ||
| 120 | redraw(); | 240 | redraw(); |
| 121 | }; | 241 | }; |
| 122 | 242 | ||
| 123 | // Paint one just-committed stroke on top of the current transform, without a | 243 | // Paint one just-committed stroke on top of the current transform, without a |
| 124 | // full redraw. The transform matches redraw()'s so it lands in the same place. | 244 | // full redraw. The transform matches redraw()'s so it lands in the same place. |
| 125 | - const paintOne = (stroke: Stroke) => { | 245 | + const paintOne = (stroke: BoardStroke) => { |
| 126 | const c = context(); | 246 | const c = context(); |
| 127 | - if (!c || !canvas) return; | 247 | + if (!c) return; |
| 128 | - const scale = ratio(); | 248 | + worldTransform(c); |
| 129 | - const p = pan(); | ||
| 130 | - const z = zoom(); | ||
| 131 | - c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); | ||
| 132 | paintStroke(c, stroke); | 249 | paintStroke(c, stroke); |
| 133 | }; | 250 | }; |
| 134 | 251 | ||
| 252 | + const removeLocal = (ids: Iterable<string>) => { | ||
| 253 | + for (const id of ids) removed.add(id); | ||
| 254 | + const kept = committed.filter((stroke) => !(stroke.id && removed.has(stroke.id))); | ||
| 255 | + if (kept.length === committed.length) return; | ||
| 256 | + committed.length = 0; | ||
| 257 | + committed.push(...kept); | ||
| 258 | + setEmpty(committed.length === 0); | ||
| 259 | + redraw(); | ||
| 260 | + }; | ||
| 261 | + | ||
| 135 | const controller: WhiteboardCanvasController = { | 262 | const controller: WhiteboardCanvasController = { |
| 136 | applyStroke: (stroke) => { | 263 | applyStroke: (stroke) => { |
| 264 | + if (stroke.id && removed.has(stroke.id)) return; | ||
| 137 | committed.push(stroke); | 265 | committed.push(stroke); |
| 138 | setEmpty(false); | 266 | setEmpty(false); |
| 139 | paintOne(stroke); | 267 | paintOne(stroke); |
| 140 | }, | 268 | }, |
| 141 | loadStrokes: (strokes) => { | 269 | loadStrokes: (strokes) => { |
| 270 | + removed.clear(); | ||
| 142 | committed.length = 0; | 271 | committed.length = 0; |
| 143 | committed.push(...strokes); | 272 | committed.push(...strokes); |
| 144 | setEmpty(committed.length === 0); | 273 | setEmpty(committed.length === 0); |
| 145 | redraw(); | 274 | redraw(); |
| 146 | }, | 275 | }, |
| 276 | + removeStrokes: (ids) => removeLocal(ids), | ||
| 147 | reset: () => { | 277 | reset: () => { |
| 278 | + removed.clear(); | ||
| 148 | committed.length = 0; | 279 | committed.length = 0; |
| 149 | setEmpty(true); | 280 | setEmpty(true); |
| 150 | redraw(); | 281 | redraw(); |
| 151 | }, | 282 | }, |
| 152 | }; | 283 | }; |
| 153 | 284 | ||
| 285 | + const zoomAt = (cx: number, cy: number, factor: number) => { | ||
| 286 | + const p = pan(); | ||
| 287 | + const z0 = zoom(); | ||
| 288 | + const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); | ||
| 289 | + if (z1 === z0) return; | ||
| 290 | + const wx = (cx - p.x) / z0; | ||
| 291 | + const wy = (cy - p.y) / z0; | ||
| 292 | + setZoom(z1); | ||
| 293 | + setPan({ x: cx - wx * z1, y: cy - wy * z1 }); | ||
| 294 | + redraw(); | ||
| 295 | + }; | ||
| 296 | + | ||
| 297 | + const zoomBy = (factor: number) => { | ||
| 298 | + if (!canvas) return; | ||
| 299 | + const rect = canvas.getBoundingClientRect(); | ||
| 300 | + zoomAt(rect.width / 2, rect.height / 2, factor); | ||
| 301 | + }; | ||
| 302 | + | ||
| 303 | + const resetZoom = () => zoomBy(1 / zoom()); | ||
| 304 | + | ||
| 305 | + const pickTool = (next: Tool) => { | ||
| 306 | + setTool(next); | ||
| 307 | + if (next === "hand") setStyleOpen(false); | ||
| 308 | + }; | ||
| 309 | + | ||
| 310 | + const onKeyDown = (e: KeyboardEvent) => { | ||
| 311 | + if (e.defaultPrevented || isTypingTarget(e.target)) return; | ||
| 312 | + // A side panel or confirm dialog above the board owns the keyboard. | ||
| 313 | + if (e.target instanceof Element && e.target.closest("[role='dialog']")) return; | ||
| 314 | + if (e.code === "Space") { | ||
| 315 | + // A focused button keeps Space as its own activation key. | ||
| 316 | + if (e.target instanceof HTMLButtonElement) return; | ||
| 317 | + e.preventDefault(); | ||
| 318 | + if (!e.repeat) setSpaceHeld(true); | ||
| 319 | + return; | ||
| 320 | + } | ||
| 321 | + if (e.ctrlKey || e.metaKey) { | ||
| 322 | + if (e.key === "=" || e.key === "+") zoomBy(ZOOM_STEP); | ||
| 323 | + else if (e.key === "-") zoomBy(1 / ZOOM_STEP); | ||
| 324 | + else if (e.key === "0") resetZoom(); | ||
| 325 | + else return; | ||
| 326 | + e.preventDefault(); | ||
| 327 | + return; | ||
| 328 | + } | ||
| 329 | + if (e.altKey || e.repeat) return; | ||
| 330 | + const next = TOOL_BY_KEY.get(e.key.toLowerCase()); | ||
| 331 | + if (next) { | ||
| 332 | + e.preventDefault(); | ||
| 333 | + pickTool(next); | ||
| 334 | + } | ||
| 335 | + }; | ||
| 336 | + const onKeyUp = (e: KeyboardEvent) => { | ||
| 337 | + if (e.code === "Space") setSpaceHeld(false); | ||
| 338 | + }; | ||
| 339 | + const onBlur = () => setSpaceHeld(false); | ||
| 340 | + | ||
| 154 | onMount(() => { | 341 | onMount(() => { |
| 155 | resize(); | 342 | resize(); |
| 156 | props.controllerRef?.(controller); | 343 | props.controllerRef?.(controller); |
| 157 | const observer = new ResizeObserver(() => resize()); | 344 | const observer = new ResizeObserver(() => resize()); |
| 158 | if (wrap) observer.observe(wrap); | 345 | if (wrap) observer.observe(wrap); |
| 159 | - onCleanup(() => observer.disconnect()); | 346 | + window.addEventListener("keydown", onKeyDown); |
| 347 | + window.addEventListener("keyup", onKeyUp); | ||
| 348 | + window.addEventListener("blur", onBlur); | ||
| 349 | + onCleanup(() => { | ||
| 350 | + observer.disconnect(); | ||
| 351 | + window.removeEventListener("keydown", onKeyDown); | ||
| 352 | + window.removeEventListener("keyup", onKeyUp); | ||
| 353 | + window.removeEventListener("blur", onBlur); | ||
| 354 | + }); | ||
| 160 | }); | 355 | }); |
| 161 | 356 | ||
| 162 | const pointAt = (e: PointerEvent): Point => { | 357 | const pointAt = (e: PointerEvent): Point => { |
| @@ -166,50 +361,58 @@ export function WhiteboardCanvas(props: { | |||
| 166 | return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z }; | 361 | return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z }; |
| 167 | }; | 362 | }; |
| 168 | 363 | ||
| 169 | - const zoomBy = (factor: number) => { | 364 | + /** Mark every stroke the eraser's latest move touched; true when any is new. */ |
| 170 | - if (!canvas) return; | 365 | + const sweep = (a: Point, b: Point) => { |
| 171 | - const rect = canvas.getBoundingClientRect(); | 366 | + if (!erasing) return false; |
| 172 | - const cx = rect.width / 2; | 367 | + const reach = ERASER_REACH / zoom(); |
| 173 | - const cy = rect.height / 2; | 368 | + let hit = false; |
| 174 | - const p = pan(); | 369 | + for (const stroke of committed) { |
| 175 | - const z0 = zoom(); | 370 | + if (!stroke.id || erasing.ids.has(stroke.id)) continue; |
| 176 | - const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); | 371 | + if (strokeHit(stroke, a, b, reach)) { |
| 177 | - if (z1 === z0) return; | 372 | + erasing.ids.add(stroke.id); |
| 178 | - const wx = (cx - p.x) / z0; | 373 | + hit = true; |
| 179 | - const wy = (cy - p.y) / z0; | 374 | + } |
| 180 | - setZoom(z1); | 375 | + } |
| 181 | - setPan({ x: cx - wx * z1, y: cy - wy * z1 }); | 376 | + return hit; |
| 182 | - redraw(); | ||
| 183 | }; | 377 | }; |
| 184 | 378 | ||
| 185 | - const resetZoom = () => zoomBy(1 / zoom()); | 379 | + /** A short fading grey trail behind the eraser, on the preview layer. */ |
| 186 | - | 380 | + const paintTrail = (trail: Point[]) => { |
| 187 | - const drawTip = (stroke: Stroke) => { | 381 | + const c = clearCanvas(preview); |
| 188 | - const c = context(); | 382 | + if (!c) return; |
| 189 | - if (c) paintTip(c, stroke); | 383 | + worldTransform(c); |
| 384 | + const tail = trail.slice(-12); | ||
| 385 | + paintStroke(c, { color: "rgba(120, 120, 120, 0.35)", width: 5 / zoom(), erase: false, points: tail }); | ||
| 190 | }; | 386 | }; |
| 191 | 387 | ||
| 388 | + const strokeStyle = () => ({ color: color(), width: width(), ...(dash() ? { dash: dash() } : {}) }); | ||
| 389 | + | ||
| 192 | const startStroke = (e: PointerEvent) => { | 390 | const startStroke = (e: PointerEvent) => { |
| 193 | - if (props.disabled && !(e.button === 1 || hand())) return; | 391 | + const panNow = e.button === 1 || (activeTool() === "hand" && e.button !== 2); |
| 392 | + if (props.disabled && !panNow) return; | ||
| 194 | e.preventDefault(); | 393 | e.preventDefault(); |
| 195 | canvas?.setPointerCapture(e.pointerId); | 394 | canvas?.setPointerCapture(e.pointerId); |
| 196 | - if (e.button === 1 || (hand() && e.button !== 2)) { | 395 | + if (panNow) { |
| 197 | - if (e.button === 1) setOverride("pan"); | 396 | + if (e.button === 1) setOverride("hand"); |
| 198 | const p = pan(); | 397 | const p = pan(); |
| 199 | panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y }; | 398 | panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y }; |
| 200 | setPanning(true); | 399 | setPanning(true); |
| 201 | return; | 400 | return; |
| 202 | } | 401 | } |
| 203 | - if (props.disabled) return; | 402 | + const point = pointAt(e); |
| 204 | - const eraseNow = erasing() || e.button === 2; | 403 | + if (e.button === 2 || activeTool() === "eraser") { |
| 205 | - if (e.button === 2) setOverride("erase"); | 404 | + if (e.button === 2) setOverride("eraser"); |
| 206 | - current = { | 405 | + erasing = { ids: new Set(), trail: [point] }; |
| 207 | - color: color(), | 406 | + if (sweep(point, point)) redraw(); |
| 208 | - width: eraseNow ? width() * 2.5 : width(), | 407 | + return; |
| 209 | - erase: eraseNow, | 408 | + } |
| 210 | - points: [pointAt(e)], | 409 | + const active = activeTool(); |
| 211 | - }; | 410 | + if (isShape(active)) { |
| 212 | - drawTip(current); | 411 | + shape = { kind: active, start: point, seed: Math.floor(Math.random() * 2 ** 31), strokes: [] }; |
| 412 | + return; | ||
| 413 | + } | ||
| 414 | + current = { ...strokeStyle(), erase: false, id: newId(), points: [point] }; | ||
| 415 | + paintPreview([current]); | ||
| 213 | }; | 416 | }; |
| 214 | 417 | ||
| 215 | const extendStroke = (e: PointerEvent) => { | 418 | const extendStroke = (e: PointerEvent) => { |
| @@ -218,9 +421,30 @@ export function WhiteboardCanvas(props: { | |||
| 218 | redraw(); | 421 | redraw(); |
| 219 | return; | 422 | return; |
| 220 | } | 423 | } |
| 424 | + if (shape) { | ||
| 425 | + const point = pointAt(e); | ||
| 426 | + const end = e.shiftKey ? constrainEnd(shape.kind, shape.start, point) : point; | ||
| 427 | + shape.strokes = shapeStrokes(shape.kind, shape.start, end, strokeStyle(), slop(), shape.seed); | ||
| 428 | + paintPreview(shape.strokes); | ||
| 429 | + return; | ||
| 430 | + } | ||
| 431 | + if (erasing) { | ||
| 432 | + const point = pointAt(e); | ||
| 433 | + const prev = erasing.trail[erasing.trail.length - 1]; | ||
| 434 | + erasing.trail.push(point); | ||
| 435 | + if (sweep(prev, point)) redraw(); | ||
| 436 | + paintTrail(erasing.trail); | ||
| 437 | + return; | ||
| 438 | + } | ||
| 221 | if (!current) return; | 439 | if (!current) return; |
| 222 | current.points.push(pointAt(e)); | 440 | current.points.push(pointAt(e)); |
| 223 | - drawTip(current); | 441 | + paintPreview([current]); |
| 442 | + }; | ||
| 443 | + | ||
| 444 | + const commit = (stroke: BoardStroke) => { | ||
| 445 | + committed.push(stroke); | ||
| 446 | + setEmpty(false); | ||
| 447 | + props.onStroke(stroke); | ||
| 224 | }; | 448 | }; |
| 225 | 449 | ||
| 226 | const endStroke = () => { | 450 | const endStroke = () => { |
| @@ -230,110 +454,60 @@ export function WhiteboardCanvas(props: { | |||
| 230 | setPanning(false); | 454 | setPanning(false); |
| 231 | return; | 455 | return; |
| 232 | } | 456 | } |
| 457 | + clearCanvas(preview); | ||
| 458 | + if (erasing) { | ||
| 459 | + const ids = [...erasing.ids]; | ||
| 460 | + erasing = undefined; | ||
| 461 | + if (ids.length === 0) return; | ||
| 462 | + removeLocal(ids); | ||
| 463 | + props.onErase(ids); | ||
| 464 | + return; | ||
| 465 | + } | ||
| 466 | + if (shape) { | ||
| 467 | + const strokes = shape.strokes; | ||
| 468 | + shape = undefined; | ||
| 469 | + for (const bare of strokes) { | ||
| 470 | + const stroke: BoardStroke = { ...bare, id: newId() }; | ||
| 471 | + paintOne(stroke); | ||
| 472 | + commit(stroke); | ||
| 473 | + } | ||
| 474 | + return; | ||
| 475 | + } | ||
| 233 | const done = current; | 476 | const done = current; |
| 234 | current = undefined; | 477 | current = undefined; |
| 235 | if (!done || done.points.length === 0) return; | 478 | if (!done || done.points.length === 0) return; |
| 236 | - committed.push(done); | 479 | + paintOne(done); |
| 237 | - setEmpty(false); | 480 | + commit(done); |
| 238 | - redraw(); // swap the live polyline for its smoothed replay | ||
| 239 | - props.onStroke(done); | ||
| 240 | }; | 481 | }; |
| 241 | 482 | ||
| 242 | - const toolClass = (active: boolean) => | 483 | + const onWheel = (e: WheelEvent) => { |
| 243 | - cn( | 484 | + e.preventDefault(); |
| 244 | - "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors", | 485 | + const unit = e.deltaMode === 1 ? 16 : 1; // Firefox reports lines |
| 245 | - active | 486 | + if (e.ctrlKey || e.metaKey) { |
| 246 | - ? "border-primary bg-primary text-primary-foreground shadow-xs" | 487 | + // Ctrl+wheel and trackpad pinch zoom toward the pointer. |
| 247 | - : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground", | 488 | + const rect = canvas!.getBoundingClientRect(); |
| 248 | - ); | 489 | + const delta = Math.max(-50, Math.min(50, e.deltaY * unit)); |
| 249 | - | 490 | + zoomAt(e.clientX - rect.left, e.clientY - rect.top, Math.exp(-delta * 0.01)); |
| 250 | - // Shared button groups rendered twice: once inside the mobile wrapping bar, | 491 | + return; |
| 251 | - // once inside the three desktop corner islands. Each instance mounts its own | 492 | + } |
| 252 | - // reactive scope over the same signals above, so both stay in sync. | 493 | + const horizontal = e.shiftKey && e.deltaX === 0; |
| 253 | - const ToolButtons = () => ( | 494 | + const dx = (horizontal ? e.deltaY : e.deltaX) * unit; |
| 254 | - <> | 495 | + const dy = (horizontal ? 0 : e.deltaY) * unit; |
| 255 | - <button | 496 | + setPan((p) => ({ x: p.x - dx, y: p.y - dy })); |
| 256 | - type="button" | 497 | + redraw(); |
| 257 | - class={toolClass(activeTool() === "pen")} | 498 | + }; |
| 258 | - title={t("draw.pen")} | ||
| 259 | - aria-pressed={activeTool() === "pen"} | ||
| 260 | - onClick={() => { | ||
| 261 | - setErasing(false); | ||
| 262 | - setHand(false); | ||
| 263 | - }} | ||
| 264 | - > | ||
| 265 | - <IconEdit class="h-5 w-5" /> | ||
| 266 | - <span class="sr-only">{t("draw.pen")}</span> | ||
| 267 | - </button> | ||
| 268 | - <button | ||
| 269 | - type="button" | ||
| 270 | - class={toolClass(activeTool() === "erase")} | ||
| 271 | - title={t("draw.eraser")} | ||
| 272 | - aria-pressed={activeTool() === "erase"} | ||
| 273 | - onClick={() => { | ||
| 274 | - setErasing(true); | ||
| 275 | - setHand(false); | ||
| 276 | - }} | ||
| 277 | - > | ||
| 278 | - <IconEraser class="h-5 w-5" /> | ||
| 279 | - <span class="sr-only">{t("draw.eraser")}</span> | ||
| 280 | - </button> | ||
| 281 | - <button | ||
| 282 | - type="button" | ||
| 283 | - class={toolClass(activeTool() === "pan")} | ||
| 284 | - title={t("draw.pan")} | ||
| 285 | - aria-pressed={activeTool() === "pan"} | ||
| 286 | - onClick={() => setHand(true)} | ||
| 287 | - > | ||
| 288 | - <IconMove class="h-5 w-5" /> | ||
| 289 | - <span class="sr-only">{t("draw.pan")}</span> | ||
| 290 | - </button> | ||
| 291 | - </> | ||
| 292 | - ); | ||
| 293 | - | ||
| 294 | - const ColorSwatches = () => ( | ||
| 295 | - <For each={COLORS}> | ||
| 296 | - {(swatch) => ( | ||
| 297 | - <button | ||
| 298 | - type="button" | ||
| 299 | - title={`${t("draw.color")}: ${t(COLOR_NAMES[swatch])}`} | ||
| 300 | - aria-label={`${t("draw.color")}: ${t(COLOR_NAMES[swatch])}`} | ||
| 301 | - aria-pressed={color() === swatch && activeTool() === "pen"} | ||
| 302 | - class={cn( | ||
| 303 | - "h-9 w-9 sm:h-11 sm:w-11 rounded-lg border-2 transition-transform", | ||
| 304 | - color() === swatch && activeTool() === "pen" | ||
| 305 | - ? "border-foreground scale-105" | ||
| 306 | - : "border-border/60 hover:scale-105", | ||
| 307 | - )} | ||
| 308 | - style={{ "background-color": swatch }} | ||
| 309 | - onClick={() => { | ||
| 310 | - setColor(swatch); | ||
| 311 | - setErasing(false); | ||
| 312 | - setHand(false); | ||
| 313 | - }} | ||
| 314 | - /> | ||
| 315 | - )} | ||
| 316 | - </For> | ||
| 317 | - ); | ||
| 318 | 499 | ||
| 319 | - const WidthButtons = () => ( | 500 | + const hint = () => { |
| 320 | - <For each={WIDTHS}> | 501 | + const active = activeTool(); |
| 321 | - {(size) => ( | 502 | + if (props.disabled) return active === "hand" ? t("whiteboard.panHint") : ""; |
| 322 | - <button | 503 | + if (isShape(active)) return t("whiteboard.shapeHint"); |
| 323 | - type="button" | 504 | + if (active === "eraser") return t("whiteboard.eraserHint"); |
| 324 | - title={`${t("draw.width")}: ${size}`} | 505 | + if (active === "hand" || active === "pen") return t("whiteboard.panHint"); |
| 325 | - aria-label={`${t("draw.width")}: ${size}`} | 506 | + return ""; |
| 326 | - aria-pressed={width() === size} | 507 | + }; |
| 327 | - class={toolClass(width() === size)} | ||
| 328 | - onClick={() => setWidth(size)} | ||
| 329 | - > | ||
| 330 | - <span class="rounded-full bg-current" style={{ width: `${size + 2}px`, height: `${size + 2}px` }} /> | ||
| 331 | - </button> | ||
| 332 | - )} | ||
| 333 | - </For> | ||
| 334 | - ); | ||
| 335 | 508 | ||
| 336 | const paperStyle = () => { | 509 | const paperStyle = () => { |
| 510 | + if (!grid()) return {}; | ||
| 337 | const cell = PAPER_CELL * zoom(); | 511 | const cell = PAPER_CELL * zoom(); |
| 338 | const p = pan(); | 512 | const p = pan(); |
| 339 | return { | 513 | return { |
| @@ -343,19 +517,36 @@ export function WhiteboardCanvas(props: { | |||
| 343 | }; | 517 | }; |
| 344 | }; | 518 | }; |
| 345 | 519 | ||
| 520 | + const optionClass = (active: boolean) => | ||
| 521 | + cn( | ||
| 522 | + "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", | ||
| 523 | + active ? "bg-primary/15 text-primary-text ring-1 ring-primary/40" : "bg-muted/60 text-foreground/80 hover:bg-muted", | ||
| 524 | + ); | ||
| 525 | + | ||
| 526 | + const plainButton = | ||
| 527 | + "flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"; | ||
| 528 | + | ||
| 529 | + const Section = (sectionProps: { label: string; children: JSX.Element }) => ( | ||
| 530 | + <div role="group" aria-label={sectionProps.label}> | ||
| 531 | + <p class="mb-1.5 text-[11px] font-medium text-muted-foreground">{sectionProps.label}</p> | ||
| 532 | + <div class="flex flex-wrap gap-1.5">{sectionProps.children}</div> | ||
| 533 | + </div> | ||
| 534 | + ); | ||
| 535 | + | ||
| 346 | return ( | 536 | return ( |
| 347 | - <div ref={root} class={cn("space-y-3", props.class, fullscreen.active() && FULLSCREEN_ROOT_CLASS)}> | 537 | + <div ref={root} class={cn(props.class, fullscreen.active() && FULLSCREEN_ROOT_CLASS)}> |
| 348 | <div | 538 | <div |
| 349 | ref={wrap} | 539 | ref={wrap} |
| 350 | class={cn( | 540 | class={cn( |
| 351 | - "relative h-104 overflow-hidden rounded-lg border bg-white shadow-inner sm:h-[70vh]", | 541 | + "relative overflow-hidden bg-white dark:bg-[#121212]", |
| 542 | + props.fill ? "h-full" : "h-112 rounded-xl border sm:h-[72vh]", | ||
| 352 | fullscreen.active() && "h-auto min-h-0 flex-1 sm:h-auto", | 543 | fullscreen.active() && "h-auto min-h-0 flex-1 sm:h-auto", |
| 353 | )} | 544 | )} |
| 354 | style={paperStyle()} | 545 | style={paperStyle()} |
| 355 | > | 546 | > |
| 356 | <canvas | 547 | <canvas |
| 357 | ref={canvas} | 548 | ref={canvas} |
| 358 | - class="h-full w-full touch-none" | 549 | + class={cn("h-full w-full touch-none", DARK_INK)} |
| 359 | style={{ cursor: cursor() }} | 550 | style={{ cursor: cursor() }} |
| 360 | onMouseDown={(e) => { | 551 | onMouseDown={(e) => { |
| 361 | if (e.button === 1) e.preventDefault(); | 552 | if (e.button === 1) e.preventDefault(); |
| @@ -365,80 +556,231 @@ export function WhiteboardCanvas(props: { | |||
| 365 | onPointerMove={extendStroke} | 556 | onPointerMove={extendStroke} |
| 366 | onPointerUp={endStroke} | 557 | onPointerUp={endStroke} |
| 367 | onPointerCancel={endStroke} | 558 | onPointerCancel={endStroke} |
| 368 | - onWheel={(e) => { | 559 | + onWheel={onWheel} |
| 369 | - e.preventDefault(); | ||
| 370 | - zoomBy(e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP); | ||
| 371 | - }} | ||
| 372 | /> | 560 | /> |
| 373 | - <Show when={empty() && !current}> | 561 | + <canvas ref={preview} class={cn("pointer-events-none absolute inset-0 h-full w-full", DARK_INK)} aria-hidden="true" /> |
| 374 | - <p class="pointer-events-none absolute inset-0 flex items-center justify-center text-sm text-slate-400"> | 562 | + <Show when={empty()}> |
| 375 | - {activeTool() === "pan" && !props.disabled ? t("whiteboard.canvasHintPickPen") : t("whiteboard.canvasHint")} | 563 | + <p class="pointer-events-none absolute inset-0 flex items-center justify-center px-6 text-center text-sm text-slate-400"> |
| 564 | + {activeTool() === "hand" && !props.disabled ? t("whiteboard.canvasHintPickPen") : t("whiteboard.canvasHint")} | ||
| 376 | </p> | 565 | </p> |
| 377 | </Show> | 566 | </Show> |
| 378 | 567 | ||
| 379 | - {/* Mobile: the three corner islands below overlap each other under ~640px | 568 | + {/* Corner controls the host docks beside the tools. Hidden in full |
| 380 | - (they need ~520px combined), so under sm they collapse into one | 569 | + screen: their menus portal to <body>, which full screen covers. */} |
| 381 | - wrapping bar instead; desktop keeps the original three corners. */} | 570 | + <Show when={props.topLeft && !fullscreen.active()}> |
| 382 | - <div class="absolute inset-x-2 top-2 z-10 flex flex-wrap items-center justify-center gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-xs backdrop-blur-xs sm:hidden"> | 571 | + <div class="absolute left-2 top-2 z-20 flex max-w-[45%] items-center gap-2">{props.topLeft}</div> |
| 383 | - <div class="flex gap-1.5"> | 572 | + </Show> |
| 384 | - <ToolButtons /> | 573 | + <Show when={props.topRight && !fullscreen.active()}> |
| 385 | - </div> | 574 | + <div class="absolute right-2 top-2 z-20 flex items-center gap-2">{props.topRight}</div> |
| 386 | - <div class="flex flex-wrap items-center justify-center gap-1.5" role="group" aria-label={t("draw.color")}> | 575 | + </Show> |
| 387 | - <ColorSwatches /> | ||
| 388 | - </div> | ||
| 389 | - <div class="flex gap-1.5" role="group" aria-label={t("draw.width")}> | ||
| 390 | - <WidthButtons /> | ||
| 391 | - </div> | ||
| 392 | - </div> | ||
| 393 | - | ||
| 394 | - {/* Top-left island — tools */} | ||
| 395 | - <div class={cn(OVERLAY_CARD, "left-2 top-2 hidden sm:flex")}> | ||
| 396 | - <ToolButtons /> | ||
| 397 | - </div> | ||
| 398 | 576 | ||
| 399 | - {/* Top-middle island — colours */} | 577 | + {/* Top-centre tool island, with the active tool's hint (or the host's |
| 578 | + status banner) under it. */} | ||
| 400 | <div | 579 | <div |
| 401 | - class={cn(OVERLAY_CARD, "left-1/2 top-2 hidden -translate-x-1/2 flex-wrap items-center sm:flex")} | 580 | + class={cn( |
| 402 | - role="group" | 581 | + "pointer-events-none absolute inset-x-2 z-10 flex flex-col items-center gap-1.5", |
| 403 | - aria-label={t("draw.color")} | 582 | + toolbarRow2() ? "top-14" : "top-2", |
| 583 | + )} | ||
| 404 | > | 584 | > |
| 405 | - <ColorSwatches /> | 585 | + <div role="toolbar" aria-label={t("draw.tools")} class={cn(ISLAND, "pointer-events-auto flex items-center gap-0.5 p-1 sm:gap-1.5 sm:p-1.5")}> |
| 586 | + <For each={TOOLS}> | ||
| 587 | + {(entry) => ( | ||
| 588 | + <> | ||
| 589 | + <Show when={entry.tool === "pen" || entry.tool === "eraser"}> | ||
| 590 | + <span class="mx-1 hidden h-6 w-px bg-border sm:block" aria-hidden="true" /> | ||
| 591 | + </Show> | ||
| 592 | + <button | ||
| 593 | + type="button" | ||
| 594 | + class={cn( | ||
| 595 | + "relative flex h-9 w-9 items-center justify-center rounded-md transition-colors sm:h-10 sm:w-10 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring", | ||
| 596 | + activeTool() === entry.tool | ||
| 597 | + ? "bg-primary/15 text-primary-text" | ||
| 598 | + : "text-foreground/80 hover:bg-muted", | ||
| 599 | + )} | ||
| 600 | + title={`${t(entry.label)} — ${entry.key}`} | ||
| 601 | + aria-label={t(entry.label)} | ||
| 602 | + aria-keyshortcuts={entry.key} | ||
| 603 | + aria-pressed={activeTool() === entry.tool} | ||
| 604 | + onClick={() => pickTool(entry.tool)} | ||
| 605 | + > | ||
| 606 | + <entry.icon class="h-4 w-4" /> | ||
| 607 | + <span class="pointer-events-none absolute bottom-0.5 right-1 hidden text-[11px] leading-none text-muted-foreground/80 sm:block"> | ||
| 608 | + {entry.key} | ||
| 609 | + </span> | ||
| 610 | + </button> | ||
| 611 | + </> | ||
| 612 | + )} | ||
| 613 | + </For> | ||
| 614 | + </div> | ||
| 615 | + <Show | ||
| 616 | + when={props.banner} | ||
| 617 | + fallback={ | ||
| 618 | + <Show when={hint() && !toolbarRow2()}> | ||
| 619 | + <p class="hidden text-center text-[11px] text-muted-foreground sm:block">{hint()}</p> | ||
| 620 | + </Show> | ||
| 621 | + } | ||
| 622 | + > | ||
| 623 | + <p | ||
| 624 | + role="status" | ||
| 625 | + class={cn( | ||
| 626 | + "pointer-events-auto max-w-md rounded-md border px-3 py-1.5 text-center text-xs font-medium shadow-xs", | ||
| 627 | + props.bannerTone === "error" | ||
| 628 | + ? "border-destructive/30 bg-destructive/10 text-destructive-text" | ||
| 629 | + : "border-warning/40 bg-warning/10 text-warning-text", | ||
| 630 | + )} | ||
| 631 | + > | ||
| 632 | + {props.banner} | ||
| 633 | + </p> | ||
| 634 | + </Show> | ||
| 406 | </div> | 635 | </div> |
| 407 | 636 | ||
| 408 | - {/* Top-right island — width */} | 637 | + {/* Left style island — only while a drawing tool is active. */} |
| 409 | - <div class={cn(OVERLAY_CARD, "right-2 top-2 hidden sm:flex")} role="group" aria-label={t("draw.width")}> | 638 | + <Show when={showsStyle()}> |
| 410 | - <WidthButtons /> | 639 | + <div |
| 640 | + class={cn( | ||
| 641 | + ISLAND, | ||
| 642 | + "absolute left-2 z-10 w-44 space-y-3 p-3", | ||
| 643 | + toolbarRow2() ? "top-26" : "top-14", | ||
| 644 | + styleOpen() ? "block" : "hidden sm:block", | ||
| 645 | + )} | ||
| 646 | + > | ||
| 647 | + <Section label={t("draw.color")}> | ||
| 648 | + <For each={COLORS}> | ||
| 649 | + {(swatch) => ( | ||
| 650 | + <button | ||
| 651 | + type="button" | ||
| 652 | + title={t(COLOR_NAMES[swatch])} | ||
| 653 | + aria-label={`${t("draw.color")}: ${t(COLOR_NAMES[swatch])}`} | ||
| 654 | + aria-pressed={color() === swatch} | ||
| 655 | + class={cn( | ||
| 656 | + "h-6 w-6 rounded-md transition-shadow focus-visible:outline-hidden", | ||
| 657 | + color() === swatch | ||
| 658 | + ? "ring-2 ring-primary ring-offset-2 ring-offset-card" | ||
| 659 | + : "hover:ring-2 hover:ring-border hover:ring-offset-1 hover:ring-offset-card focus-visible:ring-2 focus-visible:ring-ring", | ||
| 660 | + )} | ||
| 661 | + style={{ "background-color": swatch }} | ||
| 662 | + onClick={() => setColor(swatch)} | ||
| 663 | + /> | ||
| 664 | + )} | ||
| 665 | + </For> | ||
| 666 | + </Section> | ||
| 667 | + | ||
| 668 | + <Section label={t("draw.width")}> | ||
| 669 | + <For each={WIDTHS}> | ||
| 670 | + {(option) => ( | ||
| 671 | + <button | ||
| 672 | + type="button" | ||
| 673 | + title={t(option.label)} | ||
| 674 | + aria-label={`${t("draw.width")}: ${t(option.label)}`} | ||
| 675 | + aria-pressed={width() === option.size} | ||
| 676 | + class={optionClass(width() === option.size)} | ||
| 677 | + onClick={() => setWidth(option.size)} | ||
| 678 | + > | ||
| 679 | + <span class="w-4 rounded-full bg-current" style={{ height: `${Math.max(1, option.size / 2)}px` }} /> | ||
| 680 | + </button> | ||
| 681 | + )} | ||
| 682 | + </For> | ||
| 683 | + </Section> | ||
| 684 | + | ||
| 685 | + <Section label={t("draw.strokeStyle")}> | ||
| 686 | + <For each={DASHES}> | ||
| 687 | + {(option) => ( | ||
| 688 | + <button | ||
| 689 | + type="button" | ||
| 690 | + title={t(option.label)} | ||
| 691 | + aria-label={`${t("draw.strokeStyle")}: ${t(option.label)}`} | ||
| 692 | + aria-pressed={dash() === option.dash} | ||
| 693 | + class={optionClass(dash() === option.dash)} | ||
| 694 | + onClick={() => setDash(option.dash)} | ||
| 695 | + > | ||
| 696 | + <svg viewBox="0 0 20 20" class="h-4 w-4" aria-hidden="true"> | ||
| 697 | + <line | ||
| 698 | + x1="3" | ||
| 699 | + y1="10" | ||
| 700 | + x2="17" | ||
| 701 | + y2="10" | ||
| 702 | + stroke="currentColor" | ||
| 703 | + stroke-width="2" | ||
| 704 | + stroke-linecap="round" | ||
| 705 | + stroke-dasharray={option.pattern} | ||
| 706 | + /> | ||
| 707 | + </svg> | ||
| 708 | + </button> | ||
| 709 | + )} | ||
| 710 | + </For> | ||
| 711 | + </Section> | ||
| 712 | + | ||
| 713 | + <Show when={isShape(activeTool())}> | ||
| 714 | + <Section label={t("draw.sloppiness")}> | ||
| 715 | + <For each={SLOPPINESS}> | ||
| 716 | + {(option) => ( | ||
| 717 | + <button | ||
| 718 | + type="button" | ||
| 719 | + title={t(option.label)} | ||
| 720 | + aria-label={`${t("draw.sloppiness")}: ${t(option.label)}`} | ||
| 721 | + aria-pressed={slop() === option.slop} | ||
| 722 | + class={optionClass(slop() === option.slop)} | ||
| 723 | + onClick={() => setSlop(option.slop)} | ||
| 724 | + > | ||
| 725 | + <svg viewBox="0 0 24 20" class="h-4 w-4" aria-hidden="true"> | ||
| 726 | + <path d={option.path} fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" /> | ||
| 727 | + </svg> | ||
| 728 | + </button> | ||
| 729 | + )} | ||
| 730 | + </For> | ||
| 731 | + </Section> | ||
| 732 | + </Show> | ||
| 733 | + </div> | ||
| 734 | + </Show> | ||
| 735 | + | ||
| 736 | + {/* Bottom-left: zoom, then paper and (phones) the style toggle. */} | ||
| 737 | + <div class="absolute bottom-2 left-2 z-10 flex items-center gap-2"> | ||
| 738 | + <div class={cn(ISLAND, "flex items-center overflow-hidden")}> | ||
| 739 | + <button type="button" class={plainButton} title={t("draw.zoomOut")} aria-label={t("draw.zoomOut")} onClick={() => zoomBy(1 / ZOOM_STEP)}> | ||
| 740 | + <span class="text-lg leading-none" aria-hidden="true">−</span> | ||
| 741 | + </button> | ||
| 742 | + <button | ||
| 743 | + type="button" | ||
| 744 | + class={cn(plainButton, "w-14 font-mono text-xs tabular-nums")} | ||
| 745 | + title={t("draw.resetZoom")} | ||
| 746 | + aria-label={t("draw.resetZoom")} | ||
| 747 | + onClick={resetZoom} | ||
| 748 | + > | ||
| 749 | + {Math.round(zoom() * 100)}% | ||
| 750 | + </button> | ||
| 751 | + <button type="button" class={plainButton} title={t("draw.zoomIn")} aria-label={t("draw.zoomIn")} onClick={() => zoomBy(ZOOM_STEP)}> | ||
| 752 | + <span class="text-lg leading-none" aria-hidden="true">+</span> | ||
| 753 | + </button> | ||
| 754 | + </div> | ||
| 755 | + <div class={cn(ISLAND, "flex items-center overflow-hidden")}> | ||
| 756 | + <button | ||
| 757 | + type="button" | ||
| 758 | + class={cn(plainButton, grid() && "bg-primary/15 text-primary-text hover:bg-primary/20 hover:text-primary-text")} | ||
| 759 | + title={t("draw.showGrid")} | ||
| 760 | + aria-label={t("draw.showGrid")} | ||
| 761 | + aria-pressed={grid()} | ||
| 762 | + onClick={() => setGrid((on) => !on)} | ||
| 763 | + > | ||
| 764 | + <IconGrid class="h-4.5 w-4.5" /> | ||
| 765 | + </button> | ||
| 766 | + <Show when={showsStyle()}> | ||
| 767 | + <button | ||
| 768 | + type="button" | ||
| 769 | + class={cn(plainButton, "sm:hidden")} | ||
| 770 | + title={t("draw.style")} | ||
| 771 | + aria-label={t("draw.style")} | ||
| 772 | + aria-expanded={styleOpen()} | ||
| 773 | + onClick={() => setStyleOpen((open) => !open)} | ||
| 774 | + > | ||
| 775 | + <span class="h-4.5 w-4.5 rounded-md border border-border" style={{ "background-color": color() }} /> | ||
| 776 | + </button> | ||
| 777 | + </Show> | ||
| 778 | + </div> | ||
| 411 | </div> | 779 | </div> |
| 412 | 780 | ||
| 413 | - {/* Bottom-right zoom */} | 781 | + {/* Bottom-right: full screen. */} |
| 414 | - <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"> | 782 | + <div class={cn(ISLAND, "absolute bottom-2 right-2 z-10 overflow-hidden")}> |
| 415 | <FullscreenToggle active={fullscreen.active()} onToggle={fullscreen.toggle} /> | 783 | <FullscreenToggle active={fullscreen.active()} onToggle={fullscreen.toggle} /> |
| 416 | - <button | ||
| 417 | - type="button" | ||
| 418 | - class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" | ||
| 419 | - title={t("draw.zoomIn")} | ||
| 420 | - onClick={() => zoomBy(ZOOM_STEP)} | ||
| 421 | - > | ||
| 422 | - <IconZoomIn class="h-5 w-5" /> | ||
| 423 | - <span class="sr-only">{t("draw.zoomIn")}</span> | ||
| 424 | - </button> | ||
| 425 | - <button | ||
| 426 | - type="button" | ||
| 427 | - 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" | ||
| 428 | - title={t("draw.resetZoom")} | ||
| 429 | - onClick={resetZoom} | ||
| 430 | - > | ||
| 431 | - {Math.round(zoom() * 100)}% | ||
| 432 | - </button> | ||
| 433 | - <button | ||
| 434 | - type="button" | ||
| 435 | - class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" | ||
| 436 | - title={t("draw.zoomOut")} | ||
| 437 | - onClick={() => zoomBy(1 / ZOOM_STEP)} | ||
| 438 | - > | ||
| 439 | - <IconZoomOut class="h-5 w-5" /> | ||
| 440 | - <span class="sr-only">{t("draw.zoomOut")}</span> | ||
| 441 | - </button> | ||
| 442 | </div> | 784 | </div> |
| 443 | </div> | 785 | </div> |
| 444 | </div> | 786 | </div> |
src/components/whiteboard/whiteboard-room-ws.tsxmodified+52 -26
| @@ -1,9 +1,13 @@ | |||
| 1 | -import { Show, createEffect, createSignal, onCleanup, onMount } from "solid-js"; | 1 | +import { createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js"; |
| 2 | import { getBoardStrokes, type Board } from "@/api/boards"; | 2 | import { getBoardStrokes, type Board } from "@/api/boards"; |
| 3 | import { formatApiErrorMessage } from "@/api/client"; | 3 | import { formatApiErrorMessage } from "@/api/client"; |
| 4 | -import { IconAlert } from "@/components/ui/icons"; | 4 | +import { |
| 5 | -import { encodeStrokeSegments, decodeSegment, segmentToStroke } from "@/lib/board-stroke-codec"; | 5 | + decodeSegment, |
| 6 | -import type { Stroke } from "@/lib/draw-stroke"; | 6 | + encodeEraseMarkers, |
| 7 | + encodeStrokeSegments, | ||
| 8 | + segmentToStroke, | ||
| 9 | + type BoardStroke, | ||
| 10 | +} from "@/lib/board-stroke-codec"; | ||
| 7 | import { parseBoardWsMessage, type BoardWsMessage } from "@/lib/websocket-messages"; | 11 | import { parseBoardWsMessage, type BoardWsMessage } from "@/lib/websocket-messages"; |
| 8 | import { usePreferences } from "@/stores/preferences-context"; | 12 | import { usePreferences } from "@/stores/preferences-context"; |
| 9 | import { WhiteboardCanvas, type WhiteboardCanvasController } from "./whiteboard-canvas"; | 13 | import { WhiteboardCanvas, type WhiteboardCanvasController } from "./whiteboard-canvas"; |
| @@ -21,6 +25,8 @@ export type BoardLiveState = { | |||
| 21 | }; | 25 | }; |
| 22 | 26 | ||
| 23 | const MAX_RECONNECT = 6; | 27 | const MAX_RECONNECT = 6; |
| 28 | +/** A socket error stays on the canvas banner this long. */ | ||
| 29 | +const NOTICE_MS = 6000; | ||
| 24 | 30 | ||
| 25 | export function WhiteboardRoom(props: { | 31 | export function WhiteboardRoom(props: { |
| 26 | board: Board; | 32 | board: Board; |
| @@ -28,6 +34,12 @@ export function WhiteboardRoom(props: { | |||
| 28 | onState?: (patch: BoardLiveState) => void; | 34 | onState?: (patch: BoardLiveState) => void; |
| 29 | onConnectionChange?: (state: WsState) => void; | 35 | onConnectionChange?: (state: WsState) => void; |
| 30 | onDeleted?: () => void; | 36 | onDeleted?: () => void; |
| 37 | + /** Passed through to the canvas corners and banner. */ | ||
| 38 | + topLeft?: JSX.Element; | ||
| 39 | + topRight?: JSX.Element; | ||
| 40 | + banner?: string; | ||
| 41 | + bannerTone?: "info" | "error"; | ||
| 42 | + class?: string; | ||
| 31 | }) { | 43 | }) { |
| 32 | const { locale } = usePreferences(); | 44 | const { locale } = usePreferences(); |
| 33 | 45 | ||
| @@ -47,6 +59,7 @@ export function WhiteboardRoom(props: { | |||
| 47 | const seen = new Set<string>(); | 59 | const seen = new Set<string>(); |
| 48 | 60 | ||
| 49 | let reconnectTimer: ReturnType<typeof setTimeout> | null = null; | 61 | let reconnectTimer: ReturnType<typeof setTimeout> | null = null; |
| 62 | + let noticeTimer: ReturnType<typeof setTimeout> | undefined; | ||
| 50 | let reconnectAttempts = 0; | 63 | let reconnectAttempts = 0; |
| 51 | let closedByUs = false; | 64 | let closedByUs = false; |
| 52 | 65 | ||
| @@ -81,7 +94,9 @@ export function WhiteboardRoom(props: { | |||
| 81 | if (seen.has(row.id)) return; | 94 | if (seen.has(row.id)) return; |
| 82 | seen.add(row.id); | 95 | seen.add(row.id); |
| 83 | const seg = decodeSegment(row.payload); | 96 | const seg = decodeSegment(row.payload); |
| 84 | - if (seg) controller?.applyStroke(segmentToStroke(seg)); | 97 | + if (!seg) return; |
| 98 | + if (seg.del) controller?.removeStrokes(seg.del); | ||
| 99 | + else controller?.applyStroke({ ...segmentToStroke(seg), id: seg.sid }); | ||
| 85 | }; | 100 | }; |
| 86 | 101 | ||
| 87 | const wipe = () => { | 102 | const wipe = () => { |
| @@ -204,6 +219,8 @@ export function WhiteboardRoom(props: { | |||
| 204 | case "error": { | 219 | case "error": { |
| 205 | const message = formatApiErrorMessage(msg.message, locale()); | 220 | const message = formatApiErrorMessage(msg.message, locale()); |
| 206 | setNotice(message); | 221 | setNotice(message); |
| 222 | + if (noticeTimer) clearTimeout(noticeTimer); | ||
| 223 | + noticeTimer = setTimeout(() => setNotice(""), NOTICE_MS); | ||
| 207 | // A rejected draw (locked, full epoch, closed) or a room resync means the | 224 | // A rejected draw (locked, full epoch, closed) or a room resync means the |
| 208 | // optimistic local canvas is out of step — take the truth from the DB. | 225 | // optimistic local canvas is out of step — take the truth from the DB. |
| 209 | if (["epoch_full", "board_closed", "locked", "resync", "conflict", "forbidden"].includes(msg.code)) { | 226 | if (["epoch_full", "board_closed", "locked", "resync", "conflict", "forbidden"].includes(msg.code)) { |
| @@ -214,10 +231,22 @@ export function WhiteboardRoom(props: { | |||
| 214 | } | 231 | } |
| 215 | }; | 232 | }; |
| 216 | 233 | ||
| 217 | - const onLocalStroke = (stroke: Stroke) => { | 234 | + const nextSid = () => `${props.meId}-${Date.now()}-${(clientSeq += 1)}`; |
| 235 | + | ||
| 236 | + // The canvas tags every local stroke with an id; it is the sid on the wire, | ||
| 237 | + // so a later erase — ours or anyone's — can name it. | ||
| 238 | + const onLocalStroke = (stroke: BoardStroke) => { | ||
| 218 | if (!canDraw()) return; | 239 | if (!canDraw()) return; |
| 219 | - const sid = `${props.meId}-${Date.now()}-${(clientSeq += 1)}`; | 240 | + for (const payload of encodeStrokeSegments(stroke, stroke.id ?? nextSid())) { |
| 220 | - for (const payload of encodeStrokeSegments(stroke, sid)) { | 241 | + sendWs({ type: "stroke", payload, client_seq: (clientSeq += 1) }); |
| 242 | + } | ||
| 243 | + }; | ||
| 244 | + | ||
| 245 | + // The log is append-only, so an erase is logged as a marker naming the | ||
| 246 | + // removed sids; every client (and the history replay) drops them. | ||
| 247 | + const onLocalErase = (ids: string[]) => { | ||
| 248 | + if (!canDraw()) return; | ||
| 249 | + for (const payload of encodeEraseMarkers(ids, nextSid())) { | ||
| 221 | sendWs({ type: "stroke", payload, client_seq: (clientSeq += 1) }); | 250 | sendWs({ type: "stroke", payload, client_seq: (clientSeq += 1) }); |
| 222 | } | 251 | } |
| 223 | }; | 252 | }; |
| @@ -229,29 +258,26 @@ export function WhiteboardRoom(props: { | |||
| 229 | onCleanup(() => { | 258 | onCleanup(() => { |
| 230 | closedByUs = true; | 259 | closedByUs = true; |
| 231 | clearReconnect(); | 260 | clearReconnect(); |
| 261 | + if (noticeTimer) clearTimeout(noticeTimer); | ||
| 232 | if (ws) ws.close(); | 262 | if (ws) ws.close(); |
| 233 | }); | 263 | }); |
| 234 | 264 | ||
| 235 | createEffect(() => props.onConnectionChange?.(wsState())); | 265 | createEffect(() => props.onConnectionChange?.(wsState())); |
| 236 | 266 | ||
| 237 | return ( | 267 | return ( |
| 238 | - <div class="space-y-3"> | 268 | + <WhiteboardCanvas |
| 239 | - <Show when={notice()}> | 269 | + fill |
| 240 | - {(msg) => ( | 270 | + class={props.class} |
| 241 | - <div class="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3"> | 271 | + disabled={!canDraw()} |
| 242 | - <IconAlert class="mt-0.5 h-5 w-5 shrink-0 text-destructive-text" /> | 272 | + onStroke={onLocalStroke} |
| 243 | - <p class="min-w-0 text-sm text-destructive-text">{msg()}</p> | 273 | + onErase={onLocalErase} |
| 244 | - </div> | 274 | + topLeft={props.topLeft} |
| 245 | - )} | 275 | + topRight={props.topRight} |
| 246 | - </Show> | 276 | + banner={notice() || props.banner} |
| 247 | - | 277 | + bannerTone={notice() ? "error" : props.bannerTone} |
| 248 | - <WhiteboardCanvas | 278 | + controllerRef={(c) => { |
| 249 | - disabled={!canDraw()} | 279 | + controller = c; |
| 250 | - onStroke={onLocalStroke} | 280 | + }} |
| 251 | - controllerRef={(c) => { | 281 | + /> |
| 252 | - controller = c; | ||
| 253 | - }} | ||
| 254 | - /> | ||
| 255 | - </div> | ||
| 256 | ); | 282 | ); |
| 257 | } | 283 | } |
src/i18n/locales/en.tsmodified+30 -2
| @@ -1266,7 +1266,35 @@ export const en: Dict = { | |||
| 1266 | "draw.colorName.blue": "Blue", | 1266 | "draw.colorName.blue": "Blue", |
| 1267 | "draw.colorName.green": "Green", | 1267 | "draw.colorName.green": "Green", |
| 1268 | "draw.colorName.yellow": "Yellow", | 1268 | "draw.colorName.yellow": "Yellow", |
| 1269 | - "whiteboard.canvasHintPickPen": "Pick the pen to draw — everyone on the board sees it live.", | 1269 | + "whiteboard.canvasHintPickPen": "Pick a tool above to draw — everyone on the board sees it live.", |
| 1270 | + "draw.tools": "Tools", | ||
| 1271 | + "draw.rectangle": "Rectangle", | ||
| 1272 | + "draw.diamond": "Diamond", | ||
| 1273 | + "draw.ellipse": "Ellipse", | ||
| 1274 | + "draw.arrow": "Arrow", | ||
| 1275 | + "draw.line": "Line", | ||
| 1276 | + "draw.colorName.orange": "Orange", | ||
| 1277 | + "draw.style": "Style", | ||
| 1278 | + "draw.widthThin": "Thin", | ||
| 1279 | + "draw.widthBold": "Bold", | ||
| 1280 | + "draw.widthExtraBold": "Extra bold", | ||
| 1281 | + "draw.strokeStyle": "Stroke style", | ||
| 1282 | + "draw.styleSolid": "Solid", | ||
| 1283 | + "draw.styleDashed": "Dashed", | ||
| 1284 | + "draw.styleDotted": "Dotted", | ||
| 1285 | + "draw.sloppiness": "Sloppiness", | ||
| 1286 | + "draw.slopArchitect": "Architect", | ||
| 1287 | + "draw.slopArtist": "Artist", | ||
| 1288 | + "draw.slopCartoonist": "Cartoonist", | ||
| 1289 | + "draw.showGrid": "Show grid", | ||
| 1290 | + "whiteboard.panHint": "To move the canvas, scroll or hold Space while dragging; Ctrl + scroll zooms.", | ||
| 1291 | + "whiteboard.shapeHint": "Hold Shift for a square, a circle or a 45° line.", | ||
| 1292 | + "whiteboard.eraserHint": "Sweep over the strokes to erase; they go when you let go.", | ||
| 1293 | + "whiteboard.menu": "Board menu", | ||
| 1294 | + "whiteboard.lockedBanner": "Board locked — drawing is paused.", | ||
| 1295 | + "whiteboard.closedBanner": "Board closed: read-only for good, it can't be reopened.", | ||
| 1296 | + "whiteboard.readOnlyBanner": "You're not on this board — you can only watch.", | ||
| 1297 | + "whiteboard.you": "You", | ||
| 1270 | "exams.publishOnCreateWarning": "Not a draft: the exam opens to students before any question is added.", | 1298 | "exams.publishOnCreateWarning": "Not a draft: the exam opens to students before any question is added.", |
| 1271 | "exams.publishEmptyTitle": "Publish without questions?", | 1299 | "exams.publishEmptyTitle": "Publish without questions?", |
| 1272 | "exams.publishEmptyWarning": "This exam has no questions. If you publish it, students will see an empty exam.", | 1300 | "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 = { | |||
| 2199 | "whiteboard.clear": "Clear", | 2227 | "whiteboard.clear": "Clear", |
| 2200 | "whiteboard.clearConfirm": "Clear the live canvas? The history is kept and stays replayable.", | 2228 | "whiteboard.clearConfirm": "Clear the live canvas? The history is kept and stays replayable.", |
| 2201 | "whiteboard.close": "Close board", | 2229 | "whiteboard.close": "Close board", |
| 2202 | - "whiteboard.closeConfirm": "Close this board? It becomes permanently read-only.", | 2230 | + "whiteboard.closeConfirm": "Close this board? It becomes read-only for good and cannot be reopened — lock it for a short pause instead.", |
| 2203 | "whiteboard.delete": "Delete board", | 2231 | "whiteboard.delete": "Delete board", |
| 2204 | "whiteboard.deleteConfirm": "Delete this board and its whole history? This cannot be undone.", | 2232 | "whiteboard.deleteConfirm": "Delete this board and its whole history? This cannot be undone.", |
| 2205 | "whiteboard.creator": "Creator", | 2233 | "whiteboard.creator": "Creator", |
src/i18n/locales/tr.tsmodified+30 -2
| @@ -1262,7 +1262,35 @@ export const tr: Dict = { | |||
| 1262 | "draw.colorName.blue": "Mavi", | 1262 | "draw.colorName.blue": "Mavi", |
| 1263 | "draw.colorName.green": "Yeşil", | 1263 | "draw.colorName.green": "Yeşil", |
| 1264 | "draw.colorName.yellow": "Sarı", | 1264 | "draw.colorName.yellow": "Sarı", |
| 1265 | - "whiteboard.canvasHintPickPen": "Çizmek için kalemi seç — tahtadaki herkes anlık görür.", | 1265 | + "whiteboard.canvasHintPickPen": "Çizmek için yukarıdan bir araç seç — tahtadaki herkes anlık görür.", |
| 1266 | + "draw.tools": "Araçlar", | ||
| 1267 | + "draw.rectangle": "Dikdörtgen", | ||
| 1268 | + "draw.diamond": "Elmas", | ||
| 1269 | + "draw.ellipse": "Elips", | ||
| 1270 | + "draw.arrow": "Ok", | ||
| 1271 | + "draw.line": "Çizgi", | ||
| 1272 | + "draw.colorName.orange": "Turuncu", | ||
| 1273 | + "draw.style": "Stil", | ||
| 1274 | + "draw.widthThin": "İnce", | ||
| 1275 | + "draw.widthBold": "Kalın", | ||
| 1276 | + "draw.widthExtraBold": "Çok kalın", | ||
| 1277 | + "draw.strokeStyle": "Çizgi stili", | ||
| 1278 | + "draw.styleSolid": "Düz", | ||
| 1279 | + "draw.styleDashed": "Kesikli", | ||
| 1280 | + "draw.styleDotted": "Noktalı", | ||
| 1281 | + "draw.sloppiness": "Özensizlik", | ||
| 1282 | + "draw.slopArchitect": "Mimar", | ||
| 1283 | + "draw.slopArtist": "Sanatçı", | ||
| 1284 | + "draw.slopCartoonist": "Karikatürist", | ||
| 1285 | + "draw.showGrid": "Izgarayı göster", | ||
| 1286 | + "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.", | ||
| 1287 | + "whiteboard.shapeHint": "Kare, daire ya da 45° çizgi için Shift'e basılı tut.", | ||
| 1288 | + "whiteboard.eraserHint": "Silmek istediğin çizgilerin üzerinden geç; bırakınca silinir.", | ||
| 1289 | + "whiteboard.menu": "Tahta menüsü", | ||
| 1290 | + "whiteboard.lockedBanner": "Tahta kilitli — çizim duraklatıldı.", | ||
| 1291 | + "whiteboard.closedBanner": "Tahta kapatıldı: kalıcı olarak salt okunur, yeniden açılamaz.", | ||
| 1292 | + "whiteboard.readOnlyBanner": "Bu tahtada katılımcı değilsin; yalnızca izleyebilirsin.", | ||
| 1293 | + "whiteboard.you": "Sen", | ||
| 1266 | "exams.publishOnCreateWarning": "Taslak işaretli değil: sınav, soru eklenmeden öğrencilere açılır.", | 1294 | "exams.publishOnCreateWarning": "Taslak işaretli değil: sınav, soru eklenmeden öğrencilere açılır.", |
| 1267 | "exams.publishEmptyTitle": "Soru olmadan yayınlansın mı?", | 1295 | "exams.publishEmptyTitle": "Soru olmadan yayınlansın mı?", |
| 1268 | "exams.publishEmptyWarning": "Bu sınavda hiç soru yok. Yayınlarsan öğrenciler boş bir sınav görür.", | 1296 | "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 = { | |||
| 2195 | "whiteboard.clear": "Temizle", | 2223 | "whiteboard.clear": "Temizle", |
| 2196 | "whiteboard.clearConfirm": "Canlı tuval temizlensin mi? Geçmiş korunur ve tekrar oynatılabilir.", | 2224 | "whiteboard.clearConfirm": "Canlı tuval temizlensin mi? Geçmiş korunur ve tekrar oynatılabilir.", |
| 2197 | "whiteboard.close": "Tahtayı kapat", | 2225 | "whiteboard.close": "Tahtayı kapat", |
| 2198 | - "whiteboard.closeConfirm": "Bu tahta kapatılsın mı? Kalıcı olarak salt okunur olur.", | 2226 | + "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.", |
| 2199 | "whiteboard.delete": "Tahtayı sil", | 2227 | "whiteboard.delete": "Tahtayı sil", |
| 2200 | "whiteboard.deleteConfirm": "Bu tahta ve tüm geçmişi silinsin mi? Geri alınamaz.", | 2228 | "whiteboard.deleteConfirm": "Bu tahta ve tüm geçmişi silinsin mi? Geri alınamaz.", |
| 2201 | "whiteboard.creator": "Oluşturan", | 2229 | "whiteboard.creator": "Oluşturan", |
src/i18n/messages.tsmodified+28 -0
| @@ -1254,6 +1254,34 @@ export type MessageKey = | |||
| 1254 | | "draw.colorName.green" | 1254 | | "draw.colorName.green" |
| 1255 | | "draw.colorName.yellow" | 1255 | | "draw.colorName.yellow" |
| 1256 | | "whiteboard.canvasHintPickPen" | 1256 | | "whiteboard.canvasHintPickPen" |
| 1257 | + | "draw.tools" | ||
| 1258 | + | "draw.rectangle" | ||
| 1259 | + | "draw.diamond" | ||
| 1260 | + | "draw.ellipse" | ||
| 1261 | + | "draw.arrow" | ||
| 1262 | + | "draw.line" | ||
| 1263 | + | "draw.colorName.orange" | ||
| 1264 | + | "draw.style" | ||
| 1265 | + | "draw.widthThin" | ||
| 1266 | + | "draw.widthBold" | ||
| 1267 | + | "draw.widthExtraBold" | ||
| 1268 | + | "draw.strokeStyle" | ||
| 1269 | + | "draw.styleSolid" | ||
| 1270 | + | "draw.styleDashed" | ||
| 1271 | + | "draw.styleDotted" | ||
| 1272 | + | "draw.sloppiness" | ||
| 1273 | + | "draw.slopArchitect" | ||
| 1274 | + | "draw.slopArtist" | ||
| 1275 | + | "draw.slopCartoonist" | ||
| 1276 | + | "draw.showGrid" | ||
| 1277 | + | "whiteboard.panHint" | ||
| 1278 | + | "whiteboard.shapeHint" | ||
| 1279 | + | "whiteboard.eraserHint" | ||
| 1280 | + | "whiteboard.menu" | ||
| 1281 | + | "whiteboard.lockedBanner" | ||
| 1282 | + | "whiteboard.closedBanner" | ||
| 1283 | + | "whiteboard.readOnlyBanner" | ||
| 1284 | + | "whiteboard.you" | ||
| 1257 | | "exams.publishOnCreateWarning" | 1285 | | "exams.publishOnCreateWarning" |
| 1258 | | "exams.publishEmptyTitle" | 1286 | | "exams.publishEmptyTitle" |
| 1259 | | "exams.publishEmptyWarning" | 1287 | | "exams.publishEmptyWarning" |
src/lib/board-hit.test.tsadded+48 -0
| @@ -0,0 +1,48 @@ | |||
| 1 | +import { describe, expect, it } from "vitest"; | ||
| 2 | +import { segmentDist, strokeHit } from "./board-hit"; | ||
| 3 | +import type { Stroke } from "./draw-stroke"; | ||
| 4 | + | ||
| 5 | +const line = (over: Partial<Stroke> = {}): Stroke => ({ | ||
| 6 | + color: "#000", | ||
| 7 | + width: 4, | ||
| 8 | + erase: false, | ||
| 9 | + points: [ | ||
| 10 | + { x: 0, y: 0 }, | ||
| 11 | + { x: 100, y: 0 }, | ||
| 12 | + ], | ||
| 13 | + ...over, | ||
| 14 | +}); | ||
| 15 | + | ||
| 16 | +describe("segmentDist", () => { | ||
| 17 | + it("is zero for crossing segments", () => { | ||
| 18 | + expect(segmentDist({ x: 0, y: -5 }, { x: 0, y: 5 }, { x: -5, y: 0 }, { x: 5, y: 0 })).toBe(0); | ||
| 19 | + }); | ||
| 20 | + | ||
| 21 | + it("measures the gap between parallel segments", () => { | ||
| 22 | + expect(segmentDist({ x: 0, y: 3 }, { x: 10, y: 3 }, { x: 0, y: 0 }, { x: 10, y: 0 })).toBeCloseTo(3); | ||
| 23 | + }); | ||
| 24 | +}); | ||
| 25 | + | ||
| 26 | +describe("strokeHit", () => { | ||
| 27 | + it("hits when the eraser crosses the line", () => { | ||
| 28 | + expect(strokeHit(line(), { x: 50, y: -20 }, { x: 50, y: 20 }, 2)).toBe(true); | ||
| 29 | + }); | ||
| 30 | + | ||
| 31 | + it("hits within half the stroke width plus the eraser reach", () => { | ||
| 32 | + expect(strokeHit(line(), { x: 50, y: 5 }, { x: 60, y: 5 }, 3)).toBe(true); | ||
| 33 | + expect(strokeHit(line(), { x: 50, y: 6 }, { x: 60, y: 6 }, 3)).toBe(false); | ||
| 34 | + }); | ||
| 35 | + | ||
| 36 | + it("misses a stroke far outside its box", () => { | ||
| 37 | + expect(strokeHit(line(), { x: 500, y: 500 }, { x: 510, y: 510 }, 4)).toBe(false); | ||
| 38 | + }); | ||
| 39 | + | ||
| 40 | + it("hits a single-point dot", () => { | ||
| 41 | + expect(strokeHit(line({ points: [{ x: 10, y: 10 }] }), { x: 0, y: 12 }, { x: 20, y: 12 }, 1)).toBe(true); | ||
| 42 | + }); | ||
| 43 | + | ||
| 44 | + it("never targets a pixel-eraser stroke or an empty one", () => { | ||
| 45 | + expect(strokeHit(line({ erase: true }), { x: 50, y: -20 }, { x: 50, y: 20 }, 2)).toBe(false); | ||
| 46 | + expect(strokeHit(line({ points: [] }), { x: 50, y: -20 }, { x: 50, y: 20 }, 2)).toBe(false); | ||
| 47 | + }); | ||
| 48 | +}); | ||
src/lib/board-hit.tsadded+72 -0
| @@ -0,0 +1,72 @@ | |||
| 1 | +import type { Point, Stroke } from "./draw-stroke"; | ||
| 2 | + | ||
| 3 | +// Hit testing for the whiteboard's object eraser: a drag of the eraser is a | ||
| 4 | +// chain of short segments, and a stroke is hit when any of them passes within | ||
| 5 | +// the stroke's half-width (plus the eraser's own reach) of its polyline. | ||
| 6 | + | ||
| 7 | +type Box = { x0: number; y0: number; x1: number; y1: number }; | ||
| 8 | + | ||
| 9 | +// Stroke points never change once committed, so the box is computed once. | ||
| 10 | +const boxes = new WeakMap<Stroke, Box>(); | ||
| 11 | + | ||
| 12 | +function boxOf(stroke: Stroke): Box { | ||
| 13 | + let box = boxes.get(stroke); | ||
| 14 | + if (!box) { | ||
| 15 | + box = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity }; | ||
| 16 | + for (const p of stroke.points) { | ||
| 17 | + box.x0 = Math.min(box.x0, p.x); | ||
| 18 | + box.y0 = Math.min(box.y0, p.y); | ||
| 19 | + box.x1 = Math.max(box.x1, p.x); | ||
| 20 | + box.y1 = Math.max(box.y1, p.y); | ||
| 21 | + } | ||
| 22 | + boxes.set(stroke, box); | ||
| 23 | + } | ||
| 24 | + return box; | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +function pointSegmentDist(p: Point, a: Point, b: Point): number { | ||
| 28 | + const dx = b.x - a.x; | ||
| 29 | + const dy = b.y - a.y; | ||
| 30 | + const len2 = dx * dx + dy * dy; | ||
| 31 | + const t = len2 === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2)); | ||
| 32 | + return Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t)); | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +function cross(o: Point, a: Point, b: Point): number { | ||
| 36 | + return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/** Shortest distance between segments ab and cd (0 when they cross). */ | ||
| 40 | +export function segmentDist(a: Point, b: Point, c: Point, d: Point): number { | ||
| 41 | + const d1 = cross(c, d, a); | ||
| 42 | + const d2 = cross(c, d, b); | ||
| 43 | + const d3 = cross(a, b, c); | ||
| 44 | + const d4 = cross(a, b, d); | ||
| 45 | + if (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) return 0; | ||
| 46 | + return Math.min(pointSegmentDist(a, c, d), pointSegmentDist(b, c, d), pointSegmentDist(c, a, b), pointSegmentDist(d, a, b)); | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/** | ||
| 50 | + * Does the eraser move from `a` to `b` touch `stroke`? `radius` is the eraser's | ||
| 51 | + * reach in board-space. Pixel-eraser strokes (older boards) are never targets: | ||
| 52 | + * they carry no ink of their own. | ||
| 53 | + */ | ||
| 54 | +export function strokeHit(stroke: Stroke, a: Point, b: Point, radius: number): boolean { | ||
| 55 | + const pts = stroke.points; | ||
| 56 | + if (stroke.erase || pts.length === 0) return false; | ||
| 57 | + const reach = stroke.width / 2 + radius; | ||
| 58 | + const box = boxOf(stroke); | ||
| 59 | + if ( | ||
| 60 | + Math.max(a.x, b.x) < box.x0 - reach || | ||
| 61 | + Math.min(a.x, b.x) > box.x1 + reach || | ||
| 62 | + Math.max(a.y, b.y) < box.y0 - reach || | ||
| 63 | + Math.min(a.y, b.y) > box.y1 + reach | ||
| 64 | + ) { | ||
| 65 | + return false; | ||
| 66 | + } | ||
| 67 | + if (pts.length === 1) return pointSegmentDist(pts[0], a, b) <= reach; | ||
| 68 | + for (let i = 1; i < pts.length; i += 1) { | ||
| 69 | + if (segmentDist(a, b, pts[i - 1], pts[i]) <= reach) return true; | ||
| 70 | + } | ||
| 71 | + return false; | ||
| 72 | +} | ||
src/lib/board-shapes.test.tsadded+65 -0
| @@ -0,0 +1,65 @@ | |||
| 1 | +import { describe, expect, it } from "vitest"; | ||
| 2 | +import { constrainEnd, shapeStrokes, type ShapeKind } from "./board-shapes"; | ||
| 3 | +import { strokesBounds } from "./draw-stroke"; | ||
| 4 | + | ||
| 5 | +const style = { color: "#1e1e1e", width: 2 }; | ||
| 6 | +const a = { x: 10, y: 20 }; | ||
| 7 | +const b = { x: 210, y: 120 }; | ||
| 8 | + | ||
| 9 | +describe("board-shapes", () => { | ||
| 10 | + it("returns nothing for a click that never became a shape", () => { | ||
| 11 | + for (const kind of ["rectangle", "diamond", "ellipse", "line", "arrow"] as ShapeKind[]) { | ||
| 12 | + expect(shapeStrokes(kind, a, { x: 11, y: 20.5 }, style, 1, 7)).toEqual([]); | ||
| 13 | + } | ||
| 14 | + }); | ||
| 15 | + | ||
| 16 | + it("keeps a clean rectangle inside its dragged box", () => { | ||
| 17 | + const strokes = shapeStrokes("rectangle", a, b, style, 0, 1); | ||
| 18 | + expect(strokes).toHaveLength(1); | ||
| 19 | + const box = strokesBounds(strokes)!; | ||
| 20 | + expect(box.x).toBeCloseTo(a.x - 1, 5); | ||
| 21 | + expect(box.y).toBeCloseTo(a.y - 1, 5); | ||
| 22 | + expect(box.w).toBeCloseTo(b.x - a.x + 2, 5); | ||
| 23 | + expect(box.h).toBeCloseTo(b.y - a.y + 2, 5); | ||
| 24 | + }); | ||
| 25 | + | ||
| 26 | + it("draws a sloppy shape close to, not exactly on, its box", () => { | ||
| 27 | + const box = strokesBounds(shapeStrokes("diamond", a, b, style, 1, 3))!; | ||
| 28 | + expect(Math.abs(box.x - (a.x - 1))).toBeLessThan(6); | ||
| 29 | + expect(Math.abs(box.w - (b.x - a.x + 2))).toBeLessThan(12); | ||
| 30 | + }); | ||
| 31 | + | ||
| 32 | + it("is deterministic for a seed and varies across seeds", () => { | ||
| 33 | + const one = shapeStrokes("ellipse", a, b, style, 1, 42); | ||
| 34 | + expect(shapeStrokes("ellipse", a, b, style, 1, 42)).toEqual(one); | ||
| 35 | + expect(shapeStrokes("ellipse", a, b, style, 1, 43)).not.toEqual(one); | ||
| 36 | + }); | ||
| 37 | + | ||
| 38 | + it("splits an arrow into shaft and head, and doubles a cartoonist pass", () => { | ||
| 39 | + expect(shapeStrokes("arrow", a, b, style, 0, 1)).toHaveLength(2); | ||
| 40 | + expect(shapeStrokes("arrow", a, b, style, 2, 1)).toHaveLength(4); | ||
| 41 | + expect(shapeStrokes("rectangle", a, b, style, 2, 1)).toHaveLength(2); | ||
| 42 | + }); | ||
| 43 | + | ||
| 44 | + it("ends a clean arrow's shaft and head on the tip", () => { | ||
| 45 | + const [shaft, head] = shapeStrokes("arrow", a, b, style, 0, 1); | ||
| 46 | + expect(shaft.points[0]).toEqual(a); | ||
| 47 | + expect(shaft.points[shaft.points.length - 1]).toEqual(b); | ||
| 48 | + expect(head.points).toContainEqual(b); | ||
| 49 | + }); | ||
| 50 | + | ||
| 51 | + it("carries the dash pattern onto every stroke", () => { | ||
| 52 | + for (const s of shapeStrokes("arrow", a, b, { ...style, dash: "dotted" }, 1, 1)) { | ||
| 53 | + expect(s.dash).toBe("dotted"); | ||
| 54 | + expect(s.erase).toBe(false); | ||
| 55 | + } | ||
| 56 | + expect("dash" in shapeStrokes("line", a, b, style, 0, 1)[0]).toBe(false); | ||
| 57 | + }); | ||
| 58 | + | ||
| 59 | + it("constrains a box to a square and a line to 45° steps", () => { | ||
| 60 | + expect(constrainEnd("rectangle", { x: 0, y: 0 }, { x: -30, y: 10 })).toEqual({ x: -30, y: 30 }); | ||
| 61 | + const end = constrainEnd("line", { x: 0, y: 0 }, { x: 100, y: 10 }); | ||
| 62 | + expect(end.x).toBeCloseTo(Math.hypot(100, 10), 5); | ||
| 63 | + expect(end.y).toBeCloseTo(0, 5); | ||
| 64 | + }); | ||
| 65 | +}); | ||
src/lib/board-shapes.tsadded+194 -0
| @@ -0,0 +1,194 @@ | |||
| 1 | +import type { Point, Stroke } from "./draw-stroke"; | ||
| 2 | + | ||
| 3 | +// Whiteboard shapes (Excalidraw-style rectangle, diamond, ellipse, line and | ||
| 4 | +// arrow) are baked into ordinary freehand strokes before they leave the | ||
| 5 | +// client. The board backend only stores stroke payloads, so a shape travels, | ||
| 6 | +// persists and replays exactly like a pen line — no new wire kind, and every | ||
| 7 | +// history replay draws it without knowing it was ever a shape. | ||
| 8 | + | ||
| 9 | +export type ShapeKind = "rectangle" | "diamond" | "ellipse" | "line" | "arrow"; | ||
| 10 | +/** 0 architect (clean), 1 artist (a gentle hand wobble), 2 cartoonist (two loose passes). */ | ||
| 11 | +export type Sloppiness = 0 | 1 | 2; | ||
| 12 | +export type ShapeStyle = Pick<Stroke, "color" | "width" | "dash">; | ||
| 13 | + | ||
| 14 | +/** Below this drag distance (world px) a shape is a stray click, not a shape. */ | ||
| 15 | +const MIN_SIZE = 2; | ||
| 16 | +/** Distance of the guard points placed beside every sharp corner. */ | ||
| 17 | +const CORNER_GUARD = 1.5; | ||
| 18 | +const ELLIPSE_SEGMENTS = 72; | ||
| 19 | + | ||
| 20 | +/** Small deterministic PRNG (mulberry32) so a seed always yields the same wobble. */ | ||
| 21 | +function random(seed: number): () => number { | ||
| 22 | + let a = seed >>> 0; | ||
| 23 | + return () => { | ||
| 24 | + a = (a + 0x6d2b79f5) >>> 0; | ||
| 25 | + let t = a; | ||
| 26 | + t = Math.imul(t ^ (t >>> 15), t | 1); | ||
| 27 | + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); | ||
| 28 | + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; | ||
| 29 | + }; | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/** Shift-drag: equal sides for boxes, a 45° snap for lines and arrows. */ | ||
| 33 | +export function constrainEnd(kind: ShapeKind, a: Point, b: Point): Point { | ||
| 34 | + const dx = b.x - a.x; | ||
| 35 | + const dy = b.y - a.y; | ||
| 36 | + if (kind === "line" || kind === "arrow") { | ||
| 37 | + const step = Math.PI / 4; | ||
| 38 | + const angle = Math.round(Math.atan2(dy, dx) / step) * step; | ||
| 39 | + const len = Math.hypot(dx, dy); | ||
| 40 | + return { x: a.x + Math.cos(angle) * len, y: a.y + Math.sin(angle) * len }; | ||
| 41 | + } | ||
| 42 | + const side = Math.max(Math.abs(dx), Math.abs(dy)); | ||
| 43 | + return { x: a.x + (dx < 0 ? -side : side), y: a.y + (dy < 0 ? -side : side) }; | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/** | ||
| 47 | + * Points from `a` (inclusive) toward `b` (exclusive). The renderer smooths a | ||
| 48 | + * polyline with midpoint quadratics, which would cut a bare corner to the | ||
| 49 | + * midpoints of its edges — so a guard point sits just inside each end and the | ||
| 50 | + * corner only rounds by a pixel. A sloppy edge bows sideways along a half sine. | ||
| 51 | + */ | ||
| 52 | +function edge(a: Point, b: Point, bow: number, rand: () => number, jitter: number): Point[] { | ||
| 53 | + const dx = b.x - a.x; | ||
| 54 | + const dy = b.y - a.y; | ||
| 55 | + const len = Math.hypot(dx, dy); | ||
| 56 | + if (len === 0) return [a]; | ||
| 57 | + const nx = -dy / len; | ||
| 58 | + const ny = dx / len; | ||
| 59 | + const guard = Math.min(CORNER_GUARD, len / 4) / len; | ||
| 60 | + const inner = bow === 0 ? 0 : Math.min(16, Math.max(2, Math.ceil(len / 24))); | ||
| 61 | + const ts = [0, guard]; | ||
| 62 | + for (let i = 1; i < inner; i += 1) ts.push(i / inner); | ||
| 63 | + ts.push(1 - guard); | ||
| 64 | + const out: Point[] = []; | ||
| 65 | + for (const t of ts) { | ||
| 66 | + const off = Math.sin(Math.PI * t) * bow + (t === 0 ? (rand() * 2 - 1) * jitter : 0); | ||
| 67 | + out.push({ x: a.x + dx * t + nx * off, y: a.y + dy * t + ny * off }); | ||
| 68 | + } | ||
| 69 | + return out; | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/** One closed or open pass through `vertices`, each edge bowed by the sloppiness. */ | ||
| 73 | +function polygonPass(vertices: Point[], closed: boolean, slop: Sloppiness, rand: () => number): Point[] { | ||
| 74 | + const last = closed ? vertices.length : vertices.length - 1; | ||
| 75 | + const out: Point[] = []; | ||
| 76 | + for (let i = 0; i < last; i += 1) { | ||
| 77 | + const a = vertices[i]; | ||
| 78 | + const b = vertices[(i + 1) % vertices.length]; | ||
| 79 | + const len = Math.hypot(b.x - a.x, b.y - a.y); | ||
| 80 | + const bow = slop === 0 ? 0 : (rand() * 2 - 1) * Math.min(len * 0.015 * slop, 1.6 * slop); | ||
| 81 | + out.push(...edge(a, b, bow, rand, slop * 0.6)); | ||
| 82 | + } | ||
| 83 | + const end = closed ? vertices[0] : vertices[vertices.length - 1]; | ||
| 84 | + out.push(end); | ||
| 85 | + // A loose hand overshoots where a closed outline meets itself. | ||
| 86 | + if (closed && slop > 0 && out.length > 2) { | ||
| 87 | + const next = out[1]; | ||
| 88 | + const f = 0.35 + rand() * 0.25; | ||
| 89 | + out.push({ x: end.x + (next.x - end.x) * f * slop, y: end.y + (next.y - end.y) * f * slop }); | ||
| 90 | + } | ||
| 91 | + return out; | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/** Rounded-corner rectangle (Excalidraw's default edges) as one outline pass. */ | ||
| 95 | +function rectanglePass(x0: number, y0: number, x1: number, y1: number, width: number, slop: Sloppiness, rand: () => number): Point[] { | ||
| 96 | + const w = x1 - x0; | ||
| 97 | + const h = y1 - y0; | ||
| 98 | + const r = Math.min(32, Math.min(w, h) * 0.25); | ||
| 99 | + if (r < 2) return polygonPass([{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }], true, slop, rand); | ||
| 100 | + const corners = [ | ||
| 101 | + { cx: x1 - r, cy: y0 + r, from: -Math.PI / 2 }, | ||
| 102 | + { cx: x1 - r, cy: y1 - r, from: 0 }, | ||
| 103 | + { cx: x0 + r, cy: y1 - r, from: Math.PI / 2 }, | ||
| 104 | + { cx: x0 + r, cy: y0 + r, from: Math.PI }, | ||
| 105 | + ]; | ||
| 106 | + const arcSteps = Math.max(4, Math.ceil(r / 3)); | ||
| 107 | + const out: Point[] = []; | ||
| 108 | + let prev: Point = { x: x0 + r, y: y0 }; | ||
| 109 | + for (const c of corners) { | ||
| 110 | + const start = { x: c.cx + Math.cos(c.from) * r, y: c.cy + Math.sin(c.from) * r }; | ||
| 111 | + const len = Math.hypot(start.x - prev.x, start.y - prev.y); | ||
| 112 | + const bow = slop === 0 ? 0 : (rand() * 2 - 1) * Math.min(len * 0.012 * slop, 1.4 * slop); | ||
| 113 | + out.push(...edge(prev, start, bow, rand, slop * 0.5)); | ||
| 114 | + for (let i = 0; i < arcSteps; i += 1) { | ||
| 115 | + const a = c.from + (Math.PI / 2) * (i / arcSteps); | ||
| 116 | + out.push({ x: c.cx + Math.cos(a) * r, y: c.cy + Math.sin(a) * r }); | ||
| 117 | + } | ||
| 118 | + prev = { x: c.cx + Math.cos(c.from + Math.PI / 2) * r, y: c.cy + Math.sin(c.from + Math.PI / 2) * r }; | ||
| 119 | + } | ||
| 120 | + out.push(prev); | ||
| 121 | + if (slop > 0) { | ||
| 122 | + const reach = Math.min(w - 2 * r, 6 + width * 2) * (0.4 + rand() * 0.4) * slop; | ||
| 123 | + out.push({ x: prev.x + Math.max(0, reach), y: prev.y + (rand() * 2 - 1) * slop }); | ||
| 124 | + } | ||
| 125 | + return out; | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +function ellipsePass(cx: number, cy: number, rx: number, ry: number, slop: Sloppiness, rand: () => number): Point[] { | ||
| 129 | + const start = slop === 0 ? -Math.PI / 2 : rand() * Math.PI * 2; | ||
| 130 | + // The wobble is a slow radial wave, so the outline stays smooth, and a loose | ||
| 131 | + // pass runs a little past its start instead of closing exactly. | ||
| 132 | + const amp = 0.012 * slop; | ||
| 133 | + const phase = rand() * Math.PI * 2; | ||
| 134 | + const sweep = Math.PI * 2 * (1 + 0.04 * slop); | ||
| 135 | + const steps = Math.ceil(ELLIPSE_SEGMENTS * (1 + 0.04 * slop)); | ||
| 136 | + const out: Point[] = []; | ||
| 137 | + for (let i = 0; i <= steps; i += 1) { | ||
| 138 | + const a = start + (sweep * i) / steps; | ||
| 139 | + const k = 1 + amp * Math.sin(2 * a + phase); | ||
| 140 | + out.push({ x: cx + Math.cos(a) * rx * k, y: cy + Math.sin(a) * ry * k }); | ||
| 141 | + } | ||
| 142 | + return out; | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +function onePass(kind: ShapeKind, a: Point, b: Point, width: number, slop: Sloppiness, rand: () => number): Point[][] { | ||
| 146 | + const x0 = Math.min(a.x, b.x); | ||
| 147 | + const y0 = Math.min(a.y, b.y); | ||
| 148 | + const x1 = Math.max(a.x, b.x); | ||
| 149 | + const y1 = Math.max(a.y, b.y); | ||
| 150 | + switch (kind) { | ||
| 151 | + case "rectangle": | ||
| 152 | + return [rectanglePass(x0, y0, x1, y1, width, slop, rand)]; | ||
| 153 | + case "diamond": { | ||
| 154 | + const mx = (x0 + x1) / 2; | ||
| 155 | + const my = (y0 + y1) / 2; | ||
| 156 | + return [polygonPass([{ x: mx, y: y0 }, { x: x1, y: my }, { x: mx, y: y1 }, { x: x0, y: my }], true, slop, rand)]; | ||
| 157 | + } | ||
| 158 | + case "ellipse": | ||
| 159 | + return [ellipsePass((x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, slop, rand)]; | ||
| 160 | + case "line": | ||
| 161 | + return [polygonPass([a, b], false, slop, rand)]; | ||
| 162 | + case "arrow": { | ||
| 163 | + const len = Math.hypot(b.x - a.x, b.y - a.y); | ||
| 164 | + const angle = Math.atan2(b.y - a.y, b.x - a.x); | ||
| 165 | + const head = Math.min(len / 2.5, 14 + width * 2.5); | ||
| 166 | + const spread = Math.PI / 7; | ||
| 167 | + const left = { x: b.x - Math.cos(angle - spread) * head, y: b.y - Math.sin(angle - spread) * head }; | ||
| 168 | + const right = { x: b.x - Math.cos(angle + spread) * head, y: b.y - Math.sin(angle + spread) * head }; | ||
| 169 | + return [polygonPass([a, b], false, slop, rand), polygonPass([left, b, right], false, slop, rand)]; | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +/** | ||
| 175 | + * Bake a dragged shape from `a` to `b` (board-space) into strokes ready to send. | ||
| 176 | + * An arrow is two strokes (shaft, head); a cartoonist shape is drawn twice with | ||
| 177 | + * a fresh wobble. `seed` fixes the wobble so the live preview and the committed | ||
| 178 | + * shape match. Returns [] for a click that never became a shape. | ||
| 179 | + */ | ||
| 180 | +export function shapeStrokes(kind: ShapeKind, a: Point, b: Point, style: ShapeStyle, slop: Sloppiness, seed: number): Stroke[] { | ||
| 181 | + const dx = Math.abs(b.x - a.x); | ||
| 182 | + const dy = Math.abs(b.y - a.y); | ||
| 183 | + const tooSmall = kind === "line" || kind === "arrow" ? Math.hypot(dx, dy) < MIN_SIZE : dx < MIN_SIZE || dy < MIN_SIZE; | ||
| 184 | + if (tooSmall) return []; | ||
| 185 | + const rand = random(seed); | ||
| 186 | + const passes = slop === 2 ? 2 : 1; | ||
| 187 | + const out: Stroke[] = []; | ||
| 188 | + for (let p = 0; p < passes; p += 1) { | ||
| 189 | + for (const points of onePass(kind, a, b, style.width, slop, rand)) { | ||
| 190 | + out.push({ color: style.color, width: style.width, erase: false, ...(style.dash ? { dash: style.dash } : {}), points }); | ||
| 191 | + } | ||
| 192 | + } | ||
| 193 | + return out; | ||
| 194 | +} | ||
src/lib/board-stroke-codec.test.tsmodified+43 -0
| @@ -1,6 +1,7 @@ | |||
| 1 | import { describe, expect, it } from "vitest"; | 1 | import { describe, expect, it } from "vitest"; |
| 2 | import { | 2 | import { |
| 3 | decodeSegment, | 3 | decodeSegment, |
| 4 | + encodeEraseMarkers, | ||
| 4 | encodeStrokeSegments, | 5 | encodeStrokeSegments, |
| 5 | reassembleStrokes, | 6 | reassembleStrokes, |
| 6 | segmentToStroke, | 7 | segmentToStroke, |
| @@ -80,4 +81,46 @@ describe("board-stroke-codec", () => { | |||
| 80 | const strokes = reassembleStrokes([null, "garbage", ...good]); | 81 | const strokes = reassembleStrokes([null, "garbage", ...good]); |
| 81 | expect(strokes).toHaveLength(1); | 82 | expect(strokes).toHaveLength(1); |
| 82 | }); | 83 | }); |
| 84 | + | ||
| 85 | + it("round-trips a dash pattern and leaves a solid payload without one", () => { | ||
| 86 | + const dashed = { ...makeStroke(300), dash: "dashed" as const }; | ||
| 87 | + const payloads = encodeStrokeSegments(dashed, "d", 512); | ||
| 88 | + expect(payloads.length).toBeGreaterThan(1); | ||
| 89 | + expect(payloads.every((p) => decodeSegment(p)?.dash === "dashed")).toBe(true); | ||
| 90 | + expect(reassembleStrokes(payloads)[0].dash).toBe("dashed"); | ||
| 91 | + expect(segmentToStroke(decodeSegment(payloads[0])!).dash).toBe("dashed"); | ||
| 92 | + expect(encodeStrokeSegments(makeStroke(2), "s")[0]).not.toContain("dash"); | ||
| 93 | + }); | ||
| 94 | + | ||
| 95 | + it("rejects an unknown dash pattern", () => { | ||
| 96 | + const payload = JSON.parse(encodeStrokeSegments(makeStroke(2), "x")[0]); | ||
| 97 | + expect(decodeSegment(JSON.stringify({ ...payload, dash: "wavy" }))).toBeNull(); | ||
| 98 | + }); | ||
| 99 | + | ||
| 100 | + it("encodes an erase as ink-free markers split under the cap", () => { | ||
| 101 | + const ids = Array.from({ length: 60 }, (_, i) => `user-${i}-1700000000000-${i}`); | ||
| 102 | + const payloads = encodeEraseMarkers(ids, "e", 512); | ||
| 103 | + expect(payloads.length).toBeGreaterThan(1); | ||
| 104 | + const all: string[] = []; | ||
| 105 | + for (const p of payloads) { | ||
| 106 | + expect(new TextEncoder().encode(p).length).toBeLessThanOrEqual(512); | ||
| 107 | + const seg = decodeSegment(p)!; | ||
| 108 | + expect(seg.pts).toEqual([]); | ||
| 109 | + all.push(...seg.del!); | ||
| 110 | + } | ||
| 111 | + expect(all).toEqual(ids); | ||
| 112 | + }); | ||
| 113 | + | ||
| 114 | + it("drops erased strokes from a reassembled history", () => { | ||
| 115 | + const keep = encodeStrokeSegments(makeStroke(3), "keep"); | ||
| 116 | + const gone = encodeStrokeSegments(makeStroke(300), "gone", 512); | ||
| 117 | + const strokes = reassembleStrokes([...gone, ...keep, ...encodeEraseMarkers(["gone"], "e")]); | ||
| 118 | + expect(strokes).toHaveLength(1); | ||
| 119 | + expect(strokes[0].points).toHaveLength(3); | ||
| 120 | + }); | ||
| 121 | + | ||
| 122 | + it("rejects a marker whose del list is not strings", () => { | ||
| 123 | + const payload = JSON.parse(encodeEraseMarkers(["a"], "e")[0]); | ||
| 124 | + expect(decodeSegment(JSON.stringify({ ...payload, del: [1] }))).toBeNull(); | ||
| 125 | + }); | ||
| 83 | }); | 126 | }); |
src/lib/board-stroke-codec.tsmodified+52 -5
| @@ -1,4 +1,4 @@ | |||
| 1 | -import type { Point, Stroke } from "./draw-stroke"; | 1 | +import { isDash, type Point, type Stroke, type StrokeDash } from "./draw-stroke"; |
| 2 | 2 | ||
| 3 | // The whiteboard backend caps each stroke `payload` at 4096 bytes | 3 | // The whiteboard backend caps each stroke `payload` at 4096 bytes |
| 4 | // (board.max_stroke_payload_len, published at GET /limits). A long freehand | 4 | // (board.max_stroke_payload_len, published at GET /limits). A long freehand |
| @@ -12,6 +12,9 @@ export const MAX_STROKE_PAYLOAD_BYTES = 4096; | |||
| 12 | // boundary the server rejects. | 12 | // boundary the server rejects. |
| 13 | const DEFAULT_MAX_BYTES = MAX_STROKE_PAYLOAD_BYTES - 64; | 13 | const DEFAULT_MAX_BYTES = MAX_STROKE_PAYLOAD_BYTES - 64; |
| 14 | 14 | ||
| 15 | +/** A stroke on the live board, tagged with the `sid` it travelled under. */ | ||
| 16 | +export type BoardStroke = Stroke & { id?: string }; | ||
| 17 | + | ||
| 15 | // Wire envelope for one segment of a logical stroke. Coordinates are | 18 | // Wire envelope for one segment of a logical stroke. Coordinates are |
| 16 | // board-space (device/zoom independent); points travel as [x, y] tuples to | 19 | // board-space (device/zoom independent); points travel as [x, y] tuples to |
| 17 | // keep the payload small. | 20 | // keep the payload small. |
| @@ -23,6 +26,14 @@ export type StrokeSegment = { | |||
| 23 | color: string; | 26 | color: string; |
| 24 | width: number; | 27 | width: number; |
| 25 | erase: boolean; | 28 | erase: boolean; |
| 29 | + /** Absent for a solid line, so a solid stroke's payload is unchanged. */ | ||
| 30 | + dash?: StrokeDash; | ||
| 31 | + /** | ||
| 32 | + * Erase marker: the sids of earlier strokes this entry removes (Excalidraw's | ||
| 33 | + * object eraser). The stroke log is append-only, so a deletion is itself a | ||
| 34 | + * logged entry; a marker carries no ink (`pts` is empty). | ||
| 35 | + */ | ||
| 36 | + del?: string[]; | ||
| 26 | pts: [number, number][]; | 37 | pts: [number, number][]; |
| 27 | }; | 38 | }; |
| 28 | 39 | ||
| @@ -42,7 +53,7 @@ function segmentString( | |||
| 42 | sid: string, | 53 | sid: string, |
| 43 | seg: number, | 54 | seg: number, |
| 44 | last: boolean, | 55 | last: boolean, |
| 45 | - stroke: Pick<Stroke, "color" | "width" | "erase">, | 56 | + stroke: Pick<Stroke, "color" | "width" | "erase" | "dash">, |
| 46 | pts: [number, number][], | 57 | pts: [number, number][], |
| 47 | ): string { | 58 | ): string { |
| 48 | const envelope: StrokeSegment = { | 59 | const envelope: StrokeSegment = { |
| @@ -53,6 +64,7 @@ function segmentString( | |||
| 53 | color: stroke.color, | 64 | color: stroke.color, |
| 54 | width: stroke.width, | 65 | width: stroke.width, |
| 55 | erase: stroke.erase, | 66 | erase: stroke.erase, |
| 67 | + ...(stroke.dash ? { dash: stroke.dash } : {}), | ||
| 56 | pts, | 68 | pts, |
| 57 | }; | 69 | }; |
| 58 | return JSON.stringify(envelope); | 70 | return JSON.stringify(envelope); |
| @@ -106,6 +118,26 @@ function isTuple(v: unknown): v is [number, number] { | |||
| 106 | ); | 118 | ); |
| 107 | } | 119 | } |
| 108 | 120 | ||
| 121 | +/** | ||
| 122 | + * Serialize an erase of the strokes `ids` into marker payloads, each under | ||
| 123 | + * `maxBytes` (a long sweep can remove more sids than fit in one payload). | ||
| 124 | + */ | ||
| 125 | +export function encodeEraseMarkers(ids: string[], sid: string, maxBytes: number = DEFAULT_MAX_BYTES): string[] { | ||
| 126 | + const out: string[] = []; | ||
| 127 | + const marker = (del: string[], n: number) => | ||
| 128 | + JSON.stringify({ v: 1, sid: `${sid}-${n}`, seg: 0, last: true, color: "", width: 0, erase: true, del, pts: [] } satisfies StrokeSegment); | ||
| 129 | + let batch: string[] = []; | ||
| 130 | + for (const id of ids) { | ||
| 131 | + if (batch.length > 0 && byteLength(marker([...batch, id], out.length)) > maxBytes) { | ||
| 132 | + out.push(marker(batch, out.length)); | ||
| 133 | + batch = []; | ||
| 134 | + } | ||
| 135 | + batch.push(id); | ||
| 136 | + } | ||
| 137 | + if (batch.length > 0) out.push(marker(batch, out.length)); | ||
| 138 | + return out; | ||
| 139 | +} | ||
| 140 | + | ||
| 109 | /** Parse one segment payload, or null on anything malformed (payloads are untrusted). */ | 141 | /** Parse one segment payload, or null on anything malformed (payloads are untrusted). */ |
| 110 | export function decodeSegment(payload: string | null): StrokeSegment | null { | 142 | export function decodeSegment(payload: string | null): StrokeSegment | null { |
| 111 | if (!payload) return null; | 143 | if (!payload) return null; |
| @@ -125,6 +157,8 @@ export function decodeSegment(payload: string | null): StrokeSegment | null { | |||
| 125 | typeof s.color !== "string" || | 157 | typeof s.color !== "string" || |
| 126 | typeof s.width !== "number" || | 158 | typeof s.width !== "number" || |
| 127 | typeof s.erase !== "boolean" || | 159 | typeof s.erase !== "boolean" || |
| 160 | + (s.dash !== undefined && !isDash(s.dash)) || | ||
| 161 | + (s.del !== undefined && !(Array.isArray(s.del) && s.del.every((id) => typeof id === "string"))) || | ||
| 128 | !Array.isArray(s.pts) || | 162 | !Array.isArray(s.pts) || |
| 129 | !s.pts.every(isTuple) | 163 | !s.pts.every(isTuple) |
| 130 | ) { | 164 | ) { |
| @@ -139,6 +173,7 @@ export function segmentToStroke(seg: StrokeSegment): Stroke { | |||
| 139 | color: seg.color, | 173 | color: seg.color, |
| 140 | width: seg.width, | 174 | width: seg.width, |
| 141 | erase: seg.erase, | 175 | erase: seg.erase, |
| 176 | + ...(seg.dash ? { dash: seg.dash } : {}), | ||
| 142 | points: seg.pts.map(([x, y]) => ({ x, y }) as Point), | 177 | points: seg.pts.map(([x, y]) => ({ x, y }) as Point), |
| 143 | }; | 178 | }; |
| 144 | } | 179 | } |
| @@ -147,26 +182,38 @@ export function segmentToStroke(seg: StrokeSegment): Stroke { | |||
| 147 | * Reassemble full strokes from an ordered list of stroke payloads (e.g. a | 182 | * 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 | 183 | * 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 | 184 | * 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 | 185 | + * no duplicate vertex. Strokes removed by a later erase marker are dropped, |
| 186 | + * so a replay ends on what the board actually showed. Non-stroke rows (null payloads, clear markers) are | ||
| 151 | * skipped by the caller passing only stroke payloads. | 187 | * skipped by the caller passing only stroke payloads. |
| 152 | */ | 188 | */ |
| 153 | export function reassembleStrokes(payloads: (string | null)[]): Stroke[] { | 189 | export function reassembleStrokes(payloads: (string | null)[]): Stroke[] { |
| 154 | const order: string[] = []; | 190 | const order: string[] = []; |
| 155 | const bySid = new Map<string, Stroke>(); | 191 | const bySid = new Map<string, Stroke>(); |
| 192 | + const deleted = new Set<string>(); | ||
| 156 | 193 | ||
| 157 | for (const payload of payloads) { | 194 | for (const payload of payloads) { |
| 158 | const seg = decodeSegment(payload); | 195 | const seg = decodeSegment(payload); |
| 159 | if (!seg) continue; | 196 | if (!seg) continue; |
| 197 | + if (seg.del) { | ||
| 198 | + for (const id of seg.del) deleted.add(id); | ||
| 199 | + continue; | ||
| 200 | + } | ||
| 160 | const pts = seg.pts.map(([x, y]) => ({ x, y }) as Point); | 201 | const pts = seg.pts.map(([x, y]) => ({ x, y }) as Point); |
| 161 | const existing = bySid.get(seg.sid); | 202 | const existing = bySid.get(seg.sid); |
| 162 | if (!existing) { | 203 | if (!existing) { |
| 163 | order.push(seg.sid); | 204 | order.push(seg.sid); |
| 164 | - bySid.set(seg.sid, { color: seg.color, width: seg.width, erase: seg.erase, points: pts }); | 205 | + bySid.set(seg.sid, { |
| 206 | + color: seg.color, | ||
| 207 | + width: seg.width, | ||
| 208 | + erase: seg.erase, | ||
| 209 | + ...(seg.dash ? { dash: seg.dash } : {}), | ||
| 210 | + points: pts, | ||
| 211 | + }); | ||
| 165 | } else { | 212 | } else { |
| 166 | // Drop the leading overlap point that duplicates the previous last point. | 213 | // Drop the leading overlap point that duplicates the previous last point. |
| 167 | existing.points.push(...(seg.seg > 0 ? pts.slice(1) : pts)); | 214 | existing.points.push(...(seg.seg > 0 ? pts.slice(1) : pts)); |
| 168 | } | 215 | } |
| 169 | } | 216 | } |
| 170 | 217 | ||
| 171 | - return order.map((sid) => bySid.get(sid)!); | 218 | + return order.filter((sid) => !deleted.has(sid)).map((sid) => bySid.get(sid)!); |
| 172 | } | 219 | } |
src/lib/draw-stroke.test.tsmodified+20 -0
| @@ -20,6 +20,10 @@ function stubContext() { | |||
| 20 | arc: record("arc"), | 20 | arc: record("arc"), |
| 21 | fill: record("fill"), | 21 | fill: record("fill"), |
| 22 | stroke: record("stroke"), | 22 | stroke: record("stroke"), |
| 23 | + // a style setter, not geometry — kept out of `calls` like the other styles | ||
| 24 | + setLineDash: (segments: number[]) => { | ||
| 25 | + props.lineDash = segments; | ||
| 26 | + }, | ||
| 23 | }; | 27 | }; |
| 24 | // trap the style assignments so composite mode / width can be asserted too | 28 | // trap the style assignments so composite mode / width can be asserted too |
| 25 | return new Proxy(c, { | 29 | return new Proxy(c, { |
| @@ -81,6 +85,16 @@ describe("paintStroke", () => { | |||
| 81 | expect(c.props.globalCompositeOperation).toBe("destination-out"); | 85 | expect(c.props.globalCompositeOperation).toBe("destination-out"); |
| 82 | }); | 86 | }); |
| 83 | 87 | ||
| 88 | + it("draws a solid line unless the stroke carries a dash pattern", () => { | ||
| 89 | + const c = stubContext(); | ||
| 90 | + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }])); | ||
| 91 | + expect(c.props.lineDash).toEqual([]); | ||
| 92 | + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { dash: "dashed" })); | ||
| 93 | + expect(c.props.lineDash).toEqual([16, 12]); | ||
| 94 | + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { dash: "dotted" })); | ||
| 95 | + expect((c.props.lineDash as number[])[0]).toBe(0); | ||
| 96 | + }); | ||
| 97 | + | ||
| 84 | it("paints over the layer when not erasing", () => { | 98 | it("paints over the layer when not erasing", () => { |
| 85 | const c = stubContext(); | 99 | const c = stubContext(); |
| 86 | paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }])); | 100 | paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }])); |
| @@ -116,6 +130,12 @@ describe("parseScene", () => { | |||
| 116 | expect(parseScene(JSON.stringify(scene))).toEqual(scene); | 130 | expect(parseScene(JSON.stringify(scene))).toEqual(scene); |
| 117 | }); | 131 | }); |
| 118 | 132 | ||
| 133 | + it("keeps a known dash pattern and rejects an unknown one", () => { | ||
| 134 | + const dashed = { ...scene, strokes: [{ ...scene.strokes[0], dash: "dotted" }] }; | ||
| 135 | + expect(parseScene(JSON.stringify(dashed))).toEqual(dashed); | ||
| 136 | + expect(parseScene(JSON.stringify({ ...scene, strokes: [{ ...scene.strokes[0], dash: "wavy" }] }))).toBeNull(); | ||
| 137 | + }); | ||
| 138 | + | ||
| 119 | it("rejects a wrong version", () => { | 139 | it("rejects a wrong version", () => { |
| 120 | expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull(); | 140 | expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull(); |
| 121 | }); | 141 | }); |
src/lib/draw-stroke.tsmodified+14 -2
| @@ -1,5 +1,7 @@ | |||
| 1 | export type Point = { x: number; y: number }; | 1 | export type Point = { x: number; y: number }; |
| 2 | -export type Stroke = { color: string; width: number; erase: boolean; points: Point[] }; | 2 | +/** Line pattern of a stroke; absent means solid (every older stroke). */ |
| 3 | +export type StrokeDash = "dashed" | "dotted"; | ||
| 4 | +export type Stroke = { color: string; width: number; erase: boolean; points: Point[]; dash?: StrokeDash }; | ||
| 3 | export type BgKind = "none" | "lines" | "grid"; | 5 | export type BgKind = "none" | "lines" | "grid"; |
| 4 | /** `w`/`h` are DPR-free world px; `dpr` is the device ratio the PNG beside them was baked at. */ | 6 | /** `w`/`h` are DPR-free world px; `dpr` is the device ratio the PNG beside them was baked at. */ |
| 5 | export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind; dpr?: number }; | 7 | 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 { | |||
| 25 | return typeof n === "number" && n > 0 && n <= MAX_SIDE; // NaN/Infinity fail the comparisons | 27 | return typeof n === "number" && n > 0 && n <= MAX_SIDE; // NaN/Infinity fail the comparisons |
| 26 | } | 28 | } |
| 27 | 29 | ||
| 30 | +export function isDash(d: unknown): d is StrokeDash { | ||
| 31 | + return d === "dashed" || d === "dotted"; | ||
| 32 | +} | ||
| 33 | + | ||
| 28 | function isStroke(s: unknown): s is Stroke { | 34 | function isStroke(s: unknown): s is Stroke { |
| 29 | if (!s || typeof s !== "object") return false; | 35 | if (!s || typeof s !== "object") return false; |
| 30 | const st = s as Stroke; | 36 | const st = s as Stroke; |
| @@ -33,7 +39,8 @@ function isStroke(s: unknown): s is Stroke { | |||
| 33 | typeof st.width === "number" && | 39 | typeof st.width === "number" && |
| 34 | typeof st.erase === "boolean" && | 40 | typeof st.erase === "boolean" && |
| 35 | Array.isArray(st.points) && | 41 | Array.isArray(st.points) && |
| 36 | - st.points.every(isPoint) | 42 | + st.points.every(isPoint) && |
| 43 | + (st.dash === undefined || isDash(st.dash)) | ||
| 37 | ); | 44 | ); |
| 38 | } | 45 | } |
| 39 | 46 | ||
| @@ -143,6 +150,11 @@ function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) { | |||
| 143 | c.lineWidth = stroke.width; | 150 | c.lineWidth = stroke.width; |
| 144 | c.lineCap = "round"; | 151 | c.lineCap = "round"; |
| 145 | c.lineJoin = "round"; | 152 | c.lineJoin = "round"; |
| 153 | + // A zero-length dash with a round cap paints a dot; gaps scale with the width | ||
| 154 | + // so a thick dashed line keeps the same rhythm as a thin one. | ||
| 155 | + if (stroke.dash === "dashed") c.setLineDash([stroke.width * 4, stroke.width * 3]); | ||
| 156 | + else if (stroke.dash === "dotted") c.setLineDash([0, stroke.width * 2.2]); | ||
| 157 | + else c.setLineDash([]); | ||
| 146 | } | 158 | } |
| 147 | 159 | ||
| 148 | /** Replay a finished stroke. Midpoint quadratics so a fast drag reads as a curve, not a polygon. */ | 160 | /** Replay a finished stroke. Midpoint quadratics so a fast drag reads as a curve, not a polygon. */ |
src/pages/whiteboard-page.tsxmodified+201 -116
| @@ -16,19 +16,28 @@ import type { MessageKey } from "@/i18n/messages"; | |||
| 16 | import { WhiteboardRoom, type BoardLiveState } from "@/components/whiteboard/whiteboard-room-ws"; | 16 | import { WhiteboardRoom, type BoardLiveState } from "@/components/whiteboard/whiteboard-room-ws"; |
| 17 | import { BoardSettingsPanel } from "@/components/whiteboard/board-settings-panel"; | 17 | import { BoardSettingsPanel } from "@/components/whiteboard/board-settings-panel"; |
| 18 | import { RouteGuard } from "@/components/layout/route-guard"; | 18 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 19 | -import { PageHeader } from "@/components/layout/page-header"; | ||
| 20 | -import { Breadcrumbs } from "@/components/layout/breadcrumbs"; | ||
| 21 | import { Alert } from "@/components/ui/alert"; | 19 | import { Alert } from "@/components/ui/alert"; |
| 22 | import { Badge } from "@/components/ui/badge"; | 20 | import { Badge } from "@/components/ui/badge"; |
| 23 | import { Button } from "@/components/ui/button"; | 21 | import { Button } from "@/components/ui/button"; |
| 24 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | 22 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 25 | import { DrawingPlayback } from "@/components/ui/drawing-playback"; | 23 | import { DrawingPlayback } from "@/components/ui/drawing-playback"; |
| 26 | import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; | 24 | import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; |
| 27 | -import { IconDotsVertical, IconEraser, IconLock, IconTrash, IconX } from "@/components/ui/icons"; | 25 | +import { |
| 26 | + IconChevronLeft, | ||
| 27 | + IconEraser, | ||
| 28 | + IconLock, | ||
| 29 | + IconMenu, | ||
| 30 | + IconRotateCcw, | ||
| 31 | + IconSettings, | ||
| 32 | + IconTrash, | ||
| 33 | + IconX, | ||
| 34 | +} from "@/components/ui/icons"; | ||
| 35 | +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; | ||
| 28 | import { PageSpinner } from "@/components/ui/page-spinner"; | 36 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 29 | import { SidePanel } from "@/components/ui/side-panel"; | 37 | import { SidePanel } from "@/components/ui/side-panel"; |
| 30 | import { reassembleStrokes } from "@/lib/board-stroke-codec"; | 38 | import { reassembleStrokes } from "@/lib/board-stroke-codec"; |
| 31 | import { strokesBounds, type DrawScene } from "@/lib/draw-stroke"; | 39 | import { strokesBounds, type DrawScene } from "@/lib/draw-stroke"; |
| 40 | +import { cn } from "@/lib/cn"; | ||
| 32 | import { formatDateTime } from "@/lib/format"; | 41 | import { formatDateTime } from "@/lib/format"; |
| 33 | import { hasMinRole } from "@/lib/roles"; | 42 | import { hasMinRole } from "@/lib/roles"; |
| 34 | import { useAuth } from "@/stores/auth-context"; | 43 | import { useAuth } from "@/stores/auth-context"; |
| @@ -43,6 +52,20 @@ export default function WhiteboardPage() { | |||
| 43 | } | 52 | } |
| 44 | 53 | ||
| 45 | const EXPORT_MARGIN = 8; | 54 | const EXPORT_MARGIN = 8; |
| 55 | +// Same island look as the canvas's own tool island. | ||
| 56 | +const CORNER_ISLAND = "rounded-lg border border-border/70 bg-card shadow-[0_1px_4px_rgb(0_0_0/0.08)]"; | ||
| 57 | +const CORNER_BUTTON = cn( | ||
| 58 | + CORNER_ISLAND, | ||
| 59 | + "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", | ||
| 60 | +); | ||
| 61 | + | ||
| 62 | +/** A soft per-person colour, stable for an id, like Excalidraw's collaborator chips. */ | ||
| 63 | +function avatarStyle(userId: string) { | ||
| 64 | + let hash = 0; | ||
| 65 | + for (let i = 0; i < userId.length; i += 1) hash = (hash * 31 + userId.charCodeAt(i)) | 0; | ||
| 66 | + const hue = Math.abs(hash) % 360; | ||
| 67 | + return { "background-color": `hsl(${hue} 70% 86%)`, color: `hsl(${hue} 45% 26%)` }; | ||
| 68 | +} | ||
| 46 | 69 | ||
| 47 | // Build a replayable scene from a set of reassembled strokes (an epoch's marks), | 70 | // Build a replayable scene from a set of reassembled strokes (an epoch's marks), |
| 48 | // shifted into a tight box like the drawing export pipeline. | 71 | // shifted into a tight box like the drawing export pipeline. |
| @@ -207,6 +230,165 @@ function WhiteboardContent() { | |||
| 207 | } | 230 | } |
| 208 | }; | 231 | }; |
| 209 | 232 | ||
| 233 | + // One status line on the canvas, most important first; an action error | ||
| 234 | + // outranks all of them. | ||
| 235 | + const banner = () => { | ||
| 236 | + if (error()) return error(); | ||
| 237 | + if (closed()) return t("whiteboard.closedBanner"); | ||
| 238 | + if (locked()) return t("whiteboard.lockedBanner"); | ||
| 239 | + if (!isParticipant()) return t("whiteboard.readOnlyBanner"); | ||
| 240 | + if (connection() === "disconnected") return t("ws.disconnected"); | ||
| 241 | + return ""; | ||
| 242 | + }; | ||
| 243 | + | ||
| 244 | + const initialOf = (userId: string) => nameOf(userId).slice(0, 1).toLocaleUpperCase(locale()); | ||
| 245 | + | ||
| 246 | + const BoardMenu = () => ( | ||
| 247 | + <> | ||
| 248 | + <DropdownMenu placement="bottom-start" gutter={8}> | ||
| 249 | + <DropdownMenuTrigger class={CORNER_BUTTON} aria-label={t("whiteboard.menu")} title={t("whiteboard.menu")}> | ||
| 250 | + <IconMenu class="h-4.5 w-4.5" /> | ||
| 251 | + </DropdownMenuTrigger> | ||
| 252 | + <DropdownMenuContent class="w-56"> | ||
| 253 | + <DropdownMenuItem onSelect={() => navigate({ to: "/whiteboards" })}> | ||
| 254 | + <IconChevronLeft class="h-4 w-4" /> | ||
| 255 | + {t("whiteboard.back")} | ||
| 256 | + </DropdownMenuItem> | ||
| 257 | + <DropdownMenuSeparator /> | ||
| 258 | + <DropdownMenuItem onSelect={() => setTimeout(() => setHistoryOpen(true), 0)}> | ||
| 259 | + <IconRotateCcw class="h-4 w-4" /> | ||
| 260 | + {t("whiteboard.history")} | ||
| 261 | + </DropdownMenuItem> | ||
| 262 | + <DropdownMenuItem onSelect={() => setTimeout(() => setSettingsOpen(true), 0)}> | ||
| 263 | + <IconSettings class="h-4 w-4" /> | ||
| 264 | + {t("whiteboard.edit")} | ||
| 265 | + </DropdownMenuItem> | ||
| 266 | + <Show when={isCreator() && !closed()}> | ||
| 267 | + <DropdownMenuSeparator /> | ||
| 268 | + <DropdownMenuItem disabled={busy()} onSelect={() => void toggleLock()}> | ||
| 269 | + <IconLock class="h-4 w-4" /> | ||
| 270 | + {locked() ? t("whiteboard.unlock") : t("whiteboard.lock")} | ||
| 271 | + </DropdownMenuItem> | ||
| 272 | + <DropdownMenuItem disabled={busy()} onSelect={() => setTimeout(() => setClearOpen(true), 0)}> | ||
| 273 | + <IconEraser class="h-4 w-4" /> | ||
| 274 | + {t("whiteboard.clear")} | ||
| 275 | + </DropdownMenuItem> | ||
| 276 | + <DropdownMenuItem | ||
| 277 | + class="text-warning-text focus:bg-warning/10 focus:text-warning-text data-highlighted:bg-warning/10 data-highlighted:text-warning-text" | ||
| 278 | + disabled={busy()} | ||
| 279 | + onSelect={() => setTimeout(() => setCloseOpen(true), 0)} | ||
| 280 | + > | ||
| 281 | + <IconLock class="h-4 w-4" /> | ||
| 282 | + {t("whiteboard.close")} | ||
| 283 | + </DropdownMenuItem> | ||
| 284 | + </Show> | ||
| 285 | + <Show when={isCreator()}> | ||
| 286 | + <DropdownMenuSeparator /> | ||
| 287 | + <DropdownMenuItem destructive disabled={busy()} onSelect={() => setTimeout(() => setDeleteOpen(true), 0)}> | ||
| 288 | + <IconTrash class="h-4 w-4" /> | ||
| 289 | + {t("whiteboard.delete")} | ||
| 290 | + </DropdownMenuItem> | ||
| 291 | + </Show> | ||
| 292 | + </DropdownMenuContent> | ||
| 293 | + </DropdownMenu> | ||
| 294 | + <span class="hidden min-w-0 truncate rounded-md bg-card/80 px-2 py-1 text-sm font-semibold text-text-strong backdrop-blur-xs sm:block" title={boardTitle()}> | ||
| 295 | + {boardTitle()} | ||
| 296 | + </span> | ||
| 297 | + </> | ||
| 298 | + ); | ||
| 299 | + | ||
| 300 | + const BoardPresence = () => ( | ||
| 301 | + <> | ||
| 302 | + <Popover placement="bottom-end" gutter={8}> | ||
| 303 | + <PopoverTrigger | ||
| 304 | + class={cn(CORNER_ISLAND, "flex h-10 items-center gap-2 pl-1.5 pr-2.5 outline-hidden focus-visible:ring-2 focus-visible:ring-ring")} | ||
| 305 | + aria-label={`${t("whiteboard.roster")}: ${roster().length}`} | ||
| 306 | + title={t("whiteboard.roster")} | ||
| 307 | + > | ||
| 308 | + <span class="flex -space-x-2"> | ||
| 309 | + <For each={roster().slice(0, 3)}> | ||
| 310 | + {(userId) => ( | ||
| 311 | + <span | ||
| 312 | + class="flex h-7 w-7 items-center justify-center rounded-full text-xs font-bold ring-2 ring-card" | ||
| 313 | + style={avatarStyle(userId)} | ||
| 314 | + aria-hidden="true" | ||
| 315 | + > | ||
| 316 | + {initialOf(userId)} | ||
| 317 | + </span> | ||
| 318 | + )} | ||
| 319 | + </For> | ||
| 320 | + </span> | ||
| 321 | + <Show when={roster().length > 3}> | ||
| 322 | + <span class="text-xs font-semibold text-muted-foreground">+{roster().length - 3}</span> | ||
| 323 | + </Show> | ||
| 324 | + <span class={cn("h-2 w-2 rounded-full", connection() === "connected" ? "bg-success" : "bg-warning")} aria-hidden="true" /> | ||
| 325 | + </PopoverTrigger> | ||
| 326 | + <PopoverContent class="w-72 p-0"> | ||
| 327 | + <div class="flex items-center justify-between gap-2 border-b border-border-hairline px-4 py-3"> | ||
| 328 | + <h3 class="text-sm font-semibold text-text-strong">{t("whiteboard.roster")}</h3> | ||
| 329 | + <span class="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground"> | ||
| 330 | + <span class={cn("h-2 w-2 rounded-full", connection() === "connected" ? "bg-success" : "bg-warning")} /> | ||
| 331 | + {connection() === "connected" ? t("ws.connected") : connection() === "connecting" ? t("ws.connecting") : t("ws.disconnected")} | ||
| 332 | + </span> | ||
| 333 | + </div> | ||
| 334 | + <ul class="max-h-80 space-y-0.5 overflow-y-auto p-2"> | ||
| 335 | + <For each={roster()}> | ||
| 336 | + {(userId) => ( | ||
| 337 | + <li class="flex items-center gap-2 rounded-lg px-2 py-1.5 transition-colors hover:bg-muted/60"> | ||
| 338 | + <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold" style={avatarStyle(userId)}> | ||
| 339 | + {initialOf(userId)} | ||
| 340 | + </span> | ||
| 341 | + <span class="min-w-0 flex-1"> | ||
| 342 | + <span class="flex min-w-0 items-center gap-1.5"> | ||
| 343 | + <span class="truncate text-sm font-medium">{nameOf(userId)}</span> | ||
| 344 | + <Show when={userId === meId()}> | ||
| 345 | + <span class="shrink-0 text-xs text-muted-foreground">({t("whiteboard.you")})</span> | ||
| 346 | + </Show> | ||
| 347 | + <Show when={userId === live().creator}> | ||
| 348 | + <Badge variant="outline" class="shrink-0 text-[11px]">{t("whiteboard.creator")}</Badge> | ||
| 349 | + </Show> | ||
| 350 | + </span> | ||
| 351 | + <span class="block truncate text-xs text-muted-foreground">{roleOf(userId) || userId}</span> | ||
| 352 | + </span> | ||
| 353 | + <Show when={isCreator() && !closed() && userId !== live().creator}> | ||
| 354 | + <Button | ||
| 355 | + type="button" | ||
| 356 | + variant="ghost" | ||
| 357 | + size="icon" | ||
| 358 | + class="h-8 w-8 shrink-0 rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive-text" | ||
| 359 | + disabled={busy()} | ||
| 360 | + title={t("whiteboard.removeParticipant")} | ||
| 361 | + aria-label={t("whiteboard.removeParticipant")} | ||
| 362 | + onClick={() => void updateBoard({ participants: (live().participants ?? []).filter((id) => id !== userId) })} | ||
| 363 | + > | ||
| 364 | + <IconX class="h-4 w-4" /> | ||
| 365 | + </Button> | ||
| 366 | + </Show> | ||
| 367 | + </li> | ||
| 368 | + )} | ||
| 369 | + </For> | ||
| 370 | + </ul> | ||
| 371 | + </PopoverContent> | ||
| 372 | + </Popover> | ||
| 373 | + <Show when={isCreator() && !closed()}> | ||
| 374 | + <button | ||
| 375 | + type="button" | ||
| 376 | + class={cn(CORNER_BUTTON, locked() && "border-warning/50 bg-warning/15 text-warning-text hover:bg-warning/20")} | ||
| 377 | + disabled={busy()} | ||
| 378 | + aria-pressed={locked()} | ||
| 379 | + aria-label={locked() ? t("whiteboard.unlock") : t("whiteboard.lock")} | ||
| 380 | + title={locked() ? t("whiteboard.unlock") : t("whiteboard.lock")} | ||
| 381 | + onClick={() => void toggleLock()} | ||
| 382 | + > | ||
| 383 | + <IconLock class="h-4.5 w-4.5" /> | ||
| 384 | + </button> | ||
| 385 | + <Button type="button" size="sm" class="hidden h-10 rounded-lg px-4 sm:inline-flex" onClick={() => setSettingsOpen(true)}> | ||
| 386 | + {t("whiteboard.inviteAction")} | ||
| 387 | + </Button> | ||
| 388 | + </Show> | ||
| 389 | + </> | ||
| 390 | + ); | ||
| 391 | + | ||
| 210 | return ( | 392 | return ( |
| 211 | <Suspense fallback={<PageSpinner />}> | 393 | <Suspense fallback={<PageSpinner />}> |
| 212 | <Show | 394 | <Show |
| @@ -218,121 +400,24 @@ function WhiteboardContent() { | |||
| 218 | } | 400 | } |
| 219 | > | 401 | > |
| 220 | {(b) => ( | 402 | {(b) => ( |
| 221 | - <div class="space-y-4"> | 403 | + // Edge to edge over the content column's padding, like Excalidraw |
| 222 | - <Breadcrumbs items={[{ label: t("whiteboard.title"), to: "/whiteboards" }, { label: boardTitle() }]} /> | 404 | + // owning the viewport; the height leaves room for the shell header |
| 223 | - <PageHeader | 405 | + // (desktop) or the tab bar (phone). |
| 224 | - compact | 406 | + <div class="-mx-4 -mt-6 sm:-mx-6 lg:-mx-10 lg:-mb-6"> |
| 225 | - title={boardTitle()} | 407 | + <h1 class="sr-only">{boardTitle()}</h1> |
| 226 | - actions={ | 408 | + <WhiteboardRoom |
| 227 | - <div class="flex flex-wrap items-center gap-2"> | 409 | + board={b()} |
| 228 | - <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => setHistoryOpen(true)}> | 410 | + meId={meId()} |
| 229 | - {t("whiteboard.history")} | 411 | + class="h-[calc(100dvh-3.5rem-max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] min-h-96 lg:h-[calc(100dvh-49px-env(safe-area-inset-top))]" |
| 230 | - </Button> | 412 | + topLeft={<BoardMenu />} |
| 231 | - <Button type="button" size="sm" class="rounded-lg" onClick={() => setSettingsOpen(true)}> | 413 | + topRight={<BoardPresence />} |
| 232 | - {t("whiteboard.edit")} | 414 | + banner={banner()} |
| 233 | - </Button> | 415 | + bannerTone={error() ? "error" : "info"} |
| 234 | - <Show when={isCreator()}> | 416 | + onState={mergeLive} |
| 235 | - <DropdownMenu placement="bottom-end" gutter={8}> | 417 | + onConnectionChange={setConnection} |
| 236 | - <DropdownMenuTrigger | 418 | + onDeleted={() => navigate({ to: "/whiteboards" })} |
| 237 | - class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border-line bg-surface-tint text-foreground outline-hidden transition-colors hover:border-primary/30 hover:bg-primary/8 hover:text-primary-text focus-visible:ring-2 focus-visible:ring-ring data-expanded:border-primary/30 data-expanded:bg-primary/10 data-expanded:text-primary-text" | ||
| 238 | - aria-label={t("common.actions")} | ||
| 239 | - title={t("common.actions")} | ||
| 240 | - > | ||
| 241 | - <IconDotsVertical class="h-4 w-4" /> | ||
| 242 | - </DropdownMenuTrigger> | ||
| 243 | - <DropdownMenuContent class="w-52"> | ||
| 244 | - <Show when={!closed()}> | ||
| 245 | - <DropdownMenuItem disabled={busy()} onSelect={() => void toggleLock()}> | ||
| 246 | - <IconLock class="h-4 w-4" /> | ||
| 247 | - {locked() ? t("whiteboard.unlock") : t("whiteboard.lock")} | ||
| 248 | - </DropdownMenuItem> | ||
| 249 | - <DropdownMenuItem disabled={busy()} onSelect={() => setTimeout(() => setClearOpen(true), 0)}> | ||
| 250 | - <IconEraser class="h-4 w-4" /> | ||
| 251 | - {t("whiteboard.clear")} | ||
| 252 | - </DropdownMenuItem> | ||
| 253 | - <DropdownMenuSeparator /> | ||
| 254 | - <DropdownMenuItem class="text-warning-text focus:bg-warning/10 focus:text-warning-text data-highlighted:bg-warning/10 data-highlighted:text-warning-text" disabled={busy()} onSelect={() => setTimeout(() => setCloseOpen(true), 0)}> | ||
| 255 | - <IconLock class="h-4 w-4" /> | ||
| 256 | - {t("whiteboard.close")} | ||
| 257 | - </DropdownMenuItem> | ||
| 258 | - </Show> | ||
| 259 | - <Show when={!closed()}><DropdownMenuSeparator /></Show> | ||
| 260 | - <DropdownMenuItem destructive disabled={busy()} onSelect={() => setTimeout(() => setDeleteOpen(true), 0)}> | ||
| 261 | - <IconTrash class="h-4 w-4" /> | ||
| 262 | - {t("whiteboard.delete")} | ||
| 263 | - </DropdownMenuItem> | ||
| 264 | - </DropdownMenuContent> | ||
| 265 | - </DropdownMenu> | ||
| 266 | - </Show> | ||
| 267 | - </div> | ||
| 268 | - } | ||
| 269 | /> | 419 | /> |
| 270 | 420 | ||
| 271 | - <Show when={error()}> | ||
| 272 | - <Alert variant="destructive">{error()}</Alert> | ||
| 273 | - </Show> | ||
| 274 | - | ||
| 275 | - <div class="grid gap-4 lg:grid-cols-[minmax(0,1fr)_18rem]"> | ||
| 276 | - <WhiteboardRoom | ||
| 277 | - board={b()} | ||
| 278 | - meId={meId()} | ||
| 279 | - onState={mergeLive} | ||
| 280 | - onConnectionChange={setConnection} | ||
| 281 | - onDeleted={() => navigate({ to: "/whiteboards" })} | ||
| 282 | - /> | ||
| 283 | - <aside class="overflow-hidden rounded-xl border border-border-line bg-surface-base shadow-xs"> | ||
| 284 | - <div class="space-y-2 border-b border-border-hairline bg-surface-tint px-4 py-3"> | ||
| 285 | - <div class="flex items-center justify-between gap-2"> | ||
| 286 | - <h3 class="text-sm font-semibold text-text-strong">{t("whiteboard.roster")}</h3> | ||
| 287 | - <Badge variant="secondary">{roster().length}</Badge> | ||
| 288 | - </div> | ||
| 289 | - <span class="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground"> | ||
| 290 | - <span class={connection() === "connected" ? "h-2 w-2 rounded-full bg-success" : "h-2 w-2 rounded-full bg-warning"} /> | ||
| 291 | - {connection() === "connected" ? t("ws.connected") : connection() === "connecting" ? t("ws.connecting") : t("ws.disconnected")} | ||
| 292 | - </span> | ||
| 293 | - <div class="flex flex-wrap gap-1.5"> | ||
| 294 | - <Show when={closed()}><Badge variant="warning">{t("whiteboard.closedBadge")}</Badge></Show> | ||
| 295 | - <Show when={locked() && !closed()}><Badge variant="outline">{t("whiteboard.lockedBadge")}</Badge></Show> | ||
| 296 | - <Show when={!isParticipant()}><Badge variant="outline">{t("whiteboard.readOnlyBadge")}</Badge></Show> | ||
| 297 | - </div> | ||
| 298 | - </div> | ||
| 299 | - <ul class="space-y-1 p-2"> | ||
| 300 | - <For each={roster()}> | ||
| 301 | - {(userId) => ( | ||
| 302 | - <li class="group flex items-center gap-2 rounded-xl px-2 py-2 transition-colors hover:bg-muted/60"> | ||
| 303 | - <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary-text"> | ||
| 304 | - {nameOf(userId).slice(0, 1).toLocaleUpperCase(locale())} | ||
| 305 | - </span> | ||
| 306 | - <span class="min-w-0 flex-1"> | ||
| 307 | - <span class="flex min-w-0 items-center gap-1.5"> | ||
| 308 | - <span class="truncate text-sm font-medium">{nameOf(userId)}</span> | ||
| 309 | - <Show when={userId === live().creator}> | ||
| 310 | - <Badge variant="outline" class="shrink-0 text-[11px]">{t("whiteboard.creator")}</Badge> | ||
| 311 | - </Show> | ||
| 312 | - </span> | ||
| 313 | - <span class="block truncate text-xs text-muted-foreground">{roleOf(userId) || userId}</span> | ||
| 314 | - </span> | ||
| 315 | - <Show when={isCreator() && !closed() && userId !== live().creator}> | ||
| 316 | - <Button | ||
| 317 | - type="button" | ||
| 318 | - variant="ghost" | ||
| 319 | - size="icon" | ||
| 320 | - class="h-8 w-8 shrink-0 rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive-text" | ||
| 321 | - disabled={busy()} | ||
| 322 | - title={t("whiteboard.removeParticipant")} | ||
| 323 | - aria-label={t("whiteboard.removeParticipant")} | ||
| 324 | - onClick={() => void updateBoard({ participants: (live().participants ?? []).filter((id) => id !== userId) })} | ||
| 325 | - > | ||
| 326 | - <IconX class="h-4 w-4" /> | ||
| 327 | - </Button> | ||
| 328 | - </Show> | ||
| 329 | - </li> | ||
| 330 | - )} | ||
| 331 | - </For> | ||
| 332 | - </ul> | ||
| 333 | - </aside> | ||
| 334 | - </div> | ||
| 335 | - | ||
| 336 | <BoardSettingsPanel | 421 | <BoardSettingsPanel |
| 337 | open={settingsOpen()} | 422 | open={settingsOpen()} |
| 338 | onOpenChange={setSettingsOpen} | 423 | onOpenChange={setSettingsOpen} |