diff --git a/apps/web/e2e/plugins.test.ts b/apps/web/e2e/plugins.test.ts index b063d10..cb4fd7f 100644 --- a/apps/web/e2e/plugins.test.ts +++ b/apps/web/e2e/plugins.test.ts @@ -227,6 +227,180 @@ describe("plugin system", async () => { await page.close(); }); + it("undoes, redoes, and erases strokes", async () => { + const page = await createPage(); + await openApp(page); + + const instanceId = await page.evaluate(() => window.__typbase.installPlugin("local:drawing")); + + const action = (name: string, args: Record = {}) => + page.evaluate( + ({ id, name: actionName, args: actionArgs }) => + window.__typbase.pluginAction(id, "window", actionName, actionArgs), + { id: instanceId, name, args }, + ); + const records = () => + page.evaluate(async (id) => { + const state = await window.__typbase.pluginState(id); + + return (state.strokes ?? []) as Array>; + }, instanceId); + const stroke = (points: number[][]) => ({ + stroke: { color: "#b42828", width: 3, points }, + }); + + await action( + "stroke.add", + stroke([ + [4, 4], + [12, 18], + ]), + ); + await action( + "stroke.add", + stroke([ + [20, 20], + [30, 30], + ]), + ); + + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(2); + // `seq` is the draw order. The collection itself comes back in map order, + // which is why the canvas and the embed sort by it. + expect((await records()).map((record) => Number(record.seq)).sort((a, b) => a - b)).toEqual([ + 1, 2, + ]); + + await action("history.undo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(1); + + await action("history.undo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(0); + + // Undo past the start is a no-op. + await action("history.undo"); + expect((await records()).length).toBe(0); + + await action("history.redo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(1); + await action("history.redo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(2); + await action("history.redo"); + expect((await records()).length).toBe(2); + + // A new edit drops the redo branch. + await action("history.undo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(1); + await action( + "stroke.add", + stroke([ + [40, 40], + [48, 48], + ]), + ); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(2); + await action("history.redo"); + expect((await records()).length).toBe(2); + + // The eraser removes records and undo puts the same ones back. + const ids = (await records()).map((record) => String(record.id)); + await action("stroke.erase", { ids: [ids[0]] }); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(1); + await action("history.undo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(2); + await action("history.redo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(1); + + // Clear is one entry, so one undo restores the whole board. + await action("stroke.clear"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(0); + await action("history.undo"); + await expect.poll(async () => (await records()).length, { timeout: 30_000 }).toBe(1); + + await page.close(); + }); + + it("draws and erases on the canvas with a pointer", async () => { + const page = await createPage(); + await openApp(page); + + const instanceId = await page.evaluate(() => window.__typbase.installPlugin("local:drawing")); + await page.evaluate((id) => window.__typbase.openPlugin(id), instanceId); + await page.waitForFunction((id) => window.__typbase.pluginWindowOpen(id), instanceId, { + timeout: 30_000, + }); + await page.waitForSelector(".plugin-window canvas.tb-canvas", { timeout: 30_000 }); + + const count = () => + page.evaluate(async (id) => { + const state = await window.__typbase.pluginState(id); + + return (state.strokes ?? []).length; + }, instanceId); + const canvasBox = () => + page.evaluate(() => { + const host = document.querySelector(".plugin-window .plugin-surface"); + const canvas = host?.shadowRoot?.querySelector("canvas.tb-canvas"); + canvas?.scrollIntoView({ block: "center" }); + const rect = canvas?.getBoundingClientRect(); + + return rect ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : null; + }); + const clickButton = (label: string) => + page.evaluate((buttonLabel) => { + const host = document.querySelector(".plugin-window .plugin-surface"); + const button = [...(host?.shadowRoot?.querySelectorAll("button") ?? [])].find( + (candidate) => candidate.textContent?.trim() === buttonLabel, + ); + (button as HTMLButtonElement | undefined)?.click(); + }, label); + + const first = await canvasBox(); + expect(first).toBeTruthy(); + if (!first) return; + + await page.mouse.move(first.x + 20, first.y + 60); + await page.mouse.down(); + await page.mouse.move(first.x + Math.min(160, first.width - 20), first.y + 60, { steps: 8 }); + await page.mouse.up(); + + await expect.poll(count, { timeout: 30_000 }).toBe(1); + + await clickButton("Eraser"); + await page.waitForFunction( + () => { + const host = document.querySelector(".plugin-window .plugin-surface"); + const element = host?.shadowRoot?.querySelector('[data-tb-component="canvas"]'); + const raw = element?.getAttribute("data-tb-props"); + if (!raw) return false; + try { + return (JSON.parse(raw) as { tool?: string }).tool === "erase"; + } catch { + return false; + } + }, + null, + { timeout: 30_000 }, + ); + + const second = await canvasBox(); + expect(second).toBeTruthy(); + if (!second) return; + + await page.mouse.move(second.x + 80, second.y + 20); + await page.mouse.down(); + await page.mouse.move(second.x + 80, second.y + 110, { steps: 8 }); + await page.mouse.up(); + + await expect.poll(count, { timeout: 30_000 }).toBe(0); + + // The eraser patch is in the history, so the toolbar brings it back. + await clickButton("Undo"); + await expect.poll(count, { timeout: 30_000 }).toBe(1); + + await page.close(); + }); + it("opens the plugin when an embed's link is clicked", async () => { const page = await createPage(); await openApp(page); diff --git a/apps/web/public/plugins/drawing/main.typ b/apps/web/public/plugins/drawing/main.typ index 7723a3c..b6d94ca 100644 --- a/apps/web/public/plugins/drawing/main.typ +++ b/apps/web/public/plugins/drawing/main.typ @@ -4,12 +4,31 @@ // // The window surface owns the canvas. Colors come from `ctx.theme`, so the // swatches follow the workspace palette. +// +// Undo history is device-local view state. Each entry holds the state ops that +// undo and redo it, so replaying an entry is the whole undo implementation. +// A stroke carries a `seq` because collection records come back in map order, +// which is not insertion order. #import "/typbase/lib.typ" as typbase #import "/typbase/ui.typ": * +#let history-limit = 50 #let strokes(state) = state.at("strokes", default: ()) + +// Collection records have no guaranteed order, and two devices can draw at +// the same time. `seq` is the draw order and `id` breaks a tie. +#let ordered(all) = all.sorted(key: stroke => (stroke.at("seq", default: 0), stroke.id)) + +#let next-seq(all) = { + let highest = 0 + for stroke in all { + highest = calc.max(highest, stroke.at("seq", default: 0)) + } + highest + 1 +} + #let colors(ctx) = ( (name: "Ink", color: ctx.theme.text), (name: "Red", color: ctx.theme.red), @@ -31,13 +50,60 @@ ) } +// An entry carries both directions. Undo pops it from `undo`, applies `undo`, +// and moves it to `redo`. Redo does the reverse. +#let history-entry(label, undo, redo) = (label: label, undo: undo, redo: redo) + +#let push-history(view, entry) = { + let undo = view.at("undo", default: ()) + (entry,) + ( + undo: if undo.len() > history-limit { undo.slice(1) } else { undo }, + redo: (), + ) +} + +// Removing records is undoable by appending them back with the same ids. +#let removed-entry(label, removed) = history-entry( + label, + removed.map(stroke => op-append("strokes", stroke)), + removed.map(stroke => op-remove("strokes", stroke.id)), +) + +#let undo-step(view) = { + let undo = view.at("undo", default: ()) + if undo.len() == 0 { (:) } else { + let entry = undo.last() + ops-both( + entry.undo, + ( + undo: undo.slice(0, undo.len() - 1), + redo: view.at("redo", default: ()) + (entry,), + ), + ) + } +} + +#let redo-step(view) = { + let redo = view.at("redo", default: ()) + if redo.len() == 0 { (:) } else { + let entry = redo.last() + ops-both( + entry.redo, + ( + undo: view.at("undo", default: ()) + (entry,), + redo: redo.slice(0, redo.len() - 1), + ), + ) + } +} + // Renders the board in a note. The host answers the plugin-data query, so // the note recompiles whenever the drawing changes. #let embed(instance-id) = { let data = typbase.query("plugin-data", filter: instance-id) if data == none { return text(fill: luma(140))[Missing drawing] } - let all = data.at("strokes", default: ()) + let all = ordered(data.at("strokes", default: ())) if all.len() == 0 { return box(width: 100%, inset: 8pt, stroke: 0.5pt, radius: 4pt)[ #text(fill: luma(140))[Empty drawing] @@ -102,19 +168,48 @@ if name == "stroke.add" { let stroke = action.args.at("stroke", default: none) if stroke == none { (:) } else { - ops-state(( - op-append("strokes", ( + let points = stroke.at("points", default: ()) + if points.len() == 0 { (:) } else { + let record = ( id: action.id, + seq: next-seq(strokes(state)), color: stroke.at("color", default: ctx.theme.text), width: stroke.at("width", default: 3), - points: stroke.at("points", default: ()), - )), - )) + points: points, + ) + ops-both( + (op-append("strokes", record),), + push-history(view, history-entry( + "draw", + (op-remove("strokes", record.id),), + (op-append("strokes", record),), + )), + ) + } + } + } else if name == "stroke.erase" { + let ids = action.args.at("ids", default: ()) + let removed = strokes(state).filter(stroke => ids.contains(stroke.id)) + if removed.len() == 0 { (:) } else { + ops-both( + removed.map(stroke => op-remove("strokes", stroke.id)), + push-history(view, removed-entry("erase", removed)), + ) } } else if name == "stroke.clear" { - let ops = () - for stroke in strokes(state) { ops.push(op-remove("strokes", stroke.id)) } - ops-state(ops) + let removed = strokes(state) + if removed.len() == 0 { (:) } else { + ops-both( + removed.map(stroke => op-remove("strokes", stroke.id)), + push-history(view, removed-entry("clear", removed)), + ) + } + } else if name == "history.undo" { + undo-step(view) + } else if name == "history.redo" { + redo-step(view) + } else if name == "draw.tool" { + ops-view((tool: action.args.at("tool", default: "draw"))) } else if name == "draw.color" { ops-view((color: action.args.color)) } else if name == "draw.width" { @@ -131,16 +226,40 @@ } #let window(ctx) = { - let patch = if ctx.action != none { step(ctx.state, ctx.view, ctx.action, ctx) } else { (:) } + let patch = if ctx.action != none { + step(ctx.state, ctx.view, ctx.action, ctx) + } else { (:) } let view = ctx.view let color = view.at("color", default: ctx.theme.text) let width = view.at("width", default: 3) - let all = strokes(ctx.state) + let tool = view.at("tool", default: "draw") + let all = ordered(strokes(ctx.state)) + let undo-count = view.at("undo", default: ()).len() + let redo-count = view.at("redo", default: ()).len() surface( [ #panel(title: "Brush", body: [ #toolbar(body: [ + #button("Undo", action: "history.undo", kind: "ghost", disabled: undo-count == 0) + #button("Redo", action: "history.redo", kind: "ghost", disabled: redo-count == 0) + #button("Clear", action: "stroke.clear", kind: "danger", disabled: all.len() == 0) + ]) + #toolbar(body: [ + #button( + "Draw", + action: "draw.tool", + args: (tool: "draw"), + kind: "ghost", + selected: tool == "draw", + ) + #button( + "Eraser", + action: "draw.tool", + args: (tool: "erase"), + kind: "ghost", + selected: tool == "erase", + ) #for entry in colors(ctx) [ #swatch( entry.color, @@ -152,11 +271,11 @@ ] #button("Thin", action: "draw.width", args: (width: 2), kind: "ghost", selected: width == 2) #button("Thick", action: "draw.width", args: (width: 6), kind: "ghost", selected: width == 6) - #button("Clear", action: "stroke.clear", kind: "danger") ]) #canvas( "stroke.add", strokes: all.map(stroke => ( + id: stroke.id, color: stroke.color, width: stroke.width, points: stroke.points, @@ -164,8 +283,13 @@ color: color, width: width, height: 380, + tool: tool, + erase-action: "stroke.erase", ) - #muted(body: str(all.len()) + " strokes, synced with the workspace") + #if tool == "erase" [ + #muted(body: "Drag over a stroke to erase it.") + ] + #muted(body: str(all.len()) + " strokes ยท " + str(undo-count) + " undo steps") ]) #panel(title: "Insert in a note", body: [ diff --git a/apps/web/public/plugins/drawing/plugin.json b/apps/web/public/plugins/drawing/plugin.json index 834ef2e..9375381 100644 --- a/apps/web/public/plugins/drawing/plugin.json +++ b/apps/web/public/plugins/drawing/plugin.json @@ -1,8 +1,8 @@ { "id": "local:drawing", "name": "Drawing", - "version": "0.3.0", - "description": "A touch-friendly drawing canvas in a floating window, with a Typst embed for notes.", + "version": "0.4.0", + "description": "A touch-friendly drawing canvas in a floating window, with undo, an eraser, and a Typst embed for notes.", "api": "typbase.host.v2", "entry": "main.typ", "icon": "draw", @@ -12,7 +12,8 @@ "fields": { "color": { "type": "string" }, "width": { "type": "number" }, - "points": { "type": "json" } + "points": { "type": "json" }, + "seq": { "type": "number", "optional": true } } } }, diff --git a/apps/web/public/plugins/ui.typ b/apps/web/public/plugins/ui.typ index 3c9fe63..e88bf65 100644 --- a/apps/web/public/plugins/ui.typ +++ b/apps/web/public/plugins/ui.typ @@ -63,7 +63,7 @@ if disabled { attrs.insert("disabled", "disabled") } if style != none { attrs.insert("style", style) } - html.elem("button", attrs: attrs, (if body == none { label } else { body })) + html.elem("button", attrs: attrs, if body == none { label } else { body }) } // Color chip. The plugin passes a color from `ctx.theme` (or its own value). @@ -75,7 +75,9 @@ title: label, "aria-label": label, ) - if action != none { attrs += action-attrs(action, args: args) } + if action != none { + attrs += action-attrs(action, args: args) + } html.elem("button", attrs: attrs) } @@ -83,7 +85,12 @@ // Material Symbols ligature. The host loads the icon font. #let icon(name, size: none) = html.elem( "span", - attrs: (class: "tb-icon") + (if size != none { (style: "font-size:" + size) } else { (:) }), + attrs: (class: "tb-icon") + + ( + if size != none { + (style: "font-size:" + size) + } else { (:) } + ), name, ) @@ -159,7 +166,7 @@ "section", attrs: (class: "tb-panel"), [ - #if title != none [#html.elem("h3", attrs: (class: "tb-panel__title"), title)] + #if title != none { html.elem("h3", attrs: (class: "tb-panel__title"), title) } #body ], ) @@ -232,15 +239,35 @@ ) // Paint surface. `strokes` round-trips to the canvas as -// `((color:, width:, points: ()))`. Each point is `(x, y)`. -#let canvas(action, strokes: (), color: "#1f2328", width: 3, height: 320) = html.elem( +// `((id:, color:, width:, points: ()))`. Each point is `(x, y)`. +// +// `tool: "erase"` hit-tests the pointer path against the supplied strokes and +// emits `erase-action` once with `args: (ids: (...))`. Strokes need an `id` +// for the eraser to name them. `erase-width` is the eraser diameter in px. +#let canvas( + action, + strokes: (), + color: "#1f2328", + width: 3, + height: 320, + tool: "draw", + erase-action: none, + erase-width: 18, +) = html.elem( "div", attrs: ( class: "tb-canvas-host", style: "height:" + str(height) + "px", "data-tb-component": "canvas", "data-tb-action": action, - "data-tb-props": json.encode((strokes: strokes, color: color, width: width)), + "data-tb-props": json.encode(( + strokes: strokes, + color: color, + width: width, + tool: tool, + eraseAction: erase-action, + eraseWidth: erase-width, + )), ), ) diff --git a/apps/web/src/lib/plugins/canvas.ts b/apps/web/src/lib/plugins/canvas.ts new file mode 100644 index 0000000..f5c8004 --- /dev/null +++ b/apps/web/src/lib/plugins/canvas.ts @@ -0,0 +1,383 @@ +/** + * The `canvas` host component. Plugins hand it strokes as data and an action + * name; the host owns the pointer handling, the bitmap, and the eraser hit + * test. Erasing is geometry, so it stays here instead of asking a Typst + * surface to measure every point against every pointer sample. + * + * `mountCanvas` is mounted per render and returns its own teardown, since the + * surface runtime replaces the whole tree on every patch. + */ + +export interface CanvasPoint { + x: number; + y: number; +} + +export interface CanvasStroke { + id?: string; + color?: string; + width?: number; + points?: number[][]; +} + +export interface CanvasCallbacks { + onAction: (name: string, args: Record) => void; + onError: (message: string) => void; +} + +interface CanvasProps { + strokes?: CanvasStroke[]; + color?: string; + width?: number; + tool?: "draw" | "erase"; + eraseAction?: string | null; + eraseWidth?: number; +} + +function toPoint(raw: number[]): CanvasPoint { + return { x: Number(raw[0]), y: Number(raw[1]) }; +} + +/** Distance from a point to a line segment. Degenerate segments are points. */ +export function distanceToSegment(point: CanvasPoint, a: CanvasPoint, b: CanvasPoint): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const lengthSquared = dx * dx + dy * dy; + if (lengthSquared === 0) return Math.hypot(point.x - a.x, point.y - a.y); + + const t = Math.min(1, Math.max(0, ((point.x - a.x) * dx + (point.y - a.y) * dy) / lengthSquared)); + + return Math.hypot(point.x - (a.x + t * dx), point.y - (a.y + t * dy)); +} + +function orientation(a: CanvasPoint, b: CanvasPoint, c: CanvasPoint): number { + const value = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + if (Math.abs(value) < 1e-9) return 0; + + return value > 0 ? 1 : -1; +} + +function onSegment(a: CanvasPoint, b: CanvasPoint, c: CanvasPoint): boolean { + const slack = 1e-9; + + return ( + b.x >= Math.min(a.x, c.x) - slack && + b.x <= Math.max(a.x, c.x) + slack && + b.y >= Math.min(a.y, c.y) - slack && + b.y <= Math.max(a.y, c.y) + slack + ); +} + +export function segmentsIntersect( + a0: CanvasPoint, + a1: CanvasPoint, + b0: CanvasPoint, + b1: CanvasPoint, +): boolean { + const o1 = orientation(a0, a1, b0); + const o2 = orientation(a0, a1, b1); + const o3 = orientation(b0, b1, a0); + const o4 = orientation(b0, b1, a1); + + if (o1 !== o2 && o3 !== o4) return true; + if (o1 === 0 && onSegment(a0, b0, a1)) return true; + if (o2 === 0 && onSegment(a0, b1, a1)) return true; + if (o3 === 0 && onSegment(b0, a0, b1)) return true; + if (o4 === 0 && onSegment(b0, a1, b1)) return true; + + return false; +} + +/** + * Distance between two segments. A crossing pair is zero, which matters for + * the eraser: a fast drag has few samples, and its endpoints can both sit + * away from the stroke it crosses. + */ +export function segmentDistance( + a0: CanvasPoint, + a1: CanvasPoint, + b0: CanvasPoint, + b1: CanvasPoint, +): number { + if (segmentsIntersect(a0, a1, b0, b1)) return 0; + + return Math.min( + distanceToSegment(a0, b0, b1), + distanceToSegment(a1, b0, b1), + distanceToSegment(b0, a0, a1), + distanceToSegment(b1, a0, a1), + ); +} + +/** + * Whether an eraser moving from `from` to `to` touches a stroke. `radius` is + * the eraser radius, so a wider brush stroke is hit from its own edge. + */ +export function strokeHit( + stroke: CanvasStroke, + from: CanvasPoint, + to: CanvasPoint, + radius: number, +): boolean { + const points = Array.isArray(stroke.points) ? stroke.points : []; + if (points.length === 0) return false; + + const reach = Math.max(0, radius) + Math.max(0, Number(stroke.width) || 0) / 2; + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + for (const raw of points) { + const x = Number(raw[0]); + const y = Number(raw[1]); + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + } + + // One bounding-box check per stroke, before the segment walk. An eraser + // segment is short, so most strokes are rejected here. + if ( + minX - reach > Math.max(from.x, to.x) || + maxX + reach < Math.min(from.x, to.x) || + minY - reach > Math.max(from.y, to.y) || + maxY + reach < Math.min(from.y, to.y) + ) { + return false; + } + + if (points.length === 1) { + return distanceToSegment(toPoint(points[0]!), from, to) <= reach; + } + + for (let index = 0; index < points.length - 1; index++) { + const a = toPoint(points[index]!); + const b = toPoint(points[index + 1]!); + if (segmentDistance(a, b, from, to) <= reach) return true; + } + + return false; +} + +export function hitStrokeIndices( + strokes: readonly CanvasStroke[], + from: CanvasPoint, + to: CanvasPoint, + radius: number, +): number[] { + const hits: number[] = []; + strokes.forEach((stroke, index) => { + if (strokeHit(stroke, from, to, radius)) hits.push(index); + }); + + return hits; +} + +export function mountCanvas(hostElement: HTMLElement, callbacks: CanvasCallbacks): () => void { + let props: CanvasProps = {}; + try { + props = JSON.parse(hostElement.getAttribute("data-tb-props") ?? "{}") as CanvasProps; + } catch (error) { + callbacks.onError(`bad canvas props: ${String(error)}`); + } + + const canvas = document.createElement("canvas"); + canvas.className = "tb-canvas"; + hostElement.append(canvas); + + const context = canvas.getContext("2d"); + if (!context) { + canvas.remove(); + + return () => {}; + } + + const dpr = window.devicePixelRatio || 1; + const strokes: CanvasStroke[] = Array.isArray(props.strokes) ? props.strokes.slice() : []; + const tool = props.tool === "erase" ? "erase" : "draw"; + const eraseWidth = Number(props.eraseWidth) > 0 ? Number(props.eraseWidth) : 18; + const eraseAction = + typeof props.eraseAction === "string" && props.eraseAction ? props.eraseAction : null; + const brushColor = props.color || "#1f2328"; + const brushWidth = Number(props.width) || 3; + + canvas.style.cursor = tool === "erase" ? "cell" : "crosshair"; + + let current: { color: string; width: number; points: number[][] } | undefined; + let drawing = false; + let erasing = false; + let erasePath: CanvasPoint[] = []; + let erased = new Set(); + let ring: CanvasPoint | null = null; + + function drawStroke(stroke: CanvasStroke): void { + const points = Array.isArray(stroke.points) ? stroke.points : []; + if (points.length === 0) return; + + context!.strokeStyle = stroke.color || "#1f2328"; + context!.lineWidth = Number(stroke.width) || 3; + context!.lineCap = "round"; + context!.lineJoin = "round"; + context!.beginPath(); + points.forEach((raw, index) => { + const point = toPoint(raw); + if (index === 0) context!.moveTo(point.x, point.y); + else context!.lineTo(point.x, point.y); + }); + context!.stroke(); + } + + function ringColor(): string { + const value = getComputedStyle(hostElement).getPropertyValue("--color-text").trim(); + + return value || "#5f6368"; + } + + function drawRing(at: CanvasPoint): void { + const radius = eraseWidth / 2; + context!.save(); + context!.beginPath(); + context!.arc(at.x, at.y, radius, 0, Math.PI * 2); + context!.strokeStyle = ringColor(); + context!.globalAlpha = 0.5; + context!.lineWidth = 1.5; + context!.stroke(); + context!.globalAlpha = 0.06; + context!.fillStyle = ringColor(); + context!.fill(); + context!.restore(); + } + + function redraw(): void { + context!.setTransform(dpr, 0, 0, dpr, 0, 0); + context!.clearRect(0, 0, canvas.width / dpr, canvas.height / dpr); + strokes.forEach((stroke, index) => { + if (!erased.has(index)) drawStroke(stroke); + }); + if (current) drawStroke(current); + if (ring) drawRing(ring); + } + + function resize(): void { + const rect = hostElement.getBoundingClientRect(); + canvas.width = Math.max(1, Math.floor(rect.width * dpr)); + canvas.height = Math.max(1, Math.floor(rect.height * dpr)); + canvas.style.width = `${rect.width}px`; + canvas.style.height = `${rect.height}px`; + redraw(); + } + + function pointOf(event: PointerEvent): CanvasPoint { + const rect = canvas.getBoundingClientRect(); + + return { + x: Math.round((event.clientX - rect.left) * 10) / 10, + y: Math.round((event.clientY - rect.top) * 10) / 10, + }; + } + + function eraseSegment(from: CanvasPoint, to: CanvasPoint): void { + if (!eraseAction) return; + + const radius = eraseWidth / 2; + strokes.forEach((stroke, index) => { + if (erased.has(index)) return; + if (strokeHit(stroke, from, to, radius)) erased.add(index); + }); + } + + canvas.addEventListener("pointerdown", (event) => { + if (event.button !== 0) return; + + if (tool === "erase") { + if (!eraseAction) return; + + erasing = true; + canvas.setPointerCapture(event.pointerId); + const at = pointOf(event); + erasePath = [at]; + ring = at; + // A tap erases the stroke under the pointer, so test the point too. + eraseSegment(at, at); + redraw(); + event.preventDefault(); + return; + } + + if (!hostElement.getAttribute("data-tb-action")) return; + drawing = true; + canvas.setPointerCapture(event.pointerId); + const at = pointOf(event); + current = { color: brushColor, width: brushWidth, points: [[at.x, at.y]] }; + redraw(); + event.preventDefault(); + }); + + canvas.addEventListener("pointermove", (event) => { + if (erasing) { + const next = pointOf(event); + const previous = erasePath.at(-1) ?? next; + erasePath.push(next); + ring = next; + eraseSegment(previous, next); + redraw(); + event.preventDefault(); + return; + } + + if (!drawing || !current) return; + const at = pointOf(event); + current.points.push([at.x, at.y]); + redraw(); + event.preventDefault(); + }); + + const finish = (event: PointerEvent) => { + try { + canvas.releasePointerCapture(event.pointerId); + } catch { + // already released + } + + if (erasing) { + erasing = false; + ring = null; + const ids = [...erased] + .map((index) => strokes[index]?.id) + .filter((id): id is string => typeof id === "string" && id.length > 0); + + if (ids.length && eraseAction) { + // Keep them hidden until the surface re-renders from the patch. + redraw(); + callbacks.onAction(eraseAction, { ids }); + } else { + erased = new Set(); + redraw(); + } + erasePath = []; + return; + } + + if (!drawing || !current) return; + drawing = false; + const actionName = hostElement.getAttribute("data-tb-action"); + const stroke = { color: current.color, width: current.width, points: current.points }; + strokes.push(stroke); + current = undefined; + redraw(); + if (actionName) callbacks.onAction(actionName, { stroke }); + }; + + canvas.addEventListener("pointerup", finish); + canvas.addEventListener("pointercancel", finish); + + const observer = new ResizeObserver(resize); + observer.observe(hostElement); + resize(); + + return () => { + observer.disconnect(); + canvas.remove(); + }; +} diff --git a/apps/web/src/lib/plugins/surface.ts b/apps/web/src/lib/plugins/surface.ts index 9d7dff4..b246fd4 100644 --- a/apps/web/src/lib/plugins/surface.ts +++ b/apps/web/src/lib/plugins/surface.ts @@ -1,5 +1,6 @@ import type { PluginAction } from "@typbase/typing"; +import { mountCanvas } from "./canvas"; import hostCss from "./surface.css?inline"; /** @@ -57,7 +58,7 @@ export function attachPluginSurface( let lastHeight = 0; let inputTimer: ReturnType | undefined; - let observers: ResizeObserver[] = []; + let disposers: (() => void)[] = []; let moving: | { element: HTMLElement; @@ -261,123 +262,18 @@ export function attachPluginSurface( moving = undefined; } - function mountCanvas(hostElement: HTMLElement): void { - let props: { - strokes?: Array<{ color?: string; width?: number; points?: number[][] }>; - color?: string; - width?: number; - } = {}; - try { - props = JSON.parse(hostElement.getAttribute("data-tb-props") ?? "{}") as typeof props; - } catch (error) { - options.onError(`bad canvas props: ${String(error)}`); - } - - const canvas = document.createElement("canvas"); - canvas.className = "tb-canvas"; - hostElement.append(canvas); - - const ctx = canvas.getContext("2d"); - if (!ctx) return; - const dpr = window.devicePixelRatio || 1; - const strokes = Array.isArray(props.strokes) ? props.strokes.slice() : []; - let current: { color: string; width: number; points: number[][] } | undefined; - let drawing = false; - - function drawStroke(stroke: { color?: string; width?: number; points?: number[][] }): void { - const points = Array.isArray(stroke.points) ? stroke.points : []; - if (points.length === 0) return; - ctx!.strokeStyle = stroke.color || "#1f2328"; - ctx!.lineWidth = Number(stroke.width) || 3; - ctx!.lineCap = "round"; - ctx!.lineJoin = "round"; - ctx!.beginPath(); - points.forEach((pt, index) => { - const x = Number(pt[0]); - const y = Number(pt[1]); - if (index === 0) ctx!.moveTo(x, y); - else ctx!.lineTo(x, y); - }); - ctx!.stroke(); - } - - function redraw(): void { - ctx!.setTransform(dpr, 0, 0, dpr, 0, 0); - ctx!.clearRect(0, 0, canvas.width / dpr, canvas.height / dpr); - for (const stroke of strokes) drawStroke(stroke); - if (current) drawStroke(current); - } - - function resize(): void { - const rect = hostElement.getBoundingClientRect(); - canvas.width = Math.max(1, Math.floor(rect.width * dpr)); - canvas.height = Math.max(1, Math.floor(rect.height * dpr)); - canvas.style.width = `${rect.width}px`; - canvas.style.height = `${rect.height}px`; - redraw(); - } - - function point(event: PointerEvent): number[] { - const rect = canvas.getBoundingClientRect(); - - return [ - Math.round((event.clientX - rect.left) * 10) / 10, - Math.round((event.clientY - rect.top) * 10) / 10, - ]; - } - - canvas.addEventListener("pointerdown", (event) => { - if (!hostElement.getAttribute("data-tb-action")) return; - drawing = true; - canvas.setPointerCapture(event.pointerId); - current = { - color: props.color || "#1f2328", - width: Number(props.width) || 3, - points: [point(event)], - }; - redraw(); - event.preventDefault(); - }); - - canvas.addEventListener("pointermove", (event) => { - if (!drawing || !current) return; - current.points.push(point(event)); - redraw(); - event.preventDefault(); - }); - - const finish = (event: PointerEvent) => { - if (!drawing || !current) return; - drawing = false; - const actionName = hostElement.getAttribute("data-tb-action"); - const stroke = { color: current.color, width: current.width, points: current.points }; - strokes.push(stroke); - current = undefined; - redraw(); - if (actionName) { - options.onAction({ id: newId(), name: actionName, args: { stroke }, fields: {} }); - } - try { - canvas.releasePointerCapture(event.pointerId); - } catch { - // already released - } - }; - canvas.addEventListener("pointerup", finish); - canvas.addEventListener("pointercancel", finish); - - const observer = new ResizeObserver(resize); - observer.observe(hostElement); - observers.push(observer); - resize(); - } - function mountComponents(): void { const declared = options.components ? new Set(options.components) : undefined; // One place decides which names mount. A name that reaches here but is not // implemented cannot come from a parsed manifest, so it is a surface that // was injected after the fact and gets reported rather than ignored. - const mounters: Record void> = { canvas: mountCanvas }; + const mounters: Record () => void> = { + canvas: (element) => + mountCanvas(element, { + onAction: (name, args) => options.onAction({ id: newId(), name, args, fields: {} }), + onError: options.onError, + }), + }; for (const element of root.querySelectorAll("[data-tb-component]")) { const name = element.getAttribute("data-tb-component") ?? ""; @@ -392,13 +288,13 @@ export function attachPluginSurface( } if (element.dataset.tbMounted) continue; element.dataset.tbMounted = "1"; - mount(element); + disposers.push(mount(element)); } } function teardownComponents(): void { - for (const observer of observers) observer.disconnect(); - observers = []; + for (const dispose of disposers) dispose(); + disposers = []; } root.addEventListener("submit", (event) => event.preventDefault()); diff --git a/apps/web/test/canvas.test.ts b/apps/web/test/canvas.test.ts new file mode 100644 index 0000000..1277064 --- /dev/null +++ b/apps/web/test/canvas.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from "vitest"; + +import { + distanceToSegment, + hitStrokeIndices, + segmentDistance, + segmentsIntersect, + strokeHit, + type CanvasPoint, +} from "../src/lib/plugins/canvas"; + +const point = (x: number, y: number): CanvasPoint => ({ x, y }); + +describe("canvas eraser geometry", () => { + it("measures a point against a segment", () => { + expect(distanceToSegment(point(0, 5), point(0, 0), point(10, 0))).toBe(5); + expect(distanceToSegment(point(5, 0), point(0, 0), point(10, 0))).toBe(0); + // Past the end, so the endpoint is the closest point. + expect(distanceToSegment(point(13, 4), point(0, 0), point(10, 0))).toBe(5); + expect(distanceToSegment(point(2, 2), point(2, 2), point(2, 2))).toBe(0); + }); + + it("detects crossing segments", () => { + expect(segmentsIntersect(point(0, 5), point(10, 5), point(5, 0), point(5, 10))).toBe(true); + expect(segmentsIntersect(point(0, 0), point(4, 0), point(5, 0), point(9, 0))).toBe(false); + expect(segmentDistance(point(0, 5), point(10, 5), point(5, 0), point(5, 10))).toBe(0); + }); + + it("hits a stroke the eraser crosses between two samples", () => { + // A fast drag has no sample near the vertical stroke, so only a + // segment-to-segment test catches it. + const stroke = { + points: [ + [50, 0], + [50, 100], + ], + }; + expect(strokeHit(stroke, point(0, 50), point(100, 50), 1)).toBe(true); + // The drag stops short of the stroke, so nothing is touched. + expect(strokeHit(stroke, point(0, 20), point(40, 20), 1)).toBe(false); + }); + + it("adds the brush width to the eraser reach", () => { + const stroke = { + points: [ + [0, 50], + [100, 50], + ], + width: 30, + }; + // 18px away, 15px of stroke half-width, 4px eraser: a hit. + expect(strokeHit(stroke, point(0, 68), point(100, 68), 4)).toBe(true); + // 25px away is outside the combined reach. + expect(strokeHit(stroke, point(0, 75), point(100, 75), 4)).toBe(false); + }); + + it("handles a single-point stroke", () => { + const dot = { points: [[50, 50]], width: 6 }; + + expect(strokeHit(dot, point(0, 50), point(100, 50), 1)).toBe(true); + expect(strokeHit(dot, point(0, 80), point(100, 80), 1)).toBe(false); + }); + + it("returns the indices of every touched stroke", () => { + const strokes = [ + { + points: [ + [0, 0], + [10, 0], + ], + }, + { + points: [ + [0, 40], + [10, 40], + ], + }, + { + points: [ + [0, 20], + [10, 20], + ], + }, + { points: [] }, + ]; + + expect(hitStrokeIndices(strokes, point(5, -5), point(5, 25), 2)).toEqual([0, 2]); + }); + + it("skips a stroke whose bounding box is elsewhere", () => { + const stroke = { + points: [ + [400, 400], + [420, 420], + ], + width: 2, + }; + + expect(strokeHit(stroke, point(0, 0), point(10, 10), 4)).toBe(false); + }); +}); diff --git a/docs/plugins.md b/docs/plugins.md index ee35e25..f866787 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -157,7 +157,7 @@ leave Typst, like canvas stroke colors; the CSS variables below cover the rest. | `field` / `textarea` / `select` / `checkbox` / `form` | inputs; `#form` scopes field collection | | `panel` / `card` / `stack` / `row` / `grid` / `toolbar` / `badge` / `muted` / `empty` | layout | | `board` / `movable` / `draggable` / `droppable` | drag components; `movable` sends x/y on drop | -| `canvas(action, strokes, color, width, height)` | drawing surface; requires the `canvas` host component | +| `canvas(action, strokes, color, width, height, tool, erase-action, erase-width)` | drawing surface; `tool: "erase"` emits `erase-action` with the ids the eraser touched; requires the `canvas` host component | | `op-append` / `op-set` / `op-merge` / `op-inc` / `op-remove` | state ops | | `ai-complete` / `ai-stream` | AI calls; `format: "typst"` runs the dialect check | @@ -166,6 +166,24 @@ call `typbase.query(...)` and `typbase.embed(...)`; the host answers requests like it does for pages. `plugin-data` queries are scoped to the calling plugin. +`canvas` draws the strokes it is given and, in erase mode, hit-tests the +pointer path against them. Every stroke needs an `id` so the eraser can name +what it touched, and one action carries the ids. The drawing plugin is the +reference. + +## Undo history + +History is device-local, so it belongs in `ctx.view`, not in the synced +collections. One entry holds the ops that undo and redo one edit, and +replaying the entry is the whole undo step. The drawing plugin's +`history.undo` pops the last entry from `view.undo`, applies `entry.undo`, +and pushes the entry onto `view.redo`. + +View patches merge one level deep, so return the complete `undo` and `redo` +arrays on every edit. A new edit clears `redo`. The stacks cap at 50 entries +because a cleared board stores every removed record in one entry, and the +history is written to `local.json` with the rest of the device state. + ## Styling Host styles live in `apps/web/src/lib/plugins/surface.css` and cover the