From e927653e4bbe27a9bc8b570e141423d74f3c91c9 Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:20:20 +0100 Subject: [PATCH] Add edgeless mode: pages as a canvas with their text as a live note Phase D of docs/AFFINE.md (ADR-14). The canvas lives in the page's Y.Doc next to its text, in ydoc.getMap("surface"): one Y.Map per element, each field its own entry so concurrent edits merge. The page's text is a note on the canvas bound to the same "default" fragment, so typing on the canvas is typing in the page. Canvas edits have their own undo history through a Y.UndoManager. - New package @docwell/canvas: viewport with pan, zoom and pinch; selection, marquee, snapping, resize and rotate; notes, text, shapes (plain or scribbled), connectors (straight, curve, elbow, with arrowheads and labels), pen and eraser, frames, groups, pictures, embeds and link cards, and mind maps (right, left or both sides; Tab, Enter, arrows). A style bar over the selection; the last style per kind is the default. - Presentation through frames, stickers and templates, PNG and SVG export. - Page/Edgeless switch in the header, ?mode= in page and share links, a per-page default (pages.default_mode) and a per-device default for new pages; share links show the canvas read-only. - Server: yrs writes the canvas into the document JSON as "surface", adds its text to search, and writes it back on restores and templates. - Phone: the bridge draws the canvas read-only (protocol 3) and the page screen has a canvas button. Strings are translated into all five languages and the user guide covers edgeless mode. Co-Authored-By: Claude Opus 5.5 --- .../pb_migrations/1763900000_page_mode.js | 19 + Docs-Site/guide/using-docwell.md | 28 + Packages/api-client/src/index.ts | 2 + Packages/api-client/src/schema.d.ts | 10 +- Packages/canvas/package.json | 26 + Packages/canvas/src/canvas.css | 616 +++++ Packages/canvas/src/canvas.test.ts | 227 ++ Packages/canvas/src/export.ts | 277 +++ Packages/canvas/src/geometry.ts | 368 +++ Packages/canvas/src/index.ts | 18 + Packages/canvas/src/labels.ts | 222 ++ Packages/canvas/src/library.ts | 139 ++ Packages/canvas/src/measure.ts | 73 + Packages/canvas/src/mindmap.ts | 153 ++ Packages/canvas/src/model.ts | 354 +++ Packages/canvas/src/render.ts | 199 ++ Packages/canvas/src/store.ts | 458 ++++ Packages/canvas/src/ui.ts | 675 ++++++ Packages/canvas/src/view.ts | 2139 +++++++++++++++++ Packages/canvas/src/yxml.ts | 104 + Packages/canvas/vitest.config.ts | 7 + Packages/editor-bridge/dist/index.html | 129 +- Packages/editor-bridge/src/bridge.test.ts | 54 +- Packages/editor-bridge/src/bridge.ts | 44 +- Packages/editor-bridge/src/protocol.ts | 4 +- Packages/editor-bridge/src/style.css | 6 + Packages/editor/package.json | 4 +- Packages/editor/src/DocwellEdgeless.vue | 138 ++ Packages/editor/src/DocwellEditor.vue | 6 +- Packages/editor/src/edgeless.ts | 165 ++ Packages/editor/src/editor.css | 1 + Packages/editor/src/index.ts | 9 + Packages/editor/src/labels.ts | 9 + Packages/ui/src/icons.ts | 46 + Phone-App/lib/api/generated/models.dart | 28 +- Phone-App/lib/editor/bridge.dart | 6 +- Phone-App/lib/screens/page_screen.dart | 23 +- Phone-App/test/editor_bridge_test.dart | 11 +- Phone-App/test/widget_test.dart | 13 +- Server/internal/api/api.gen.go | 32 +- Server/internal/directory/pages.go | 29 +- Server/internal/directory/shares.go | 4 +- Server/internal/pbschema/schema.json | 14 + Server/internal/ycrdt/ycrdt_test.go | 57 + Server/ycrdt-wasm/src/lib.rs | 145 ++ .../src/composables/useEditorHosts.ts | 1 + Web-App/frontend/src/locales/de.json | 123 +- Web-App/frontend/src/locales/en.json | 123 +- Web-App/frontend/src/locales/es.json | 123 +- Web-App/frontend/src/locales/fr.json | 123 +- Web-App/frontend/src/locales/pl.json | 123 +- Web-App/frontend/src/stores/preferences.ts | 6 + Web-App/frontend/src/stores/spaces.ts | 8 +- Web-App/frontend/src/views/ShareView.vue | 59 +- Web-App/frontend/src/views/page/PageView.vue | 122 +- .../src/views/settings/AccountView.vue | 21 + api/openapi.yaml | 13 +- package-lock.json | 20 + 58 files changed, 7859 insertions(+), 97 deletions(-) create mode 100644 Database/pb_migrations/1763900000_page_mode.js create mode 100644 Packages/canvas/package.json create mode 100644 Packages/canvas/src/canvas.css create mode 100644 Packages/canvas/src/canvas.test.ts create mode 100644 Packages/canvas/src/export.ts create mode 100644 Packages/canvas/src/geometry.ts create mode 100644 Packages/canvas/src/index.ts create mode 100644 Packages/canvas/src/labels.ts create mode 100644 Packages/canvas/src/library.ts create mode 100644 Packages/canvas/src/measure.ts create mode 100644 Packages/canvas/src/mindmap.ts create mode 100644 Packages/canvas/src/model.ts create mode 100644 Packages/canvas/src/render.ts create mode 100644 Packages/canvas/src/store.ts create mode 100644 Packages/canvas/src/ui.ts create mode 100644 Packages/canvas/src/view.ts create mode 100644 Packages/canvas/src/yxml.ts create mode 100644 Packages/canvas/vitest.config.ts create mode 100644 Packages/editor/src/DocwellEdgeless.vue create mode 100644 Packages/editor/src/edgeless.ts diff --git a/Database/pb_migrations/1763900000_page_mode.js b/Database/pb_migrations/1763900000_page_mode.js new file mode 100644 index 0000000..4272dc7 --- /dev/null +++ b/Database/pb_migrations/1763900000_page_mode.js @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Which view a page opens in for everyone: its text ("" = page) or the +// edgeless canvas (ADR-14). + +migrate( + (app) => { + const pages = app.findCollectionByNameOrId("pages"); + pages.fields.add(new SelectField({ name: "default_mode", maxSelect: 1, values: ["edgeless"] })); + app.save(pages); + }, + (app) => { + const pages = app.findCollectionByNameOrId("pages"); + pages.fields.removeByName("default_mode"); + app.save(pages); + }, +); diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md index c082f1f..77154f3 100644 --- a/Docs-Site/guide/using-docwell.md +++ b/Docs-Site/guide/using-docwell.md @@ -69,6 +69,34 @@ Exports (Markdown, HTML, PDF, Word) show a database as a table of its first view record on its own, under the page that holds it, and opens it there. On a public link or in **History**, databases are read-only. +## Edgeless mode (canvas) + +Every page can also be shown as a whiteboard. The two buttons next to the page's title in the header switch between +**Page** and **Edgeless**; the page's text becomes a note on an endless canvas, and typing in that note is typing in the +page. To have a page open as a canvas for everyone, choose **Open as canvas for everyone** in the page's ⋯ menu; a link +with `?mode=edgeless` (or `?mode=page`) opens one view either way. **Account settings → Editor** can make new pages +start as canvases. + +- **Tools** sit at the bottom: select (V), hand (H), note (N), text (T), shape (S: square, rounded rectangle, + ellipse, diamond or triangle, drawn plain or scribbled), connector (C: straight, curved or elbowed, stuck to what it + joins), pen (P), eraser (E), frame (F), mind map (M), picture (I), link (L), and stickers and templates. +- **Moving around:** scroll to pan, Ctrl+scroll or pinch to zoom, hold Space or the middle button to drag the view. + Ctrl+= and Ctrl+- zoom, Alt+0 goes to 100%, Alt+1 fits everything and Alt+2 fits the selection. +- **Editing:** click to select, Shift+click or drag a box for more; drag to move (edges line up with what is nearby; + hold Alt to stop that), drag the corners to resize and the round handle to turn. Double-click a shape, text, frame + title or line to type in it, and a note to write in it. The bar above the selection changes colours, line styles, + arrowheads, fonts and order. Ctrl+G groups, Ctrl+Shift+G ungroups, Ctrl+D duplicates, Ctrl+Z undoes, and copy and + paste work between canvases. The style you pick last for a kind of element is what the next one gets. +- **Mind maps:** pick a node and press Tab for a branch, Enter for a sibling, the arrow keys to move and Delete to + remove one. The bar above the map lays it out to the right, to the left or on both sides. +- **Frames** carry what is inside them when they move. **Present** (in the tools, or the ⋯ menu) shows the frames + one after another, full screen; the arrow keys step and Escape ends. +- **Export:** the ⋯ menu saves the canvas as a PNG or SVG picture. + +Readers of a public link see the canvas read-only, and so does the mobile app: the canvas button in its title bar +switches between the text and the canvas. The canvas's text (shapes, notes, frames, mind maps) is found by search, and +**History** brings an old canvas back with the text. + ## Comments Select text and choose **Comment** to start a discussion; the text stays highlighted and the comment appears in diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 62e3070..c651c8d 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -30,6 +30,7 @@ export type TrashedPage = Schemas["TrashedPage"]; export type ArchivedPage = Schemas["ArchivedPage"]; export type PinnedPage = Schemas["PinnedPage"]; export type PageFont = Schemas["PageFont"]; +export type PageMode = Schemas["PageMode"]; export type LinkPreview = Schemas["LinkPreview"]; export type PageContent = Schemas["PageContent"]; export type PageVersion = Schemas["PageVersion"]; @@ -483,6 +484,7 @@ export function createClient(opts: ClientOptions) { isTemplate?: boolean; fullWidth?: boolean; font?: PageFont; + defaultMode?: PageMode; tags?: string[]; /** Property values by property id; null clears one. */ properties?: Record; diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index 52072e8..70d83e5 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -2630,6 +2630,7 @@ export interface components { /** @description Shown across the whole window instead of the reading column */ fullWidth: boolean; font: components["schemas"]["PageFont"]; + defaultMode: components["schemas"]["PageMode"]; /** @description Tag ids */ tags: string[]; /** @description Custom property values by property id (see Property for their shapes) */ @@ -2641,6 +2642,11 @@ export interface components { createdBy: components["schemas"]["PageUser"]; lastEditedBy: components["schemas"]["PageUser"]; }; + /** + * @description The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it + * @enum {string} + */ + PageMode: "page" | "edgeless"; /** * @description The body font for everyone reading the page; empty is the default sans * @enum {string} @@ -3088,10 +3094,11 @@ export interface components { title: string; icon: string; updated: string; - /** @description Tiptap JSON; files load from /api/v1/share/{token}/files/{fileId} */ + /** @description Tiptap JSON (with "surface", the edgeless canvas, when it has one); files load from /api/v1/share/{token}/files/{fileId} */ content: { [key: string]: unknown; } | null; + mode: components["schemas"]["PageMode"]; root: components["schemas"]["PageRef"]; /** @description Pages under the shared page */ pages: components["schemas"]["PageNode"][]; @@ -4831,6 +4838,7 @@ export interface operations { /** @description Use the whole window instead of the reading column */ fullWidth?: boolean; font?: components["schemas"]["PageFont"]; + defaultMode?: components["schemas"]["PageMode"]; /** @description Replaces the page's tags (tag ids) */ tags?: string[]; /** @description Sets these custom property values by property id; null clears one */ diff --git a/Packages/canvas/package.json b/Packages/canvas/package.json new file mode 100644 index 0000000..61ff6e4 --- /dev/null +++ b/Packages/canvas/package.json @@ -0,0 +1,26 @@ +{ + "name": "@docwell/canvas", + "version": "0.0.1", + "private": true, + "license": "AGPL-3.0-or-later", + "type": "module", + "description": "The edgeless canvas: shapes, connectors, drawings, frames and notes on an endless surface (ADR-14)", + "main": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./canvas.css": "./src/canvas.css" + }, + "scripts": { + "test": "vitest run" + }, + "dependencies": { + "@docwell/ui": "*", + "perfect-freehand": "^1.2.0", + "roughjs": "^4.6.4", + "yjs": "^13.6.33" + }, + "devDependencies": { + "jsdom": "^30.1.3", + "vitest": "^5.0.5" + } +} diff --git a/Packages/canvas/src/canvas.css b/Packages/canvas/src/canvas.css new file mode 100644 index 0000000..7db21c2 --- /dev/null +++ b/Packages/canvas/src/canvas.css @@ -0,0 +1,616 @@ +/* SPDX-License-Identifier: AGPL-3.0-or-later */ + +/* The edgeless canvas (ADR-14). Colours come from the design system's + variables, so the canvas follows the light and dark themes. */ + +.dw-cv { + position: relative; + overflow: hidden; + width: 100%; + height: 100%; + min-height: 320px; + background-color: var(--dw-surface-sunken); + background-image: radial-gradient(circle, color-mix(in srgb, var(--dw-ink) 16%, transparent) 1px, transparent 1.2px); + touch-action: none; + outline: none; + user-select: none; + -webkit-user-select: none; + cursor: default; + font-family: var(--font-sans, ui-sans-serif, system-ui, sans-serif); + color: var(--dw-ink); +} +.dw-cv[data-tool="hand"], +.dw-cv.dw-cv-panning, +.dw-cv.dw-cv-readonly { + cursor: grab; +} +.dw-cv.dw-cv-panning:active { + cursor: grabbing; +} +.dw-cv[data-tool="pen"], +.dw-cv[data-tool="shape"], +.dw-cv[data-tool="frame"], +.dw-cv[data-tool="connector"], +.dw-cv[data-tool="note"], +.dw-cv[data-tool="mindmap"] { + cursor: crosshair; +} +.dw-cv[data-tool="text"] { + cursor: text; +} +.dw-cv[data-tool="eraser"] { + cursor: cell; +} + +.dw-cv-world { + position: absolute; + left: 0; + top: 0; + width: 0; + height: 0; + transform-origin: 0 0; +} + +.dw-cv-el { + position: absolute; + left: 0; + top: 0; + transform-origin: center; + box-sizing: border-box; +} +.dw-cv-svg { + position: absolute; + left: 0; + top: 0; + overflow: visible; + pointer-events: none; +} +.dw-cv-erasing { + opacity: 0.25; +} + +/* Shapes: the box takes the pointer; the label sits in the middle. */ +.dw-cv-shape { + display: grid; + place-items: center; +} +.dw-cv-label { + position: relative; + max-width: calc(100% - 16px); + max-height: 100%; + overflow: hidden; + text-align: center; + white-space: pre-wrap; + overflow-wrap: anywhere; + line-height: 1.35; + outline: none; +} +.dw-cv-label:empty:not(.dw-cv-typing) { + display: none; +} +.dw-cv-label.dw-cv-typing { + min-width: 1ch; + cursor: text; + user-select: text; + -webkit-user-select: text; +} + +/* Text boxes size themselves unless given a width. */ +.dw-cv-textbody { + line-height: 1.35; + min-width: 2px; + min-height: 1em; + overflow-wrap: anywhere; + outline: none; +} +.dw-cv-textbody.dw-cv-typing { + cursor: text; + user-select: text; + -webkit-user-select: text; +} +.dw-cv-textbody:empty::before { + content: attr(data-placeholder); + color: var(--dw-ink-faint); +} + +/* Connectors and pen strokes take the pointer on their line only. */ +.dw-cv-connector, +.dw-cv-brush, +.dw-cv-frame, +.dw-cv-mindmap { + pointer-events: none; +} +.dw-cv-hit { + fill: none; + stroke: transparent; + pointer-events: stroke; +} +.dw-cv-hitfill { + stroke: transparent; + stroke-width: 8px; + pointer-events: all; +} +.dw-cv-connector .dw-cv-svg, +.dw-cv-brush .dw-cv-svg { + pointer-events: none; +} +.dw-cv-connector .dw-cv-hit, +.dw-cv-brush .dw-cv-hitfill { + pointer-events: all; +} +.dw-cv-connector .dw-cv-hit { + pointer-events: stroke; +} +.dw-cv-clabel { + position: absolute; + transform: translate(-50%, -50%); + padding: 2px 6px; + border-radius: 4px; + background: var(--dw-surface); + font-size: 13px; + line-height: 18px; + white-space: pre; + pointer-events: auto; + outline: none; +} +.dw-cv-clabel:empty:not(.dw-cv-typing) { + display: none; +} + +/* Frames: a box underneath everything, picked by its edge or title. */ +.dw-cv-framebox { + stroke: var(--dw-line-strong); + stroke-width: calc(1.5px / var(--dw-cv-zoom, 1)); + pointer-events: stroke; +} +.dw-cv-frame .dw-cv-svg { + pointer-events: none; +} +.dw-cv-frame .dw-cv-framebox { + pointer-events: stroke; + stroke-width: calc(1.5px / var(--dw-cv-zoom, 1)); +} +.dw-cv-frametitle { + position: absolute; + left: 0; + bottom: 100%; + margin-bottom: calc(4px / var(--dw-cv-zoom, 1)); + padding: 0 4px; + max-width: 100%; + font-size: calc(13px / var(--dw-cv-zoom, 1)); + line-height: 1.4; + font-weight: 600; + color: var(--dw-ink-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + border-radius: 4px; + pointer-events: auto; + outline: none; +} +.dw-cv-frametitle:hover { + background: var(--dw-surface-hover); +} + +/* Notes: a card holding an editor. The text takes the pointer only while + someone types in it (double click), or always for readers. */ +.dw-cv-note { + min-height: 48px; + padding: 18px 24px; + border-radius: 8px; + background: var(--dw-cv-note-bg, var(--dw-surface-raised)); + border: 1px solid var(--dw-line); + box-shadow: + 0 1px 2px rgb(0 0 0 / 0.06), + 0 4px 14px rgb(0 0 0 / 0.06); +} +.dw-cv-notehead { + font-family: var(--font-serif, Georgia, serif); + font-size: 30px; + line-height: 1.25; + font-weight: 600; + margin-bottom: 8px; +} +.dw-cv-notehead:empty { + display: none; +} +.dw-cv-notebody { + pointer-events: none; + min-height: 24px; +} +.dw-cv-editing .dw-cv-notebody, +.dw-cv-readonly .dw-cv-notebody { + pointer-events: auto; + user-select: text; + -webkit-user-select: text; +} +.dw-cv-note .dw-prose { + outline: none; + min-height: 24px; +} +.dw-cv-note.dw-cv-editing { + box-shadow: + 0 0 0 2px var(--dw-focus-ring), + 0 4px 14px rgb(0 0 0 / 0.08); +} + +/* Pictures, players and link cards. */ +.dw-cv-image img { + display: block; + width: 100%; + height: 100%; + object-fit: contain; + pointer-events: none; +} +.dw-cv-embed iframe { + display: block; + width: 100%; + height: 100%; + border: 0; + border-radius: 8px; + background: #000; + pointer-events: none; +} +.dw-cv-embed.dw-cv-editing iframe, +.dw-cv-readonly .dw-cv-embed iframe { + pointer-events: auto; +} +.dw-cv-card { + display: flex; + gap: 12px; + height: 100%; + padding: 12px; + box-sizing: border-box; + overflow: hidden; + border: 1px solid var(--dw-line); + border-radius: 8px; + background: var(--dw-surface-raised); + color: inherit; + text-decoration: none; + -webkit-user-drag: none; +} +.dw-cv-card img { + width: 30%; + max-width: 140px; + height: 100%; + object-fit: cover; + border-radius: 4px; + pointer-events: none; +} +.dw-cv-cardtext { + display: flex; + min-width: 0; + flex-direction: column; + gap: 4px; + font-size: 13px; + line-height: 18px; +} +.dw-cv-cardtext strong { + font-size: 14px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.dw-cv-cardtext span { + color: var(--dw-ink-muted); + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} +.dw-cv-cardtext small { + color: var(--dw-ink-faint); +} + +/* Mind maps: nodes take the pointer; lines do not. */ +.dw-cv-node { + position: absolute; + box-sizing: border-box; + display: grid; + place-items: center; + padding: 0 10px; + border: 1.5px solid transparent; + border-radius: 8px; + background: var(--dw-surface-raised); + font-size: 15px; + line-height: 1.4; + text-align: center; + white-space: pre-wrap; + overflow-wrap: anywhere; + pointer-events: auto; + outline: none; +} +.dw-cv-root { + border-radius: 10px; + font-size: 18px; + font-weight: 600; +} +.dw-cv-node.dw-cv-active { + box-shadow: + 0 0 0 2px var(--dw-surface), + 0 0 0 4px var(--dw-focus-ring); +} +.dw-cv-node.dw-cv-typing { + cursor: text; + user-select: text; + -webkit-user-select: text; +} + +.dw-cv-temp { + position: absolute; + left: 0; + top: 0; + overflow: visible; + pointer-events: none; +} + +/* The overlay: selection, handles, guides, in screen units. */ +.dw-cv-overlay { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + pointer-events: none; + overflow: visible; +} +.dw-cv-sel, +.dw-cv-selline { + fill: none; + stroke: var(--dw-accent, #2f7d6d); + stroke-width: 1.5; +} +.dw-cv-selline { + stroke-width: 6; + stroke-opacity: 0.3; + stroke-linecap: round; + stroke-linejoin: round; +} +.dw-cv-selall { + stroke-dasharray: 4 3; +} +.dw-cv-groupbox { + fill: none; + stroke: var(--dw-ink-faint); + stroke-dasharray: 4 3; +} +.dw-cv-hover { + fill: color-mix(in srgb, var(--dw-accent, #2f7d6d) 8%, transparent); + stroke: var(--dw-accent, #2f7d6d); + stroke-width: 1; +} +.dw-cv-handle { + fill: var(--dw-surface); + stroke: var(--dw-accent, #2f7d6d); + stroke-width: 1.5; + pointer-events: all; + cursor: pointer; +} +.dw-cv-handle[data-handle="nw"], +.dw-cv-handle[data-handle="se"] { + cursor: nwse-resize; +} +.dw-cv-handle[data-handle="ne"], +.dw-cv-handle[data-handle="sw"] { + cursor: nesw-resize; +} +.dw-cv-handle[data-handle="n"], +.dw-cv-handle[data-handle="s"] { + cursor: ns-resize; +} +.dw-cv-handle[data-handle="e"], +.dw-cv-handle[data-handle="w"] { + cursor: ew-resize; +} +.dw-cv-rotate { + cursor: grab; +} +.dw-cv-marquee { + fill: color-mix(in srgb, var(--dw-accent, #2f7d6d) 10%, transparent); + stroke: var(--dw-accent, #2f7d6d); + stroke-width: 1; +} +.dw-cv-guide { + stroke: var(--dw-c-pink, #b8327a); + stroke-width: 1; + stroke-dasharray: 3 3; +} + +/* Controls. */ +.dw-cv-ui { + position: absolute; + z-index: 2; + display: flex; + align-items: center; + gap: 2px; + padding: 4px; + border: 1px solid var(--dw-line); + border-radius: 10px; + background: var(--dw-surface-raised); + box-shadow: 0 4px 16px rgb(0 0 0 / 0.12); + cursor: default; + font-size: 13px; +} +.dw-cv-ui[hidden] { + display: none; +} +.dw-cv-toolbar { + left: 50%; + bottom: 16px; + transform: translateX(-50%); + max-width: calc(100% - 32px); + overflow-x: auto; + scrollbar-width: none; +} +.dw-cv-zoom { + top: 12px; + right: 12px; +} +.dw-cv-props { + flex-wrap: wrap; + max-width: calc(100% - 16px); +} +.dw-cv-btn { + display: grid; + flex-shrink: 0; + place-items: center; + min-width: 32px; + height: 32px; + padding: 0 6px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--dw-ink-muted); + cursor: pointer; + font: inherit; +} +.dw-cv-btn:hover { + background: var(--dw-surface-hover); + color: var(--dw-ink); +} +.dw-cv-btn[aria-pressed="true"] { + background: var(--dw-accent-soft, var(--dw-surface-hover)); + color: var(--dw-accent, var(--dw-ink)); +} +.dw-cv-btn:focus-visible { + outline: 2px solid var(--dw-focus-ring); + outline-offset: -2px; +} +.dw-cv-danger:hover { + color: var(--dw-danger); +} +.dw-cv-wide { + justify-content: start; + width: 100%; +} +.dw-cv-zoomlabel { + min-width: 52px; + font-variant-numeric: tabular-nums; +} +.dw-cv-sep { + flex-shrink: 0; + width: 1px; + height: 20px; + margin: 0 4px; + background: var(--dw-line); +} +.dw-cv-pop { + flex-direction: column; + align-items: stretch; + gap: 4px; + padding: 6px; +} +.dw-cv-row { + display: flex; + flex-wrap: wrap; + gap: 2px; +} +.dw-cv-colors { + max-width: 220px; +} +.dw-cv-swatch { + display: block; + width: 18px; + height: 18px; + border-radius: 999px; + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--dw-ink) 18%, transparent); +} +.dw-cv-swatch-none { + background: linear-gradient( + 135deg, + transparent 45%, + var(--dw-danger, #c0392b) 45%, + var(--dw-danger, #c0392b) 55%, + transparent 55% + ) !important; +} +.dw-cv-dot { + display: block; + border-radius: 999px; + background: currentColor; +} +.dw-cv-bar { + display: block; + width: 18px; + border-radius: 2px; + background: currentColor; +} +.dw-cv-word { + font-size: 13px; + font-weight: 600; + white-space: nowrap; +} +.dw-cv-scribble { + font-style: italic; +} +.dw-cv-font-serif { + font-family: var(--font-serif, Georgia, serif); +} +.dw-cv-font-mono { + font-family: var(--font-mono, ui-monospace, monospace); +} +.dw-cv-flip svg { + transform: scaleX(-1); +} +.dw-cv-library { + width: 260px; +} +.dw-cv-poptitle { + padding: 4px 6px 0; + font-size: 12px; + font-weight: 600; + color: var(--dw-ink-muted); +} +.dw-cv-stickers { + display: grid; + grid-template-columns: repeat(8, 1fr); + gap: 2px; +} +.dw-cv-emoji { + font-size: 20px; + line-height: 1; +} +.dw-cv-templates { + display: flex; + flex-direction: column; +} +.dw-cv-toast { + left: 50%; + bottom: 72px; + transform: translateX(-50%); + padding: 8px 12px; + background: var(--dw-ink); + color: var(--dw-surface); + border-color: transparent; +} + +/* Presenting: only the frames and the step bar. */ +.dw-cv-presenting { + background-image: none; + cursor: default; +} +.dw-cv-presenting .dw-cv-toolbar, +.dw-cv-presenting .dw-cv-zoom, +.dw-cv-presenting .dw-cv-props, +.dw-cv-presenting .dw-cv-frametitle { + display: none; +} +.dw-cv-presentbar { + left: 50%; + bottom: 16px; + transform: translateX(-50%); +} +.dw-cv-step { + min-width: 56px; + text-align: center; + font-variant-numeric: tabular-nums; +} + +@media (max-width: 640px) { + .dw-cv-zoom { + top: 8px; + right: 8px; + } + .dw-cv-toolbar { + bottom: 8px; + } +} diff --git a/Packages/canvas/src/canvas.test.ts b/Packages/canvas/src/canvas.test.ts new file mode 100644 index 0000000..e4103be --- /dev/null +++ b/Packages/canvas/src/canvas.test.ts @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { describe, expect, it } from "vitest"; +import * as Y from "yjs"; +import { resolveEnds, route, snap } from "./geometry"; +import { layoutMindmap, neighbour } from "./mindmap"; +import { normalize, readStyles } from "./model"; +import { SurfaceStore } from "./store"; +import { fragmentToJSON, plainText, writeJSON } from "./yxml"; + +const size = (text: string) => ({ w: 40 + text.length * 8, h: 30 }); + +describe("SurfaceStore", () => { + it("lists the page note before anything is drawn and writes it on first change", () => { + const store = new SurfaceStore(new Y.Doc()); + const [note] = store.elements(); + expect(note).toMatchObject({ id: "page", type: "note", page: true, x: 0, y: 0 }); + expect(store.isEmpty).toBe(true); + store.update("page", { x: 100 }); + expect(store.isEmpty).toBe(false); + expect(store.get("page")).toMatchObject({ x: 100, w: 760 }); + }); + + it("adds, restyles and removes elements, and undoes them", () => { + const store = new SurfaceStore(new Y.Doc()); + const id = store.add({ type: "shape", shape: "ellipse", x: 1, y: 2, w: 30, h: 40 }); + store.undo!.stopCapturing(); + store.update(id, { fill: "red" }); + expect(store.get(id)).toMatchObject({ type: "shape", shape: "ellipse", fill: "red" }); + store.undo!.undo(); + expect(store.get(id)).toMatchObject({ fill: "none" }); + store.remove([id]); + expect(store.get(id)).toBeUndefined(); + // The page's note is the page: it stays. + store.remove(["page"]); + expect(store.get("page")).toBeDefined(); + }); + + it("keeps a connector's end where its element was when the element goes", () => { + const store = new SurfaceStore(new Y.Doc()); + const a = store.add({ type: "shape", x: 0, y: 0, w: 100, h: 100 }); + const c = store.add({ type: "connector", source: { id: a, pos: [1, 0.5] }, target: { x: 300, y: 50 } } as never); + store.remove([a]); + expect(store.get(c)).toMatchObject({ source: { x: 100, y: 50 } }); + }); + + it("copies elements with new ids, keeping connectors, groups and note bodies", () => { + const store = new SurfaceStore(new Y.Doc()); + const a = store.add({ type: "shape", x: 0, y: 0, w: 10, h: 10 }); + const b = store.add({ type: "note", x: 50, y: 0, w: 200, h: 80 }, [ + { type: "paragraph", content: [{ type: "text", text: "Hello" }] }, + ]); + const c = store.add({ type: "connector", source: { id: a }, target: { id: b } } as never); + const g = store.groupOf([a, b])!; + const ids = store.insertJSON(store.toJSON([g, c]), 10, 10); + expect(ids).toHaveLength(4); + const copies = ids.map((id) => store.get(id)!); + const shape = copies.find((e) => e.type === "shape")!; + const note = copies.find((e) => e.type === "note")!; + const conn = copies.find((e) => e.type === "connector")!; + const group = copies.find((e) => e.type === "group")!; + expect(shape).toMatchObject({ x: 10, y: 10, group: group.id }); + expect(conn).toMatchObject({ source: { id: shape.id }, target: { id: note.id } }); + expect(fragmentToJSON(store.body(note.id)!)).toEqual([ + { type: "paragraph", content: [{ type: "text", text: "Hello" }] }, + ]); + }); + + it("adds and removes mind map branches", () => { + const store = new SurfaceStore(new Y.Doc()); + const id = store.add({ type: "mindmap", x: 0, y: 0, nodes: { r: { text: "Root", parent: "", pos: 0 } } } as never); + const child = store.addNode(id, "r", 0, "A"); + store.addNode(id, child, 0, "A1"); + const el = store.get(id)!; + expect(el.type === "mindmap" && Object.keys(el.nodes)).toHaveLength(3); + store.removeNode(id, child); + const after = store.get(id)!; + expect(after.type === "mindmap" && Object.keys(after.nodes)).toEqual(["r"]); + store.removeNode(id, "r"); + expect(store.get(id)).toBeUndefined(); + }); + + it("orders frames underneath and moves elements to the front", () => { + const store = new SurfaceStore(new Y.Doc()); + const a = store.add({ type: "shape", x: 0, y: 0, w: 1, h: 1 }); + const b = store.add({ type: "shape", x: 0, y: 0, w: 1, h: 1 }); + const f = store.add({ type: "frame", x: 0, y: 0, w: 1, h: 1 }); + expect(store.elements()[0]!.id).toBe(f); + store.reorder([a], "front"); + const order = store.elements().map((e) => e.id); + expect(order.indexOf(a)).toBeGreaterThan(order.indexOf(b)); + }); + + it("replaces everything with a snapshot", () => { + const store = new SurfaceStore(new Y.Doc()); + store.add({ type: "shape", x: 0, y: 0, w: 1, h: 1 }); + store.load([{ id: "n1", type: "note", x: 5, y: 5, w: 100, h: 50, body: [{ type: "paragraph" }] }]); + expect( + store + .elements() + .map((e) => e.id) + .sort(), + ).toEqual(["n1", "page"]); + }); +}); + +describe("model", () => { + it("fills in defaults and drops unknown types", () => { + expect(normalize({ type: "nope" })).toBeNull(); + expect(normalize({ type: "connector" })).toMatchObject({ + mode: "curve", + endArrow: "arrow", + source: { x: 0, y: 0 }, + }); + expect(readStyles({ shape: { fill: "red", stroke: "purple-ish" } }).shape).toMatchObject({ + fill: "red", + stroke: "blue", + }); + }); +}); + +describe("geometry", () => { + it("routes connectors between boxes", () => { + const boxes: Record = { + a: { box: { x: 0, y: 0, w: 100, h: 100 }, ellipse: false }, + b: { box: { x: 300, y: 0, w: 100, h: 100 }, ellipse: false }, + }; + const ends = resolveEnds({ source: { id: "a" }, target: { id: "b" } }, (id) => boxes[id] ?? null); + expect(ends[0].at).toEqual([100, 50]); + expect(ends[1].at).toEqual([300, 50]); + const elbow = route("elbow", ends[0], ends[1]); + expect(elbow.points[0]).toEqual([100, 50]); + expect(elbow.points.at(-1)).toEqual([300, 50]); + expect(route("curve", ends[0], ends[1]).d).toMatch(/^M100 50 C/); + }); + + it("snaps edges that are close", () => { + const s = snap({ x: 103, y: 0, w: 50, h: 50 }, [{ x: 100, y: 200, w: 80, h: 40 }], 6); + expect(s.dx).toBe(-3); + expect(s.guides[0]).toMatchObject({ axis: "x", value: 100 }); + }); +}); + +describe("mind maps", () => { + const nodes = { + r: { text: "Root", parent: "", pos: 0 }, + a: { text: "A", parent: "r", pos: 0 }, + b: { text: "B", parent: "r", pos: 1 }, + c: { text: "C", parent: "a", pos: 0 }, + }; + + it("lays branches out to the right, left or both sides", () => { + const right = layoutMindmap(nodes, "right", size); + expect(right.boxes.get("a")!.x).toBeGreaterThan(right.boxes.get("r")!.w); + expect(right.boxes.get("c")!.x).toBeGreaterThan(right.boxes.get("a")!.x); + const left = layoutMindmap(nodes, "left", size); + expect(left.boxes.get("a")!.x).toBeLessThan(0); + const radial = layoutMindmap(nodes, "radial", size); + expect(radial.boxes.get("a")!.dir).toBe(1); + expect(radial.boxes.get("b")!.dir).toBe(-1); + expect(right.edges).toHaveLength(3); + }); + + it("moves between nodes with the arrow keys", () => { + const l = layoutMindmap(nodes, "right", size); + expect(neighbour(l, nodes, "r", "ArrowRight")).toBe("a"); + expect(neighbour(l, nodes, "a", "ArrowDown")).toBe("b"); + expect(neighbour(l, nodes, "a", "ArrowRight")).toBe("c"); + expect(neighbour(l, nodes, "c", "ArrowLeft")).toBe("a"); + }); +}); + +describe("yxml", () => { + it("round-trips ProseMirror JSON through a fragment", () => { + const doc = new Y.Doc(); + const f = doc.getXmlFragment("x"); + const json = [ + { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Title" }] }, + { + type: "paragraph", + content: [ + { type: "text", text: "plain " }, + { type: "text", text: "bold", marks: [{ type: "bold", attrs: {} }] }, + ], + }, + ]; + writeJSON(f, json); + expect(fragmentToJSON(f)).toEqual(json); + expect(plainText(json)).toEqual(["Title", "plain bold"]); + }); +}); + +describe("CanvasView", () => { + it("draws a document's elements and exports them as SVG", async () => { + const { CanvasView } = await import("./view"); + const doc = new Y.Doc(); + writeJSON(doc.getXmlFragment("default"), [{ type: "paragraph", content: [{ type: "text", text: "Page body" }] }]); + const store = new SurfaceStore(doc); + store.add({ type: "shape", shape: "diamond", x: 900, y: 0, w: 120, h: 80, text: "Choose" } as never); + store.add({ type: "mindmap", x: 0, y: 500, nodes: { r: { text: "Root idea", parent: "", pos: 0 } } } as never); + store.destroy(); + const host = document.createElement("div"); + document.body.append(host); + const mounted: string[] = []; + const view = new CanvasView(host, { + doc, + editable: true, + pageTitle: () => "My page", + notes: { + mount: (el, note) => { + mounted.push(note.page ? "page" : note.id); + el.textContent = note.page ? "Page body" : ""; + return { destroy: () => {}, focus: () => {}, setEditable: () => {} }; + }, + }, + }); + expect(mounted).toEqual(["page"]); + expect(host.querySelector(".dw-cv-shape")?.textContent).toBe("Choose"); + expect(host.querySelector(".dw-cv-root")?.textContent).toBe("Root idea"); + expect(host.querySelectorAll(".dw-cv-toolbar .dw-cv-btn").length).toBeGreaterThan(10); + const svg = await (await view.exportImage("svg")).text(); + expect(svg).toMatch(/^ css.getPropertyValue(name).trim() || d; + const surface = v("--dw-surface", "#ffffff"); + const parse = (hex: string): number[] | null => { + const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex); + if (!m) return null; + const h = m[1]!.length === 3 ? [...m[1]!].map((c) => c + c).join("") : m[1]!; + return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); + }; + const mix = (a: string, b: string, t: number) => { + const x = parse(a); + const y = parse(b); + if (!x || !y) return a; + return `#${x + .map((c, i) => + Math.round(c * t + y[i]! * (1 - t)) + .toString(16) + .padStart(2, "0"), + ) + .join("")}`; + }; + return (c: Color, use) => { + if (c === "none") return "none"; + if (c === "ink") return use === "fill" ? v("--dw-surface-sunken", "#f3f3f1") : v("--dw-ink", "#1d1f1e"); + if (c === "paper") return use === "fill" ? v("--dw-surface-raised", "#ffffff") : surface; + const base = v(`--dw-c-${c}`, "#888888"); + return use === "fill" ? mix(base, surface, 0.22) : base; + }; +} + +/** Text blocks of a note for drawing: headings bigger, list items with a bullet. */ +function blocks(nodes: PMNode[]): { text: string; size: number; weight: number }[] { + const out: { text: string; size: number; weight: number }[] = []; + const inline = (n: PMNode): string => + (n.content ?? []) + .map((c) => (c.type === "text" ? (c.text ?? "") : c.type === "hardBreak" ? "\n" : inline(c))) + .join(""); + const walk = (list: PMNode[], bullet: string) => { + for (const n of list) { + if (n.type === "heading") { + const level = Number(n.attrs?.level) || 1; + out.push({ text: inline(n), size: [0, 26, 21, 18, 16, 16, 16][level] ?? 16, weight: 650 }); + } else if (n.type === "paragraph") out.push({ text: bullet + inline(n), size: 15, weight: 400 }); + else if (n.type === "listItem" || n.type === "taskItem") { + const mark = n.type === "taskItem" ? (n.attrs?.checked ? "☑ " : "☐ ") : "• "; + const [first, ...rest] = n.content ?? []; + if (first) out.push({ text: mark + inline(first), size: 15, weight: 400 }); + walk(rest, " "); + } else if (n.type === "codeBlock") out.push({ text: inline(n), size: 13, weight: 400 }); + else if (n.content?.length) walk(n.content, bullet); + } + }; + walk(nodes, ""); + return out; +} + +function textLines( + x: number, + y: number, + lines: string[], + size: number, + color: string, + family: string, + weight = 400, + anchor = "start", +): string { + const lh = Math.round(size * 1.35); + return lines + .map( + (l, i) => + `${esc(l)}`, + ) + .join(""); +} + +async function inline(src: string): Promise { + if (src.startsWith("data:")) return src; + try { + const res = await fetch(src, { credentials: "include" }); + if (!res.ok) return null; + const blob = await res.blob(); + return await new Promise((resolve) => { + const r = new FileReader(); + r.onload = () => resolve(typeof r.result === "string" ? r.result : null); + r.onerror = () => resolve(null); + r.readAsDataURL(blob); + }); + } catch { + return null; + } +} + +/** The elements as SVG markup and the box it covers. */ +export async function canvasSVG(ctx: ExportContext): Promise<{ svg: string; box: Box }> { + const paint = exportPaint(ctx.root); + const els = ctx.elements.filter((e) => e.type !== "group"); + const box = inflate(union(els.map((e) => ctx.boxOf(e))) ?? { x: 0, y: 0, w: 400, h: 300 }, 32); + const ink = paint("ink", "line"); + const parts: string[] = []; + for (const e of els) { + const b = ctx.boxOf(e); + const rot = e.rotate ? ` rotate(${e.rotate} ${b.w / 2} ${b.h / 2})` : ""; + const g = (inner: string) => `${inner}`; + switch (e.type) { + case "shape": { + const lines = wrap(e.text, e.fontSize, Math.max(20, b.w - 16)); + const lh = Math.round(e.fontSize * 1.35); + const top = b.h / 2 - (lines.length * lh) / 2 - e.fontSize * 0.25; + parts.push( + g( + shapeSVG(e, paint) + + (e.text + ? textLines(b.w / 2, top, lines, e.fontSize, paint(e.textColor, "line"), SANS, 400, "middle") + : ""), + ), + ); + break; + } + case "text": { + const family = fontFamily(e.font); + const lines = e.w ? wrap(e.text, e.fontSize, e.w, family) : e.text.split("\n"); + const x = e.align === "center" ? b.w / 2 : e.align === "right" ? b.w : 0; + const anchor = e.align === "center" ? "middle" : e.align === "right" ? "end" : "start"; + parts.push(g(textLines(x, 0, lines, e.fontSize, paint(e.color, "line"), family, e.bold ? 650 : 400, anchor))); + break; + } + case "connector": { + const r = ctx.routeOf(e); + parts.push(connectorSVG(e, r, paint)); + if (e.label) { + const w = Math.min(240, e.label.length * 8 + 16); + parts.push( + `` + + textLines(r.mid[0], r.mid[1] - 12 + 3, [e.label], 13, ink, SANS, 400, "middle"), + ); + } + break; + } + case "brush": + parts.push(g(brushSVG(e, paint))); + break; + case "frame": + parts.push( + g( + `` + + textLines(4, -24, [e.title], 13, paint("gray", "line"), SANS, 600), + ), + ); + break; + case "note": { + const body = ctx.noteBody(e); + const content = body ? blocks(fragmentToJSON(body)) : []; + let y = 18; + let inner = ``; + if (e.page && ctx.pageTitle) { + const lines = wrap(ctx.pageTitle, 26, b.w - 48, SANS, 650); + inner += textLines(24, y - 4, lines, 26, ink, SANS, 650); + y += lines.length * 35 + 8; + } + for (const bl of content) { + const lines = wrap(bl.text, bl.size, b.w - 48, SANS, bl.weight); + inner += textLines(24, y, lines, bl.size, ink, SANS, bl.weight); + y += lines.length * Math.round(bl.size * 1.35) + 8; + if (y > b.h - 12) break; + } + parts.push(g(inner)); + break; + } + case "image": { + const data = await inline(ctx.resolve(e.src)); + parts.push( + g( + data + ? `` + : ``, + ), + ); + break; + } + case "embed": + parts.push( + g( + `` + + textLines(16, 16, wrap(e.url, 13, b.w - 32), 13, paint("blue", "line"), SANS), + ), + ); + break; + case "mindmap": { + const l = ctx.layoutOf(e); + const line = paint(e.color, "line"); + const fill = paint(e.color, "fill"); + let inner = l.edges + .map((ed) => ``) + .join(""); + for (const n of l.boxes.values()) { + const size = n.depth === 0 ? 18 : 15; + const weight = n.depth === 0 ? 600 : 400; + const bg = n.depth === 0 ? line : n.depth === 1 ? fill : paint("paper", "line"); + const fg = n.depth === 0 ? paint("paper", "line") : ink; + inner += ``; + const lines = wrap(e.nodes[n.id]?.text || " ", size, 260, SANS, weight); + inner += textLines( + n.x + n.w / 2, + n.y + (n.h - lines.length * Math.round(size * 1.4)) / 2 - 2, + lines, + size, + fg, + SANS, + weight, + "middle", + ); + } + parts.push(`${inner}`); + break; + } + } + } + const svg = `${parts.join("")}`; + return { svg, box }; +} + +export async function exportCanvas(kind: ExportKind, ctx: ExportContext): Promise { + const { svg, box } = await canvasSVG(ctx); + const file = new Blob([svg], { type: "image/svg+xml" }); + if (kind === "svg") return file; + // Twice the size for sharp text, within what browsers draw on one canvas. + const scale = Math.min(2, 8192 / Math.max(box.w, box.h, 1)); + const url = URL.createObjectURL(file); + try { + const img = await new Promise((resolve, reject) => { + const i = new Image(); + i.onload = () => resolve(i); + i.onerror = () => reject(new Error("could not draw the canvas")); + i.src = url; + }); + const c = document.createElement("canvas"); + c.width = Math.ceil(box.w * scale); + c.height = Math.ceil(box.h * scale); + const g = c.getContext("2d"); + if (!g) throw new Error("could not draw the canvas"); + g.drawImage(img, 0, 0, c.width, c.height); + return await new Promise((resolve, reject) => + c.toBlob((b) => (b ? resolve(b) : reject(new Error("could not draw the canvas"))), "image/png"), + ); + } finally { + URL.revokeObjectURL(url); + } +} diff --git a/Packages/canvas/src/geometry.ts b/Packages/canvas/src/geometry.ts new file mode 100644 index 0000000..4fd06ae --- /dev/null +++ b/Packages/canvas/src/geometry.ts @@ -0,0 +1,368 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Boxes, points and connector routes. Everything is in canvas units. + +import type { CanvasElement, ConnectorElement, End } from "./model"; + +export interface Box { + x: number; + y: number; + w: number; + h: number; +} +export type Point = [number, number]; + +export const center = (b: Box): Point => [b.x + b.w / 2, b.y + b.h / 2]; + +export function union(boxes: Box[]): Box | null { + if (!boxes.length) return null; + let x1 = Infinity; + let y1 = Infinity; + let x2 = -Infinity; + let y2 = -Infinity; + for (const b of boxes) { + x1 = Math.min(x1, b.x); + y1 = Math.min(y1, b.y); + x2 = Math.max(x2, b.x + b.w); + y2 = Math.max(y2, b.y + b.h); + } + return { x: x1, y: y1, w: x2 - x1, h: y2 - y1 }; +} + +export const inflate = (b: Box, d: number): Box => ({ x: b.x - d, y: b.y - d, w: b.w + 2 * d, h: b.h + 2 * d }); + +export const intersects = (a: Box, b: Box) => + a.x <= b.x + b.w && b.x <= a.x + a.w && a.y <= b.y + b.h && b.y <= a.y + a.h; + +export const containsBox = (outer: Box, inner: Box) => + inner.x >= outer.x && + inner.y >= outer.y && + inner.x + inner.w <= outer.x + outer.w && + inner.y + inner.h <= outer.y + outer.h; + +export const containsPoint = (b: Box, [x, y]: Point) => x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h; + +/** The box from two corners in any order. */ +export function boxOf(a: Point, b: Point): Box { + return { x: Math.min(a[0], b[0]), y: Math.min(a[1], b[1]), w: Math.abs(a[0] - b[0]), h: Math.abs(a[1] - b[1]) }; +} + +export function rotatePoint([x, y]: Point, [cx, cy]: Point, deg: number): Point { + if (!deg) return [x, y]; + const r = (deg * Math.PI) / 180; + const cos = Math.cos(r); + const sin = Math.sin(r); + return [cx + (x - cx) * cos - (y - cy) * sin, cy + (x - cx) * sin + (y - cy) * cos]; +} + +/** The axis-aligned box around a rotated box. */ +export function rotatedBox(b: Box, deg: number): Box { + if (!deg) return b; + const c = center(b); + const corners: Point[] = [ + [b.x, b.y], + [b.x + b.w, b.y], + [b.x + b.w, b.y + b.h], + [b.x, b.y + b.h], + ].map((p) => rotatePoint(p as Point, c, deg)); + return boxOf( + [Math.min(...corners.map((p) => p[0])), Math.min(...corners.map((p) => p[1]))], + [Math.max(...corners.map((p) => p[0])), Math.max(...corners.map((p) => p[1]))], + ); +} + +export function distToSegment([px, py]: Point, [ax, ay]: Point, [bx, by]: Point): number { + const dx = bx - ax; + const dy = by - ay; + const len = dx * dx + dy * dy; + const t = len ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / len)) : 0; + return Math.hypot(px - (ax + t * dx), py - (ay + t * dy)); +} + +export function distToPolyline(p: Point, pts: Point[]): number { + if (pts.length === 1) return Math.hypot(p[0] - pts[0]![0], p[1] - pts[0]![1]); + let d = Infinity; + for (let i = 1; i < pts.length; i++) d = Math.min(d, distToSegment(p, pts[i - 1]!, pts[i]!)); + return d; +} + +// ---- Connectors ---- + +/** Which side of a box a point is closest to. */ +export type Side = "left" | "right" | "top" | "bottom"; + +export function nearestSide(b: Box, [x, y]: Point): Side { + const d: [Side, number][] = [ + ["left", Math.abs(x - b.x)], + ["right", Math.abs(x - (b.x + b.w))], + ["top", Math.abs(y - b.y)], + ["bottom", Math.abs(y - (b.y + b.h))], + ]; + d.sort((a, z) => a[1] - z[1]); + return d[0]![0]; +} + +const normals: Record = { left: [-1, 0], right: [1, 0], top: [0, -1], bottom: [0, 1] }; + +/** Where the line from the box's centre towards p leaves the box (or the ellipse inside it). */ +export function edgeToward(b: Box, p: Point, ellipse = false): Point { + const [cx, cy] = center(b); + const dx = p[0] - cx; + const dy = p[1] - cy; + if (!dx && !dy) return [cx, cy]; + const hw = Math.max(b.w / 2, 0.5); + const hh = Math.max(b.h / 2, 0.5); + const t = ellipse + ? 1 / Math.sqrt((dx * dx) / (hw * hw) + (dy * dy) / (hh * hh)) + : Math.min(Math.abs(hw / (dx || 1e-9)), Math.abs(hh / (dy || 1e-9))); + return [cx + dx * t, cy + dy * t]; +} + +/** The four side midpoints of a box, where a connector can snap to. */ +export const anchors = (b: Box): [Side, Point][] => [ + ["top", [b.x + b.w / 2, b.y]], + ["right", [b.x + b.w, b.y + b.h / 2]], + ["bottom", [b.x + b.w / 2, b.y + b.h]], + ["left", [b.x, b.y + b.h / 2]], +]; + +export interface Route { + points: Point[]; + /** An SVG path in canvas units. */ + d: string; + /** Where the label goes. */ + mid: Point; + /** Directions the line leaves the source and enters the target, for arrowheads (radians). */ + startAngle: number; + endAngle: number; +} + +interface Resolved { + at: Point; + side: Side | null; +} + +/** + * Where a connector's ends are: a free point, a point inside an element's + * box, or the point where the line towards the other end leaves the box. + */ +export function resolveEnds( + c: Pick, + boxOfId: (id: string) => { box: Box; ellipse: boolean } | null, +): [Resolved, Resolved] { + const loose = (e: End): Point | null => { + if (!e.id) return [e.x ?? 0, e.y ?? 0]; + const t = boxOfId(e.id); + if (!t) return [e.x ?? 0, e.y ?? 0]; + if (e.pos) return [t.box.x + t.box.w * e.pos[0], t.box.y + t.box.h * e.pos[1]]; + return null; + }; + const centreOf = (e: End): Point => { + const t = e.id ? boxOfId(e.id) : null; + return t ? center(t.box) : [e.x ?? 0, e.y ?? 0]; + }; + const one = (e: End, other: End): Resolved => { + const fixed = loose(e); + const t = e.id ? boxOfId(e.id) : null; + if (fixed) return { at: fixed, side: t ? nearestSide(t.box, fixed) : null }; + const at = edgeToward(t!.box, loose(other) ?? centreOf(other), t!.ellipse); + return { at, side: nearestSide(t!.box, at) }; + }; + return [one(c.source, c.target), one(c.target, c.source)]; +} + +const fmt = (n: number) => Math.round(n * 100) / 100; +const pathOf = (pts: Point[]) => pts.map((p, i) => `${i ? "L" : "M"}${fmt(p[0])} ${fmt(p[1])}`).join(" "); +const angle = (from: Point, to: Point) => Math.atan2(to[1] - from[1], to[0] - from[0]); + +/** A connector's line between its resolved ends. */ +export function route(mode: ConnectorElement["mode"], a: Resolved, b: Resolved): Route { + const [ax, ay] = a.at; + const [bx, by] = b.at; + const dist = Math.hypot(bx - ax, by - ay); + if (mode === "straight" || dist < 1) { + return { + points: [a.at, b.at], + d: pathOf([a.at, b.at]), + mid: [(ax + bx) / 2, (ay + by) / 2], + startAngle: angle(b.at, a.at), + endAngle: angle(a.at, b.at), + }; + } + if (mode === "curve") { + const k = Math.min(dist / 2, 160); + const na = a.side ? normals[a.side] : unit(a.at, b.at); + const nb = b.side ? normals[b.side] : unit(b.at, a.at); + const c1: Point = [ax + na[0] * k, ay + na[1] * k]; + const c2: Point = [bx + nb[0] * k, by + nb[1] * k]; + const pts: Point[] = []; + for (let i = 0; i <= 24; i++) pts.push(bezier(a.at, c1, c2, b.at, i / 24)); + return { + points: pts, + d: `M${fmt(ax)} ${fmt(ay)} C${fmt(c1[0])} ${fmt(c1[1])} ${fmt(c2[0])} ${fmt(c2[1])} ${fmt(bx)} ${fmt(by)}`, + mid: bezier(a.at, c1, c2, b.at, 0.5), + startAngle: angle(c1, a.at), + endAngle: angle(c2, b.at), + }; + } + // Elbow: leave and enter along the sides' normals with right angles between. + const gap = 24; + const sa = + a.side ?? (Math.abs(bx - ax) > Math.abs(by - ay) ? (bx > ax ? "right" : "left") : by > ay ? "bottom" : "top"); + const sb = + b.side ?? (Math.abs(bx - ax) > Math.abs(by - ay) ? (bx > ax ? "left" : "right") : by > ay ? "top" : "bottom"); + const pa: Point = [ax + normals[sa][0] * gap, ay + normals[sa][1] * gap]; + const pb: Point = [bx + normals[sb][0] * gap, by + normals[sb][1] * gap]; + const horizA = sa === "left" || sa === "right"; + const horizB = sb === "left" || sb === "right"; + let middle: Point[]; + if (horizA && horizB) { + const mx = (pa[0] + pb[0]) / 2; + middle = [ + [mx, pa[1]], + [mx, pb[1]], + ]; + } else if (!horizA && !horizB) { + const my = (pa[1] + pb[1]) / 2; + middle = [ + [pa[0], my], + [pb[0], my], + ]; + } else if (horizA) middle = [[pb[0], pa[1]]]; + else middle = [[pa[0], pb[1]]]; + const pts = simplify([a.at, pa, ...middle, pb, b.at]); + return { + points: pts, + d: pathOf(pts), + mid: polylineMid(pts), + startAngle: angle(pts[1] ?? b.at, a.at), + endAngle: angle(pts[pts.length - 2] ?? a.at, b.at), + }; +} + +function unit(a: Point, b: Point): Point { + const d = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1; + return [(b[0] - a[0]) / d, (b[1] - a[1]) / d]; +} + +function bezier(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point { + const u = 1 - t; + const a = u * u * u; + const b = 3 * u * u * t; + const c = 3 * u * t * t; + const d = t * t * t; + return [a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]]; +} + +/** Drops points that lie on the line between their neighbours. */ +function simplify(pts: Point[]): Point[] { + const out: Point[] = []; + for (const p of pts) { + const last = out[out.length - 1]; + if (last && Math.abs(last[0] - p[0]) < 0.01 && Math.abs(last[1] - p[1]) < 0.01) continue; + const prev = out[out.length - 2]; + if (prev && last) { + const cross = (last[0] - prev[0]) * (p[1] - prev[1]) - (last[1] - prev[1]) * (p[0] - prev[0]); + if (Math.abs(cross) < 0.01) out.pop(); + } + out.push(p); + } + return out; +} + +export function polylineMid(pts: Point[]): Point { + let total = 0; + for (let i = 1; i < pts.length; i++) total += Math.hypot(pts[i]![0] - pts[i - 1]![0], pts[i]![1] - pts[i - 1]![1]); + let left = total / 2; + for (let i = 1; i < pts.length; i++) { + const a = pts[i - 1]!; + const b = pts[i]!; + const len = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (len >= left && len > 0) return [a[0] + ((b[0] - a[0]) * left) / len, a[1] + ((b[1] - a[1]) * left) / len]; + left -= len; + } + return pts[0] ?? [0, 0]; +} + +// ---- Snapping ---- + +export interface Guide { + /** "x" draws a vertical line at value, "y" a horizontal one. */ + axis: "x" | "y"; + value: number; + from: number; + to: number; +} + +/** + * Nudges a moving box so its edges or centre line up with another box's, + * when they are within threshold. Returns the shift and the lines to draw. + */ +export function snap(moving: Box, others: Box[], threshold: number): { dx: number; dy: number; guides: Guide[] } { + const xs = (b: Box) => [b.x, b.x + b.w / 2, b.x + b.w]; + const ys = (b: Box) => [b.y, b.y + b.h / 2, b.y + b.h]; + let best: { dx: number; ox: Box | null; vx: number } = { dx: 0, ox: null, vx: 0 }; + let bestY: { dy: number; oy: Box | null; vy: number } = { dy: 0, oy: null, vy: 0 }; + let minX = threshold + 1; + let minY = threshold + 1; + for (const o of others) { + for (const a of xs(moving)) + for (const b of xs(o)) { + const d = Math.abs(b - a); + if (d < minX) { + minX = d; + best = { dx: b - a, ox: o, vx: b }; + } + } + for (const a of ys(moving)) + for (const b of ys(o)) { + const d = Math.abs(b - a); + if (d < minY) { + minY = d; + bestY = { dy: b - a, oy: o, vy: b }; + } + } + } + const guides: Guide[] = []; + const dx = minX <= threshold ? best.dx : 0; + const dy = minY <= threshold ? bestY.dy : 0; + const moved = { ...moving, x: moving.x + dx, y: moving.y + dy }; + if (minX <= threshold && best.ox) { + const o = best.ox; + guides.push({ + axis: "x", + value: best.vx, + from: Math.min(o.y, moved.y), + to: Math.max(o.y + o.h, moved.y + moved.h), + }); + } + if (minY <= threshold && bestY.oy) { + const o = bestY.oy; + guides.push({ + axis: "y", + value: bestY.vy, + from: Math.min(o.x, moved.x), + to: Math.max(o.x + o.w, moved.x + moved.w), + }); + } + return { dx, dy, guides }; +} + +/** Moves a free end onto the nearest side midpoint of a box when it is close. */ +export function snapToAnchor(b: Box, p: Point, threshold: number): Point | null { + let best: Point | null = null; + let min = threshold; + for (const [, a] of anchors(b)) { + const d = Math.hypot(a[0] - p[0], a[1] - p[1]); + if (d < min) { + min = d; + best = a; + } + } + return best; +} + +/** The box an element takes up, rotation included. */ +export function outerBox(e: CanvasElement, box: Box): Box { + return rotatedBox(box, e.rotate); +} diff --git a/Packages/canvas/src/index.ts b/Packages/canvas/src/index.ts new file mode 100644 index 0000000..5766f58 --- /dev/null +++ b/Packages/canvas/src/index.ts @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +export { + CanvasView, + type CanvasOptions, + type CanvasFiles, + type CanvasLinks, + type NoteHandle, + type NoteHost, + type NoteMount, + type Tool, +} from "./view"; +export { SurfaceStore, CANVAS_ORIGIN, surfaceOf, type ElementJSON } from "./store"; +export { englishCanvasLabels, type CanvasLabels } from "./labels"; +export { defaultStyles, readStyles, normalize, PAGE_NOTE_ID, type CanvasElement, type StyleDefaults } from "./model"; +export { fragmentToJSON, writeJSON, type PMNode } from "./yxml"; +export { layoutMindmap } from "./mindmap"; +export type { ExportKind } from "./export"; diff --git a/Packages/canvas/src/labels.ts b/Packages/canvas/src/labels.ts new file mode 100644 index 0000000..0424ac3 --- /dev/null +++ b/Packages/canvas/src/labels.ts @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/** The canvas's own words; hosts pass translated ones, English is the default. */ +export interface CanvasLabels { + toolbar: string; + select: string; + hand: string; + note: string; + text: string; + shape: string; + connector: string; + pen: string; + eraser: string; + frame: string; + mindmap: string; + image: string; + link: string; + library: string; + present: string; + zoomIn: string; + zoomOut: string; + zoomFit: string; + zoomReset: string; + rect: string; + roundrect: string; + ellipse: string; + diamond: string; + triangle: string; + general: string; + scribbled: string; + straight: string; + curve: string; + elbow: string; + stroke: string; + fill: string; + textColor: string; + background: string; + thickness: string; + lineStyle: string; + solid: string; + dash: string; + noLine: string; + startArrow: string; + endArrow: string; + fontSize: string; + font: string; + sans: string; + serif: string; + mono: string; + alignLeft: string; + alignCenter: string; + alignRight: string; + bold: string; + layout: string; + layoutRight: string; + layoutLeft: string; + layoutRadial: string; + addChild: string; + addSibling: string; + bringFront: string; + sendBack: string; + group: string; + ungroup: string; + duplicate: string; + delete: string; + copy: string; + editText: string; + openLink: string; + frameTitle: string; + groupTitle: string; + linkPrompt: string; + pageNote: string; + stickers: string; + templates: string; + presentNoFrames: string; + presentExit: string; + presentNext: string; + presentPrevious: string; + /** "{n} / {total}" while presenting. */ + presentStep: string; + textPlaceholder: string; + templateKanban: string; + templateSwot: string; + templateFlow: string; + templateBrainstorm: string; + templateRetro: string; + todo: string; + doing: string; + done: string; + strengths: string; + weaknesses: string; + opportunities: string; + threats: string; + start: string; + step: string; + decision: string; + end: string; + centralIdea: string; + idea: string; + wentWell: string; + toImprove: string; + actions: string; + colorInk: string; + colorPaper: string; + colorNone: string; + /** Names of the palette colours, by name. */ + colors: Record; +} + +export const englishCanvasLabels: CanvasLabels = { + toolbar: "Canvas tools", + select: "Select (V)", + hand: "Hand (H)", + note: "Note (N)", + text: "Text (T)", + shape: "Shape (S)", + connector: "Connector (C)", + pen: "Pen (P)", + eraser: "Eraser (E)", + frame: "Frame (F)", + mindmap: "Mind map (M)", + image: "Picture (I)", + link: "Link (L)", + library: "Stickers and templates", + present: "Present", + zoomIn: "Zoom in", + zoomOut: "Zoom out", + zoomFit: "Fit to screen", + zoomReset: "Zoom to 100%", + rect: "Square", + roundrect: "Rounded rectangle", + ellipse: "Ellipse", + diamond: "Diamond", + triangle: "Triangle", + general: "General", + scribbled: "Scribbled", + straight: "Straight", + curve: "Curve", + elbow: "Elbowed", + stroke: "Line colour", + fill: "Fill", + textColor: "Text colour", + background: "Background", + thickness: "Thickness", + lineStyle: "Line style", + solid: "Solid", + dash: "Dashed", + noLine: "No line", + startArrow: "Start", + endArrow: "End", + fontSize: "Size", + font: "Font", + sans: "Sans", + serif: "Serif", + mono: "Mono", + alignLeft: "Align left", + alignCenter: "Align centre", + alignRight: "Align right", + bold: "Bold", + layout: "Layout", + layoutRight: "Right", + layoutLeft: "Left", + layoutRadial: "Both sides", + addChild: "Add branch (Tab)", + addSibling: "Add sibling (Enter)", + bringFront: "Bring to front", + sendBack: "Send to back", + group: "Group (Ctrl+G)", + ungroup: "Ungroup", + duplicate: "Duplicate (Ctrl+D)", + delete: "Delete", + copy: "Copy", + editText: "Edit text", + openLink: "Open link", + frameTitle: "Frame", + groupTitle: "Group", + linkPrompt: "Link address", + pageNote: "Page", + stickers: "Stickers", + templates: "Templates", + presentNoFrames: "Add frames to present them one by one.", + presentExit: "Stop presenting", + presentNext: "Next frame", + presentPrevious: "Previous frame", + presentStep: "{n} / {total}", + textPlaceholder: "Type…", + templateKanban: "Board", + templateSwot: "SWOT", + templateFlow: "Flowchart", + templateBrainstorm: "Brainstorm", + templateRetro: "Retrospective", + todo: "To do", + doing: "Doing", + done: "Done", + strengths: "Strengths", + weaknesses: "Weaknesses", + opportunities: "Opportunities", + threats: "Threats", + start: "Start", + step: "Step", + decision: "Decision?", + end: "End", + centralIdea: "Central idea", + idea: "Idea", + wentWell: "Went well", + toImprove: "To improve", + actions: "Actions", + colorInk: "Default", + colorPaper: "Paper", + colorNone: "None", + colors: { + gray: "Gray", + red: "Red", + orange: "Orange", + yellow: "Yellow", + green: "Green", + teal: "Teal", + blue: "Blue", + purple: "Purple", + pink: "Pink", + }, +}; diff --git a/Packages/canvas/src/library.ts b/Packages/canvas/src/library.ts new file mode 100644 index 0000000..9a52170 --- /dev/null +++ b/Packages/canvas/src/library.ts @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Stickers and templates: ready-made elements dropped in the middle of the +// view. Everything is built from the canvas's own elements, so a template is +// editable like anything drawn by hand. + +import type { CanvasLabels } from "./labels"; +import { newId, type Color } from "./model"; +import type { ElementJSON } from "./store"; +import type { PMNode } from "./yxml"; + +/** Stickers are large emoji in a text box. */ +export const stickers = [ + "👍", + "⭐", + "❤️", + "✅", + "❌", + "💡", + "❓", + "❗", + "🎉", + "🔥", + "📌", + "🚀", + "👀", + "🎯", + "⚠️", + "🙂", +]; + +export function sticker(emoji: string): ElementJSON[] { + return [{ id: newId(), type: "text", text: emoji, fontSize: 64, x: 0, y: 0, w: 0, h: 0 }]; +} + +export type TemplateId = "kanban" | "swot" | "flow" | "brainstorm" | "retro"; +export const templates: TemplateId[] = ["kanban", "swot", "flow", "brainstorm", "retro"]; + +const para = (text: string): PMNode[] => [{ type: "paragraph", content: text ? [{ type: "text", text }] : [] }]; + +const frame = (title: string, x: number, y: number, w: number, h: number, background: Color = "none"): ElementJSON => ({ + id: newId(), + type: "frame", + title, + x, + y, + w, + h, + background, +}); + +const note = (text: string, x: number, y: number, background: Color, w = 220): ElementJSON => ({ + id: newId(), + type: "note", + background, + x, + y, + w, + h: 90, + body: para(text), +}); + +const shape = (kind: string, text: string, x: number, y: number, w: number, h: number, color: Color): ElementJSON => ({ + id: newId(), + type: "shape", + shape: kind, + text, + x, + y, + w, + h, + stroke: color, + fill: color, + strokeWidth: 2, +}); + +const arrow = (from: string, to: string, mode = "elbow"): ElementJSON => ({ + id: newId(), + type: "connector", + source: { id: from }, + target: { id: to }, + mode, + stroke: "gray", + endArrow: "arrow", +}); + +export function template(id: TemplateId, l: CanvasLabels): ElementJSON[] { + switch (id) { + case "kanban": { + const cols: [string, Color][] = [ + [l.todo, "gray"], + [l.doing, "blue"], + [l.done, "green"], + ]; + return cols.flatMap(([title, c], i) => [ + frame(title, i * 300, 0, 280, 520), + note("", i * 300 + 30, 50, c), + note("", i * 300 + 30, 170, c), + ]); + } + case "swot": { + const parts: [string, Color][] = [ + [l.strengths, "green"], + [l.weaknesses, "red"], + [l.opportunities, "blue"], + [l.threats, "orange"], + ]; + return parts.flatMap(([title, c], i) => { + const x = (i % 2) * 380; + const y = Math.floor(i / 2) * 300; + return [shape("roundrect", title, x, y, 360, 280, c)]; + }); + } + case "flow": { + const a = shape("ellipse", l.start, 0, 0, 180, 70, "green"); + const b = shape("rect", l.step, 0, 140, 180, 80, "blue"); + const c = shape("diamond", l.decision, -10, 290, 200, 120, "orange"); + const d = shape("rect", l.step, 280, 310, 180, 80, "blue"); + const e = shape("ellipse", l.end, 0, 480, 180, 70, "red"); + return [a, b, c, d, e, arrow(a.id, b.id), arrow(b.id, c.id), arrow(c.id, d.id), arrow(c.id, e.id)]; + } + case "brainstorm": { + const root = newId(); + const nodes: Record = { + [root]: { text: l.centralIdea, parent: "", pos: 0 }, + }; + for (let i = 0; i < 4; i++) nodes[newId()] = { text: `${l.idea} ${i + 1}`, parent: root, pos: i }; + return [{ id: newId(), type: "mindmap", layout: "radial", color: "purple", x: 0, y: 0, nodes }]; + } + case "retro": { + const cols: [string, Color][] = [ + [l.wentWell, "green"], + [l.toImprove, "orange"], + [l.actions, "blue"], + ]; + return cols.flatMap(([title, c], i) => [frame(title, i * 300, 0, 280, 420), note("", i * 300 + 30, 50, c)]); + } + } +} diff --git a/Packages/canvas/src/measure.ts b/Packages/canvas/src/measure.ts new file mode 100644 index 0000000..c34368c --- /dev/null +++ b/Packages/canvas/src/measure.ts @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Text measuring for layouts that cannot wait for the DOM (mind maps, +// exports). Falls back to an estimate where there is no 2D canvas (tests). + +let ctx: CanvasRenderingContext2D | null | undefined; + +function context(): CanvasRenderingContext2D | null { + if (ctx !== undefined) return ctx; + try { + ctx = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : null; + } catch { + ctx = null; + } + return ctx; +} + +export const SANS = '"Inter Variable", Inter, ui-sans-serif, system-ui, sans-serif'; +export const SERIF = '"Source Serif 4 Variable", "Source Serif 4", Georgia, serif'; +export const MONO = '"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, monospace'; + +export function fontFamily(font: "" | "serif" | "mono"): string { + return font === "serif" ? SERIF : font === "mono" ? MONO : SANS; +} + +export function textWidth(text: string, size: number, family = SANS, weight = 400): number { + const c = context(); + if (!c) return text.length * size * 0.56; + c.font = `${weight} ${size}px ${family}`; + return c.measureText(text).width; +} + +/** Breaks text into lines no wider than max (words first, then characters). */ +export function wrap(text: string, size: number, max: number, family = SANS, weight = 400): string[] { + const out: string[] = []; + for (const para of text.split("\n")) { + if (!para) { + out.push(""); + continue; + } + let line = ""; + for (const word of para.split(/(\s+)/)) { + const next = line + word; + if (!line || textWidth(next, size, family, weight) <= max) { + line = next; + continue; + } + out.push(line.trimEnd()); + line = word.trimStart(); + // A word longer than the line is broken where it must. + while (line && textWidth(line, size, family, weight) > max) { + let cut = line.length - 1; + while (cut > 1 && textWidth(line.slice(0, cut), size, family, weight) > max) cut--; + out.push(line.slice(0, cut)); + line = line.slice(cut); + } + } + out.push(line); + } + return out; +} + +/** The size of a mind map node: its text on one or more lines, with padding. */ +export function nodeSize(text: string, depth: number): { w: number; h: number } { + const size = depth === 0 ? 18 : 15; + const weight = depth === 0 ? 600 : 400; + const lines = wrap(text || " ", size, 260, SANS, weight); + const w = Math.max(...lines.map((l) => textWidth(l, size, SANS, weight)), depth === 0 ? 60 : 40); + return { + w: Math.ceil(w) + (depth === 0 ? 32 : 24), + h: lines.length * Math.round(size * 1.4) + (depth === 0 ? 20 : 14), + }; +} diff --git a/Packages/canvas/src/mindmap.ts b/Packages/canvas/src/mindmap.ts new file mode 100644 index 0000000..b291ac2 --- /dev/null +++ b/Packages/canvas/src/mindmap.ts @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Mind map layouts: the root on one side (right, left) or in the middle +// with branches on both sides (radial). Positions are relative to the +// root's top-left corner, which is the element's x, y. + +import type { Box, Point } from "./geometry"; +import type { MindmapLayout, MindmapNode } from "./model"; + +export interface NodeBox extends Box { + id: string; + depth: number; + /** Which way the branch grows from its parent. */ + dir: 1 | -1; + parent: string; +} + +export interface MindmapLayoutResult { + root: string; + boxes: Map; + /** Parent → child lines, each as [from, to] points. */ + edges: { from: Point; to: Point; child: string }[]; + /** The whole map, relative to the root's corner. */ + bounds: Box; +} + +const H_GAP = 56; +const V_GAP = 14; + +/** The root node's id: the one without a parent (the first, if several). */ +export function rootOf(nodes: Record): string | null { + const roots = Object.entries(nodes).filter(([, n]) => !n.parent || !nodes[n.parent]); + roots.sort((a, b) => a[1].pos - b[1].pos || (a[0] < b[0] ? -1 : 1)); + return roots[0]?.[0] ?? null; +} + +/** A node's children in order. */ +export function childrenOf(nodes: Record, id: string): string[] { + return Object.entries(nodes) + .filter(([cid, n]) => n.parent === id && cid !== id) + .sort((a, b) => a[1].pos - b[1].pos || (a[0] < b[0] ? -1 : 1)) + .map(([cid]) => cid); +} + +export function layoutMindmap( + nodes: Record, + layout: MindmapLayout, + measure: (text: string, depth: number) => { w: number; h: number }, +): MindmapLayoutResult { + const root = rootOf(nodes); + const boxes = new Map(); + const edges: MindmapLayoutResult["edges"] = []; + if (!root) return { root: "", boxes, edges, bounds: { x: 0, y: 0, w: 0, h: 0 } }; + const size = new Map(); + const seen = new Set(); + const measureAll = (id: string, depth: number) => { + if (seen.has(id) || depth > 50) return; + seen.add(id); + size.set(id, measure(nodes[id]!.text, depth)); + for (const c of childrenOf(nodes, id)) measureAll(c, depth + 1); + }; + measureAll(root, 0); + const kids = (id: string) => childrenOf(nodes, id).filter((c) => size.has(c)); + + // The height a branch needs: its node or its children stacked, whichever is taller. + const heights = new Map(); + const height = (id: string): number => { + const known = heights.get(id); + if (known !== undefined) return known; + const cs = kids(id); + const stack = cs.reduce((s, c) => s + height(c), 0) + V_GAP * Math.max(0, cs.length - 1); + const h = Math.max(size.get(id)!.h, stack); + heights.set(id, h); + return h; + }; + + const place = (id: string, x: number, centreY: number, depth: number, dir: 1 | -1, parent: string) => { + const s = size.get(id)!; + const bx = dir === 1 ? x : x - s.w; + boxes.set(id, { id, x: bx, y: centreY - s.h / 2, w: s.w, h: s.h, depth, dir, parent }); + placeChildren(id, kids(id), dir === 1 ? bx + s.w + H_GAP : bx - H_GAP, centreY, depth + 1, dir); + }; + const placeChildren = (parent: string, cs: string[], x: number, centreY: number, depth: number, dir: 1 | -1) => { + const total = cs.reduce((s, c) => s + height(c), 0) + V_GAP * Math.max(0, cs.length - 1); + let y = centreY - total / 2; + for (const c of cs) { + const h = height(c); + place(c, x, y + h / 2, depth, dir, parent); + y += h + V_GAP; + } + }; + + const rs = size.get(root)!; + boxes.set(root, { id: root, x: 0, y: 0, w: rs.w, h: rs.h, depth: 0, dir: 1, parent: "" }); + const cy = rs.h / 2; + const cs = kids(root); + if (layout === "right") placeChildren(root, cs, rs.w + H_GAP, cy, 1, 1); + else if (layout === "left") placeChildren(root, cs, -H_GAP, cy, 1, -1); + else { + // Radial: the first half of the branches to the right, the rest to the left. + const half = Math.ceil(cs.length / 2); + placeChildren(root, cs.slice(0, half), rs.w + H_GAP, cy, 1, 1); + placeChildren(root, cs.slice(half), -H_GAP, cy, 1, -1); + } + + for (const b of boxes.values()) { + if (!b.parent) continue; + const p = boxes.get(b.parent)!; + const from: Point = b.dir === 1 ? [p.x + p.w, p.y + p.h / 2] : [p.x, p.y + p.h / 2]; + const to: Point = b.dir === 1 ? [b.x, b.y + b.h / 2] : [b.x + b.w, b.y + b.h / 2]; + edges.push({ from, to, child: b.id }); + } + let x1 = Infinity; + let y1 = Infinity; + let x2 = -Infinity; + let y2 = -Infinity; + for (const b of boxes.values()) { + x1 = Math.min(x1, b.x); + y1 = Math.min(y1, b.y); + x2 = Math.max(x2, b.x + b.w); + y2 = Math.max(y2, b.y + b.h); + } + return { root, boxes, edges, bounds: { x: x1, y: y1, w: x2 - x1, h: y2 - y1 } }; +} + +/** The node an arrow key moves to from id, or null. */ +export function neighbour( + result: MindmapLayoutResult, + nodes: Record, + id: string, + key: "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight", +): string | null { + const b = result.boxes.get(id); + if (!b) return null; + if (key === "ArrowUp" || key === "ArrowDown") { + const siblings = b.parent ? childrenOf(nodes, b.parent).filter((c) => result.boxes.get(c)?.dir === b.dir) : []; + const i = siblings.indexOf(id); + return siblings[i + (key === "ArrowUp" ? -1 : 1)] ?? null; + } + const want = key === "ArrowRight" ? 1 : -1; + if (!b.parent) { + // From the root, go to the first branch on that side. + return childrenOf(nodes, id).find((c) => result.boxes.get(c)?.dir === want) ?? null; + } + if (want === b.dir) return childrenOf(nodes, id)[0] ?? null; + return b.parent; +} + +/** Curved line from a parent to a child, as an SVG path. */ +export function edgePath(from: Point, to: Point): string { + const mx = (from[0] + to[0]) / 2; + return `M${from[0]} ${from[1]} C${mx} ${from[1]} ${mx} ${to[1]} ${to[0]} ${to[1]}`; +} diff --git a/Packages/canvas/src/model.ts b/Packages/canvas/src/model.ts new file mode 100644 index 0000000..5366170 --- /dev/null +++ b/Packages/canvas/src/model.ts @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The elements of an edgeless canvas (ADR-14). Each one is a Y.Map in +// ydoc.getMap("surface") keyed by its id; these types are what the maps +// read as. Coordinates are canvas units; x, y is the top-left corner. + +/** The theme colours elements use; documents store the name, not a value. */ +export const palette = ["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"] as const; +/** A palette colour, "ink" (the text colour), "paper" (the page colour) or "none". */ +export type Color = (typeof palette)[number] | "ink" | "paper" | "none"; +export const colors: readonly Color[] = ["ink", ...palette, "paper", "none"]; + +export const isColor = (c: unknown): c is Color => typeof c === "string" && (colors as readonly string[]).includes(c); + +export type ElementType = + "shape" | "text" | "connector" | "brush" | "note" | "frame" | "image" | "embed" | "group" | "mindmap"; + +export const shapeKinds = ["rect", "roundrect", "ellipse", "diamond", "triangle"] as const; +export type ShapeKind = (typeof shapeKinds)[number]; +export type StrokeStyle = "solid" | "dash" | "none"; +export const connectorModes = ["straight", "curve", "elbow"] as const; +export type ConnectorMode = (typeof connectorModes)[number]; +export const arrowKinds = ["none", "arrow", "triangle", "circle", "diamond"] as const; +export type Arrow = (typeof arrowKinds)[number]; +export type TextFont = "" | "serif" | "mono"; +export type TextAlign = "left" | "center" | "right"; +export const mindmapLayouts = ["right", "left", "radial"] as const; +export type MindmapLayout = (typeof mindmapLayouts)[number]; + +interface Base { + id: string; + type: ElementType; + /** Z-order: higher draws on top. Frames always draw below everything else. */ + index: number; + x: number; + y: number; + w: number; + h: number; + /** Degrees clockwise around the centre. */ + rotate: number; + /** The group the element belongs to, if any. */ + group: string; +} + +export interface ShapeElement extends Base { + type: "shape"; + shape: ShapeKind; + stroke: Color; + fill: Color; + strokeWidth: number; + strokeStyle: StrokeStyle; + /** The hand-drawn ("scribbled") style. */ + rough: boolean; + text: string; + textColor: Color; + fontSize: number; +} + +export interface TextElement extends Base { + type: "text"; + text: string; + color: Color; + fontSize: number; + font: TextFont; + align: TextAlign; + bold: boolean; +} + +/** One end of a connector: stuck to an element (at pos inside its box, or the nearest side) or a free point. */ +export interface End { + id?: string; + /** Where on the element, as fractions of its box; without it the end slides to the nearest side. */ + pos?: [number, number]; + x?: number; + y?: number; +} + +export interface ConnectorElement extends Base { + type: "connector"; + source: End; + target: End; + mode: ConnectorMode; + stroke: Color; + strokeWidth: number; + strokeStyle: StrokeStyle; + startArrow: Arrow; + endArrow: Arrow; + label: string; + rough: boolean; +} + +export interface BrushElement extends Base { + type: "brush"; + /** [x, y, pressure] relative to x, y. */ + points: number[][]; + color: Color; + size: number; +} + +export interface NoteElement extends Base { + type: "note"; + /** The page's own text (the "default" fragment) instead of a body of its own. */ + page: boolean; + background: Color; +} + +export interface FrameElement extends Base { + type: "frame"; + title: string; + background: Color; +} + +export interface ImageElement extends Base { + type: "image"; + src: string; + alt: string; +} + +/** A link: a player for the sites the editor embeds, a card for any other address. */ +export interface EmbedElement extends Base { + type: "embed"; + url: string; +} + +/** Elements grouped with Ctrl+G; its box is its members' box. */ +export interface GroupElement extends Base { + type: "group"; + title: string; +} + +export interface MindmapNode { + text: string; + /** The parent node's id; "" for the root. */ + parent: string; + /** Order among siblings. */ + pos: number; +} + +/** A mind map; x, y is the root's top-left corner, the box follows the layout. */ +export interface MindmapElement extends Base { + type: "mindmap"; + layout: MindmapLayout; + color: Color; + nodes: Record; +} + +export type CanvasElement = + | ShapeElement + | TextElement + | ConnectorElement + | BrushElement + | NoteElement + | FrameElement + | ImageElement + | EmbedElement + | GroupElement + | MindmapElement; + +export type ElementOf = Extract; + +/** The default width of the page's note, about the reading column. */ +export const PAGE_NOTE_WIDTH = 760; +/** The id of the page's note; it exists before anyone moves it (ADR-14). */ +export const PAGE_NOTE_ID = "page"; + +const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) ? v : d); +const str = (v: unknown, d = "") => (typeof v === "string" ? v : d); +const bool = (v: unknown) => v === true; +const color = (v: unknown, d: Color): Color => (isColor(v) ? v : d); +const oneOf = (v: unknown, list: readonly T[], d: T): T => + typeof v === "string" && (list as readonly string[]).includes(v) ? (v as T) : d; + +function end(v: unknown): End { + if (!v || typeof v !== "object") return { x: 0, y: 0 }; + const o = v as Record; + const out: End = {}; + if (typeof o.id === "string" && o.id) out.id = o.id; + if (Array.isArray(o.pos) && o.pos.length === 2) out.pos = [num(o.pos[0], 0.5), num(o.pos[1], 0.5)]; + if (!out.id) { + out.x = num(o.x, 0); + out.y = num(o.y, 0); + } + return out; +} + +function nodes(v: unknown): Record { + const out: Record = {}; + if (!v || typeof v !== "object") return out; + for (const [id, n] of Object.entries(v as Record)) { + if (!n || typeof n !== "object") continue; + const o = n as Record; + out[id] = { text: str(o.text), parent: str(o.parent), pos: num(o.pos, 0) }; + } + return out; +} + +/** Reads an element from its stored fields, filling in what is missing; null for an unknown type. */ +export function normalize(raw: Record): CanvasElement | null { + const base = { + id: str(raw.id), + index: num(raw.index, 0), + x: num(raw.x, 0), + y: num(raw.y, 0), + w: Math.max(0, num(raw.w, 0)), + h: Math.max(0, num(raw.h, 0)), + rotate: num(raw.rotate, 0), + group: str(raw.group), + }; + switch (raw.type) { + case "shape": + return { + ...base, + type: "shape", + shape: oneOf(raw.shape, shapeKinds, "rect"), + stroke: color(raw.stroke, "ink"), + fill: color(raw.fill, "none"), + strokeWidth: num(raw.strokeWidth, 2), + strokeStyle: oneOf(raw.strokeStyle, ["solid", "dash", "none"] as const, "solid"), + rough: bool(raw.rough), + text: str(raw.text), + textColor: color(raw.textColor, "ink"), + fontSize: num(raw.fontSize, 18), + }; + case "text": + return { + ...base, + type: "text", + text: str(raw.text), + color: color(raw.color, "ink"), + fontSize: num(raw.fontSize, 24), + font: oneOf(raw.font, ["", "serif", "mono"] as const, ""), + align: oneOf(raw.align, ["left", "center", "right"] as const, "left"), + bold: bool(raw.bold), + }; + case "connector": + return { + ...base, + type: "connector", + source: end(raw.source), + target: end(raw.target), + mode: oneOf(raw.mode, connectorModes, "curve"), + stroke: color(raw.stroke, "ink"), + strokeWidth: num(raw.strokeWidth, 2), + strokeStyle: oneOf(raw.strokeStyle, ["solid", "dash", "none"] as const, "solid"), + startArrow: oneOf(raw.startArrow, arrowKinds, "none"), + endArrow: oneOf(raw.endArrow, arrowKinds, "arrow"), + label: str(raw.label), + rough: bool(raw.rough), + }; + case "brush": + return { + ...base, + type: "brush", + points: Array.isArray(raw.points) + ? raw.points + .filter((p): p is number[] => Array.isArray(p) && p.length >= 2) + .map((p) => [num(p[0], 0), num(p[1], 0), num(p[2], 0.5)]) + : [], + color: color(raw.color, "ink"), + size: num(raw.size, 4), + }; + case "note": + return { ...base, type: "note", page: bool(raw.page), background: color(raw.background, "paper") }; + case "frame": + return { ...base, type: "frame", title: str(raw.title), background: color(raw.background, "none") }; + case "image": + return { ...base, type: "image", src: str(raw.src), alt: str(raw.alt) }; + case "embed": + return { ...base, type: "embed", url: str(raw.url) }; + case "group": + return { ...base, type: "group", title: str(raw.title) }; + case "mindmap": + return { + ...base, + type: "mindmap", + layout: oneOf(raw.layout, mindmapLayouts, "right"), + color: color(raw.color, "blue"), + nodes: nodes(raw.nodes), + }; + default: + return null; + } +} + +/** Elements whose box can be dragged by its corners. */ +export const resizable = (e: CanvasElement) => !["connector", "group", "mindmap"].includes(e.type); +/** Elements that turn around their centre. */ +export const rotatable = (e: CanvasElement) => ["shape", "text", "image", "brush"].includes(e.type); +/** Elements a connector can stick to. */ +export const connectable = (e: CanvasElement) => !["connector", "brush", "group"].includes(e.type); + +let counter = 0; +/** A new element or node id: short, random enough for one canvas. */ +export function newId(): string { + counter = (counter + 1) % 1296; + return ( + Date.now().toString(36).slice(-6) + counter.toString(36).padStart(2, "0") + Math.random().toString(36).slice(2, 8) + ); +} + +/** What new elements look like; the last style picked for a kind becomes its default. */ +export interface StyleDefaults { + shape: Pick; + connector: Pick; + brush: Pick; + text: Pick; + note: Pick; + frame: Pick; + mindmap: Pick; +} + +export const defaultStyles: StyleDefaults = { + shape: { + shape: "rect", + stroke: "blue", + fill: "blue", + strokeWidth: 2, + strokeStyle: "solid", + rough: false, + textColor: "ink", + }, + connector: { + mode: "curve", + stroke: "gray", + strokeWidth: 2, + strokeStyle: "solid", + startArrow: "none", + endArrow: "arrow", + }, + brush: { color: "ink", size: 4 }, + text: { color: "ink", fontSize: 24, font: "" }, + note: { background: "yellow" }, + frame: { background: "none" }, + mindmap: { layout: "right", color: "blue" }, +}; + +/** Merges stored defaults over the built-in ones, dropping anything that does not fit. */ +export function readStyles(raw: unknown): StyleDefaults { + const out = structuredClone(defaultStyles); + if (!raw || typeof raw !== "object") return out; + for (const kind of Object.keys(out) as (keyof StyleDefaults)[]) { + const src = (raw as Record)[kind]; + if (!src || typeof src !== "object") continue; + const probe = normalize({ ...out[kind], ...(src as object), type: kind === "note" ? "note" : kind }); + if (!probe) continue; + // A stored value counts only when it reads back as itself (it is valid). + for (const key of Object.keys(out[kind])) { + const v = (src as Record)[key]; + if (v !== undefined && (probe as unknown as Record)[key] === v) + (out[kind] as Record)[key] = v; + } + } + return out; +} diff --git a/Packages/canvas/src/render.ts b/Packages/canvas/src/render.ts new file mode 100644 index 0000000..9f48ea1 --- /dev/null +++ b/Packages/canvas/src/render.ts @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// SVG markup for the drawn elements. The live canvas and the exports share +// it; only the paint differs (CSS variables live, resolved colours in a +// file). Shapes draw in their own box (0..w, 0..h); connectors in canvas units. + +import { getStroke } from "perfect-freehand"; +import rough from "roughjs"; +import type { Point, Route } from "./geometry"; +import type { Arrow, BrushElement, Color, ShapeElement, StrokeStyle } from "./model"; + +/** Turns a colour name into a CSS colour: "line" for strokes and text, "fill" for soft backgrounds. */ +export type Paint = (c: Color, use: "line" | "fill") => string; + +export const livePaint: Paint = (c, use) => { + if (c === "none") return "none"; + if (c === "ink") return use === "fill" ? "var(--dw-surface-sunken)" : "var(--dw-ink)"; + if (c === "paper") return use === "fill" ? "var(--dw-surface-raised)" : "var(--dw-surface)"; + return use === "fill" ? `color-mix(in srgb, var(--dw-c-${c}) 22%, var(--dw-surface))` : `var(--dw-c-${c})`; +}; + +export const esc = (s: string) => + s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + +const n = (v: number) => Math.round(v * 100) / 100; +const LINE = "#000001"; +const FILL = "#000002"; + +function dash(style: StrokeStyle, width: number): string { + return style === "dash" ? `stroke-dasharray:${n(width * 4)} ${n(width * 3)};` : ""; +} + +/** A number from an id, so a scribbled shape looks the same on every screen. */ +export function seedOf(id: string): number { + let h = 2166136261; + for (const ch of id) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); + return (h >>> 0) % 2 ** 31 || 1; +} + +/** The outline of a shape as points (for polygons) or null for curves. */ +function polygon(kind: ShapeElement["shape"], w: number, h: number): Point[] | null { + switch (kind) { + case "diamond": + return [ + [w / 2, 0], + [w, h / 2], + [w / 2, h], + [0, h / 2], + ]; + case "triangle": + return [ + [w / 2, 0], + [w, h], + [0, h], + ]; + case "rect": + return [ + [0, 0], + [w, 0], + [w, h], + [0, h], + ]; + default: + return null; + } +} + +function roundRectPath(w: number, h: number): string { + const r = Math.min(16, w * 0.15, h * 0.15); + return `M${n(r)} 0 H${n(w - r)} Q${n(w)} 0 ${n(w)} ${n(r)} V${n(h - r)} Q${n(w)} ${n(h)} ${n(w - r)} ${n(h)} H${n(r)} Q0 ${n(h)} 0 ${n(h - r)} V${n(r)} Q0 0 ${n(r)} 0 Z`; +} + +/** A shape's body (without its text) in its own box. */ +export function shapeSVG(el: ShapeElement, paint: Paint): string { + const { w, h } = el; + const stroke = el.strokeStyle === "none" ? "none" : paint(el.stroke, "line"); + const fill = paint(el.fill, "fill"); + const sw = el.strokeStyle === "none" ? 0 : el.strokeWidth; + if (el.rough) { + const gen = rough.generator(); + const opts = { + seed: seedOf(el.id), + roughness: 1.2, + bowing: 1, + strokeWidth: Math.max(sw, 1), + // Marker colours, swapped for the theme's below. + stroke: stroke === "none" ? "none" : LINE, + fill: fill === "none" ? undefined : FILL, + fillStyle: "hachure", + hachureGap: 8, + fillWeight: 1.4, + disableMultiStroke: sw === 0, + }; + const pts = polygon(el.shape, w, h); + const drawable = + el.shape === "ellipse" + ? gen.ellipse(w / 2, h / 2, w, h, opts) + : el.shape === "roundrect" + ? gen.path(roundRectPath(w, h), opts) + : gen.polygon(pts!, opts); + return gen + .toPaths(drawable) + .map((p) => { + if (p.fill === FILL) return ``; + // Hachure lines are drawn in the fill colour, a little stronger than a flat fill. + const hachure = p.stroke === FILL; + const color = hachure ? fill.replace("22%", "60%") : stroke; + if (color === "none" || p.stroke === "none") return ""; + return ``; + }) + .join(""); + } + const style = `fill:${fill};stroke:${stroke};stroke-width:${n(sw)};stroke-linejoin:round;${dash(el.strokeStyle, sw)}`; + if (el.shape === "ellipse") + return ``; + if (el.shape === "roundrect") return ``; + const pts = polygon(el.shape, w, h)!; + return ``; +} + +/** Arrowhead at p pointing along angle (radians). */ +function arrowHead(kind: Arrow, p: Point, angle: number, width: number, color: string): string { + if (kind === "none") return ""; + const size = 6 + width * 2.5; + const at = (dx: number, dy: number): string => { + const cos = Math.cos(angle); + const sin = Math.sin(angle); + return `${n(p[0] + dx * cos - dy * sin)},${n(p[1] + dx * sin + dy * cos)}`; + }; + switch (kind) { + case "arrow": + return ``; + case "triangle": + return ``; + case "circle": { + const [cx, cy] = at(-size * 0.45, 0) + .split(",") + .map(Number); + return ``; + } + case "diamond": + return ``; + } +} + +export interface ConnectorStyle { + id: string; + stroke: Color; + strokeWidth: number; + strokeStyle: StrokeStyle; + startArrow: Arrow; + endArrow: Arrow; + rough: boolean; +} + +/** A connector's line and arrowheads, in canvas units. */ +export function connectorSVG(c: ConnectorStyle, r: Route, paint: Paint): string { + const color = c.strokeStyle === "none" ? paint("gray", "line") : paint(c.stroke, "line"); + const w = c.strokeWidth; + let line: string; + if (c.rough) { + const gen = rough.generator(); + const d = gen.toPaths(gen.path(r.d, { seed: seedOf(c.id), roughness: 1, strokeWidth: w, stroke: "#000" })); + line = d.map((p) => ``).join(""); + } else { + line = ``; + } + const last = r.points[r.points.length - 1]!; + return ( + line + + arrowHead(c.startArrow, r.points[0]!, r.startAngle, w, color) + + arrowHead(c.endArrow, last, r.endAngle, w, color) + ); +} + +/** A pen stroke's outline as an SVG path, relative to the element's corner. */ +export function brushPath(points: number[][], size: number): string { + const outline = getStroke(points, { + size, + thinning: 0.55, + smoothing: 0.5, + streamline: 0.4, + simulatePressure: points.every((p) => p[2] === 0.5), + last: true, + }); + if (!outline.length) return ""; + const avg = (a: number, b: number) => (a + b) / 2; + let d = `M${n(outline[0]![0]!)} ${n(outline[0]![1]!)} Q`; + for (let i = 0; i < outline.length; i++) { + const [x0, y0] = outline[i]!; + const [x1, y1] = outline[(i + 1) % outline.length]!; + d += `${n(x0!)} ${n(y0!)} ${n(avg(x0!, x1!))} ${n(avg(y0!, y1!))} `; + } + return d + "Z"; +} + +export function brushSVG(el: BrushElement, paint: Paint): string { + return ``; +} diff --git a/Packages/canvas/src/store.ts b/Packages/canvas/src/store.ts new file mode 100644 index 0000000..de90427 --- /dev/null +++ b/Packages/canvas/src/store.ts @@ -0,0 +1,458 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The canvas's live data in the page's Y.Doc (ADR-14): +// ydoc.getMap("surface") → id → Y.Map of the element's fields. A note's body +// is a Y.XmlFragment under "body"; a mind map's nodes a Y.Map under "nodes". +// Every edit runs in one transaction with CANVAS_ORIGIN, tracked by the +// canvas's undo manager. + +import * as Y from "yjs"; +import { + PAGE_NOTE_ID, + PAGE_NOTE_WIDTH, + newId, + normalize, + type CanvasElement, + type End, + type MindmapNode, +} from "./model"; +import { fragmentToJSON, writeJSON, type PMNode } from "./yxml"; + +/** The transaction origin of canvas edits; the canvas's undo manager tracks it. */ +export const CANVAS_ORIGIN = "docwell-canvas"; + +export const surfaceOf = (doc: Y.Doc) => doc.getMap>("surface"); + +/** An element as copied, pasted or stored in JSON: its fields plus a note's body. */ +export type ElementJSON = Record & { id: string; type: string; body?: PMNode[] }; + +type YItem = Y.Map; + +/** Reads a stored element; nested types (a note body) are left out, a mind map's nodes read as JSON. */ +function read(m: YItem): CanvasElement | null { + const raw: Record = {}; + for (const [k, v] of m.entries()) { + if (v instanceof Y.Map) raw[k] = v.toJSON(); + else if (!(v instanceof Y.AbstractType)) raw[k] = v; + } + return normalize(raw); +} + +/** Frames first (always underneath), then by index, then by id so every client agrees. */ +export function zOrder(a: CanvasElement, b: CanvasElement): number { + const fa = a.type === "frame" ? 0 : 1; + const fb = b.type === "frame" ? 0 : 1; + return fa - fb || a.index - b.index || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0); +} + +/** The page's note as it is drawn before anyone moved it. */ +export function defaultPageNote(): CanvasElement { + return normalize({ + id: PAGE_NOTE_ID, + type: "note", + page: true, + background: "paper", + x: 0, + y: 0, + w: PAGE_NOTE_WIDTH, + h: 400, + index: 0, + })!; +} + +export class SurfaceStore { + readonly map: Y.Map; + readonly undo: Y.UndoManager | null; + private cache: CanvasElement[] | null = null; + private byId = new Map(); + private listeners = new Set<(changed: Set | null) => void>(); + private readonly observer = (events: Y.YEvent>[]) => { + this.cache = null; + // Which elements changed; null means the list itself changed. + let changed: Set | null = new Set(); + for (const ev of events) { + if (ev.target === this.map) { + changed = null; + break; + } + let t: Y.AbstractType | null = ev.target; + while (t && t.parent !== this.map) t = t.parent as Y.AbstractType | null; + const key = t && (t as unknown as { _item?: { parentSub?: string } })._item?.parentSub; + if (key) changed.add(key); + } + for (const fn of this.listeners) fn(changed); + }; + + constructor( + readonly doc: Y.Doc, + opts: { undo?: boolean } = {}, + ) { + this.map = surfaceOf(doc); + this.map.observeDeep(this.observer); + this.undo = + opts.undo === false + ? null + : new Y.UndoManager(this.map, { trackedOrigins: new Set([CANVAS_ORIGIN]), captureTimeout: 400 }); + } + + destroy(): void { + this.map.unobserveDeep(this.observer); + this.undo?.destroy(); + this.listeners.clear(); + } + + /** Calls fn after each change with the ids that changed, or null when elements came or went. */ + onChange(fn: (changed: Set | null) => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + /** Every element in drawing order, the page's note included. */ + elements(): CanvasElement[] { + if (this.cache) return this.cache; + const list: CanvasElement[] = []; + for (const [id, m] of this.map.entries()) { + const el = m instanceof Y.Map ? read(m) : null; + if (el) list.push({ ...el, id }); + } + if (!list.some((e) => e.type === "note" && e.page)) list.push(defaultPageNote()); + list.sort(zOrder); + this.cache = list; + this.byId = new Map(list.map((e) => [e.id, e])); + return list; + } + + get(id: string): CanvasElement | undefined { + this.elements(); + return this.byId.get(id); + } + + /** Whether the canvas has anything besides an unmoved page note. */ + get isEmpty(): boolean { + return this.map.size === 0; + } + + /** A note's body, made on first use (not for the page's note). */ + body(id: string): Y.XmlFragment | null { + const m = this.map.get(id); + if (!(m instanceof Y.Map)) return null; + const b = m.get("body"); + return b instanceof Y.XmlFragment ? b : null; + } + + /** A mind map's nodes map. */ + nodes(id: string): Y.Map | null { + const n = this.map.get(id)?.get("nodes"); + return n instanceof Y.Map ? (n as Y.Map) : null; + } + + transact(fn: () => void): void { + this.doc.transact(fn, CANVAS_ORIGIN); + } + + private nextIndex(): number { + let max = 0; + for (const e of this.elements()) if (e.type !== "frame") max = Math.max(max, e.index); + return max + 1; + } + + /** Writes the page's note at its default place, so it can be changed like any other element. */ + private ensure(id: string): YItem | null { + const m = this.map.get(id); + if (m instanceof Y.Map) return m; + if (id !== PAGE_NOTE_ID) return null; + const note = this.get(id)!; + const y = new Y.Map(); + this.map.set(id, y); + for (const [k, v] of Object.entries(note)) if (k !== "id") y.set(k, v); + return y; + } + + /** Adds an element; returns its id. Notes get an empty body, mind maps a root. */ + add(fields: Partial & { type: CanvasElement["type"] }, body?: PMNode[]): string { + const id = fields.id || newId(); + this.transact(() => { + const m = new Y.Map(); + this.map.set(id, m); + const { nodes, ...rest } = fields as Record & { nodes?: Record }; + for (const [k, v] of Object.entries(rest)) if (k !== "id" && v !== undefined) m.set(k, v); + if (!("index" in rest)) m.set("index", fields.type === "frame" ? -this.nextIndex() : this.nextIndex()); + if (fields.type === "note" && !(fields as { page?: boolean }).page) { + const frag = new Y.XmlFragment(); + m.set("body", frag); + writeJSON(frag, body?.length ? body : [{ type: "paragraph" }]); + } + if (fields.type === "mindmap") { + const n = new Y.Map(); + m.set("nodes", n); + const list = nodes && Object.keys(nodes).length ? nodes : { [newId()]: { text: "", parent: "", pos: 0 } }; + for (const [nid, node] of Object.entries(list)) n.set(nid, nodeToY(node)); + } + }); + return id; + } + + /** Changes fields of one element; undefined removes a field. */ + update(id: string, patch: Record): void { + this.updateMany([[id, patch]]); + } + + updateMany(patches: [string, Record][]): void { + if (!patches.length) return; + this.transact(() => { + for (const [id, patch] of patches) { + const m = this.ensure(id); + if (!m) continue; + for (const [k, v] of Object.entries(patch)) { + if (k === "id" || k === "type" || k === "body" || k === "nodes") continue; + if (v === undefined) m.delete(k); + else if (!sameValue(m.get(k), v)) m.set(k, v); + } + } + }); + } + + /** + * Deletes elements with their group members. Connectors stuck to a + * deleted element keep their end where it was. + */ + remove(ids: Iterable): void { + const all = this.elements(); + const gone = new Set(); + for (const id of ids) { + gone.add(id); + for (const e of all) if (e.group === id) gone.add(e.id); + } + // The page's note cannot be deleted: it is the page. + gone.delete(PAGE_NOTE_ID); + for (const e of all) if (e.type === "note" && e.page) gone.delete(e.id); + if (!gone.size) return; + this.transact(() => { + for (const e of all) { + if (e.type !== "connector" || gone.has(e.id)) continue; + for (const side of ["source", "target"] as const) { + const end = e[side]; + if (end.id && gone.has(end.id)) { + const at = this.endPoint(end); + this.map.get(e.id)?.set(side, { x: at[0], y: at[1] }); + } + } + } + for (const id of gone) this.map.delete(id); + // Groups left with fewer than two members dissolve. + const left = this.elements(); + for (const g of left.filter((e) => e.type === "group")) { + const members = left.filter((e) => e.group === g.id); + if (members.length < 2) { + for (const m of members) this.map.get(m.id)?.delete("group"); + this.map.delete(g.id); + } + } + }); + } + + /** Where an end attached to an element is, for when the element goes away. */ + private endPoint(end: End): [number, number] { + const el = end.id ? this.get(end.id) : undefined; + if (!el) return [end.x ?? 0, end.y ?? 0]; + const [px, py] = end.pos ?? [0.5, 0.5]; + return [el.x + el.w * px, el.y + el.h * py]; + } + + /** Moves elements to the top or bottom of the drawing order, keeping their own order. */ + reorder(ids: string[], to: "front" | "back" | "forward" | "backward"): void { + const all = this.elements().filter((e) => e.type !== "frame"); + const chosen = new Set(ids); + const picked = all.filter((e) => chosen.has(e.id)); + if (!picked.length) return; + const rest = all.filter((e) => !chosen.has(e.id)); + let order: CanvasElement[]; + if (to === "front") order = [...rest, ...picked]; + else if (to === "back") order = [...picked, ...rest]; + else { + // One step: past the next (or previous) element that is not chosen. + order = [...all]; + const step = to === "forward" ? 1 : -1; + const idx = (e: CanvasElement) => order.indexOf(e); + const list = step === 1 ? [...picked].reverse() : picked; + for (const e of list) { + const i = idx(e); + const j = i + step; + if (j < 0 || j >= order.length || chosen.has(order[j]!.id)) continue; + [order[i], order[j]] = [order[j]!, order[i]!]; + } + } + this.updateMany( + order + .map((e, i) => [e.id, { index: i + 1 }] as [string, Record]) + .filter(([id, p]) => this.get(id)?.index !== p.index), + ); + } + + /** Puts elements in a new group; returns its id. */ + groupOf(ids: string[]): string | null { + const members = ids.filter((id) => { + const e = this.get(id); + return e && e.type !== "group" && !(e.type === "note" && e.page); + }); + if (members.length < 2) return null; + const gid = newId(); + this.transact(() => { + const g = new Y.Map(); + this.map.set(gid, g); + g.set("type", "group"); + g.set("index", this.nextIndex()); + for (const id of members) this.ensure(id)?.set("group", gid); + }); + return gid; + } + + ungroup(groupId: string): string[] { + const members = this.elements() + .filter((e) => e.group === groupId) + .map((e) => e.id); + this.transact(() => { + for (const id of members) this.map.get(id)?.delete("group"); + this.map.delete(groupId); + }); + return members; + } + + // ---- Mind maps ---- + + addNode(mapId: string, parent: string, pos: number, text = ""): string { + const id = newId(); + this.transact(() => this.nodes(mapId)?.set(id, nodeToY({ text, parent, pos }))); + return id; + } + + updateNode(mapId: string, nodeId: string, patch: Partial): void { + this.transact(() => { + const n = this.nodes(mapId)?.get(nodeId); + if (!n) return; + for (const [k, v] of Object.entries(patch)) if (n.get(k) !== v) n.set(k, v); + }); + } + + /** Removes a node and its branch. Removing the root removes the map. */ + removeNode(mapId: string, nodeId: string): void { + const el = this.get(mapId); + if (el?.type !== "mindmap") return; + const root = Object.entries(el.nodes).find(([, n]) => !n.parent)?.[0]; + if (nodeId === root) { + this.remove([mapId]); + return; + } + const gone = new Set([nodeId]); + let grew = true; + while (grew) { + grew = false; + for (const [id, n] of Object.entries(el.nodes)) { + if (!gone.has(id) && gone.has(n.parent)) { + gone.add(id); + grew = true; + } + } + } + this.transact(() => { + const nodes = this.nodes(mapId); + for (const id of gone) nodes?.delete(id); + }); + } + + // ---- JSON: copy, paste, templates, read-only snapshots ---- + + /** Elements as JSON (with group members and note bodies), for copying. */ + toJSON(ids?: Iterable): ElementJSON[] { + const all = this.elements(); + let chosen: Set; + if (ids) { + chosen = new Set(ids); + for (const e of all) if (chosen.has(e.group)) chosen.add(e.id); + } else chosen = new Set(all.map((e) => e.id)); + return all + .filter((e) => chosen.has(e.id)) + .map((e) => { + const out: ElementJSON = { ...(e as unknown as Record), id: e.id, type: e.type }; + const body = e.type === "note" && !e.page ? this.body(e.id) : null; + if (body) out.body = fragmentToJSON(body); + return out; + }); + } + + /** + * Adds copies of elements, moved by dx, dy, with new ids; connectors, groups + * and mind maps keep pointing at the copies. The page's note is never copied. + * Returns the new ids, in order. + */ + insertJSON(list: ElementJSON[], dx = 0, dy = 0): string[] { + const items = list.filter((e) => e && typeof e === "object" && !(e.type === "note" && e.page)); + const ids = new Map(items.map((e) => [String(e.id), newId()])); + const out: string[] = []; + let index = this.nextIndex(); + this.transact(() => { + for (const raw of items) { + const el = normalize(raw); + if (!el) continue; + const id = ids.get(String(raw.id))!; + const fields: Record = { ...(el as unknown as Record) }; + delete fields.id; + fields.x = el.x + dx; + fields.y = el.y + dy; + fields.index = el.type === "frame" ? -index++ : index++; + fields.group = el.group && ids.has(el.group) ? ids.get(el.group) : undefined; + if (el.type === "connector") { + for (const side of ["source", "target"] as const) { + const end = el[side]; + if (end.id && ids.has(end.id)) fields[side] = { id: ids.get(end.id), ...(end.pos ? { pos: end.pos } : {}) }; + else if (end.id) { + // The other end was not copied: it becomes a free point near where it was. + const at = this.endPoint(end); + fields[side] = { x: at[0] + dx, y: at[1] + dy }; + } else fields[side] = { x: (end.x ?? 0) + dx, y: (end.y ?? 0) + dy }; + } + } + for (const k of Object.keys(fields)) if (fields[k] === undefined || fields[k] === "") delete fields[k]; + this.add( + { ...(fields as Partial), id, type: el.type }, + Array.isArray(raw.body) ? raw.body : undefined, + ); + out.push(id); + } + }); + return out; + } + + /** Replaces the whole canvas with a JSON snapshot (read-only views of a share link or the phone). */ + load(list: ElementJSON[]): void { + this.transact(() => { + for (const k of [...this.map.keys()]) this.map.delete(k); + for (const raw of list) { + const el = normalize(raw); + if (!el || !raw.id) continue; + const fields: Record = { ...(el as unknown as Record) }; + const id = String(raw.id); + delete fields.id; + for (const k of Object.keys(fields)) if (fields[k] === "") delete fields[k]; + this.add( + { ...(fields as Partial), id, type: el.type }, + Array.isArray(raw.body) ? raw.body : undefined, + ); + } + }); + } +} + +function nodeToY(n: MindmapNode): YItem { + const m = new Y.Map(); + m.set("text", n.text); + m.set("parent", n.parent); + m.set("pos", n.pos); + return m; +} + +function sameValue(a: unknown, b: unknown): boolean { + if (a === b) return true; + if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false; + return JSON.stringify(a) === JSON.stringify(b); +} diff --git a/Packages/canvas/src/ui.ts b/Packages/canvas/src/ui.ts new file mode 100644 index 0000000..f789ce6 --- /dev/null +++ b/Packages/canvas/src/ui.ts @@ -0,0 +1,675 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The canvas's controls: the tool bar at the bottom, the zoom buttons, and +// the style bar over the selection. Plain DOM, like the database block, so +// the phone's editor page can use the same canvas without Vue. + +import { iconPaths, type IconName } from "@docwell/ui/icons"; +import { + arrowKinds, + connectorModes, + mindmapLayouts, + palette, + shapeKinds, + type CanvasElement, + type Color, +} from "./model"; +import { stickers, templates, type TemplateId } from "./library"; +import type { CanvasView, Tool } from "./view"; + +const icon = (name: IconName, size = 18) => + ``; + +const shapeIcons: Record = { + rect: '', + roundrect: '', + ellipse: '', + diamond: '', + triangle: '', + straight: '', + curve: '', + elbow: '', + none: '', + arrow: '', + triangleEnd: '', + circle: '', + diamondEnd: '', + solid: '', + dash: '', + noLine: '', + right: + '', + left: '', + radial: + '', +}; +const drawn = (key: string) => + ``; + +function swatchStyle(c: Color): string { + if (c === "none") return "background:transparent"; + if (c === "ink") return "background:var(--dw-ink)"; + if (c === "paper") return "background:var(--dw-surface)"; + return `background:var(--dw-c-${c})`; +} + +export class CanvasUI { + private readonly bar: HTMLElement; + private readonly zoomBox: HTMLElement; + private readonly props: HTMLElement; + private readonly zoomLabel: HTMLButtonElement; + private pop: HTMLElement | null = null; + private popFor = ""; + private readonly fileInput: HTMLInputElement; + private lastProps = ""; + private readonly closePop = (e: PointerEvent) => { + if (this.pop && !this.pop.contains(e.target as Node) && !(e.target as Element).closest?.("[data-pop]")) + this.hidePop(); + }; + + constructor(private readonly v: CanvasView) { + const root = v.root; + this.bar = this.div("dw-cv-ui dw-cv-toolbar"); + this.bar.setAttribute("role", "toolbar"); + this.bar.setAttribute("aria-label", v.labels.toolbar); + this.zoomBox = this.div("dw-cv-ui dw-cv-zoom"); + this.props = this.div("dw-cv-ui dw-cv-props"); + this.props.setAttribute("role", "toolbar"); + this.zoomLabel = document.createElement("button"); + this.fileInput = document.createElement("input"); + this.fileInput.type = "file"; + this.fileInput.accept = "image/*"; + this.fileInput.multiple = true; + this.fileInput.hidden = true; + this.fileInput.addEventListener("change", () => { + const files = [...(this.fileInput.files ?? [])]; + this.fileInput.value = ""; + if (files.length) void v.addImages(files); + }); + root.append(this.bar, this.zoomBox, this.props, this.fileInput); + document.addEventListener("pointerdown", this.closePop, true); + this.buildZoom(); + this.refresh(); + } + + destroy(): void { + document.removeEventListener("pointerdown", this.closePop, true); + } + + private div(cls: string): HTMLElement { + const d = document.createElement("div"); + d.className = cls; + return d; + } + + private button( + html: string, + label: string, + run: () => void, + opts: { active?: boolean; pop?: string; cls?: string } = {}, + ): HTMLButtonElement { + const b = document.createElement("button"); + b.type = "button"; + b.className = `dw-cv-btn${opts.cls ? ` ${opts.cls}` : ""}`; + b.innerHTML = html; + b.title = label; + b.setAttribute("aria-label", label); + if (opts.active !== undefined) b.setAttribute("aria-pressed", String(opts.active)); + if (opts.pop) b.dataset.pop = opts.pop; + b.addEventListener("pointerdown", (e) => e.stopPropagation()); + b.addEventListener("click", (e) => { + e.stopPropagation(); + run(); + }); + return b; + } + + // ---- Tool bar ---- + + private buildBar(): void { + const v = this.v; + const l = v.labels; + this.bar.replaceChildren(); + this.bar.hidden = v.isPresenting; + if (!v.editable) { + this.bar.append( + this.button(icon("cursor"), l.select, () => v.setTool("select"), { active: v.tool === "select" }), + this.button(icon("hand"), l.hand, () => v.setTool("hand"), { active: v.tool === "hand" }), + this.sep(), + this.button(icon("present"), l.present, () => v.present()), + ); + return; + } + const tool = (t: Tool, name: IconName, label: string) => + this.button(icon(name), label, () => v.setTool(t), { active: v.tool === t }); + const shapeBtn = this.button( + drawn(v.shapeKind), + l.shape, + () => { + v.setTool("shape"); + this.togglePop("shape", shapeBtn, () => this.shapePop()); + }, + { active: v.tool === "shape", pop: "shape" }, + ); + const penBtn = this.button( + icon("pen"), + l.pen, + () => { + v.setTool("pen"); + this.togglePop("pen", penBtn, () => this.penPop()); + }, + { active: v.tool === "pen", pop: "pen" }, + ); + const conBtn = this.button( + icon("connector"), + l.connector, + () => { + v.setTool("connector"); + this.togglePop("connector", conBtn, () => this.connectorPop()); + }, + { active: v.tool === "connector", pop: "connector" }, + ); + const libBtn = this.button( + icon("sticker"), + l.library, + () => this.togglePop("library", libBtn, () => this.libraryPop()), + { + pop: "library", + }, + ); + this.bar.append( + tool("select", "cursor", l.select), + tool("hand", "hand", l.hand), + this.sep(), + tool("note", "note", l.note), + tool("text", "type", l.text), + shapeBtn, + conBtn, + penBtn, + tool("eraser", "eraser", l.eraser), + tool("frame", "frame", l.frame), + tool("mindmap", "mindmap", l.mindmap), + this.button(icon("image"), l.image, () => this.pickImage()), + this.button(icon("link"), l.link, () => void v.addLink()), + libBtn, + this.sep(), + this.button(icon("present"), l.present, () => v.present()), + ); + } + + private sep(): HTMLElement { + return this.div("dw-cv-sep"); + } + + pickImage(): void { + if (this.v.editable && this.v.opts.files?.upload) this.fileInput.click(); + } + + // ---- Pop-up panels ---- + + private togglePop(id: string, anchor: HTMLElement, build: () => HTMLElement): void { + if (this.pop && this.popFor === id) return this.hidePop(); + this.hidePop(); + const p = build(); + p.classList.add("dw-cv-ui", "dw-cv-pop"); + p.addEventListener("pointerdown", (e) => e.stopPropagation()); + this.v.root.append(p); + this.pop = p; + this.popFor = id; + // Above the anchor, kept inside the canvas. + const r = this.v.root.getBoundingClientRect(); + const a = anchor.getBoundingClientRect(); + const w = p.offsetWidth; + const h = p.offsetHeight; + let x = a.left - r.left + a.width / 2 - w / 2; + x = Math.max(8, Math.min(r.width - w - 8, x)); + let y = a.top - r.top - h - 8; + if (y < 8) y = a.bottom - r.top + 8; + p.style.left = `${x}px`; + p.style.top = `${y}px`; + } + + private hidePop(): void { + this.pop?.remove(); + this.pop = null; + this.popFor = ""; + } + + private row(...children: HTMLElement[]): HTMLElement { + const r = this.div("dw-cv-row"); + r.append(...children); + return r; + } + + private colorRow(current: Color, pick: (c: Color) => void, withNone: boolean, title: string): HTMLElement { + const r = this.div("dw-cv-row dw-cv-colors"); + r.setAttribute("role", "group"); + r.setAttribute("aria-label", title); + const l = this.v.labels; + const list: Color[] = ["ink", ...palette, ...(withNone ? (["paper", "none"] as Color[]) : [])]; + for (const c of list) { + const name = + c === "ink" ? l.colorInk : c === "paper" ? l.colorPaper : c === "none" ? l.colorNone : (l.colors[c] ?? c); + const b = this.button( + ``, + name, + () => { + pick(c); + this.lastProps = ""; + this.refresh(); + }, + { active: c === current }, + ); + r.append(b); + } + return r; + } + + private shapePop(): HTMLElement { + const v = this.v; + const l = v.labels; + const p = this.div(""); + p.append( + this.row( + ...shapeKinds.map((k) => + this.button( + drawn(k), + l[k], + () => { + v.setShapeKind(k); + this.hidePop(); + }, + { active: v.shapeKind === k }, + ), + ), + ), + this.row( + this.button( + `${l.general}`, + l.general, + () => { + v.setStyle("shape", { rough: false }); + this.hidePop(); + }, + { active: !v.styles.shape.rough }, + ), + this.button( + `${l.scribbled}`, + l.scribbled, + () => { + v.setStyle("shape", { rough: true }); + this.hidePop(); + }, + { active: v.styles.shape.rough }, + ), + ), + ); + return p; + } + + private penPop(): HTMLElement { + const v = this.v; + const p = this.div(""); + p.append( + this.colorRow(v.styles.brush.color, (c) => v.setStyle("brush", { color: c }), false, v.labels.stroke), + this.row( + ...[2, 4, 8, 14].map((s) => + this.button( + ``, + `${v.labels.thickness} ${s}`, + () => { + v.setStyle("brush", { size: s }); + this.hidePop(); + }, + { active: v.styles.brush.size === s }, + ), + ), + ), + ); + return p; + } + + private connectorPop(): HTMLElement { + const v = this.v; + const p = this.div(""); + p.append( + this.row( + ...connectorModes.map((m) => + this.button( + drawn(m), + v.labels[m], + () => { + v.setStyle("connector", { mode: m }); + this.hidePop(); + }, + { active: v.styles.connector.mode === m }, + ), + ), + ), + ); + return p; + } + + private libraryPop(): HTMLElement { + const v = this.v; + const l = v.labels; + const p = this.div("dw-cv-library"); + const h1 = this.div("dw-cv-poptitle"); + h1.textContent = l.stickers; + const grid = this.div("dw-cv-stickers"); + for (const s of stickers) { + grid.append( + this.button(`${s}`, s, () => { + v.insertSticker(s); + this.hidePop(); + }), + ); + } + const h2 = this.div("dw-cv-poptitle"); + h2.textContent = l.templates; + const list = this.div("dw-cv-templates"); + const names: Record = { + kanban: l.templateKanban, + swot: l.templateSwot, + flow: l.templateFlow, + brainstorm: l.templateBrainstorm, + retro: l.templateRetro, + }; + for (const t of templates) { + const b = this.button( + `${names[t]}`, + names[t], + () => { + v.insertTemplate(t); + this.hidePop(); + }, + { cls: "dw-cv-wide" }, + ); + list.append(b); + } + p.append(h1, grid, h2, list); + return p; + } + + // ---- Zoom ---- + + private buildZoom(): void { + const v = this.v; + const l = v.labels; + this.zoomLabel.type = "button"; + this.zoomLabel.className = "dw-cv-btn dw-cv-zoomlabel"; + this.zoomLabel.title = l.zoomReset; + this.zoomLabel.addEventListener("pointerdown", (e) => e.stopPropagation()); + this.zoomLabel.addEventListener("click", () => v.zoomAt(1)); + this.zoomBox.append( + this.button(icon("zoom-out"), l.zoomOut, () => v.zoomBy(0.8)), + this.zoomLabel, + this.button(icon("zoom-in"), l.zoomIn, () => v.zoomBy(1.25)), + this.button(icon("fit"), l.zoomFit, () => v.fit()), + ); + } + + zoomChanged(): void { + this.zoomLabel.textContent = `${Math.round(this.v.zoom * 100)}%`; + } + + // ---- The style bar over the selection ---- + + refresh(): void { + this.buildBar(); + const sel = this.v.editable && !this.v.editing && !this.v.isPresenting ? this.v.selection() : []; + const key = JSON.stringify([sel, this.v.activeNode, this.v.styles.shape.rough]); + if (key !== this.lastProps) { + this.lastProps = key; + this.buildProps(sel); + } + this.place(); + } + + place(): void { + const p = this.props; + if (p.hidden) return; + const b = this.v.selectionScreenBox(); + if (!b) { + p.hidden = true; + return; + } + const r = this.v.root.getBoundingClientRect(); + const w = p.offsetWidth; + const h = p.offsetHeight; + let x = b.x + b.w / 2 - w / 2; + x = Math.max(8, Math.min(r.width - w - 8, x)); + let y = b.y - h - 40; + if (y < 8) y = Math.min(r.height - h - 64, b.y + b.h + 16); + p.style.left = `${x}px`; + p.style.top = `${Math.max(8, y)}px`; + } + + private buildProps(sel: CanvasElement[]): void { + const p = this.props; + p.replaceChildren(); + if (!sel.length) { + p.hidden = true; + return; + } + p.hidden = false; + const v = this.v; + const l = v.labels; + const types = new Set(sel.map((e) => e.type)); + const one = types.size === 1 ? sel[0]! : null; + const group: HTMLElement[] = []; + const menu = (id: string, html: string, label: string, build: () => HTMLElement) => { + const b: HTMLButtonElement = this.button(html, label, () => this.togglePop(id, b, build), { pop: id }); + group.push(b); + }; + const colorMenu = (id: string, label: string, current: Color, field: string, withNone: boolean) => + menu( + id, + ``, + label, + () => { + const d = this.div(""); + d.append(this.colorRow(current, (c) => v.restyle({ [field]: c }), withNone, label)); + return d; + }, + ); + const choice = ( + id: string, + label: string, + current: T, + list: readonly T[], + art: (x: T) => string, + field: string, + names: (x: T) => string, + parse: (x: T) => unknown = (x) => x, + ) => + menu(id, art(current), label, () => { + const d = this.div(""); + d.append( + this.row( + ...list.map((x) => + this.button( + art(x), + names(x), + () => { + v.restyle({ [field]: parse(x) }); + this.hidePop(); + this.lastProps = ""; + this.refresh(); + }, + { active: x === current }, + ), + ), + ), + ); + return d; + }); + const toggle = (html: string, label: string, on: boolean, run: () => void) => + group.push(this.button(html, label, run, { active: on })); + + if (one?.type === "shape") { + choice("kind", l.shape, one.shape, shapeKinds, drawn, "shape", (k) => l[k]); + colorMenu("fill", l.fill, one.fill, "fill", true); + colorMenu("stroke", l.stroke, one.stroke, "stroke", true); + choice( + "style", + l.lineStyle, + one.strokeStyle, + ["solid", "dash", "none"] as const, + (s) => drawn(s === "none" ? "noLine" : s), + "strokeStyle", + (s) => (s === "none" ? l.noLine : l[s]), + ); + choice( + "width", + l.thickness, + String(one.strokeWidth) as "2", + ["1", "2", "4", "6"] as const, + (s) => ``, + "strokeWidth", + (s) => `${l.thickness} ${s}`, + Number, + ); + toggle(`${l.scribbled}`, l.scribbled, one.rough, () => { + v.restyle({ rough: !one.rough }); + this.lastProps = ""; + this.refresh(); + }); + colorMenu("textColor", l.textColor, one.textColor, "textColor", false); + } else if (one?.type === "connector") { + choice("mode", l.connector, one.mode, connectorModes, drawn, "mode", (m) => l[m]); + colorMenu("stroke", l.stroke, one.stroke, "stroke", false); + choice( + "style", + l.lineStyle, + one.strokeStyle === "none" ? "solid" : one.strokeStyle, + ["solid", "dash"] as const, + drawn, + "strokeStyle", + (s) => l[s], + ); + const art = (a: string) => drawn(a === "triangle" ? "triangleEnd" : a === "diamond" ? "diamondEnd" : a); + choice( + "start", + l.startArrow, + one.startArrow, + arrowKinds, + (a) => `${art(a)}`, + "startArrow", + (a) => a, + ); + choice("end", l.endArrow, one.endArrow, arrowKinds, art, "endArrow", (a) => a); + } else if (one?.type === "brush") { + colorMenu("color", l.stroke, one.color, "color", false); + } else if (one?.type === "text") { + colorMenu("color", l.textColor, one.color, "color", false); + choice( + "size", + l.fontSize, + String(one.fontSize) as "24", + ["16", "24", "32", "48", "64"] as const, + (s) => `${s}`, + "fontSize", + (s) => `${l.fontSize} ${s}`, + Number, + ); + choice( + "font", + l.font, + one.font || "sans", + ["sans", "serif", "mono"] as const, + (f) => `Aa`, + "font", + (f) => l[f], + (f) => (f === "sans" ? "" : f), + ); + choice( + "align", + l.alignLeft, + one.align, + ["left", "center", "right"] as const, + (a) => icon(`align-${a}` as IconName), + "align", + (a) => l[a === "left" ? "alignLeft" : a === "center" ? "alignCenter" : "alignRight"], + ); + toggle(icon("bold"), l.bold, one.bold, () => { + v.restyle({ bold: !one.bold }); + this.lastProps = ""; + this.refresh(); + }); + } else if (one?.type === "note") { + colorMenu("bg", l.background, one.background, "background", true); + } else if (one?.type === "frame") { + colorMenu("bg", l.background, one.background, "background", true); + } else if (one?.type === "mindmap") { + choice( + "layout", + l.layout, + one.layout, + mindmapLayouts, + (x) => drawn(x), + "layout", + (x) => l[x === "right" ? "layoutRight" : x === "left" ? "layoutLeft" : "layoutRadial"], + ); + colorMenu("color", l.stroke, one.color, "color", false); + if (v.activeNode?.map === one.id) { + group.push( + this.button(`+ ${l.addChild}`, l.addChild, () => v.mindmapAdd("child"), { + cls: "dw-cv-wide", + }), + ); + } + } else if (one?.type === "embed" && sel.length === 1) { + group.push(this.button(icon("open"), l.openLink, () => window.open(one.url, "_blank", "noopener,noreferrer"))); + } + p.append(...group); + if (group.length) p.append(this.sep()); + const groups = sel.filter((e) => e.type === "group"); + if (sel.length > 1 && !groups.length) p.append(this.button(icon("group"), l.group, () => v.group())); + if (groups.length) p.append(this.button(icon("layers"), l.ungroup, () => v.ungroup())); + const pageOnly = sel.every((e) => e.type === "note" && e.page); + p.append( + this.button(icon("arrow-up"), l.bringFront, () => v.reorder("front")), + this.button(icon("send-back"), l.sendBack, () => v.reorder("back")), + ); + if (!pageOnly) { + p.append( + this.button(icon("copy"), l.duplicate, () => v.duplicate()), + this.button(icon("trash"), l.delete, () => v.deleteSelection(), { cls: "dw-cv-danger" }), + ); + } + } + + // ---- Messages and presenting ---- + + toast(text: string): void { + const t = this.div("dw-cv-ui dw-cv-toast"); + t.setAttribute("role", "status"); + t.textContent = text; + this.v.root.append(t); + setTimeout(() => t.remove(), 2600); + } + + presentBar(): HTMLElement { + const v = this.v; + const l = v.labels; + const bar = this.div("dw-cv-ui dw-cv-presentbar"); + const step = this.div("dw-cv-step"); + step.setAttribute("aria-live", "polite"); + bar.append( + this.button(icon("chevron-left"), l.presentPrevious, () => v.presentStep(-1)), + step, + this.button(icon("chevron-right"), l.presentNext, () => v.presentStep(1)), + this.button(icon("close"), l.presentExit, () => v.stopPresenting()), + ); + v.root.append(bar); + this.hidePop(); + this.refresh(); + return bar; + } + + presentStep(i: number, total: number): void { + const s = this.v.root.querySelector(".dw-cv-step"); + if (s) s.textContent = this.v.labels.presentStep.replace("{n}", String(i + 1)).replace("{total}", String(total)); + } +} diff --git a/Packages/canvas/src/view.ts b/Packages/canvas/src/view.ts new file mode 100644 index 0000000..cd65fd5 --- /dev/null +++ b/Packages/canvas/src/view.ts @@ -0,0 +1,2139 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The edgeless canvas on screen (ADR-14). Every element is one absolutely +// placed box in a single layer that pans and zooms with a CSS transform, +// in drawing order; selection handles and guides are drawn in screen units +// on an overlay above it. Notes are mounted by the host (Tiptap editors). + +import type * as Y from "yjs"; +import { + boxOf as boxFrom, + center, + containsBox, + distToPolyline, + intersects, + rotatePoint, + rotatedBox, + resolveEnds, + route, + snap, + snapToAnchor, + union, + type Box, + type Guide, + type Point, + type Route, +} from "./geometry"; +import { englishCanvasLabels, type CanvasLabels } from "./labels"; +import { sticker, template, type TemplateId } from "./library"; +import { fontFamily, nodeSize } from "./measure"; +import { childrenOf, edgePath, layoutMindmap, neighbour, rootOf, type MindmapLayoutResult } from "./mindmap"; +import { + connectable, + readStyles, + resizable, + rotatable, + type CanvasElement, + type ConnectorElement, + type ElementOf, + type End, + type MindmapElement, + type ShapeKind, + type StyleDefaults, +} from "./model"; +import { brushPath, brushSVG, connectorSVG, esc, livePaint, shapeSVG } from "./render"; +import { SurfaceStore, type ElementJSON } from "./store"; +import { CanvasUI } from "./ui"; +import { exportCanvas, type ExportKind } from "./export"; + +/** A note mounted by the host: the page's text or a note body, as an editor. */ +export interface NoteMount { + id: string; + /** The page's own text: the document's "default" fragment. */ + page: boolean; + fragment: Y.XmlFragment; + doc: Y.Doc; + editable: boolean; +} + +export interface NoteHandle { + destroy(): void; + focus(): void; + setEditable(editable: boolean): void; +} + +export interface NoteHost { + mount(el: HTMLElement, note: NoteMount): NoteHandle; +} + +export interface CanvasFiles { + resolve(src: string): string; + upload?(file: File): Promise<{ url: string; name: string; mime: string }>; +} + +export interface CanvasLinks { + preview(url: string): Promise<{ url: string; title?: string; description?: string; image?: string; site?: string }>; +} + +export interface CanvasOptions { + doc: Y.Doc; + editable: boolean; + notes: NoteHost; + labels?: CanvasLabels; + files?: CanvasFiles; + links?: CanvasLinks; + /** The player address for an embeddable link (the editor's embedSource). */ + embedSource?: (url: string) => { src: string; ratio: string } | null; + /** Styles new elements start with; changed when someone restyles an element. */ + styles?: StyleDefaults; + onStyles?: (styles: StyleDefaults) => void; + /** Keeps the view (pan and zoom) on this device under this key. */ + viewKey?: string; + /** The page's title, shown on the page's note. */ + pageTitle?: () => string; + /** Tracks undo for canvas edits (off for read-only snapshots). */ + undo?: boolean; + onError?: (e: unknown) => void; +} + +export type Tool = "select" | "hand" | "note" | "text" | "shape" | "connector" | "pen" | "eraser" | "frame" | "mindmap"; + +interface Rendered { + el: HTMLElement; + key: string; + type: CanvasElement["type"]; + note?: NoteHandle; +} + +type Handle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w"; + +type Drag = + | { kind: "pan"; sx: number; sy: number; vx: number; vy: number } + | { + kind: "move"; + start: Point; + ids: string[]; + orig: Map; + box: Box; + moved: boolean; + clickId: string; + } + | { kind: "marquee"; start: Point; add: boolean; base: Set } + | { kind: "resize"; handle: Handle; box: Box; deg: number; orig: Map; keep: boolean } + | { kind: "rotate"; id: string; c: Point; a0: number; r0: number } + | { kind: "create"; type: "shape" | "frame"; start: Point; id: string | null } + | { kind: "end"; id: string; side: "source" | "target" } + | { kind: "pen"; points: number[][]; temp: SVGSVGElement } + | { kind: "erase"; hits: Set }; + +const ZOOM_MIN = 0.1; +const ZOOM_MAX = 4; +const SVG_NS = "http://www.w3.org/2000/svg"; + +const isEditable = (t: EventTarget | null) => + t instanceof HTMLElement && (t.isContentEditable || t.tagName === "INPUT" || t.tagName === "TEXTAREA"); + +export class CanvasView { + readonly store: SurfaceStore; + readonly labels: CanvasLabels; + readonly root: HTMLElement; + styles: StyleDefaults; + editable: boolean; + tool: Tool = "select"; + shapeKind: ShapeKind; + readonly selected = new Set(); + /** The mind map node picked inside a selected mind map. */ + activeNode: { map: string; node: string } | null = null; + /** The element being typed in (a note, a label, a text box, a node). */ + editing: { id: string; node?: string } | null = null; + /** A group opened with a double click: its members are picked one by one. */ + private entered: string | null = null; + readonly world: HTMLElement; + private readonly overlay: SVGSVGElement; + private readonly ui: CanvasUI; + private view = { x: 0, y: 0, zoom: 1 }; + private rendered = new Map(); + private measured = new Map(); + private layouts = new Map(); + private routes = new Map(); + private previews = new Map> | "loading" | null>(); + private drag: Drag | null = null; + private guides: Guide[] = []; + private marquee: Box | null = null; + private hover: string | null = null; + private raf = 0; + private spaceDown = false; + private pointers = new Map(); + private pinch: { dist: number; mid: Point; zoom: number; vx: number; vy: number } | null = null; + private presenting: { frames: string[]; at: number; bar: HTMLElement } | null = null; + // Missing in some test environments; sizes then come from the stored boxes. + private readonly resize = + typeof ResizeObserver === "undefined" ? null : new ResizeObserver((entries) => this.onResize(entries)); + private readonly unsub: () => void; + private readonly cleanups: (() => void)[] = []; + private saveTimer: ReturnType | undefined; + + constructor( + host: HTMLElement, + readonly opts: CanvasOptions, + ) { + this.labels = opts.labels ?? englishCanvasLabels; + this.editable = opts.editable; + this.styles = readStyles(opts.styles); + this.shapeKind = this.styles.shape.shape; + this.store = new SurfaceStore(opts.doc, { undo: opts.undo !== false }); + this.root = document.createElement("div"); + this.root.className = "dw-cv"; + this.root.tabIndex = 0; + this.root.setAttribute("role", "application"); + this.root.dataset.testid = "edgeless-canvas"; + this.world = document.createElement("div"); + this.world.className = "dw-cv-world"; + this.overlay = document.createElementNS(SVG_NS, "svg"); + this.overlay.classList.add("dw-cv-overlay"); + this.root.append(this.world, this.overlay); + host.append(this.root); + this.ui = new CanvasUI(this); + this.root.classList.toggle("dw-cv-readonly", !this.editable); + this.unsub = this.store.onChange(() => this.schedule()); + this.listen(); + this.render(); + if (!this.restoreView()) this.fit(undefined, false); + this.applyView(); + } + + destroy(): void { + cancelAnimationFrame(this.raf); + clearTimeout(this.saveTimer); + this.saveView(); + this.unsub(); + this.resize?.disconnect(); + for (const c of this.cleanups) c(); + for (const r of this.rendered.values()) r.note?.destroy(); + this.rendered.clear(); + this.ui.destroy(); + this.store.destroy(); + this.root.remove(); + } + + setEditable(editable: boolean): void { + if (editable === this.editable) return; + this.editable = editable; + this.root.classList.toggle("dw-cv-readonly", !editable); + if (!editable) { + this.stopEditing(); + this.tool = "select"; + } + for (const r of this.rendered.values()) r.note?.setEditable(editable); + this.ui.refresh(); + } + + // ---- Elements and their boxes ---- + + get(id: string): CanvasElement | undefined { + return this.store.get(id); + } + + elements(): CanvasElement[] { + return this.store.elements(); + } + + /** An element's box, measured where it sizes itself (notes, text, mind maps). */ + boxOf(e: CanvasElement): Box { + switch (e.type) { + case "note": { + const m = this.measured.get(e.id); + return { x: e.x, y: e.y, w: e.w, h: m?.h ?? e.h }; + } + case "text": { + const m = this.measured.get(e.id); + return { x: e.x, y: e.y, w: m?.w ?? e.w, h: m?.h ?? e.h }; + } + case "group": + return ( + union( + this.elements() + .filter((m) => m.group === e.id) + .map((m) => this.outerBox(m)), + ) ?? { x: e.x, y: e.y, w: 0, h: 0 } + ); + case "mindmap": { + const l = this.layoutOf(e); + return { x: e.x + l.bounds.x, y: e.y + l.bounds.y, w: l.bounds.w, h: l.bounds.h }; + } + case "connector": { + const r = this.routeOf(e); + const xs = r.points.map((p) => p[0]); + const ys = r.points.map((p) => p[1]); + return boxFrom([Math.min(...xs), Math.min(...ys)], [Math.max(...xs), Math.max(...ys)]); + } + default: + return { x: e.x, y: e.y, w: e.w, h: e.h }; + } + } + + /** The axis-aligned box an element covers, rotation included. */ + outerBox(e: CanvasElement): Box { + const b = this.boxOf(e); + return e.rotate ? rotatedBox(b, e.rotate) : b; + } + + layoutOf(e: MindmapElement): MindmapLayoutResult { + let l = this.layouts.get(e.id); + const key = JSON.stringify([e.layout, e.nodes]); + if (!l || (l as MindmapLayoutResult & { key?: string }).key !== key) { + l = layoutMindmap(e.nodes, e.layout, nodeSize); + (l as MindmapLayoutResult & { key?: string }).key = key; + this.layouts.set(e.id, l); + } + return l; + } + + routeOf(c: ConnectorElement): Route { + const ends = resolveEnds(c, (id) => { + const t = this.get(id); + if (!t || t.type === "connector") return null; + return { box: this.outerBox(t), ellipse: t.type === "shape" && t.shape === "ellipse" }; + }); + return route(c.mode, ends[0], ends[1]); + } + + /** The selected elements, groups as themselves. */ + selection(): CanvasElement[] { + return [...this.selected].map((id) => this.get(id)).filter((e): e is CanvasElement => !!e); + } + + /** The selected elements with their group members, for moving and copying. */ + private expanded(ids: Iterable): string[] { + const out = new Set(); + const all = this.elements(); + for (const id of ids) { + out.add(id); + for (const e of all) if (e.group === id) out.add(e.id); + } + return [...out]; + } + + // ---- Rendering ---- + + schedule(): void { + if (this.raf) return; + this.raf = requestAnimationFrame(() => { + this.raf = 0; + this.render(); + }); + } + + private render(): void { + const list = this.elements(); + const seen = new Set(); + let prev: Element | null = null; + for (const e of list) { + seen.add(e.id); + let r = this.rendered.get(e.id); + if (r && r.type !== e.type) { + r.note?.destroy(); + r.el.remove(); + r = undefined; + } + if (!r) { + r = { el: document.createElement("div"), key: "", type: e.type }; + r.el.className = `dw-cv-el dw-cv-${e.type}`; + r.el.dataset.id = e.id; + this.rendered.set(e.id, r); + if (e.type === "note" || e.type === "text") this.resize?.observe(r.el); + } + const key = this.keyOf(e); + // Redrawing would replace the box someone is typing in and take their + // focus; it is redrawn when they finish (notes edit in place). + if (r.key !== key && (this.editing?.id !== e.id || !this.stopEditingFn || e.type === "note")) { + this.draw(r, e); + r.key = key; + } + r.el.classList.toggle("dw-cv-selected", this.selected.has(e.id)); + r.el.classList.toggle("dw-cv-editing", this.editing?.id === e.id); + // Keep DOM order equal to drawing order. + const want: Element | null = prev ? prev.nextElementSibling : this.world.firstElementChild; + if (want !== r.el) this.world.insertBefore(r.el, want); + prev = r.el; + } + for (const [id, r] of this.rendered) { + if (seen.has(id)) continue; + r.note?.destroy(); + this.resize?.unobserve(r.el); + r.el.remove(); + this.rendered.delete(id); + this.measured.delete(id); + this.selected.delete(id); + } + if (this.editing && !seen.has(this.editing.id)) this.editing = null; + this.drawOverlay(); + this.ui.refresh(); + } + + /** What an element's drawing depends on; it is redrawn when this changes. */ + private keyOf(e: CanvasElement): string { + if (e.type === "connector") { + const r = this.routeOf(e); + this.routes.set(e.id, r); + return JSON.stringify(e) + r.d; + } + if (e.type === "note" && e.page) return JSON.stringify(e) + (this.opts.pageTitle?.() ?? ""); + return JSON.stringify(e); + } + + private place(el: HTMLElement, b: Box, rotate = 0, autoSize = false): void { + el.style.transform = `translate(${b.x}px, ${b.y}px)${rotate ? ` rotate(${rotate}deg)` : ""}`; + el.style.width = autoSize ? "" : `${b.w}px`; + el.style.height = autoSize ? "" : `${b.h}px`; + } + + private draw(r: Rendered, e: CanvasElement): void { + const el = r.el; + const editingThis = this.editing?.id === e.id; + switch (e.type) { + case "shape": { + this.place(el, e, e.rotate); + const label = editingThis ? el.querySelector(".dw-cv-label") : null; + el.innerHTML = `${shapeSVG(e, livePaint)}`; + const l = label ?? document.createElement("div"); + l.className = "dw-cv-label"; + if (!label) l.textContent = e.text; + l.style.color = livePaint(e.textColor, "line"); + l.style.fontSize = `${e.fontSize}px`; + el.append(l); + return; + } + case "text": { + el.style.transform = `translate(${e.x}px, ${e.y}px)${e.rotate ? ` rotate(${e.rotate}deg)` : ""}`; + el.style.width = e.w ? `${e.w}px` : ""; + el.style.height = ""; + let t = el.querySelector(".dw-cv-textbody"); + if (!t) { + t = document.createElement("div"); + t.className = "dw-cv-textbody"; + el.append(t); + } + if (!editingThis) t.textContent = e.text; + t.dataset.placeholder = this.labels.textPlaceholder; + Object.assign(t.style, { + color: livePaint(e.color, "line"), + fontSize: `${e.fontSize}px`, + fontFamily: fontFamily(e.font), + textAlign: e.align, + fontWeight: e.bold ? "650" : "", + whiteSpace: e.w ? "pre-wrap" : "pre", + }); + return; + } + case "connector": { + const rt = this.routes.get(e.id) ?? this.routeOf(e); + const b = this.boxOf(e); + const pad = 24 + e.strokeWidth * 3; + const box = { x: b.x - pad, y: b.y - pad, w: b.w + pad * 2, h: b.h + pad * 2 }; + this.place(el, box); + const hit = ``; + const label = e.label || editingThis; + el.innerHTML = + `${connectorSVG(e, rt, livePaint)}${hit}` + + (label + ? `
${esc(e.label)}
` + : ""); + return; + } + case "brush": { + this.place(el, e, e.rotate); + el.innerHTML = `${brushSVG(e, livePaint).replace("`; + return; + } + case "note": + this.drawNote(r, e); + return; + case "frame": { + this.place(el, e); + const title = editingThis ? el.querySelector(".dw-cv-frametitle") : null; + el.innerHTML = ``; + const t = title ?? document.createElement("div"); + t.className = "dw-cv-frametitle"; + if (!title) t.textContent = e.title || this.labels.frameTitle; + el.append(t); + return; + } + case "image": { + this.place(el, e, e.rotate); + const src = this.opts.files?.resolve(e.src) ?? e.src; + let img = el.querySelector("img"); + if (!img) { + img = document.createElement("img"); + img.draggable = false; + el.replaceChildren(img); + } + if (img.getAttribute("src") !== src) img.src = src; + img.alt = e.alt; + return; + } + case "embed": + this.drawEmbed(el, e); + return; + case "group": + el.style.display = "none"; + return; + case "mindmap": + this.drawMindmap(el, e); + return; + } + } + + private drawNote(r: Rendered, e: ElementOf<"note">): void { + const el = r.el; + el.style.transform = `translate(${e.x}px, ${e.y}px)`; + el.style.width = `${e.w}px`; + el.style.height = ""; + el.style.setProperty("--dw-cv-note-bg", livePaint(e.background, "fill")); + el.classList.toggle("dw-cv-pagenote", e.page); + if (!r.note) { + const head = document.createElement("div"); + head.className = "dw-cv-notehead"; + const body = document.createElement("div"); + body.className = "dw-cv-notebody"; + el.replaceChildren(head, body); + const fragment = e.page ? this.opts.doc.getXmlFragment("default") : this.store.body(e.id); + if (fragment) { + try { + r.note = this.opts.notes.mount(body, { + id: e.id, + page: e.page, + fragment, + doc: this.opts.doc, + editable: this.editable, + }); + } catch (err) { + this.opts.onError?.(err); + } + } + } + const head = el.querySelector(".dw-cv-notehead"); + if (head) head.textContent = e.page ? this.opts.pageTitle?.() || this.labels.pageNote : ""; + } + + private drawEmbed(el: HTMLElement, e: ElementOf<"embed">): void { + this.place(el, e); + const player = this.opts.embedSource?.(e.url) ?? null; + if (player) { + const frame = el.querySelector("iframe"); + if (frame?.getAttribute("src") === player.src) return; + const f = document.createElement("iframe"); + f.src = player.src; + f.title = e.url; + f.allow = "fullscreen; picture-in-picture; encrypted-media"; + f.referrerPolicy = "strict-origin-when-cross-origin"; + f.setAttribute("sandbox", "allow-scripts allow-same-origin allow-popups allow-presentation"); + el.replaceChildren(f); + return; + } + let p = this.previews.get(e.url); + if (p === undefined && this.opts.links) { + this.previews.set(e.url, "loading"); + this.opts.links + .preview(e.url) + .then((v) => this.previews.set(e.url, v)) + .catch(() => this.previews.set(e.url, null)) + .finally(() => { + const r = this.rendered.get(e.id); + if (r) r.key = ""; + this.schedule(); + }); + p = "loading"; + } + const info = p && p !== "loading" ? p : null; + let host = e.url; + try { + host = new URL(e.url).hostname; + } catch { + // shown as typed + } + const img = info?.image ? `` : ""; + el.innerHTML = `${img}${esc(info?.title || host)}${info?.description ? `${esc(info.description)}` : ""}${esc(info?.site || host)}`; + } + + private drawMindmap(el: HTMLElement, e: MindmapElement): void { + const l = this.layoutOf(e); + const b = l.bounds; + this.place(el, { x: e.x + b.x, y: e.y + b.y, w: b.w, h: b.h }); + const line = livePaint(e.color, "line"); + const fill = livePaint(e.color, "fill"); + const edges = l.edges + .map((g) => ``) + .join(""); + const editingNode = this.editing?.id === e.id ? this.editing.node : undefined; + const keep = editingNode ? el.querySelector(`[data-node="${editingNode}"]`) : null; + const nodes = [...l.boxes.values()].map((n) => { + const cls = n.depth === 0 ? "dw-cv-node dw-cv-root" : "dw-cv-node"; + const active = this.activeNode?.map === e.id && this.activeNode.node === n.id ? " dw-cv-active" : ""; + const style = `left:${n.x - b.x}px;top:${n.y - b.y}px;width:${n.w}px;height:${n.h}px;${n.depth === 0 ? `background:${line};color:var(--dw-surface)` : n.depth === 1 ? `background:${fill};border-color:${line}` : `border-color:${line}`}`; + return `
${esc(e.nodes[n.id]?.text ?? "")}
`; + }); + el.innerHTML = `${edges}${nodes.join("")}`; + if (keep && editingNode) el.querySelector(`[data-node="${editingNode}"]`)?.replaceWith(keep); + } + + private onResize(entries: ResizeObserverEntry[]): void { + let changed = false; + for (const en of entries) { + const el = en.target as HTMLElement; + const id = el.dataset.id; + if (!id) continue; + // offsetWidth is the box before the canvas's zoom, which is what we want. + const size = { w: el.offsetWidth, h: el.offsetHeight }; + const old = this.measured.get(id); + if (!old || old.w !== size.w || old.h !== size.h) { + this.measured.set(id, size); + changed = true; + } + } + if (!changed) return; + // Connectors stuck to a note follow its height. + for (const r of this.rendered.values()) if (r.type === "connector") r.key = ""; + this.schedule(); + } + + // ---- The overlay: selection, handles, guides ---- + + toScreen([x, y]: Point): Point { + return [x * this.view.zoom + this.view.x, y * this.view.zoom + this.view.y]; + } + + toWorld(clientX: number, clientY: number): Point { + const r = this.root.getBoundingClientRect(); + return [(clientX - r.left - this.view.x) / this.view.zoom, (clientY - r.top - this.view.y) / this.view.zoom]; + } + + get zoom(): number { + return this.view.zoom; + } + + /** The selection's box on screen, for placing the style bar. */ + selectionScreenBox(): Box | null { + const boxes = this.selection().map((e) => this.outerBox(e)); + const b = union(boxes); + if (!b) return null; + const [x, y] = this.toScreen([b.x, b.y]); + return { x, y, w: b.w * this.view.zoom, h: b.h * this.view.zoom }; + } + + private drawOverlay(): void { + const parts: string[] = []; + const z = this.view.zoom; + const poly = (b: Box, deg: number) => { + const c = center(b); + return ( + [ + [b.x, b.y], + [b.x + b.w, b.y], + [b.x + b.w, b.y + b.h], + [b.x, b.y + b.h], + ] as Point[] + ) + .map((p) => this.toScreen(rotatePoint(p, c, deg)).join(",")) + .join(" "); + }; + if (this.entered) { + const g = this.get(this.entered); + if (g) parts.push(``); + } + if (this.hover && this.hover !== this.editing?.id) { + const h = this.get(this.hover); + if (h) parts.push(``); + } + const sel = this.presenting ? [] : this.selection(); + for (const e of sel) { + if (e.type === "connector") { + const r = this.routes.get(e.id) ?? this.routeOf(e); + parts.push( + ``, + ); + continue; + } + parts.push(``); + } + const editable = this.editable && !this.presenting; + if (editable && sel.length && !this.editing) { + const single = sel.length === 1 ? sel[0]! : null; + if (single?.type === "connector") { + const r = this.routes.get(single.id) ?? this.routeOf(single); + for (const [side, p] of [ + ["source", r.points[0]!], + ["target", r.points[r.points.length - 1]!], + ] as const) { + const [x, y] = this.toScreen(p); + parts.push(``); + } + } else if (sel.some(resizable) && !(single?.type === "mindmap")) { + const deg = single ? single.rotate : 0; + const b = single ? this.boxOf(single) : union(sel.map((e) => this.outerBox(e)))!; + if (sel.length > 1) parts.push(``); + const c = center(b); + const handles: [Handle, Point][] = [ + ["nw", [b.x, b.y]], + ["n", [b.x + b.w / 2, b.y]], + ["ne", [b.x + b.w, b.y]], + ["e", [b.x + b.w, b.y + b.h / 2]], + ["se", [b.x + b.w, b.y + b.h]], + ["s", [b.x + b.w / 2, b.y + b.h]], + ["sw", [b.x, b.y + b.h]], + ["w", [b.x, b.y + b.h / 2]], + ]; + // Notes size their own height: only their sides resize. + const widthOnly = single?.type === "note"; + for (const [h, p] of handles) { + if (widthOnly && h !== "e" && h !== "w") continue; + if (b.w * z < 24 && (h === "n" || h === "s")) continue; + if (b.h * z < 24 && (h === "e" || h === "w")) continue; + const [x, y] = this.toScreen(rotatePoint(p, c, deg)); + parts.push( + ``, + ); + } + if (single && rotatable(single)) { + const [x, y] = this.toScreen(rotatePoint([b.x + b.w / 2, b.y - 28 / z], c, deg)); + parts.push(``); + } + } + } + if (this.marquee) { + const [x, y] = this.toScreen([this.marquee.x, this.marquee.y]); + parts.push( + ``, + ); + } + for (const g of this.guides) { + const a = this.toScreen(g.axis === "x" ? [g.value, g.from] : [g.from, g.value]); + const b = this.toScreen(g.axis === "x" ? [g.value, g.to] : [g.to, g.value]); + parts.push(``); + } + this.overlay.innerHTML = parts.join(""); + this.ui.place(); + } + + // ---- The view: pan and zoom ---- + + private applyView(): void { + const { x, y, zoom } = this.view; + this.world.style.transform = `translate(${x}px, ${y}px) scale(${zoom})`; + const grid = 24 * zoom; + this.root.style.backgroundSize = `${grid}px ${grid}px`; + this.root.style.backgroundPosition = `${x}px ${y}px`; + this.root.style.setProperty("--dw-cv-zoom", String(zoom)); + this.drawOverlay(); + this.ui.zoomChanged(); + clearTimeout(this.saveTimer); + this.saveTimer = setTimeout(() => this.saveView(), 500); + } + + private saveView(): void { + if (!this.opts.viewKey) return; + try { + localStorage.setItem(this.opts.viewKey, JSON.stringify(this.view)); + } catch { + // per-device convenience only + } + } + + private restoreView(): boolean { + if (!this.opts.viewKey) return false; + try { + const v = JSON.parse(localStorage.getItem(this.opts.viewKey) ?? "null") as typeof this.view | null; + if (v && [v.x, v.y, v.zoom].every((n) => typeof n === "number" && Number.isFinite(n)) && v.zoom > 0) { + this.view = { x: v.x, y: v.y, zoom: Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, v.zoom)) }; + return true; + } + } catch { + // per-device convenience only + } + return false; + } + + zoomAt(zoom: number, at?: Point): void { + const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom)); + const r = this.root.getBoundingClientRect(); + const [sx, sy] = at ?? [r.width / 2, r.height / 2]; + const wx = (sx - this.view.x) / this.view.zoom; + const wy = (sy - this.view.y) / this.view.zoom; + this.view = { zoom: z, x: sx - wx * z, y: sy - wy * z }; + this.applyView(); + } + + zoomBy(factor: number): void { + this.zoomAt(this.view.zoom * factor); + } + + /** Fits a box (by default everything) into the view. */ + fit(box?: Box, apply = true, pad = 48): void { + const b = box ?? union(this.elements().map((e) => this.outerBox(e))); + const r = this.root.getBoundingClientRect(); + const w = r.width || 800; + const h = r.height || 600; + if (!b) { + this.view = { x: w / 2, y: h / 3, zoom: 1 }; + } else { + const zoom = Math.min( + ZOOM_MAX, + Math.max( + ZOOM_MIN, + Math.min((w - pad * 2) / Math.max(b.w, 1), (h - pad * 2) / Math.max(b.h, 1), box ? ZOOM_MAX : 1), + ), + ); + this.view = { zoom, x: w / 2 - (b.x + b.w / 2) * zoom, y: h / 2 - (b.y + b.h / 2) * zoom }; + // A tall page note starts at its top, not its middle. + if (!box && b.h * zoom > h) this.view.y = pad - b.y * zoom; + } + if (apply) this.applyView(); + } + + private animateTo(target: typeof this.view): void { + const from = { ...this.view }; + const t0 = performance.now(); + const step = (t: number) => { + const k = Math.min(1, (t - t0) / 350); + const e = 1 - (1 - k) ** 3; + this.view = { + x: from.x + (target.x - from.x) * e, + y: from.y + (target.y - from.y) * e, + zoom: from.zoom + (target.zoom - from.zoom) * e, + }; + this.applyView(); + if (k < 1) requestAnimationFrame(step); + }; + requestAnimationFrame(step); + } + + // ---- Tools ---- + + setTool(tool: Tool): void { + if (!this.editable && tool !== "select" && tool !== "hand") return; + this.stopEditing(); + this.tool = tool; + if (tool !== "select") this.clearSelection(); + this.root.dataset.tool = tool; + this.ui.refresh(); + } + + setShapeKind(kind: ShapeKind): void { + this.shapeKind = kind; + this.setStyle("shape", { shape: kind }); + this.setTool("shape"); + } + + /** Changes the default style of a kind and tells the host. */ + setStyle(kind: K, patch: Partial): void { + this.styles = { ...this.styles, [kind]: { ...this.styles[kind], ...patch } }; + this.opts.onStyles?.(this.styles); + } + + /** Restyles the selection, and makes the style the default for its kinds. */ + restyle(patch: Record): void { + const patches: [string, Record][] = []; + for (const e of this.selection()) { + const fields = Object.fromEntries(Object.entries(patch).filter(([k]) => k in e)); + if (!Object.keys(fields).length) continue; + patches.push([e.id, fields]); + const kind = e.type as keyof StyleDefaults; + if (kind in this.styles) { + const known = Object.fromEntries(Object.entries(fields).filter(([k]) => k in this.styles[kind])); + if (Object.keys(known).length && !(e.type === "note" && e.page)) this.setStyle(kind, known as never); + } + } + this.store.updateMany(patches); + } + + select(ids: Iterable, add = false): void { + if (!add) this.selected.clear(); + for (const id of ids) this.selected.add(id); + if (this.activeNode && !this.selected.has(this.activeNode.map)) this.activeNode = null; + this.refreshSelection(); + } + + clearSelection(): void { + if (!this.selected.size && !this.activeNode && !this.entered) return; + this.selected.clear(); + this.activeNode = null; + this.entered = null; + this.refreshSelection(); + } + + private refreshSelection(): void { + for (const [id, r] of this.rendered) { + r.el.classList.toggle("dw-cv-selected", this.selected.has(id)); + if (r.type === "mindmap") r.key = ""; + } + this.schedule(); + this.drawOverlay(); + this.ui.refresh(); + } + + /** The element a click on id picks: its group unless the group is open. */ + private pick(id: string): string { + const e = this.get(id); + if (e?.group && this.entered !== e.group && this.get(e.group)) return e.group; + return id; + } + + /** The element (and mind map node) under an event, from the DOM. */ + private hit(target: EventTarget | null): { id: string; node?: string } | null { + if (!(target instanceof Element) || !this.world.contains(target)) return null; + const el = target.closest("[data-id]"); + if (!el?.dataset.id) return null; + const node = target.closest("[data-node]")?.dataset.node; + return { id: el.dataset.id, node }; + } + + /** The connectable element under a screen point, ignoring some ids. */ + private connectableAt(clientX: number, clientY: number, skip: Set): CanvasElement | null { + for (const t of document.elementsFromPoint(clientX, clientY)) { + const h = this.hit(t); + if (!h || skip.has(h.id)) continue; + const e = this.get(h.id); + if (e && connectable(e)) return e; + } + return null; + } + + // ---- Events ---- + + private listen(): void { + const on = ( + t: HTMLElement | Document | Window, + type: K, + fn: (e: HTMLElementEventMap[K]) => void, + o?: AddEventListenerOptions, + ) => { + t.addEventListener(type, fn as EventListener, o); + this.cleanups.push(() => t.removeEventListener(type, fn as EventListener, o)); + }; + on(this.root, "pointerdown", (e) => this.onDown(e)); + on(this.root, "pointermove", (e) => this.onMove(e)); + on(this.root, "pointerup", (e) => this.onUp(e)); + on(this.root, "pointercancel", (e) => this.onUp(e)); + on(this.root, "dblclick", (e) => this.onDouble(e)); + on(this.root, "wheel", (e) => this.onWheel(e), { passive: false }); + on(this.root, "keydown", (e) => this.onKey(e)); + on(this.root, "keyup", (e) => { + if (e.key === " ") { + this.spaceDown = false; + this.root.classList.remove("dw-cv-panning"); + } + }); + on(document, "copy", (e) => this.onCopy(e as ClipboardEvent, false)); + on(document, "cut", (e) => this.onCopy(e as ClipboardEvent, true)); + on(document, "paste", (e) => this.onPaste(e as ClipboardEvent)); + on(this.root, "dragover", (e) => { + if (this.editable && e.dataTransfer?.types.includes("Files")) e.preventDefault(); + }); + on(this.root, "drop", (e) => { + const files = [...(e.dataTransfer?.files ?? [])].filter((f) => f.type.startsWith("image/")); + if (!this.editable || !files.length) return; + e.preventDefault(); + void this.addImages(files, this.toWorld(e.clientX, e.clientY)); + }); + on(document, "fullscreenchange", () => { + if (!document.fullscreenElement && this.presenting) this.stopPresenting(); + }); + // Clicks on links in read-only notes and cards still work; elsewhere the canvas handles them. + on(this.root, "click", (e) => { + const a = (e.target as Element).closest?.("a.dw-cv-card"); + if (a && this.editable) e.preventDefault(); + }); + } + + /** Whether an event belongs to text being typed, which the canvas leaves alone. */ + private inEditor(target: EventTarget | null): boolean { + if (!(target instanceof Element)) return false; + if (target.closest(".dw-cv-ui")) return true; + if (this.editing) { + const r = this.rendered.get(this.editing.id); + if ( + r && + r.el.contains(target) && + (target.closest("[contenteditable=true]") || target.closest(".dw-cv-notebody") || target.closest("iframe")) + ) + return true; + } + // Read-only notes keep their text selectable and their links working. + if (!this.editable && target.closest(".dw-cv-notebody, a.dw-cv-card")) return true; + return false; + } + + private onDown(e: PointerEvent): void { + if (this.inEditor(e.target)) return; + if (e.button === 2) return; + // The canvas moves focus itself (to a new note or label); the browser's + // own focus change on mouse down would take it away again. + e.preventDefault(); + this.root.focus({ preventScroll: true }); + this.pointers.set(e.pointerId, [e.clientX, e.clientY]); + if (this.pointers.size === 2) { + // Two fingers: pinch to zoom and pan, whatever was started. + this.cancelDrag(); + const [a, b] = [...this.pointers.values()] as [Point, Point]; + const r = this.root.getBoundingClientRect(); + this.pinch = { + dist: Math.hypot(a[0] - b[0], a[1] - b[1]), + mid: [(a[0] + b[0]) / 2 - r.left, (a[1] + b[1]) / 2 - r.top], + zoom: this.view.zoom, + vx: this.view.x, + vy: this.view.y, + }; + return; + } + if (this.pointers.size > 2) return; + if (this.editing) this.stopEditing(); + const p = this.toWorld(e.clientX, e.clientY); + const touch = e.pointerType === "touch"; + const pan = () => { + this.drag = { kind: "pan", sx: e.clientX, sy: e.clientY, vx: this.view.x, vy: this.view.y }; + this.root.classList.add("dw-cv-panning"); + }; + this.root.setPointerCapture?.(e.pointerId); + if (e.button === 1 || this.tool === "hand" || this.spaceDown || this.presenting) { + e.preventDefault(); + return pan(); + } + const target = e.target as Element; + if (!this.editable) return pan(); + + switch (this.tool) { + case "pen": { + const temp = document.createElementNS(SVG_NS, "svg"); + temp.classList.add("dw-cv-temp"); + this.world.append(temp); + this.drag = { kind: "pen", points: [[p[0], p[1], e.pressure || 0.5]], temp }; + return; + } + case "eraser": + this.drag = { kind: "erase", hits: new Set() }; + this.erase(e); + return; + case "shape": + case "frame": + this.drag = { kind: "create", type: this.tool, start: p, id: null }; + return; + case "connector": { + const t = this.connectableAt(e.clientX, e.clientY, new Set()); + const source = t ? this.endOn(t, p) : { x: p[0], y: p[1] }; + const id = this.store.add({ + type: "connector", + ...this.styles.connector, + source, + target: { x: p[0], y: p[1] }, + } as Partial & { type: "connector" }); + this.drag = { kind: "end", id, side: "target" }; + return; + } + case "note": + this.addNote(p); + return; + case "text": + this.addText(p); + return; + case "mindmap": + this.addMindmap(p); + return; + default: + break; + } + + // The select tool. + const handle = (target as SVGElement).dataset?.handle as Handle | "rotate" | undefined; + const endSide = (target as SVGElement).dataset?.end as "source" | "target" | undefined; + if (endSide) { + const c = this.selection()[0]; + if (c?.type === "connector") { + this.store.undo?.stopCapturing(); + this.drag = { kind: "end", id: c.id, side: endSide }; + } + return; + } + if (handle === "rotate") { + const s = this.selection()[0]!; + const c = center(this.boxOf(s)); + this.store.undo?.stopCapturing(); + this.drag = { kind: "rotate", id: s.id, c, a0: Math.atan2(p[1] - c[1], p[0] - c[0]), r0: s.rotate }; + return; + } + if (handle) { + const sel = this.selection(); + const single = sel.length === 1 ? sel[0]! : null; + const orig = new Map(this.expanded(this.selected).map((id) => [id, this.get(id)!] as [string, CanvasElement])); + // Text keeps its measured size, so resizing scales what is seen. + for (const [id, el] of orig) { + const m = this.measured.get(id); + if (el.type === "text" && m) orig.set(id, { ...el, w: m.w, h: m.h }); + if (el.type === "note" && m) orig.set(id, { ...el, h: m.h }); + } + this.store.undo?.stopCapturing(); + this.drag = { + kind: "resize", + handle, + box: single ? this.boxOf(single) : union(sel.map((x) => this.outerBox(x)))!, + deg: single ? single.rotate : 0, + orig, + keep: sel.some((x) => x.type === "image" || x.type === "text" || x.type === "brush") || sel.length > 1, + }; + return; + } + const h = this.hit(target); + if (h) { + const id = this.pick(h.id); + const el = this.get(id); + if (el?.type === "mindmap" && h.node) { + this.activeNode = { map: id, node: h.node }; + const r = this.rendered.get(id); + if (r) r.key = ""; + } else if (el?.type !== "mindmap") this.activeNode = null; + if (e.shiftKey) { + if (this.selected.has(id)) this.selected.delete(id); + else this.selected.add(id); + this.refreshSelection(); + } else if (!this.selected.has(id)) this.select([id]); + else this.refreshSelection(); + this.startMove(p, id); + return; + } + // Empty canvas: a touch pans, a mouse draws a selection box. + if (touch) return pan(); + this.entered = null; + this.drag = { kind: "marquee", start: p, add: e.shiftKey, base: e.shiftKey ? new Set(this.selected) : new Set() }; + if (!e.shiftKey) this.clearSelection(); + } + + private startMove(p: Point, clickId: string): void { + const ids = this.expanded(this.selected); + // A frame carries what lies inside it. + for (const id of [...ids]) { + const f = this.get(id); + if (f?.type !== "frame") continue; + for (const o of this.elements()) { + if (o.type !== "frame" && !ids.includes(o.id) && containsBox(f, this.outerBox(o))) + ids.push(...this.expanded([o.id])); + } + } + const unique = [...new Set(ids)].filter((id) => this.get(id)?.type !== "group"); + const orig = new Map(unique.map((id) => [id, this.get(id)!] as [string, CanvasElement])); + const box = union(unique.map((id) => this.outerBox(this.get(id)!))) ?? { x: p[0], y: p[1], w: 0, h: 0 }; + this.store.undo?.stopCapturing(); + this.drag = { kind: "move", start: p, ids: unique, orig, box, moved: false, clickId }; + } + + private endOn(t: CanvasElement, p: Point): End { + const b = this.outerBox(t); + const a = snapToAnchor(b, p, 14 / this.view.zoom); + if (a) return { id: t.id, pos: [(a[0] - b.x) / Math.max(b.w, 1), (a[1] - b.y) / Math.max(b.h, 1)] }; + return { id: t.id }; + } + + private onMove(e: PointerEvent): void { + if (this.pointers.has(e.pointerId)) this.pointers.set(e.pointerId, [e.clientX, e.clientY]); + if (this.pinch && this.pointers.size >= 2) { + const [a, b] = [...this.pointers.values()] as [Point, Point]; + const r = this.root.getBoundingClientRect(); + const dist = Math.hypot(a[0] - b[0], a[1] - b[1]); + const mid: Point = [(a[0] + b[0]) / 2 - r.left, (a[1] + b[1]) / 2 - r.top]; + const pz = this.pinch; + const zoom = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, (pz.zoom * dist) / Math.max(pz.dist, 1))); + const wx = (pz.mid[0] - pz.vx) / pz.zoom; + const wy = (pz.mid[1] - pz.vy) / pz.zoom; + this.view = { zoom, x: mid[0] - wx * zoom, y: mid[1] - wy * zoom }; + this.applyView(); + return; + } + const d = this.drag; + const p = this.toWorld(e.clientX, e.clientY); + if (!d) { + if (this.editable && this.tool === "connector") { + const t = this.connectableAt(e.clientX, e.clientY, new Set()); + if ((t?.id ?? null) !== this.hover) { + this.hover = t?.id ?? null; + this.drawOverlay(); + } + } + return; + } + switch (d.kind) { + case "pan": + this.view = { ...this.view, x: d.vx + e.clientX - d.sx, y: d.vy + e.clientY - d.sy }; + this.applyView(); + return; + case "move": { + let dx = p[0] - d.start[0]; + let dy = p[1] - d.start[1]; + if (!d.moved && Math.hypot(dx, dy) * this.view.zoom < 3) return; + d.moved = true; + if (!e.altKey) { + const moving = new Set(d.ids); + const others = this.visibleBoxes() + .filter(([id]) => !moving.has(id)) + .map(([, b]) => b); + const s = snap({ ...d.box, x: d.box.x + dx, y: d.box.y + dy }, others, 6 / this.view.zoom); + dx += s.dx; + dy += s.dy; + this.guides = s.guides; + } else this.guides = []; + const patches: [string, Record][] = []; + for (const [id, o] of d.orig) { + if (o.type === "connector") { + const patch: Record = {}; + for (const side of ["source", "target"] as const) { + const end = o[side]; + if (!end.id) patch[side] = { x: (end.x ?? 0) + dx, y: (end.y ?? 0) + dy }; + } + if (Object.keys(patch).length) patches.push([id, patch]); + continue; + } + patches.push([id, { x: o.x + dx, y: o.y + dy }]); + } + this.store.updateMany(patches); + return; + } + case "marquee": { + this.marquee = boxFrom(d.start, p); + const ids = new Set(d.base); + const m = this.marquee; + for (const el of this.elements()) { + if (el.group && this.get(el.group)) continue; + const b = this.outerBox(el); + // Frames are picked only when wholly inside; anything else when touched. + if (el.type === "frame" ? containsBox(m, b) : intersects(m, b)) ids.add(el.id); + } + for (const g of this.elements().filter((x) => x.type === "group")) + if (intersects(m, this.boxOf(g))) ids.add(g.id); + this.selected.clear(); + for (const id of ids) this.selected.add(id); + this.refreshSelection(); + return; + } + case "resize": + this.doResize(d, p, e.shiftKey); + return; + case "rotate": { + let deg = d.r0 + ((Math.atan2(p[1] - d.c[1], p[0] - d.c[0]) - d.a0) * 180) / Math.PI; + if (e.shiftKey) deg = Math.round(deg / 15) * 15; + deg = ((deg % 360) + 360) % 360; + this.store.update(d.id, { rotate: Math.round(deg * 10) / 10 }); + return; + } + case "create": { + const b = boxFrom(d.start, p); + if (!d.id && b.w * this.view.zoom < 4 && b.h * this.view.zoom < 4) return; + if (e.shiftKey) b.w = b.h = Math.max(b.w, b.h); + if (!d.id) { + d.id = + d.type === "shape" + ? this.store.add({ type: "shape", ...this.styles.shape, shape: this.shapeKind, ...b } as never) + : this.store.add({ type: "frame", ...this.styles.frame, title: this.frameName(), ...b } as never); + } else this.store.update(d.id, { ...b }); + return; + } + case "end": { + const c = this.get(d.id); + if (c?.type !== "connector") return; + const other = c[d.side === "source" ? "target" : "source"]; + const skip = new Set([d.id]); + const t = this.connectableAt(e.clientX, e.clientY, skip); + this.hover = t?.id ?? null; + const end = t && t.id !== other.id ? this.endOn(t, p) : { x: p[0], y: p[1] }; + this.store.update(d.id, { [d.side]: end }); + return; + } + case "pen": { + d.points.push([p[0], p[1], e.pressure || 0.5]); + d.temp.innerHTML = ``; + return; + } + case "erase": + this.erase(e); + return; + } + } + + private erase(e: PointerEvent): void { + const d = this.drag; + if (d?.kind !== "erase") return; + const p = this.toWorld(e.clientX, e.clientY); + const r = 6 / this.view.zoom; + for (const t of document.elementsFromPoint(e.clientX, e.clientY)) { + const h = this.hit(t); + if (!h) continue; + const el = this.get(h.id); + if (!el || el.type === "note" || el.type === "frame") continue; + d.hits.add(el.id); + this.rendered.get(el.id)?.el.classList.add("dw-cv-erasing"); + } + // Thin strokes are easy to miss with the pointer; check them by distance too. + for (const el of this.elements()) { + if (el.type !== "brush" || d.hits.has(el.id)) continue; + const pts = el.points.map((q) => [q[0]! + el.x, q[1]! + el.y] as Point); + if (distToPolyline(p, pts) <= r + el.size / 2) { + d.hits.add(el.id); + this.rendered.get(el.id)?.el.classList.add("dw-cv-erasing"); + } + } + } + + private doResize(d: Extract, p: Point, shift: boolean): void { + const b0 = d.box; + const c0 = center(b0); + const q = rotatePoint(p, c0, -d.deg); + let x1 = b0.x; + let y1 = b0.y; + let x2 = b0.x + b0.w; + let y2 = b0.y + b0.h; + if (d.handle.includes("w")) x1 = q[0]; + if (d.handle.includes("e")) x2 = q[0]; + if (d.handle.includes("n")) y1 = q[1]; + if (d.handle.includes("s")) y2 = q[1]; + const min = 8 / this.view.zoom; + if (x2 - x1 < min) { + if (d.handle.includes("w")) x1 = x2 - min; + else x2 = x1 + min; + } + if (y2 - y1 < min) { + if (d.handle.includes("n")) y1 = y2 - min; + else y2 = y1 + min; + } + let w = x2 - x1; + let h = y2 - y1; + const corner = d.handle.length === 2; + if (d.keep !== shift && corner && b0.w && b0.h) { + const s = Math.max(w / b0.w, h / b0.h); + w = b0.w * s; + h = b0.h * s; + // The opposite corner stays where it was. + if (d.handle.includes("w")) x1 = x2 - w; + if (d.handle.includes("n")) y1 = y2 - h; + } + const sx = w / Math.max(b0.w, 1e-6); + const sy = h / Math.max(b0.h, 1e-6); + // The new box's centre, back in canvas coordinates. + const wc = rotatePoint([x1 + w / 2, y1 + h / 2], c0, d.deg); + const nb = { x: wc[0] - w / 2, y: wc[1] - h / 2, w, h }; + const patches: [string, Record][] = []; + for (const [id, o] of d.orig) { + const nx = nb.x + (o.x - b0.x) * sx; + const ny = nb.y + (o.y - b0.y) * sy; + switch (o.type) { + case "connector": { + const patch: Record = {}; + for (const side of ["source", "target"] as const) { + const end = o[side]; + if (!end.id) patch[side] = { x: nb.x + ((end.x ?? 0) - b0.x) * sx, y: nb.y + ((end.y ?? 0) - b0.y) * sy }; + } + patches.push([id, patch]); + break; + } + case "text": { + // Corners scale the text; sides set its width. + if (corner) + patches.push([ + id, + { x: nx, y: ny, w: Math.max(8, o.w * sx), fontSize: Math.max(6, Math.round(o.fontSize * sx * 10) / 10) }, + ]); + else patches.push([id, { x: nx, y: ny, w: Math.max(16, o.w * sx) }]); + break; + } + case "note": + patches.push([id, { x: nx, y: ny, w: Math.max(160, o.w * sx) }]); + break; + case "brush": + patches.push([ + id, + { + x: nx, + y: ny, + w: o.w * sx, + h: o.h * sy, + points: o.points.map((pt) => [pt[0]! * sx, pt[1]! * sy, pt[2] ?? 0.5]), + }, + ]); + break; + case "mindmap": + case "group": + patches.push([id, { x: nx, y: ny }]); + break; + default: + patches.push([id, { x: nx, y: ny, w: o.w * sx, h: o.h * sy }]); + } + } + this.store.updateMany(patches); + } + + private visibleBoxes(): [string, Box][] { + const r = this.root.getBoundingClientRect(); + const tl = this.toWorld(r.left, r.top); + const br = this.toWorld(r.right, r.bottom); + const view = boxFrom(tl, br); + const out: [string, Box][] = []; + for (const e of this.elements()) { + if (e.type === "connector" || e.type === "group") continue; + const b = this.outerBox(e); + if (intersects(view, b)) out.push([e.id, b]); + if (out.length > 300) break; + } + return out; + } + + private onUp(e: PointerEvent): void { + this.pointers.delete(e.pointerId); + if (this.pinch) { + if (this.pointers.size < 2) this.pinch = null; + return; + } + const d = this.drag; + this.drag = null; + this.root.classList.remove("dw-cv-panning"); + this.guides = []; + this.marquee = null; + this.hover = null; + if (!d) return; + const p = this.toWorld(e.clientX, e.clientY); + switch (d.kind) { + case "create": { + let id = d.id; + if (!id) { + // A click places a default size. + const size = d.type === "frame" ? { w: 800, h: 600 } : { w: 140, h: 100 }; + const at = { x: p[0] - size.w / 2, y: p[1] - size.h / 2, ...size }; + id = + d.type === "shape" + ? this.store.add({ type: "shape", ...this.styles.shape, shape: this.shapeKind, ...at } as never) + : this.store.add({ type: "frame", ...this.styles.frame, title: this.frameName(), ...at } as never); + } + this.tool = "select"; + this.root.dataset.tool = "select"; + this.select([id]); + break; + } + case "end": { + const c = this.get(d.id); + if (c?.type === "connector") { + const r = this.routeOf(c); + // A connector that was only clicked, not dragged, is dropped again. + const a = r.points[0]!; + const b = r.points[r.points.length - 1]!; + if (Math.hypot(a[0] - b[0], a[1] - b[1]) * this.view.zoom < 8 && this.tool === "connector") + this.store.remove([d.id]); + else if (this.tool === "connector") this.select([d.id]); + } + break; + } + case "pen": { + d.temp.remove(); + if (d.points.length < 2) d.points.push([d.points[0]![0]! + 0.5, d.points[0]![1]! + 0.5, 0.5]); + const xs = d.points.map((q) => q[0]!); + const ys = d.points.map((q) => q[1]!); + const pad = this.styles.brush.size; + const x = Math.min(...xs) - pad; + const y = Math.min(...ys) - pad; + const w = Math.max(...xs) + pad - x; + const h = Math.max(...ys) + pad - y; + this.store.add({ + type: "brush", + ...this.styles.brush, + x, + y, + w, + h, + points: d.points.map((q) => [ + Math.round((q[0]! - x) * 10) / 10, + Math.round((q[1]! - y) * 10) / 10, + Math.round((q[2] ?? 0.5) * 100) / 100, + ]), + } as never); + break; + } + case "erase": + for (const id of d.hits) this.rendered.get(id)?.el.classList.remove("dw-cv-erasing"); + if (d.hits.size) this.store.remove(d.hits); + break; + default: + break; + } + this.drawOverlay(); + this.ui.refresh(); + } + + private cancelDrag(): void { + const d = this.drag; + if (d?.kind === "pen") d.temp.remove(); + this.drag = null; + this.marquee = null; + this.guides = []; + } + + private onDouble(e: MouseEvent): void { + if (this.inEditor(e.target) || !this.editable || this.tool !== "select") return; + const h = this.hit(e.target); + if (!h) { + // A double click on empty canvas writes text there. + this.addText(this.toWorld(e.clientX, e.clientY)); + return; + } + const el = this.get(h.id); + if (!el) return; + // A group opens: its members can then be picked one by one. + if (el.group && this.entered !== el.group && this.get(el.group)) { + this.entered = el.group; + this.select([el.id]); + return; + } + if (el.type === "frame" && !(e.target as Element).closest(".dw-cv-frametitle")) return; + this.startEdit(el.id, h.node); + } + + private onWheel(e: WheelEvent): void { + if (this.presenting) return; + if (e.target instanceof Element && e.target.closest(".dw-cv-ui")) return; + e.preventDefault(); + const r = this.root.getBoundingClientRect(); + if (e.ctrlKey || e.metaKey) { + this.zoomAt(this.view.zoom * Math.exp(-e.deltaY * 0.01), [e.clientX - r.left, e.clientY - r.top]); + return; + } + const k = e.deltaMode === 1 ? 16 : 1; + const dx = e.shiftKey && !e.deltaX ? e.deltaY : e.deltaX; + const dy = e.shiftKey && !e.deltaX ? 0 : e.deltaY; + this.view = { ...this.view, x: this.view.x - dx * k, y: this.view.y - dy * k }; + this.applyView(); + } + + private onKey(e: KeyboardEvent): void { + if (this.presenting) { + this.presentKey(e); + return; + } + if (isEditable(e.target) || this.inEditor(e.target)) return; + const mod = e.ctrlKey || e.metaKey; + const key = e.key.toLowerCase(); + if (e.key === " " && !mod) { + this.spaceDown = true; + this.root.classList.add("dw-cv-panning"); + e.preventDefault(); + return; + } + // Zoom works for readers too. + if (mod && (key === "=" || key === "+")) { + e.preventDefault(); + return this.zoomBy(1.25); + } + if (mod && key === "-") { + e.preventDefault(); + return this.zoomBy(0.8); + } + if (e.altKey && !mod && (e.code === "Digit0" || e.code === "Digit1" || e.code === "Digit2")) { + e.preventDefault(); + if (e.code === "Digit0") return this.zoomAt(1); + if (e.code === "Digit1") return this.fit(); + const b = union(this.selection().map((x) => this.outerBox(x))); + return this.fit(b ?? undefined); + } + if (e.key === "Escape") { + if (this.entered) { + this.select([this.entered]); + this.entered = null; + } else if (this.selected.size) this.clearSelection(); + else this.setTool("select"); + return; + } + if (!this.editable) { + if (!mod && key === "h") this.setTool("hand"); + if (!mod && key === "v") this.setTool("select"); + return; + } + if (this.activeNode && this.mindmapKey(e)) return; + if (mod && key === "z") { + e.preventDefault(); + if (e.shiftKey) this.store.undo?.redo(); + else this.store.undo?.undo(); + return; + } + if (mod && key === "y") { + e.preventDefault(); + this.store.undo?.redo(); + return; + } + if (mod && key === "a") { + e.preventDefault(); + this.select( + this.elements() + .filter((x) => !x.group || !this.get(x.group)) + .map((x) => x.id), + ); + return; + } + if (mod && key === "d") { + e.preventDefault(); + this.duplicate(); + return; + } + if (mod && key === "g") { + e.preventDefault(); + if (e.shiftKey) this.ungroup(); + else this.group(); + return; + } + if ((e.key === "Delete" || e.key === "Backspace") && this.selected.size) { + e.preventDefault(); + this.deleteSelection(); + return; + } + if (e.key === "Enter" && this.selected.size === 1) { + e.preventDefault(); + const only = [...this.selected][0]!; + this.startEdit(only); + return; + } + if (e.key.startsWith("Arrow") && this.selected.size) { + e.preventDefault(); + const step = e.shiftKey ? 10 : 1; + const dx = e.key === "ArrowLeft" ? -step : e.key === "ArrowRight" ? step : 0; + const dy = e.key === "ArrowUp" ? -step : e.key === "ArrowDown" ? step : 0; + this.nudge(dx, dy); + return; + } + if (mod || e.altKey) return; + const tools: Record = { + v: "select", + h: "hand", + n: "note", + t: "text", + s: "shape", + c: "connector", + p: "pen", + e: "eraser", + f: "frame", + m: "mindmap", + }; + if (tools[key]) { + e.preventDefault(); + this.setTool(tools[key]); + } else if (key === "i") this.ui.pickImage(); + else if (key === "l") void this.addLink(); + } + + private nudge(dx: number, dy: number): void { + const ids = this.expanded(this.selected); + const patches: [string, Record][] = []; + for (const id of ids) { + const o = this.get(id); + if (!o || o.type === "group") continue; + if (o.type === "connector") { + const patch: Record = {}; + for (const side of ["source", "target"] as const) { + const end = o[side]; + if (!end.id) patch[side] = { x: (end.x ?? 0) + dx, y: (end.y ?? 0) + dy }; + } + patches.push([id, patch]); + } else patches.push([id, { x: o.x + dx, y: o.y + dy }]); + } + this.store.updateMany(patches); + } + + // ---- Editing text ---- + + /** Starts typing in an element: a note's editor, a label, a text box or a mind map node. */ + startEdit(id: string, node?: string): void { + if (!this.editable) return; + const el = this.get(id); + const r = this.rendered.get(id); + if (!el || !r) return; + if (el.type === "group") { + this.entered = id; + return; + } + if (el.type === "mindmap") { + const target = node ?? (this.activeNode?.map === id ? this.activeNode.node : rootOf(el.nodes)); + if (!target) return; + this.activeNode = { map: id, node: target }; + this.editing = { id, node: target }; + this.draw(r, el); + const div = r.el.querySelector(`[data-node="${target}"]`); + if (div) + this.editText(div, el.nodes[target]?.text ?? "", true, (text) => this.store.updateNode(id, target, { text })); + return; + } + if (el.type === "image" || el.type === "brush") return; + this.select([id]); + this.editing = { id, node }; + r.el.classList.add("dw-cv-editing"); + this.drawOverlay(); + this.ui.refresh(); + switch (el.type) { + case "note": + r.note?.focus(); + return; + case "embed": + // The player takes the pointer until the canvas is clicked again. + return; + case "text": { + const t = r.el.querySelector(".dw-cv-textbody"); + if (t) + this.editText(t, el.text, false, (text) => + text.trim() ? this.store.update(id, { text }) : this.store.remove([id]), + ); + return; + } + case "shape": { + const t = r.el.querySelector(".dw-cv-label"); + if (t) this.editText(t, el.text, false, (text) => this.store.update(id, { text })); + return; + } + case "frame": { + const t = r.el.querySelector(".dw-cv-frametitle"); + if (t) this.editText(t, el.title, true, (title) => this.store.update(id, { title })); + return; + } + case "connector": { + this.draw(r, el); + const t = r.el.querySelector(".dw-cv-clabel"); + if (t) this.editText(t, el.label, true, (label) => this.store.update(id, { label })); + return; + } + } + } + + /** Makes a box editable as plain text; commit runs once, when typing ends. */ + private editText(div: HTMLElement, text: string, single: boolean, commit: (text: string) => void): void { + div.contentEditable = "true"; + div.spellcheck = true; + div.textContent = text; + div.classList.add("dw-cv-typing"); + let done = false; + const finish = (save: boolean) => { + if (done) return; + done = true; + this.stopEditingFn = null; + div.contentEditable = "false"; + div.classList.remove("dw-cv-typing"); + div.removeEventListener("keydown", onKey); + div.removeEventListener("blur", onBlur); + div.removeEventListener("paste", onPaste); + const value = (div.innerText ?? div.textContent ?? "").replace(/\n$/, ""); + const id = this.editing?.id; + this.editing = null; + if (save && value !== text) commit(value); + else if (save && !value.trim()) commit(value); + if (id) { + const r = this.rendered.get(id); + if (r) r.key = ""; + } + this.schedule(); + this.ui.refresh(); + }; + const onKey = (e: KeyboardEvent) => { + e.stopPropagation(); + if (e.key === "Escape") { + e.preventDefault(); + finish(true); + this.root.focus({ preventScroll: true }); + } else if (e.key === "Enter" && (single || e.ctrlKey || e.metaKey) && !e.shiftKey) { + e.preventDefault(); + finish(true); + this.root.focus({ preventScroll: true }); + } else if (e.key === "Tab" && this.activeNode) { + e.preventDefault(); + finish(true); + this.mindmapAdd("child"); + } + }; + const onBlur = () => finish(true); + const onPaste = (e: ClipboardEvent) => { + e.preventDefault(); + e.stopPropagation(); + document.execCommand("insertText", false, e.clipboardData?.getData("text/plain") ?? ""); + }; + div.addEventListener("keydown", onKey); + div.addEventListener("blur", onBlur); + div.addEventListener("paste", onPaste); + this.stopEditingFn = () => finish(true); + div.focus({ preventScroll: true }); + const range = document.createRange(); + range.selectNodeContents(div); + const sel = getSelection(); + sel?.removeAllRanges(); + sel?.addRange(range); + } + + private stopEditingFn: (() => void) | null = null; + + stopEditing(): void { + const fn = this.stopEditingFn; + this.stopEditingFn = null; + fn?.(); + if (this.editing) { + const r = this.rendered.get(this.editing.id); + r?.el.classList.remove("dw-cv-editing"); + if (r?.note && document.activeElement && r.el.contains(document.activeElement)) + (document.activeElement as HTMLElement).blur(); + this.editing = null; + this.drawOverlay(); + this.ui.refresh(); + } + } + + // ---- Adding things ---- + + private frameName(): string { + const n = this.elements().filter((e) => e.type === "frame").length + 1; + return `${this.labels.frameTitle} ${n}`; + } + + addNote(p: Point): void { + const w = 320; + const id = this.store.add({ type: "note", ...this.styles.note, x: p[0] - 24, y: p[1] - 24, w, h: 120 } as never); + this.setTool("select"); + this.select([id]); + this.render(); + this.startEdit(id); + } + + addText(p: Point): void { + const id = this.store.add({ + type: "text", + ...this.styles.text, + x: p[0], + y: p[1] - this.styles.text.fontSize * 0.7, + w: 0, + h: 0, + text: "", + } as never); + this.setTool("select"); + this.render(); + this.startEdit(id); + } + + addMindmap(p: Point): void { + const root = `r${Date.now().toString(36)}`; + const id = this.store.add({ + type: "mindmap", + ...this.styles.mindmap, + x: p[0], + y: p[1], + nodes: { [root]: { text: this.labels.centralIdea, parent: "", pos: 0 } }, + } as never); + this.setTool("select"); + this.select([id]); + this.activeNode = { map: id, node: root }; + this.render(); + this.startEdit(id, root); + } + + /** The middle of the view in canvas units. */ + viewCentre(): Point { + const r = this.root.getBoundingClientRect(); + return this.toWorld(r.left + r.width / 2, r.top + r.height / 2); + } + + async addImages(files: File[], at?: Point): Promise { + const upload = this.opts.files?.upload; + if (!upload) return; + let [x, y] = at ?? this.viewCentre(); + const ids: string[] = []; + for (const file of files) { + try { + const up = await upload.call(this.opts.files, file); + const size = await imageSize(this.opts.files?.resolve(up.url) ?? up.url); + const scale = Math.min(1, 480 / Math.max(size.w, 1)); + const w = size.w * scale; + const h = size.h * scale; + ids.push( + this.store.add({ type: "image", src: up.url, alt: up.name, x: x - w / 2, y: y - h / 2, w, h } as never), + ); + x += 24; + y += 24; + } catch (err) { + this.opts.onError?.(err); + } + } + if (ids.length) this.select(ids); + } + + async addLink(url?: string, at?: Point): Promise { + const raw = url ?? window.prompt(this.labels.linkPrompt, "https://"); + const href = raw?.trim(); + if (!href || !/^https?:\/\//i.test(href)) return; + const [x, y] = at ?? this.viewCentre(); + const player = this.opts.embedSource?.(href); + const w = player ? 560 : 380; + const h = player ? (player.ratio === "video" ? 315 : 420) : 120; + const id = this.store.add({ type: "embed", url: href, x: x - w / 2, y: y - h / 2, w, h } as never); + this.setTool("select"); + this.select([id]); + } + + /** Drops elements (a sticker or a template) in the middle of the view. */ + insertElements(list: ElementJSON[]): void { + const b = union( + list.map((e) => ({ + x: Number(e.x) || 0, + y: Number(e.y) || 0, + w: Number(e.w) || 0, + h: Number(e.h) || 0, + })), + ) ?? { x: 0, y: 0, w: 0, h: 0 }; + const [cx, cy] = this.viewCentre(); + const ids = this.store.insertJSON(list, cx - (b.x + b.w / 2), cy - (b.y + b.h / 2)); + this.setTool("select"); + // Group members come with their group. + this.select(ids.filter((id) => !ids.includes(this.get(id)?.group ?? ""))); + } + + insertSticker(emoji: string): void { + this.insertElements(sticker(emoji)); + } + + insertTemplate(id: TemplateId): void { + this.insertElements(template(id, this.labels)); + } + + // ---- Selection actions ---- + + deleteSelection(): void { + const ids = [...this.selected]; + this.clearSelection(); + this.store.remove(ids); + } + + duplicate(): void { + const json = this.store.toJSON(this.selected); + if (!json.length) return; + const ids = this.store.insertJSON(json, 24, 24); + this.select(ids.filter((id) => !this.get(id)?.group || !ids.includes(this.get(id)!.group))); + } + + group(): void { + const g = this.store.groupOf([...this.selected]); + if (g) this.select([g]); + } + + ungroup(): void { + const groups = this.selection().filter((e) => e.type === "group"); + const members = groups.flatMap((g) => this.store.ungroup(g.id)); + if (groups.length) this.select(members); + } + + reorder(to: "front" | "back"): void { + this.store.reorder(this.expanded(this.selected), to); + } + + /** Adds a branch (Tab) or a sibling (Enter) to the picked mind map node and types in it. */ + mindmapAdd(kind: "child" | "sibling"): void { + const a = this.activeNode; + const el = a ? this.get(a.map) : undefined; + if (!a || el?.type !== "mindmap") return; + const node = el.nodes[a.node]; + if (!node) return; + const parent = kind === "child" || !node.parent ? a.node : node.parent; + const siblings = childrenOf(el.nodes, parent); + let pos: number; + if (kind === "sibling" && node.parent) { + const i = siblings.indexOf(a.node); + const here = el.nodes[siblings[i]!]?.pos ?? 0; + const next = siblings[i + 1] ? (el.nodes[siblings[i + 1]!]?.pos ?? here + 2) : here + 2; + pos = (here + next) / 2; + } else pos = siblings.length ? Math.max(...siblings.map((s) => el.nodes[s]?.pos ?? 0)) + 1 : 0; + const id = this.store.addNode(a.map, parent, pos, ""); + this.activeNode = { map: a.map, node: id }; + this.render(); + this.startEdit(a.map, id); + } + + private mindmapKey(e: KeyboardEvent): boolean { + const a = this.activeNode!; + const el = this.get(a.map); + if (el?.type !== "mindmap" || !this.selected.has(a.map)) return false; + if (e.key === "Tab") { + e.preventDefault(); + this.mindmapAdd("child"); + return true; + } + if (e.key === "Enter") { + e.preventDefault(); + this.mindmapAdd("sibling"); + return true; + } + if (e.key === "F2") { + e.preventDefault(); + this.startEdit(a.map, a.node); + return true; + } + if (e.key === "Delete" || e.key === "Backspace") { + e.preventDefault(); + const parent = el.nodes[a.node]?.parent; + this.store.removeNode(a.map, a.node); + this.activeNode = parent ? { map: a.map, node: parent } : null; + this.schedule(); + return true; + } + if (e.key.startsWith("Arrow") && !e.shiftKey) { + e.preventDefault(); + const next = neighbour(this.layoutOf(el), el.nodes, a.node, e.key as "ArrowUp"); + if (next) { + this.activeNode = { map: a.map, node: next }; + const r = this.rendered.get(a.map); + if (r) r.key = ""; + this.schedule(); + } + return true; + } + return false; + } + + // ---- Clipboard ---- + + private owns(): boolean { + const a = document.activeElement; + return !!a && (a === this.root || (this.root.contains(a) && !isEditable(a) && !this.inEditor(a))); + } + + private onCopy(e: ClipboardEvent, cut: boolean): void { + if (!this.owns() || !this.selected.size || getSelection()?.toString()) return; + const json = this.store.toJSON(this.selected); + e.clipboardData?.setData("text/plain", `docwell-canvas:${JSON.stringify(json)}`); + e.preventDefault(); + if (cut && this.editable) this.deleteSelection(); + } + + private onPaste(e: ClipboardEvent): void { + if (!this.editable || !this.owns()) return; + const files = [...(e.clipboardData?.files ?? [])].filter((f) => f.type.startsWith("image/")); + if (files.length) { + e.preventDefault(); + void this.addImages(files); + return; + } + const text = e.clipboardData?.getData("text/plain") ?? ""; + if (!text) return; + e.preventDefault(); + if (text.startsWith("docwell-canvas:")) { + try { + const list = JSON.parse(text.slice("docwell-canvas:".length)) as ElementJSON[]; + if (Array.isArray(list)) this.insertElements(list); + } catch { + // not ours after all + } + return; + } + if (/^https?:\/\/\S+$/i.test(text.trim())) { + void this.addLink(text.trim()); + return; + } + const [x, y] = this.viewCentre(); + const id = this.store.add({ + type: "text", + ...this.styles.text, + x, + y, + w: text.length > 60 ? 480 : 0, + h: 0, + text, + } as never); + this.select([id]); + } + + // ---- Export ---- + + /** The canvas (or the selection) as an SVG or PNG file. */ + async exportImage(kind: ExportKind, selectionOnly = false): Promise { + const ids = selectionOnly && this.selected.size ? new Set(this.expanded(this.selected)) : null; + const list = this.elements().filter((e) => !ids || ids.has(e.id)); + return exportCanvas(kind, { + root: this.root, + elements: list, + boxOf: (e) => this.boxOf(e), + routeOf: (c) => this.routes.get(c.id) ?? this.routeOf(c), + layoutOf: (m) => this.layoutOf(m), + noteBody: (e) => (e.page ? this.opts.doc.getXmlFragment("default") : this.store.body(e.id)), + pageTitle: this.opts.pageTitle?.() ?? "", + resolve: (src) => this.opts.files?.resolve(src) ?? src, + }); + } + + // ---- Presentation ---- + + /** The frames in the order they were made, for presenting. */ + frames(): CanvasElement[] { + return this.elements() + .filter((e) => e.type === "frame") + .sort((a, b) => b.index - a.index); + } + + present(): void { + const frames = this.frames().map((f) => f.id); + if (!frames.length) { + this.ui.toast(this.labels.presentNoFrames); + return; + } + this.stopEditing(); + this.clearSelection(); + const bar = this.ui.presentBar(); + this.presenting = { frames, at: 0, bar }; + this.root.classList.add("dw-cv-presenting"); + void this.root.requestFullscreen?.().catch(() => {}); + // Wait a frame for the full-screen size before fitting. + requestAnimationFrame(() => this.goTo(0)); + } + + private goTo(i: number): void { + const p = this.presenting; + if (!p) return; + p.at = Math.max(0, Math.min(p.frames.length - 1, i)); + const f = this.get(p.frames[p.at]!); + if (f) { + const from = { ...this.view }; + this.fit(this.boxOf(f), false, 24); + const to = { ...this.view }; + this.view = from; + this.animateTo(to); + } + this.ui.presentStep(p.at, p.frames.length); + } + + presentStep(delta: number): void { + if (this.presenting) this.goTo(this.presenting.at + delta); + } + + stopPresenting(): void { + const p = this.presenting; + if (!p) return; + this.presenting = null; + p.bar.remove(); + this.root.classList.remove("dw-cv-presenting"); + if (document.fullscreenElement === this.root) void document.exitFullscreen().catch(() => {}); + this.drawOverlay(); + } + + get isPresenting(): boolean { + return !!this.presenting; + } + + private presentKey(e: KeyboardEvent): void { + if (["ArrowRight", "ArrowDown", "PageDown", " ", "Enter"].includes(e.key)) { + e.preventDefault(); + this.presentStep(1); + } else if (["ArrowLeft", "ArrowUp", "PageUp", "Backspace"].includes(e.key)) { + e.preventDefault(); + this.presentStep(-1); + } else if (e.key === "Escape") { + e.preventDefault(); + this.stopPresenting(); + } + } +} + +function imageSize(src: string): Promise<{ w: number; h: number }> { + return new Promise((resolve) => { + const img = new Image(); + img.onload = () => resolve({ w: img.naturalWidth || 320, h: img.naturalHeight || 240 }); + img.onerror = () => resolve({ w: 320, h: 240 }); + img.src = src; + }); +} diff --git a/Packages/canvas/src/yxml.ts b/Packages/canvas/src/yxml.ts new file mode 100644 index 0000000..82b6d6e --- /dev/null +++ b/Packages/canvas/src/yxml.ts @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// ProseMirror JSON to and from a Y.XmlFragment, the way y-prosemirror writes +// it (and the server's yrs reads it): one XmlElement per node, attributes as +// they are, runs of text in an XmlText whose formatting attributes are the +// marks. Notes use it to copy and paste their bodies and to show JSON +// snapshots (share links, the phone) with the same code as the live canvas. + +import * as Y from "yjs"; + +export interface PMNode { + type: string; + attrs?: Record; + content?: PMNode[]; + text?: string; + marks?: { type: string; attrs?: Record }[]; +} + +/** A fragment's children as ProseMirror nodes. */ +export function fragmentToJSON(fragment: Y.XmlFragment | Y.XmlElement): PMNode[] { + const out: PMNode[] = []; + for (const child of fragment.toArray()) { + if (child instanceof Y.XmlText) { + for (const d of child.toDelta() as { insert: unknown; attributes?: Record }[]) { + if (typeof d.insert !== "string") continue; + const node: PMNode = { type: "text", text: d.insert }; + if (d.attributes) { + node.marks = Object.entries(d.attributes).map(([type, attrs]) => ({ + type, + attrs: attrs && typeof attrs === "object" ? (attrs as Record) : {}, + })); + } + out.push(node); + } + } else if (child instanceof Y.XmlElement) { + const node: PMNode = { type: child.nodeName }; + const attrs = child.getAttributes() as Record; + if (Object.keys(attrs).length) node.attrs = attrs; + if (child.length) node.content = fragmentToJSON(child); + out.push(node); + } + } + return out; +} + +/** Appends ProseMirror nodes to a fragment that is already part of a document. */ +export function writeJSON(parent: Y.XmlFragment | Y.XmlElement, nodes: PMNode[], depth = 0): void { + if (depth > 100) return; + let i = 0; + while (i < nodes.length) { + const n = nodes[i]!; + if (n.type === "text") { + const text = new Y.XmlText(); + parent.insert(parent.length, [text]); + while (i < nodes.length && nodes[i]!.type === "text") { + const t = nodes[i]!; + const attrs: Record = {}; + for (const m of t.marks ?? []) attrs[m.type] = m.attrs ?? {}; + text.insert(text.length, t.text ?? "", Object.keys(attrs).length ? attrs : undefined); + i++; + } + continue; + } + const el = new Y.XmlElement(n.type); + parent.insert(parent.length, [el]); + for (const [k, v] of Object.entries(n.attrs ?? {})) { + // y-prosemirror leaves null attributes out. + if (v !== null && v !== undefined) el.setAttribute(k, v as string); + } + if (n.content?.length) writeJSON(el, n.content, depth + 1); + i++; + } +} + +/** The plain text of ProseMirror nodes, one line per block. */ +export function plainText(nodes: PMNode[]): string[] { + const lines: string[] = []; + const walk = (list: PMNode[]) => { + let line = ""; + let inline = false; + for (const n of list) { + if (n.type === "text") { + line += n.text ?? ""; + inline = true; + } else if (n.type === "hardBreak") { + lines.push(line); + line = ""; + } else if (n.content?.length && n.content.some((c) => c.type !== "text" && c.type !== "hardBreak")) { + if (inline) lines.push(line); + line = ""; + inline = false; + walk(n.content); + } else { + if (inline) lines.push(line); + lines.push((n.content ?? []).map((c) => c.text ?? "").join("")); + line = ""; + inline = false; + } + } + if (inline) lines.push(line); + }; + walk(nodes); + return lines; +} diff --git a/Packages/canvas/vitest.config.ts b/Packages/canvas/vitest.config.ts new file mode 100644 index 0000000..b581c66 --- /dev/null +++ b/Packages/canvas/vitest.config.ts @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { environment: "jsdom" }, +}); diff --git a/Packages/editor-bridge/dist/index.html b/Packages/editor-bridge/dist/index.html index 7feba15..3c68c46 100644 --- a/Packages/editor-bridge/dist/index.html +++ b/Packages/editor-bridge/dist/index.html @@ -5,18 +5,18 @@ Docwell editor - +?)[ \r ]*`,Rq=`[̀-ͯ]`,zq=RegExp(Rq+`+$`),Bq=`(`+Nq+`+)|`+(Lq+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(Rq+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(Rq+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+Iq)+(`|`+Fq+`)`),Vq=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(Bq,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new VK(`EOF`,new BK(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new L(`Unexpected character: '`+e[t]+`'`,new VK(e[t],new BK(this,t,t+1)));var r=n[6]||n[3]||(n[2]?`\\ `:` `);if(this.catcodes[r]===14){var i=e.indexOf(` +`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=i+1,this.lex()}return new VK(r,new BK(this,t,this.tokenRegex.lastIndex))}},Hq=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new L(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var e=this.undefStack.pop();for(var t of Object.keys(e))e[t]===void 0?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){if(Object.prototype.hasOwnProperty.call(this.current,e))return this.current[e];if(Object.prototype.hasOwnProperty.call(this.builtins,e))return this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!Object.prototype.hasOwnProperty.call(i,e)&&(i[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}t==null?delete this.current[e]:this.current[e]=t}},Uq=zK;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var Wq={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(e){var t=e.popToken(),n,r=0;if(t.text===`'`)n=8,t=e.popToken();else if(t.text===`"`)n=16,t=e.popToken();else if(t.text==="`"){if(t=e.popToken(),t.text[0]===`\\`)r=t.text.charCodeAt(1);else if(t.text===`EOF`)throw new L("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=Wq[t.text],r==null||r>=n)throw new L(`Invalid base-`+n+` digit `+t.text);for(var i;(i=Wq[e.future().text])!=null&&i{var i=e.consumeArg().tokens;if(i.length!==1)throw new L(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new L(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new L(`\\renewcommand{`+a+`} when command `+a+` does not yet exist; use \\newcommand`);var s=0;if(i=e.consumeArg().tokens,i.length===1&&i[0].text===`[`){for(var c=``,l=e.expandNextToken();l.text!==`]`&&l.text!==`EOF`;)c+=l.text,l=e.expandNextToken();if(!c.match(/^\s*[0-9]+\s*$/))throw new L(`Invalid number of arguments: `+c);s=parseInt(c),i=e.consumeArg().tokens}return o&&r||e.macros.set(a,{tokens:i,numArgs:s}),``};$(`\\newcommand`,e=>Gq(e,!1,!0,!1)),$(`\\renewcommand`,e=>Gq(e,!0,!1,!1)),$(`\\providecommand`,e=>Gq(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),Mq[n],EU.math[n],EU.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}"),$(`\\ne`,`\\neq`),$(`≠`,`\\neq`),$(`\\notin`,"\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`∉}}"),$(`∉`,`\\notin`),$(`≘`,"\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`≘}}"),$(`≙`,"\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`≘}}"),$(`≚`,"\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`≚}}"),$(`≛`,"\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`≛}}"),$(`≝`,"\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`≝}}"),$(`≞`,"\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`≞}}"),$(`≟`,"\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`≟}}"),$(`⟂`,`\\perp`),$(`‼`,`\\mathclose{!\\mkern-0.8mu!}`),$(`∌`,`\\notni`),$(`⌜`,`\\ulcorner`),$(`⌝`,`\\urcorner`),$(`⌞`,`\\llcorner`),$(`⌟`,`\\lrcorner`),$(`©`,`\\copyright`),$(`®`,`\\textregistered`),$(`\\ulcorner`,`\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}`),$(`\\urcorner`,`\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}`),$(`\\llcorner`,`\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}`),$(`\\lrcorner`,`\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}`),$(`\\vdots`,`{\\varvdots\\rule{0pt}{15pt}}`),$(`⋮`,`\\vdots`),$(`\\varGamma`,`\\mathit{\\Gamma}`),$(`\\varDelta`,`\\mathit{\\Delta}`),$(`\\varTheta`,`\\mathit{\\Theta}`),$(`\\varLambda`,`\\mathit{\\Lambda}`),$(`\\varXi`,`\\mathit{\\Xi}`),$(`\\varPi`,`\\mathit{\\Pi}`),$(`\\varSigma`,`\\mathit{\\Sigma}`),$(`\\varUpsilon`,`\\mathit{\\Upsilon}`),$(`\\varPhi`,`\\mathit{\\Phi}`),$(`\\varPsi`,`\\mathit{\\Psi}`),$(`\\varOmega`,`\\mathit{\\Omega}`),$(`\\substack`,`\\begin{subarray}{c}#1\\end{subarray}`),$(`\\colon`,`\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax`),$(`\\boxed`,`\\fbox{$\\displaystyle{#1}$}`),$(`\\iff`,`\\DOTSB\\;\\Longleftrightarrow\\;`),$(`\\implies`,`\\DOTSB\\;\\Longrightarrow\\;`),$(`\\impliedby`,`\\DOTSB\\;\\Longleftarrow\\;`),$(`\\dddot`,`{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}`),$(`\\ddddot`,`{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}`);var Kq={",":`\\dotsc`,"\\not":`\\dotsb`,"+":`\\dotsb`,"=":`\\dotsb`,"<":`\\dotsb`,">":`\\dotsb`,"-":`\\dotsb`,"*":`\\dotsb`,":":`\\dotsb`,"\\DOTSB":`\\dotsb`,"\\coprod":`\\dotsb`,"\\bigvee":`\\dotsb`,"\\bigwedge":`\\dotsb`,"\\biguplus":`\\dotsb`,"\\bigcap":`\\dotsb`,"\\bigcup":`\\dotsb`,"\\prod":`\\dotsb`,"\\sum":`\\dotsb`,"\\bigotimes":`\\dotsb`,"\\bigoplus":`\\dotsb`,"\\bigodot":`\\dotsb`,"\\bigsqcup":`\\dotsb`,"\\And":`\\dotsb`,"\\longrightarrow":`\\dotsb`,"\\Longrightarrow":`\\dotsb`,"\\longleftarrow":`\\dotsb`,"\\Longleftarrow":`\\dotsb`,"\\longleftrightarrow":`\\dotsb`,"\\Longleftrightarrow":`\\dotsb`,"\\mapsto":`\\dotsb`,"\\longmapsto":`\\dotsb`,"\\hookrightarrow":`\\dotsb`,"\\doteq":`\\dotsb`,"\\mathbin":`\\dotsb`,"\\mathrel":`\\dotsb`,"\\relbar":`\\dotsb`,"\\Relbar":`\\dotsb`,"\\xrightarrow":`\\dotsb`,"\\xleftarrow":`\\dotsb`,"\\DOTSI":`\\dotsi`,"\\int":`\\dotsi`,"\\oint":`\\dotsi`,"\\iint":`\\dotsi`,"\\iiint":`\\dotsi`,"\\iiiint":`\\dotsi`,"\\idotsint":`\\dotsi`,"\\DOTSX":`\\dotsx`},qq=new Set([`bin`,`rel`]);$(`\\dots`,function(e){var t=`\\dotso`,n=e.expandAfterFuture().text;return n in Kq?t=Kq[n]:(n.slice(0,4)===`\\not`||n in EU.math&&qq.has(EU.math[n].group))&&(t=`\\dotsb`),t});var Jq={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};$(`\\dotso`,function(e){return e.future().text in Jq?`\\ldots\\,`:`\\ldots`}),$(`\\dotsc`,function(e){var t=e.future().text;return t in Jq&&t!==`,`?`\\ldots\\,`:`\\ldots`}),$(`\\cdots`,function(e){return e.future().text in Jq?`\\@cdots\\,`:`\\@cdots`}),$(`\\dotsb`,`\\cdots`),$(`\\dotsm`,`\\cdots`),$(`\\dotsi`,`\\!\\cdots`),$(`\\dotsx`,`\\ldots\\,`),$(`\\DOTSI`,`\\relax`),$(`\\DOTSB`,`\\relax`),$(`\\DOTSX`,`\\relax`),$(`\\tmspace`,`\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax`),$(`\\,`,`\\tmspace+{3mu}{.1667em}`),$(`\\thinspace`,`\\,`),$(`\\>`,`\\mskip{4mu}`),$(`\\:`,`\\tmspace+{4mu}{.2222em}`),$(`\\medspace`,`\\:`),$(`\\;`,`\\tmspace+{5mu}{.2777em}`),$(`\\thickspace`,`\\;`),$(`\\!`,`\\tmspace-{3mu}{.1667em}`),$(`\\negthinspace`,`\\!`),$(`\\negmedspace`,`\\tmspace-{4mu}{.2222em}`),$(`\\negthickspace`,`\\tmspace-{5mu}{.277em}`),$(`\\enspace`,`\\kern.5em `),$(`\\enskip`,`\\hskip.5em\\relax`),$(`\\quad`,`\\hskip1em\\relax`),$(`\\qquad`,`\\hskip2em\\relax`),$(`\\tag`,`\\@ifstar\\tag@literal\\tag@paren`),$(`\\tag@paren`,`\\tag@literal{({#1})}`),$(`\\tag@literal`,e=>{if(e.macros.get(`\\df@tag`))throw new L(`Multiple \\tag`);return`\\gdef\\df@tag{\\text{#1}}`}),$(`\\bmod`,`\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}`),$(`\\pod`,`\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)`),$(`\\pmod`,`\\pod{{\\rm mod}\\mkern6mu#1}`),$(`\\mod`,`\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1`),$(`\\newline`,`\\\\\\relax`),$(`\\TeX`,`\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}`);var Yq=z(yU[`Main-Regular`][84][1]-.7*yU[`Main-Regular`][65][1]);$(`\\LaTeX`,`\\textrm{\\html@mathml{`+(`L\\kern-.36em\\raisebox{`+Yq+`}{\\scriptstyle A}`)+`\\kern-.15em\\TeX}{LaTeX}}`),$(`\\KaTeX`,`\\textrm{\\html@mathml{`+(`K\\kern-.17em\\raisebox{`+Yq+`}{\\scriptstyle A}`)+`\\kern-.15em\\TeX}{KaTeX}}`),$(`\\hspace`,`\\@ifstar\\@hspacer\\@hspace`),$(`\\@hspace`,`\\hskip #1\\relax`),$(`\\@hspacer`,`\\rule{0pt}{0pt}\\hskip #1\\relax`),$(`\\ordinarycolon`,`:`),$(`\\vcentcolon`,`\\mathrel{\\mathop\\ordinarycolon}`),$(`\\dblcolon`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}`),$(`\\coloneqq`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}`),$(`\\Coloneqq`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}`),$(`\\coloneq`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}`),$(`\\Coloneq`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}`),$(`\\eqqcolon`,`\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}`),$(`\\Eqqcolon`,`\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}`),$(`\\eqcolon`,`\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}`),$(`\\Eqcolon`,`\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}`),$(`\\colonapprox`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}`),$(`\\Colonapprox`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}`),$(`\\colonsim`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}`),$(`\\Colonsim`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}`),$(`∷`,`\\dblcolon`),$(`∹`,`\\eqcolon`),$(`≔`,`\\coloneqq`),$(`≕`,`\\eqqcolon`),$(`⩴`,`\\Coloneqq`),$(`\\ratio`,`\\vcentcolon`),$(`\\coloncolon`,`\\dblcolon`),$(`\\colonequals`,`\\coloneqq`),$(`\\coloncolonequals`,`\\Coloneqq`),$(`\\equalscolon`,`\\eqqcolon`),$(`\\equalscoloncolon`,`\\Eqqcolon`),$(`\\colonminus`,`\\coloneq`),$(`\\coloncolonminus`,`\\Coloneq`),$(`\\minuscolon`,`\\eqcolon`),$(`\\minuscoloncolon`,`\\Eqcolon`),$(`\\coloncolonapprox`,`\\Colonapprox`),$(`\\coloncolonsim`,`\\Colonsim`),$(`\\simcolon`,`\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}`),$(`\\simcoloncolon`,`\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}`),$(`\\approxcolon`,`\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}`),$(`\\approxcoloncolon`,`\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}`),$(`\\notni`,"\\html@mathml{\\not\\ni}{\\mathrel{\\char`∌}}"),$(`\\limsup`,`\\DOTSB\\operatorname*{lim\\,sup}`),$(`\\liminf`,`\\DOTSB\\operatorname*{lim\\,inf}`),$(`\\injlim`,`\\DOTSB\\operatorname*{inj\\,lim}`),$(`\\projlim`,`\\DOTSB\\operatorname*{proj\\,lim}`),$(`\\varlimsup`,`\\DOTSB\\operatorname*{\\overline{lim}}`),$(`\\varliminf`,`\\DOTSB\\operatorname*{\\underline{lim}}`),$(`\\varinjlim`,`\\DOTSB\\operatorname*{\\underrightarrow{lim}}`),$(`\\varprojlim`,`\\DOTSB\\operatorname*{\\underleftarrow{lim}}`),$(`\\gvertneqq`,`\\html@mathml{\\@gvertneqq}{≩}`),$(`\\lvertneqq`,`\\html@mathml{\\@lvertneqq}{≨}`),$(`\\ngeqq`,`\\html@mathml{\\@ngeqq}{≱}`),$(`\\ngeqslant`,`\\html@mathml{\\@ngeqslant}{≱}`),$(`\\nleqq`,`\\html@mathml{\\@nleqq}{≰}`),$(`\\nleqslant`,`\\html@mathml{\\@nleqslant}{≰}`),$(`\\nshortmid`,`\\html@mathml{\\@nshortmid}{∤}`),$(`\\nshortparallel`,`\\html@mathml{\\@nshortparallel}{∦}`),$(`\\nsubseteqq`,`\\html@mathml{\\@nsubseteqq}{⊈}`),$(`\\nsupseteqq`,`\\html@mathml{\\@nsupseteqq}{⊉}`),$(`\\varsubsetneq`,`\\html@mathml{\\@varsubsetneq}{⊊}`),$(`\\varsubsetneqq`,`\\html@mathml{\\@varsubsetneqq}{⫋}`),$(`\\varsupsetneq`,`\\html@mathml{\\@varsupsetneq}{⊋}`),$(`\\varsupsetneqq`,`\\html@mathml{\\@varsupsetneqq}{⫌}`),$(`\\imath`,`\\html@mathml{\\@imath}{ı}`),$(`\\jmath`,`\\html@mathml{\\@jmath}{ȷ}`),$(`\\llbracket`,"\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`⟦}}"),$(`\\rrbracket`,"\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`⟧}}"),$(`⟦`,`\\llbracket`),$(`⟧`,`\\rrbracket`),$(`\\lBrace`,"\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`⦃}}"),$(`\\rBrace`,"\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`⦄}}"),$(`↤`,`\\mapsfrom`),$(`\\mapsfrom`,"\\html@mathml{\\mathrel{\\mathreflectbox{\\mapsto}}}{\\mathrel{\\char`↤}}"),$(`⦃`,`\\lBrace`),$(`⦄`,`\\rBrace`),$(`\\minuso`,"\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`⦵}}"),$(`⦵`,`\\minuso`),$(`\\darr`,`\\downarrow`),$(`\\dArr`,`\\Downarrow`),$(`\\Darr`,`\\Downarrow`),$(`\\lang`,`\\langle`),$(`\\rang`,`\\rangle`),$(`\\uarr`,`\\uparrow`),$(`\\uArr`,`\\Uparrow`),$(`\\Uarr`,`\\Uparrow`),$(`\\N`,`\\mathbb{N}`),$(`\\R`,`\\mathbb{R}`),$(`\\Z`,`\\mathbb{Z}`),$(`\\alef`,`\\aleph`),$(`\\alefsym`,`\\aleph`),$(`\\Alpha`,`\\mathrm{A}`),$(`\\Beta`,`\\mathrm{B}`),$(`\\bull`,`\\bullet`),$(`\\Chi`,`\\mathrm{X}`),$(`\\clubs`,`\\clubsuit`),$(`\\cnums`,`\\mathbb{C}`),$(`\\Complex`,`\\mathbb{C}`),$(`\\Dagger`,`\\ddagger`),$(`\\diamonds`,`\\diamondsuit`),$(`\\empty`,`\\emptyset`),$(`\\Epsilon`,`\\mathrm{E}`),$(`\\Eta`,`\\mathrm{H}`),$(`\\exist`,`\\exists`),$(`\\harr`,`\\leftrightarrow`),$(`\\hArr`,`\\Leftrightarrow`),$(`\\Harr`,`\\Leftrightarrow`),$(`\\hearts`,`\\heartsuit`),$(`\\image`,`\\Im`),$(`\\infin`,`\\infty`),$(`\\Iota`,`\\mathrm{I}`),$(`\\isin`,`\\in`),$(`\\Kappa`,`\\mathrm{K}`),$(`\\larr`,`\\leftarrow`),$(`\\lArr`,`\\Leftarrow`),$(`\\Larr`,`\\Leftarrow`),$(`\\lrarr`,`\\leftrightarrow`),$(`\\lrArr`,`\\Leftrightarrow`),$(`\\Lrarr`,`\\Leftrightarrow`),$(`\\Mu`,`\\mathrm{M}`),$(`\\natnums`,`\\mathbb{N}`),$(`\\Nu`,`\\mathrm{N}`),$(`\\Omicron`,`\\mathrm{O}`),$(`\\plusmn`,`\\pm`),$(`\\rarr`,`\\rightarrow`),$(`\\rArr`,`\\Rightarrow`),$(`\\Rarr`,`\\Rightarrow`),$(`\\real`,`\\Re`),$(`\\reals`,`\\mathbb{R}`),$(`\\Reals`,`\\mathbb{R}`),$(`\\Rho`,`\\mathrm{P}`),$(`\\sdot`,`\\cdot`),$(`\\sect`,`\\S`),$(`\\spades`,`\\spadesuit`),$(`\\sub`,`\\subset`),$(`\\sube`,`\\subseteq`),$(`\\supe`,`\\supseteq`),$(`\\Tau`,`\\mathrm{T}`),$(`\\thetasym`,`\\vartheta`),$(`\\weierp`,`\\wp`),$(`\\Zeta`,`\\mathrm{Z}`),$(`\\argmin`,`\\DOTSB\\operatorname*{arg\\,min}`),$(`\\argmax`,`\\DOTSB\\operatorname*{arg\\,max}`),$(`\\plim`,`\\DOTSB\\mathop{\\operatorname{plim}}\\limits`),$(`\\bra`,`\\mathinner{\\langle{#1}|}`),$(`\\ket`,`\\mathinner{|{#1}\\rangle}`),$(`\\braket`,`\\mathinner{\\langle{#1}\\rangle}`),$(`\\Bra`,`\\left\\langle#1\\right|`),$(`\\Ket`,`\\left|#1\\right\\rangle`);var Xq=e=>t=>{var n=t.consumeArg().tokens,r=t.consumeArg().tokens,i=t.consumeArg().tokens,a=t.consumeArg().tokens,o=t.macros.get(`|`),s=t.macros.get(`\\|`);t.macros.beginGroup();var c=t=>n=>{e&&(n.macros.set(`|`,o),i.length&&n.macros.set(`\\|`,s));var a=t;return!t&&i.length&&n.future().text===`|`&&(n.popToken(),a=!0),{tokens:a?i:r,numArgs:0}};t.macros.set(`|`,c(!1)),i.length&&t.macros.set(`\\|`,c(!0));var l=t.consumeArg().tokens,u=t.expandTokens([...a,...l,...n]);return t.macros.endGroup(),{tokens:u.reverse(),numArgs:0}};$(`\\bra@ket`,Xq(!1)),$(`\\bra@set`,Xq(!0)),$(`\\Braket`,`\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}`),$(`\\Set`,`\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}`),$(`\\set`,`\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}`),$(`\\angln`,`{\\angl n}`),$(`\\blue`,`\\textcolor{##6495ed}{#1}`),$(`\\orange`,`\\textcolor{##ffa500}{#1}`),$(`\\pink`,`\\textcolor{##ff00af}{#1}`),$(`\\red`,`\\textcolor{##df0030}{#1}`),$(`\\green`,`\\textcolor{##28ae7b}{#1}`),$(`\\gray`,`\\textcolor{gray}{#1}`),$(`\\purple`,`\\textcolor{##9d38bd}{#1}`),$(`\\blueA`,`\\textcolor{##ccfaff}{#1}`),$(`\\blueB`,`\\textcolor{##80f6ff}{#1}`),$(`\\blueC`,`\\textcolor{##63d9ea}{#1}`),$(`\\blueD`,`\\textcolor{##11accd}{#1}`),$(`\\blueE`,`\\textcolor{##0c7f99}{#1}`),$(`\\tealA`,`\\textcolor{##94fff5}{#1}`),$(`\\tealB`,`\\textcolor{##26edd5}{#1}`),$(`\\tealC`,`\\textcolor{##01d1c1}{#1}`),$(`\\tealD`,`\\textcolor{##01a995}{#1}`),$(`\\tealE`,`\\textcolor{##208170}{#1}`),$(`\\greenA`,`\\textcolor{##b6ffb0}{#1}`),$(`\\greenB`,`\\textcolor{##8af281}{#1}`),$(`\\greenC`,`\\textcolor{##74cf70}{#1}`),$(`\\greenD`,`\\textcolor{##1fab54}{#1}`),$(`\\greenE`,`\\textcolor{##0d923f}{#1}`),$(`\\goldA`,`\\textcolor{##ffd0a9}{#1}`),$(`\\goldB`,`\\textcolor{##ffbb71}{#1}`),$(`\\goldC`,`\\textcolor{##ff9c39}{#1}`),$(`\\goldD`,`\\textcolor{##e07d10}{#1}`),$(`\\goldE`,`\\textcolor{##a75a05}{#1}`),$(`\\redA`,`\\textcolor{##fca9a9}{#1}`),$(`\\redB`,`\\textcolor{##ff8482}{#1}`),$(`\\redC`,`\\textcolor{##f9685d}{#1}`),$(`\\redD`,`\\textcolor{##e84d39}{#1}`),$(`\\redE`,`\\textcolor{##bc2612}{#1}`),$(`\\maroonA`,`\\textcolor{##ffbde0}{#1}`),$(`\\maroonB`,`\\textcolor{##ff92c6}{#1}`),$(`\\maroonC`,`\\textcolor{##ed5fa6}{#1}`),$(`\\maroonD`,`\\textcolor{##ca337c}{#1}`),$(`\\maroonE`,`\\textcolor{##9e034e}{#1}`),$(`\\purpleA`,`\\textcolor{##ddd7ff}{#1}`),$(`\\purpleB`,`\\textcolor{##c6b9fc}{#1}`),$(`\\purpleC`,`\\textcolor{##aa87ff}{#1}`),$(`\\purpleD`,`\\textcolor{##7854ab}{#1}`),$(`\\purpleE`,`\\textcolor{##543b78}{#1}`),$(`\\mintA`,`\\textcolor{##f5f9e8}{#1}`),$(`\\mintB`,`\\textcolor{##edf2df}{#1}`),$(`\\mintC`,`\\textcolor{##e0e5cc}{#1}`),$(`\\grayA`,`\\textcolor{##f6f7f7}{#1}`),$(`\\grayB`,`\\textcolor{##f0f1f2}{#1}`),$(`\\grayC`,`\\textcolor{##e3e5e6}{#1}`),$(`\\grayD`,`\\textcolor{##d6d8da}{#1}`),$(`\\grayE`,`\\textcolor{##babec2}{#1}`),$(`\\grayF`,`\\textcolor{##888d93}{#1}`),$(`\\grayG`,`\\textcolor{##626569}{#1}`),$(`\\grayH`,`\\textcolor{##3b3e40}{#1}`),$(`\\grayI`,`\\textcolor{##21242c}{#1}`),$(`\\kaBlue`,`\\textcolor{##314453}{#1}`),$(`\\kaGreen`,`\\textcolor{##71B307}{#1}`);var Zq={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0},Qq=class{constructor(e,t,n){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=t,this.expansionCount=0,this.feed(e),this.macros=new Hq(Uq,t.macros),this.mode=n,this.stack=[]}feed(e){this.lexer=new Vq(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return this.stack.length===0&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){var t,n,r;if(e){if(this.consumeSpaces(),this.future().text!==`[`)return null;t=this.popToken();var i=this.consumeArg([`]`]);r=i.tokens,n=i.end}else{var a=this.consumeArg();r=a.tokens,t=a.start,n=a.end}return this.pushToken(new VK(`EOF`,n.loc)),this.pushTokens(r),new VK(``,BK.range(t,n))}consumeSpaces(){for(;this.future().text===` `;)this.stack.pop()}consumeArg(e){var t=[],n=e&&e.length>0;n||this.consumeSpaces();var r=this.future(),i,a=0,o=0;do{if(i=this.popToken(),t.push(i),i.text===`{`)++a;else if(i.text===`}`){if(--a,a===-1)throw new L(`Extra }`,i)}else if(i.text===`EOF`)throw new L(`Unexpected end of input in a macro argument, expected '`+(e&&n?e[o]:`}`)+`'`,i);if(e&&n){if((a===0||a===1&&e[o]===`{`)&&i.text===e[o]){if(++o,o===e.length){t.splice(-o,o);break}}else o=0}}while(a!==0||n);return r.text===`{`&&t[t.length-1].text===`}`&&(t.pop(),t.shift()),t.reverse(),{tokens:t,start:r,end:i}}consumeArgs(e,t){if(t){if(t.length!==e+1)throw new L(`The length of delimiters doesn't match the number of args!`);for(var n=t[0],r=0;rthis.settings.maxExpand)throw new L(`Too many expansions: infinite loop or need to increase maxExpand setting`)}expandOnce(e){var t=this.popToken(),n=t.text,r=t.noexpand?null:this._getExpansion(n);if(r==null||e&&r.unexpandable){if(e&&r==null&&n[0]===`\\`&&!this.isDefined(n))throw new L(`Undefined control sequence: `+n);return this.pushToken(t),!1}this.countExpansion(1);var i=r.tokens,a=this.consumeArgs(r.numArgs,r.delimiters);if(r.numArgs){i=i.slice();for(var o=i.length-1;o>=0;--o){var s=i[o];if(s.text===`#`){if(o===0)throw new L(`Incomplete placeholder at end of macro body`,s);if(s=i[--o],s.text===`#`)i.splice(o+1,1);else if(/^[1-9]$/.test(s.text))i.splice(o,2,...a[s.text-1]);else throw new L(`Not a valid argument number`,s)}}}return this.pushTokens(i),i.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(this.expandOnce()===!1){var e=this.stack.pop();return e.treatAsRelax&&(e.text=`\\relax`),e}}expandMacro(e){return this.macros.has(e)?this.expandTokens([new VK(e)]):void 0}expandTokens(e){var t=[],n=this.stack.length;for(this.pushTokens(e);this.stack.length>n;)if(this.expandOnce(!0)===!1){var r=this.stack.pop();r.treatAsRelax&&=(r.noexpand=!1,!1),t.push(r)}return this.countExpansion(t.length),t}expandMacroAsText(e){var t=this.expandMacro(e);return t&&t.map(e=>e.text).join(``)}_getExpansion(e){var t=this.macros.get(e);if(t==null)return t;if(e.length===1){var n=this.lexer.catcodes[e];if(n!=null&&n!==13)return}var r=typeof t==`function`?t(this):t;if(typeof r==`string`){var i=0;if(r.includes(`#`))for(var a=r.replace(/##/g,``);a.includes(`#`+(i+1));)++i;for(var o=new Vq(r,this.settings),s=[],c=o.lex();c.text!==`EOF`;)s.push(c),c=o.lex();return s.reverse(),{tokens:s,numArgs:i}}return r}isDefined(e){return this.macros.has(e)||Object.prototype.hasOwnProperty.call(Mq,e)||Object.prototype.hasOwnProperty.call(EU.math,e)||Object.prototype.hasOwnProperty.call(EU.text,e)||Object.prototype.hasOwnProperty.call(Zq,e)}isExpandable(e){var t=this.macros.get(e);return t==null?Object.prototype.hasOwnProperty.call(Mq,e)&&!Mq[e].primitive:typeof t==`string`||typeof t==`function`||!t.unexpandable}},$q=/^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/,eJ=Object.freeze({"₊":`+`,"₋":`-`,"₌":`=`,"₍":`(`,"₎":`)`,"₀":`0`,"₁":`1`,"₂":`2`,"₃":`3`,"₄":`4`,"₅":`5`,"₆":`6`,"₇":`7`,"₈":`8`,"₉":`9`,ₐ:`a`,ₑ:`e`,ₕ:`h`,ᵢ:`i`,ⱼ:`j`,ₖ:`k`,ₗ:`l`,ₘ:`m`,ₙ:`n`,ₒ:`o`,ₚ:`p`,ᵣ:`r`,ₛ:`s`,ₜ:`t`,ᵤ:`u`,ᵥ:`v`,ₓ:`x`,ᵦ:`β`,ᵧ:`γ`,ᵨ:`ρ`,ᵩ:`ϕ`,ᵪ:`χ`,"⁺":`+`,"⁻":`-`,"⁼":`=`,"⁽":`(`,"⁾":`)`,"⁰":`0`,"¹":`1`,"²":`2`,"³":`3`,"⁴":`4`,"⁵":`5`,"⁶":`6`,"⁷":`7`,"⁸":`8`,"⁹":`9`,ᴬ:`A`,ᴮ:`B`,ᴰ:`D`,ᴱ:`E`,ᴳ:`G`,ᴴ:`H`,ᴵ:`I`,ᴶ:`J`,ᴷ:`K`,ᴸ:`L`,ᴹ:`M`,ᴺ:`N`,ᴼ:`O`,ᴾ:`P`,ᴿ:`R`,ᵀ:`T`,ᵁ:`U`,ⱽ:`V`,ᵂ:`W`,ᵃ:`a`,ᵇ:`b`,ᶜ:`c`,ᵈ:`d`,ᵉ:`e`,ᶠ:`f`,ᵍ:`g`,ʰ:`h`,ⁱ:`i`,ʲ:`j`,ᵏ:`k`,ˡ:`l`,ᵐ:`m`,ⁿ:`n`,ᵒ:`o`,ᵖ:`p`,ʳ:`r`,ˢ:`s`,ᵗ:`t`,ᵘ:`u`,ᵛ:`v`,ʷ:`w`,ˣ:`x`,ʸ:`y`,ᶻ:`z`,ᵝ:`β`,ᵞ:`γ`,ᵟ:`δ`,ᵠ:`ϕ`,ᵡ:`χ`,ᶿ:`θ`}),tJ={"́":{text:`\\'`,math:`\\acute`},"̀":{text:"\\`",math:`\\grave`},"̈":{text:`\\"`,math:`\\ddot`},"̃":{text:`\\~`,math:`\\tilde`},"̄":{text:`\\=`,math:`\\bar`},"̆":{text:`\\u`,math:`\\breve`},"̌":{text:`\\v`,math:`\\check`},"̂":{text:`\\^`,math:`\\hat`},"̇":{text:`\\.`,math:`\\dot`},"̊":{text:`\\r`,math:`\\mathring`},"̋":{text:`\\H`},"̧":{text:`\\c`}},nJ={á:`á`,à:`à`,ä:`ä`,ǟ:`ǟ`,ã:`ã`,ā:`ā`,ă:`ă`,ắ:`ắ`,ằ:`ằ`,ẵ:`ẵ`,ǎ:`ǎ`,â:`â`,ấ:`ấ`,ầ:`ầ`,ẫ:`ẫ`,ȧ:`ȧ`,ǡ:`ǡ`,å:`å`,ǻ:`ǻ`,ḃ:`ḃ`,ć:`ć`,ḉ:`ḉ`,č:`č`,ĉ:`ĉ`,ċ:`ċ`,ç:`ç`,ď:`ď`,ḋ:`ḋ`,ḑ:`ḑ`,é:`é`,è:`è`,ë:`ë`,ẽ:`ẽ`,ē:`ē`,ḗ:`ḗ`,ḕ:`ḕ`,ĕ:`ĕ`,ḝ:`ḝ`,ě:`ě`,ê:`ê`,ế:`ế`,ề:`ề`,ễ:`ễ`,ė:`ė`,ȩ:`ȩ`,ḟ:`ḟ`,ǵ:`ǵ`,ḡ:`ḡ`,ğ:`ğ`,ǧ:`ǧ`,ĝ:`ĝ`,ġ:`ġ`,ģ:`ģ`,ḧ:`ḧ`,ȟ:`ȟ`,ĥ:`ĥ`,ḣ:`ḣ`,ḩ:`ḩ`,í:`í`,ì:`ì`,ï:`ï`,ḯ:`ḯ`,ĩ:`ĩ`,ī:`ī`,ĭ:`ĭ`,ǐ:`ǐ`,î:`î`,ǰ:`ǰ`,ĵ:`ĵ`,ḱ:`ḱ`,ǩ:`ǩ`,ķ:`ķ`,ĺ:`ĺ`,ľ:`ľ`,ļ:`ļ`,ḿ:`ḿ`,ṁ:`ṁ`,ń:`ń`,ǹ:`ǹ`,ñ:`ñ`,ň:`ň`,ṅ:`ṅ`,ņ:`ņ`,ó:`ó`,ò:`ò`,ö:`ö`,ȫ:`ȫ`,õ:`õ`,ṍ:`ṍ`,ṏ:`ṏ`,ȭ:`ȭ`,ō:`ō`,ṓ:`ṓ`,ṑ:`ṑ`,ŏ:`ŏ`,ǒ:`ǒ`,ô:`ô`,ố:`ố`,ồ:`ồ`,ỗ:`ỗ`,ȯ:`ȯ`,ȱ:`ȱ`,ő:`ő`,ṕ:`ṕ`,ṗ:`ṗ`,ŕ:`ŕ`,ř:`ř`,ṙ:`ṙ`,ŗ:`ŗ`,ś:`ś`,ṥ:`ṥ`,š:`š`,ṧ:`ṧ`,ŝ:`ŝ`,ṡ:`ṡ`,ş:`ş`,ẗ:`ẗ`,ť:`ť`,ṫ:`ṫ`,ţ:`ţ`,ú:`ú`,ù:`ù`,ü:`ü`,ǘ:`ǘ`,ǜ:`ǜ`,ǖ:`ǖ`,ǚ:`ǚ`,ũ:`ũ`,ṹ:`ṹ`,ū:`ū`,ṻ:`ṻ`,ŭ:`ŭ`,ǔ:`ǔ`,û:`û`,ů:`ů`,ű:`ű`,ṽ:`ṽ`,ẃ:`ẃ`,ẁ:`ẁ`,ẅ:`ẅ`,ŵ:`ŵ`,ẇ:`ẇ`,ẘ:`ẘ`,ẍ:`ẍ`,ẋ:`ẋ`,ý:`ý`,ỳ:`ỳ`,ÿ:`ÿ`,ỹ:`ỹ`,ȳ:`ȳ`,ŷ:`ŷ`,ẏ:`ẏ`,ẙ:`ẙ`,ź:`ź`,ž:`ž`,ẑ:`ẑ`,ż:`ż`,Á:`Á`,À:`À`,Ä:`Ä`,Ǟ:`Ǟ`,Ã:`Ã`,Ā:`Ā`,Ă:`Ă`,Ắ:`Ắ`,Ằ:`Ằ`,Ẵ:`Ẵ`,Ǎ:`Ǎ`,Â:`Â`,Ấ:`Ấ`,Ầ:`Ầ`,Ẫ:`Ẫ`,Ȧ:`Ȧ`,Ǡ:`Ǡ`,Å:`Å`,Ǻ:`Ǻ`,Ḃ:`Ḃ`,Ć:`Ć`,Ḉ:`Ḉ`,Č:`Č`,Ĉ:`Ĉ`,Ċ:`Ċ`,Ç:`Ç`,Ď:`Ď`,Ḋ:`Ḋ`,Ḑ:`Ḑ`,É:`É`,È:`È`,Ë:`Ë`,Ẽ:`Ẽ`,Ē:`Ē`,Ḗ:`Ḗ`,Ḕ:`Ḕ`,Ĕ:`Ĕ`,Ḝ:`Ḝ`,Ě:`Ě`,Ê:`Ê`,Ế:`Ế`,Ề:`Ề`,Ễ:`Ễ`,Ė:`Ė`,Ȩ:`Ȩ`,Ḟ:`Ḟ`,Ǵ:`Ǵ`,Ḡ:`Ḡ`,Ğ:`Ğ`,Ǧ:`Ǧ`,Ĝ:`Ĝ`,Ġ:`Ġ`,Ģ:`Ģ`,Ḧ:`Ḧ`,Ȟ:`Ȟ`,Ĥ:`Ĥ`,Ḣ:`Ḣ`,Ḩ:`Ḩ`,Í:`Í`,Ì:`Ì`,Ï:`Ï`,Ḯ:`Ḯ`,Ĩ:`Ĩ`,Ī:`Ī`,Ĭ:`Ĭ`,Ǐ:`Ǐ`,Î:`Î`,İ:`İ`,Ĵ:`Ĵ`,Ḱ:`Ḱ`,Ǩ:`Ǩ`,Ķ:`Ķ`,Ĺ:`Ĺ`,Ľ:`Ľ`,Ļ:`Ļ`,Ḿ:`Ḿ`,Ṁ:`Ṁ`,Ń:`Ń`,Ǹ:`Ǹ`,Ñ:`Ñ`,Ň:`Ň`,Ṅ:`Ṅ`,Ņ:`Ņ`,Ó:`Ó`,Ò:`Ò`,Ö:`Ö`,Ȫ:`Ȫ`,Õ:`Õ`,Ṍ:`Ṍ`,Ṏ:`Ṏ`,Ȭ:`Ȭ`,Ō:`Ō`,Ṓ:`Ṓ`,Ṑ:`Ṑ`,Ŏ:`Ŏ`,Ǒ:`Ǒ`,Ô:`Ô`,Ố:`Ố`,Ồ:`Ồ`,Ỗ:`Ỗ`,Ȯ:`Ȯ`,Ȱ:`Ȱ`,Ő:`Ő`,Ṕ:`Ṕ`,Ṗ:`Ṗ`,Ŕ:`Ŕ`,Ř:`Ř`,Ṙ:`Ṙ`,Ŗ:`Ŗ`,Ś:`Ś`,Ṥ:`Ṥ`,Š:`Š`,Ṧ:`Ṧ`,Ŝ:`Ŝ`,Ṡ:`Ṡ`,Ş:`Ş`,Ť:`Ť`,Ṫ:`Ṫ`,Ţ:`Ţ`,Ú:`Ú`,Ù:`Ù`,Ü:`Ü`,Ǘ:`Ǘ`,Ǜ:`Ǜ`,Ǖ:`Ǖ`,Ǚ:`Ǚ`,Ũ:`Ũ`,Ṹ:`Ṹ`,Ū:`Ū`,Ṻ:`Ṻ`,Ŭ:`Ŭ`,Ǔ:`Ǔ`,Û:`Û`,Ů:`Ů`,Ű:`Ű`,Ṽ:`Ṽ`,Ẃ:`Ẃ`,Ẁ:`Ẁ`,Ẅ:`Ẅ`,Ŵ:`Ŵ`,Ẇ:`Ẇ`,Ẍ:`Ẍ`,Ẋ:`Ẋ`,Ý:`Ý`,Ỳ:`Ỳ`,Ÿ:`Ÿ`,Ỹ:`Ỹ`,Ȳ:`Ȳ`,Ŷ:`Ŷ`,Ẏ:`Ẏ`,Ź:`Ź`,Ž:`Ž`,Ẑ:`Ẑ`,Ż:`Ż`,ά:`ά`,ὰ:`ὰ`,ᾱ:`ᾱ`,ᾰ:`ᾰ`,έ:`έ`,ὲ:`ὲ`,ή:`ή`,ὴ:`ὴ`,ί:`ί`,ὶ:`ὶ`,ϊ:`ϊ`,ΐ:`ΐ`,ῒ:`ῒ`,ῑ:`ῑ`,ῐ:`ῐ`,ό:`ό`,ὸ:`ὸ`,ύ:`ύ`,ὺ:`ὺ`,ϋ:`ϋ`,ΰ:`ΰ`,ῢ:`ῢ`,ῡ:`ῡ`,ῠ:`ῠ`,ώ:`ώ`,ὼ:`ὼ`,Ύ:`Ύ`,Ὺ:`Ὺ`,Ϋ:`Ϋ`,Ῡ:`Ῡ`,Ῠ:`Ῠ`,Ώ:`Ώ`,Ὼ:`Ὼ`},rJ=class e{constructor(e,t){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode=`math`,this.gullet=new Qq(e,t,this.mode),this.settings=t,this.leftrightDepth=0,this.nextToken=null}expect(e,t){if(t===void 0&&(t=!0),this.fetch().text!==e)throw new L(`Expected '`+e+`', got '`+this.fetch().text+`'`,this.fetch());t&&this.consume()}consume(){this.nextToken=null}fetch(){return this.nextToken??=this.gullet.expandNextToken(),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set(`\\color`,`\\textcolor`);try{var e=this.parseExpression(!1);return this.expect(`EOF`),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){var t=this.nextToken;this.consume(),this.gullet.pushToken(new VK(`}`)),this.gullet.pushTokens(e);var n=this.parseExpression(!1);return this.expect(`}`),this.nextToken=t,n}parseExpression(t,n){for(var r=[];;){this.mode===`math`&&this.consumeSpaces();var i=this.fetch();if(e.endOfExpression.has(i.text)||n&&i.text===n||t&&Mq[i.text]&&Mq[i.text].infix)break;var a=this.parseAtom(n);if(!a)break;a.type!==`internal`&&r.push(a)}return this.mode===`text`&&this.formLigatures(r),this.handleInfixNodes(r)}handleInfixNodes(e){for(var t=-1,n,r=0;r=128)this.settings.strict&&(IH(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:BK.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;ce.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(` +`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{uJ.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),fJ=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},pJ=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:fJ,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{uJ.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),mJ=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[dJ.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),pJ.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function hJ(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;MV({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return mJ.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function gJ({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new Un,command:({editor:e,range:t,props:i})=>{var a,o;let s=e.view.state.selection.$to.nodeAfter;s!=null&&(a=s.text)!=null&&a.startsWith(` `)&&(t.to+=1),e.chain().focus().insertContentAt(t,[{type:n,attrs:{...i,mentionSuggestionChar:r}},{type:`text`,text:` `}]).run(),(o=e.view.dom.ownerDocument.defaultView)==null||(o=o.getSelection())==null||o.collapseToEnd()},allow:({state:e,range:t})=>{let r=e.doc.resolve(t.from),i=e.schema.nodes[n];return!!r.parent.type.contentMatch.matchType(i)},...t}}function _J(e){return(e.options.suggestions.length?e.options.suggestions:[e.options.suggestion]).map(t=>gJ({editor:e.editor,overrideSuggestionOptions:t,extensionName:e.name,char:t.char}))}function vJ(e,t){let n=_J(e);return n.find(e=>e.char===t)||(n.length?n[0]:null)}var yJ=Jp.create({name:`mention`,priority:101,addOptions(){return{HTMLAttributes:{},renderText({node:e,suggestion:t}){return`${t?.char??`@`}${e.attrs.label??e.attrs.id}`},deleteTriggerWithBackspace:!1,renderHTML({options:e,node:t,suggestion:n}){return[`span`,A(this.HTMLAttributes,e.HTMLAttributes),`${n?.char??`@`}${t.attrs.label??t.attrs.id}`]},suggestions:[],suggestion:{}}},group:`inline`,inline:!0,selectable:!1,atom:!0,addAttributes(){return{id:{default:null,parseHTML:e=>e.getAttribute(`data-id`),renderHTML:e=>e.id?{"data-id":e.id}:{}},label:{default:null,parseHTML:e=>e.getAttribute(`data-label`),renderHTML:e=>e.label?{"data-label":e.label}:{}},mentionSuggestionChar:{default:`@`,parseHTML:e=>e.getAttribute(`data-mention-suggestion-char`),renderHTML:e=>({"data-mention-suggestion-char":e.mentionSuggestionChar})}}},parseHTML(){return[{tag:`span[data-type="${this.name}"]`}]},renderHTML({node:e,HTMLAttributes:t}){let n=vJ(this,e.attrs.mentionSuggestionChar);if(this.options.renderLabel!==void 0)return console.warn(`renderLabel is deprecated use renderText and renderHTML instead`),[`span`,A({"data-type":this.name},this.options.HTMLAttributes,t),this.options.renderLabel({options:this.options,node:e,suggestion:n})];let r={...this.options};r.HTMLAttributes=A({"data-type":this.name},this.options.HTMLAttributes,t);let i=this.options.renderHTML({options:r,node:e,suggestion:n});return typeof i==`string`?[`span`,A({"data-type":this.name},this.options.HTMLAttributes,t),i]:i},...$f({nodeName:`mention`,name:`@`,selfClosing:!0,allowedAttributes:[`id`,`label`,{name:`mentionSuggestionChar`,skipIfDefault:`@`}],parseAttributes:e=>{let t={},n=/(?:^|\s)(\w+)=(?:"([^"]*)"|'([^']*)')/g,r=n.exec(e);for(;r!==null;){let[,i,a,o]=r;t[i===`char`?`mentionSuggestionChar`:i]=a??o,r=n.exec(e)}return t},serializeAttributes:e=>Object.entries(e).filter(([,e])=>e!=null).map(([e,t])=>`${e===`mentionSuggestionChar`?`char`:e}="${t}"`).join(` `)}),renderText({node:e}){let t={options:this.options,node:e,suggestion:vJ(this,e.attrs.mentionSuggestionChar)};return this.options.renderLabel===void 0?this.options.renderText(t):(console.warn(`renderLabel is deprecated use renderText and renderHTML instead`),this.options.renderLabel(t))},addKeyboardShortcuts(){return{Backspace:()=>this.editor.commands.command(({tr:e,state:t})=>{let n=!1,{selection:r}=t,{empty:i,anchor:a}=r;if(!i)return!1;let o=new ce,s=0;return t.doc.nodesBetween(a-1,a,(e,t)=>{if(e.type.name===this.name)return n=!0,o=e,s=t,!1}),n&&e.insertText(this.options.deleteTriggerWithBackspace?``:o.attrs.mentionSuggestionChar,s,s+o.nodeSize),n})}},addProseMirrorPlugins(){return _J(this).map(uV)}});function bJ(e,t){return yJ.configure({HTMLAttributes:{class:`dw-mention`},renderText:({node:e})=>`@${e.attrs.label??e.attrs.id}`,suggestion:{char:`@`,allow:()=>!!t,findSuggestionMatch:t=>{let n=XB({...t,allowSpaces:!0});return n&&GB(n.query,e)?n:XB({...t,allowSpaces:!1})},items:async({query:n})=>{if(!t)return[];let r=WB(n,e,!!t.me).map(e=>({date:e})),i=(await t.search(n).catch(()=>[])).map(e=>({person:e}));return n.trim()?[...r,...i].slice(0,8):[...i.slice(0,6),...r]},render:Bj({label:e.mentions,empty:e.noPeople,toItem:t=>`person`in t?{label:t.person.label,description:t.person.hint,icon:`at`}:{label:HB(t.date.date,e),description:t.date.remind?`${e.dates.remindMe} · ${UB(t.date.date,e)}`:UB(t.date.date,e),icon:t.date.remind?`bell`:`calendar`},pick:(e,n)=>{`person`in n?e.command({id:n.person.id,label:n.person.label}):JB(e.editor,e.range,n.date,t?.me)}})}})}var xJ=`flowchart LR + Idea --> Draft --> Review --> Published`,SJ=null;function CJ(e){return SJ??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),SJ}var wJ=0;async function TJ(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await CJ(r)).render(`dw-mermaid-${++wJ}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var EJ=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=xJ)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return TJ(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;MV({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void TJ(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),TJ(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void TJ(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),TJ(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function DJ(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function OJ(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`database`,`database`,[`kanban`,`board`,`calendar`,`records`,`tracker`,`notion`],(e,t)=>e.chain().focus().deleteRange(t).insertDatabase().run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().focus().deleteRange(r).run(),RV(t,e,a,n)}),o(`linkCard`,`link`,[`bookmark`,`preview`,`card`,`url`,`web`],(t,r)=>{t.chain().focus().deleteRange(r).run(),zV(t,e,a,n)})],c=e=>{let t=new Date;return RB(new Date(t.getFullYear(),t.getMonth(),t.getDate()+e))};if(s.push(o(`today`,`calendar`,[`date`,`day`],(e,t)=>JB(e,t,{date:c(0),remind:!1})),o(`tomorrow`,`calendar`,[`date`,`day`],(e,t)=>JB(e,t,{date:c(1),remind:!1})),o(`yesterday`,`calendar`,[`date`,`day`],(e,t)=>JB(e,t,{date:c(-1),remind:!1})),o(`now`,`clock`,[`time`,`date`,`timestamp`],(t,n)=>{JB(t,n,{date:c(0),remind:!1});let r=new Intl.DateTimeFormat(e.locale,{hour:`numeric`,minute:`2-digit`}).format(new Date);t.chain().focus().insertContent(`${r} `).run()})),r&&(s.push(o(`pageLink`,`link`,[`page`,`link`,`[[`,`wiki`],(e,t)=>e.chain().focus().deleteRange(t).insertContent(`[[`).run())),s.push(o(`syncedPage`,`copy`,[`embed`,`transclude`,`include`,`mirror`,`![[`],(e,t)=>e.chain().focus().deleteRange(t).insertContent(`![[`).run())),r.create&&s.push(o(`newPage`,`page-plus`,[`page`,`doc`,`subpage`,`create`],(e,t)=>{e.chain().focus().deleteRange(t).run(),gV(e,r,``).catch(n)}))),t?.upload){let e=e=>(r,i)=>{r.chain().focus().deleteRange(i).run(),DJ(e).then(e=>GV(r,t,e).catch(n))};s.push(o(`image`,`image`,[`picture`,`photo`,`img`],e(`image/*`)),o(`file`,`paperclip`,[`attachment`,`upload`,`pdf`],e(``)),o(`drawio`,`diagram`,[`diagram`,`diagrams.net`,`draw`,`chart`,`uml`],(e,t)=>e.chain().focus().deleteRange(t).insertDiagram(`drawio`).run())),i&&s.push(o(`excalidraw`,`pencil`,[`drawing`,`sketch`,`whiteboard`,`draw`],(e,t)=>e.chain().focus().deleteRange(t).insertDiagram(`excalidraw`).run()))}return s}function kJ(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e=>e.label.toLowerCase().includes(n)||e.id.startsWith(n)||e.keywords.some(e=>e.toLowerCase().startsWith(n));return e.flatMap(e=>{let t=e.children?.filter(r)??[];return t.length?t:r(e)?[e]:[]})}var AJ=Tp.create({name:`slashMenu`,addOptions(){return{commands:[],labels:void 0}},addProseMirrorPlugins(){return[dV({editor:this.editor,pluginKey:new Un(`slashMenu`),char:`/`,allowSpaces:!1,startOfLine:!1,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:({query:e})=>kJ(this.options.commands,e),render:Bj({label:this.options.labels.slashMenu,empty:this.options.labels.noMatches,showQuery:!0,toItem:e=>({label:e.label,description:e.description,icon:e.icon}),children:e=>e.children,pick:(e,t)=>t.run(e.editor,e.range)})})]}});function jJ(e,t){let n=!0,r=e.firstChild?.childCount??0;return e.forEach(e=>{t===`column`&&e.childCount!==r&&(n=!1),e.forEach(e=>{((t===`row`?e.attrs.rowspan:e.attrs.colspan)??1)>1&&(n=!1)})}),n}function MJ(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}var NJ=e=>{let t=[];return e.forEach(e=>t.push(e)),t};function PJ(e,t,n,r,i,a=0){let o=e.doc.nodeAt(t);if(!o||o.type.name!==`table`||!jJ(o,n))return null;let c=NJ(o),l=n===`row`?c.length:c[0]?.childCount??0;if(r===i||r<0||i<0||r>=l||i>=l)return null;let u=n===`row`?MJ(c,r,i):c.map(e=>e.copy(s.fromArray(MJ(NJ(e),r,i)))),d=e.tr.replaceWith(t,t+o.nodeSize,o.copy(s.fromArray(u))),[f,p]=n===`row`?[i,0]:[Math.min(a,u.length-1),i],m=t+1;for(let e=0;e0;e--)if(n.node(e).type.name===`table`)return{tablePos:n.before(e),row:n.index(e),column:e+1<=n.depth?n.index(e+1):0};return null}var IJ=Tp.create({name:`tableMove`,addOptions(){return{labels:null}},addCommands(){let e=e=>t=>({state:n,dispatch:r})=>{let i=FJ(n,n.selection.from);if(!i)return!1;let a=e===`row`?i.row:i.column,o=PJ(n,i.tablePos,e,a,a+t,i.row);return o?(r?.(o),!0):!1};return{moveTableRow:e(`row`),moveTableColumn:e(`column`)}},addKeyboardShortcuts(){return{"Mod-Alt-ArrowUp":()=>this.editor.commands.moveTableRow(-1),"Mod-Alt-ArrowDown":()=>this.editor.commands.moveTableRow(1),"Mod-Alt-ArrowLeft":()=>this.editor.commands.moveTableColumn(-1),"Mod-Alt-ArrowRight":()=>this.editor.commands.moveTableColumn(1)}},addProseMirrorPlugins(){let e=this.options.labels?.table;return[new D({key:new Un(`tableMove`),view:t=>new LJ(t,{row:e?.dragRow??`Drag to move the row`,column:e?.dragColumn??`Drag to move the column`})})]}}),LJ=class{view;grips={row:document.createElement(`button`),column:document.createElement(`button`)};line=document.createElement(`div`);cell=null;drag=null;constructor(e,t){this.view=e;for(let e of[`row`,`column`]){let n=this.grips[e];n.type=`button`,n.className=`dw-table-grip dw-table-grip--${e}`,n.contentEditable=`false`,n.setAttribute(`aria-label`,t[e]),n.title=t[e],n.hidden=!0,n.tabIndex=-1,n.addEventListener(`pointerdown`,t=>this.start(t,e)),n.addEventListener(`mouseleave`,this.leave)}this.line.className=`dw-table-drop`,this.line.hidden=!0,e.dom.addEventListener(`mousemove`,this.move),e.dom.addEventListener(`mouseleave`,this.leave)}get host(){let e=this.view.dom.parentElement;return e&&this.line.parentElement!==e&&(e.classList.add(`dw-block-host`),e.append(this.grips.row,this.grips.column,this.line)),e}hide=()=>{this.drag||(this.grips.row.hidden=!0,this.grips.column.hidden=!0,this.cell=null)};leave=e=>{let t=e.relatedTarget;t&&(this.grips.row.contains(t)||this.grips.column.contains(t)||this.view.dom.contains(t))||this.hide()};move=e=>{if(this.drag)return;let t=e.target?.closest?.(`td, th`),n=this.host;if(!this.view.editable||!n||!(t instanceof HTMLTableCellElement)||!this.view.dom.contains(t))return this.hide();let r=this.locate(t),i=r&&this.view.state.doc.nodeAt(r.tablePos);if(!r||!i)return this.hide();this.cell=t;let a=n.getBoundingClientRect(),o=t.closest(`table`).getBoundingClientRect(),s=t.parentElement.getBoundingClientRect(),c=t.getBoundingClientRect(),l=i.childCount>1&&jJ(i,`row`),u=(i.firstChild?.childCount??0)>1&&jJ(i,`column`);Object.assign(this.grips.row.style,{top:`${s.top-a.top+s.height/2-11}px`,left:`${o.left-a.left-7}px`}),Object.assign(this.grips.column.style,{top:`${o.top-a.top-7}px`,left:`${c.left-a.left+c.width/2-11}px`}),this.grips.row.hidden=!l,this.grips.column.hidden=!u};locate(e){try{return FJ(this.view.state,this.view.posAtDOM(e,0))}catch{return null}}start(e,t){let n=this.cell;if(!n||e.button!==0)return;let r=this.locate(n),i=n.parentElement?.parentElement;if(!r||!i)return;e.preventDefault();let a=this.grips[t];a.setPointerCapture(e.pointerId);let o=[...i.children].filter(e=>e instanceof HTMLTableRowElement),s=t===`row`?r.row:r.column,c=t===`row`?o:[...o[0]?.children??[]],l=t===`row`?[o[s]]:o.map(e=>e.children[s]).filter(Boolean);for(let e of l)e.classList.add(`dw-table-dragging`);this.drag={axis:t,tablePos:r.tablePos,from:s,slots:c,dimmed:l,to:s,cursorRow:r.row},a.addEventListener(`pointermove`,this.dragMove),a.addEventListener(`pointerup`,this.drop),a.addEventListener(`pointercancel`,this.cancel)}dragMove=e=>{let t=this.drag,n=this.host;if(!t||!n)return;let r=t.axis===`row`,i=r?e.clientY:e.clientX,a=t.slots.length;for(let[e,n]of t.slots.entries()){let t=n.getBoundingClientRect();if(i<(r?t.top+t.height/2:t.left+t.width/2)){a=e;break}}t.to=a>t.from?a-1:a;let o=n.getBoundingClientRect(),s=t.slots[0].closest(`table`).getBoundingClientRect(),c=t.slots.at(-1).getBoundingClientRect(),l=t.slots[a]?.getBoundingClientRect(),u=r?l?.top??c.bottom:l?.left??c.right;Object.assign(this.line.style,r?{top:`${u-o.top-1}px`,left:`${s.left-o.left}px`,width:`${s.width}px`,height:`2px`}:{top:`${s.top-o.top}px`,left:`${u-o.left-1}px`,width:`2px`,height:`${s.height}px`}),this.line.hidden=t.to===t.from};drop=()=>{let e=this.drag;if(this.cancel(),!e||e.to===e.from)return;let t=PJ(this.view.state,e.tablePos,e.axis,e.from,e.to,e.cursorRow);t&&this.view.dispatch(t),this.view.focus()};cancel=()=>{let e=this.drag;for(let t of e?.dimmed??[])t.classList.remove(`dw-table-dragging`);this.drag=null,this.line.hidden=!0;for(let e of Object.values(this.grips))e.removeEventListener(`pointermove`,this.dragMove),e.removeEventListener(`pointerup`,this.drop),e.removeEventListener(`pointercancel`,this.cancel);this.hide()};update(){this.cell&&!this.cell.isConnected&&this.hide()}destroy(){this.cancel();for(let e of Object.values(this.grips))e.remove();this.line.remove(),this.view.dom.removeEventListener(`mousemove`,this.move),this.view.dom.removeEventListener(`mouseleave`,this.leave)}};function RJ(e){let t=[];return e.descendants((e,n)=>e.type.name!==`heading`||(t.push({level:Number(e.attrs.level)||1,text:e.textContent.trim(),pos:n}),!1)),t}function zJ(e,t){let n=e.view.nodeDOM(t);n instanceof HTMLElement&&n.scrollIntoView({behavior:`smooth`,block:`start`}),e.isEditable&&e.commands.setTextSelection(t+1)}var BJ=Jp.create({name:`tableOfContents`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},parseHTML(){return[{tag:`nav[data-type='toc']`}]},renderHTML(){return[`nav`,{"data-type":`toc`}]},addCommands(){return{insertTableOfContents:()=>({commands:e})=>e.insertContent({type:this.name})}},addNodeView(){return({editor:e})=>{let t=this.options.labels.blocks,n=document.createElement(`nav`);n.className=`dw-toc`,n.setAttribute(`data-type`,`toc`),n.setAttribute(`aria-label`,t.toc),n.contentEditable=`false`;let r=document.createElement(`p`);r.className=`dw-toc__title`,r.textContent=t.toc;let i=document.createElement(`ol`);i.className=`dw-toc__list`,n.append(r,i);let a=``,o=()=>{let n=RJ(e.state.doc),r=JSON.stringify(n.map(e=>[e.level,e.text]));if(r===a){i.querySelectorAll(`a`).forEach((e,t)=>e.dataset.pos=String(n[t]?.pos??0));return}if(a=r,i.replaceChildren(),!n.length){let e=document.createElement(`li`);e.className=`dw-toc__empty`,e.textContent=t.tocEmpty,i.append(e);return}let o=Math.min(...n.map(e=>e.level));for(let t of n){let n=document.createElement(`li`);n.style.paddingLeft=`${(t.level-o)*1}rem`;let r=document.createElement(`a`);r.href=`#`,r.textContent=t.text||`…`,r.dataset.pos=String(t.pos),r.addEventListener(`click`,t=>{t.preventDefault(),zJ(e,Number(r.dataset.pos))}),n.append(r),i.append(n)}};return o(),e.on(`update`,o),{dom:n,update:e=>e.type.name===`tableOfContents`,ignoreMutation:()=>!0,stopEvent:e=>e.target instanceof Element&&!!e.target.closest(`a`),destroy:()=>e.off(`update`,o)}}}}),VJ=(e,t)=>{let n=t.view.domAtPos(e).node,r=n.nodeType===Node.ELEMENT_NODE?n:n.parentElement;return r?r.offsetParent!==null:!1},HJ=(e,t,n)=>{for(let r=e.depth;r>0;--r){let i=e.node(r),a=t(i),o=VJ(e.start(r),n);if(a&&o)return{pos:r>0?e.before(r):0,start:e.start(r),depth:r,node:i}}},UJ=(e,t)=>{let{state:n,view:r,extensionManager:i}=e,{schema:a,selection:o}=n,{empty:s,$anchor:c}=o,l=!!i.extensions.find(e=>e.name===`gapCursor`);if(!s||c.parent.type!==a.nodes.detailsSummary||!l||t===`right`&&c.parentOffset!==c.parent.nodeSize-2)return!1;let u=yu(e=>e.type===a.nodes.details)(o);if(!u)return!1;let d=gu(u.node,e=>e.type===a.nodes.detailsContent);if(!d.length||VJ(u.start+d[0].pos+1,e))return!1;let f=n.doc.resolve(u.pos+u.node.nodeSize),p=Iw.findFrom(f,1,!1);if(!p)return!1;let{tr:m}=n,h=new Iw(p);return m.setSelection(h),m.scrollIntoView(),r.dispatch(m),!0},WJ=Jp.create({name:`details`,content:`detailsSummary detailsContent`,group:`block`,defining:!0,isolating:!0,allowGapCursor:!1,addOptions(){return{persist:!1,openClassName:`is-open`,HTMLAttributes:{},renderToggleButton:({element:e,isOpen:t})=>{e.setAttribute(`aria-label`,t?`Collapse details content`:`Expand details content`)}}},addAttributes(){return this.options.persist?{open:{default:!1,parseHTML:e=>e.hasAttribute(`open`),renderHTML:({open:e})=>e?{open:``}:{}}}:[]},parseHTML(){return[{tag:`details`}]},renderHTML({HTMLAttributes:e}){return[`details`,A(this.options.HTMLAttributes,e),0]},...Xf({nodeName:`details`,content:`block`}),addNodeView(){return({editor:e,getPos:t,node:n,HTMLAttributes:r})=>{let i=document.createElement(`div`),a=A(this.options.HTMLAttributes,r,{"data-type":this.name});Object.entries(a).forEach(([e,t])=>i.setAttribute(e,t));let o=document.createElement(`button`);o.type=`button`;let s=e=>{this.options.renderToggleButton({element:o,...e})};i.append(o);let c=document.createElement(`div`);i.append(c);let l=e=>{let{setToValue:t,node:r=n}=e||{};if(t!==void 0){if(t){if(i.classList.contains(this.options.openClassName))return;i.classList.add(this.options.openClassName)}else{if(!i.classList.contains(this.options.openClassName))return;i.classList.remove(this.options.openClassName)}}else i.classList.toggle(this.options.openClassName);let a=i.classList.contains(this.options.openClassName);s({isOpen:a,node:r});let o=new Event(`toggleDetailsContent`);c.querySelector(`:scope > div[data-type="detailsContent"]`)?.dispatchEvent(o)};return s({isOpen:!!n.attrs.open,node:n}),n.attrs.open&&setTimeout(()=>l()),o.addEventListener(`click`,()=>{if(l(),!this.options.persist)e.commands.focus(void 0,{scrollIntoView:!1});else if(e.isEditable&&typeof t==`function`){let{from:n,to:r}=e.state.selection;e.chain().command(({tr:e})=>{let n=t();if(typeof n!=`number`)return!1;let r=e.doc.nodeAt(n);return r?.type===this.type&&(e.setNodeMarkup(n,void 0,{open:!r.attrs.open}),!0)}).setTextSelection({from:n,to:r}).focus(void 0,{scrollIntoView:!1}).run()}}),{dom:i,contentDOM:c,ignoreMutation(e){if(e.type===`selection`)return!1;let t=e.target,n=i.contains(t);return o.contains(t)||!n||i===t},update:e=>e.type===this.type&&(e.attrs.open===void 0?s({isOpen:i.classList.contains(this.options.openClassName),node:e}):l({setToValue:e.attrs.open,node:e}),!0)}}},addCommands(){return{setDetails:()=>({state:e,chain:t})=>{let{schema:n,selection:r}=e,{$from:i,$to:a}=r,o=i.blockRange(a);if(!o)return!1;let s=e.doc.slice(o.start,o.end);if(!n.nodes.detailsContent.contentMatch.matchFragment(s.content))return!1;let c=s.toJSON()?.content||[];return t().insertContentAt({from:o.start,to:o.end},{type:this.name,content:[{type:`detailsSummary`},{type:`detailsContent`,content:c}]}).setTextSelection(o.start+2).run()},unsetDetails:()=>({state:e,chain:t})=>{let{selection:n,schema:r}=e,i=yu(e=>e.type===this.type)(n);if(!i)return!1;let a=gu(i.node,e=>e.type===r.nodes.detailsSummary),o=gu(i.node,e=>e.type===r.nodes.detailsContent);if(!a.length||!o.length)return!1;let s=a[0],c=o[0],l=i.pos,u=e.doc.resolve(l),d={from:l,to:l+i.node.nodeSize},f=c.node.content.toJSON()||[],p=[u.parent.type.contentMatch.defaultType?.create(null,s.node.content).toJSON(),...f];return t().insertContentAt(d,p).setTextSelection(l+1).run()}}},addKeyboardShortcuts(){return{Backspace:()=>{let{schema:e,selection:t}=this.editor.state,{empty:n,$anchor:r}=t;return!n||r.parent.type!==e.nodes.detailsSummary?!1:r.parentOffset===0?this.editor.commands.unsetDetails():this.editor.commands.command(({tr:e})=>{let t=r.pos-1,n=r.pos;return e.delete(t,n),!0})},Enter:({editor:e})=>{let{state:t,view:n}=e,{schema:r,selection:i}=t,{$head:a}=i;if(a.parent.type!==r.nodes.detailsSummary)return!1;let o=VJ(a.after()+1,e),s=o?t.doc.nodeAt(a.after()):a.node(-2);if(!s)return!1;let c=o?0:a.indexAfter(-1),l=Ll(s.contentMatchAt(c));if(!l||!s.canReplaceWith(c,c,l))return!1;let u=l.createAndFill();if(!u)return!1;let d=o?a.after()+1:a.after(-1),f=t.tr.replaceWith(d,d,u),p=f.doc.resolve(d),m=w.near(p,1);return f.setSelection(m),f.scrollIntoView(),n.dispatch(f),!0},ArrowRight:({editor:e})=>UJ(e,`right`),ArrowDown:({editor:e})=>UJ(e,`down`)}},addProseMirrorPlugins(){return[new D({key:new Un(`detailsSelection`),appendTransaction:(e,t,n)=>{let{editor:r,type:i}=this;if(r.view.composing||!e.some(e=>e.selectionSet)||!t.selection.empty||!n.selection.empty||!sd(n,i.name))return;let{$from:a}=n.selection;if(VJ(a.pos,r))return;let o=HJ(a,e=>e.type===i,r);if(!o)return;let s=gu(o.node,e=>e.type===n.schema.nodes.detailsSummary);if(!s.length)return;let c=s[0],l=(t.selection.from{let t=document.createElement(`div`),n=A(this.options.HTMLAttributes,e,{"data-type":this.name,hidden:`hidden`});return Object.entries(n).forEach(([e,n])=>t.setAttribute(e,n)),t.addEventListener(`toggleDetailsContent`,()=>{t.toggleAttribute(`hidden`)}),{dom:t,contentDOM:t,ignoreMutation(e){return e.type===`selection`?!1:!t.contains(e.target)||t===e.target},update:e=>e.type===this.type}}},addKeyboardShortcuts(){return{Enter:({editor:e})=>{let{state:t,view:n}=e,{selection:r}=t,{$from:i,empty:a}=r,o=yu(e=>e.type===this.type)(r);if(!a||!o||!o.node.childCount)return!1;let s=i.index(o.depth),{childCount:c}=o.node;if(c!==s+1)return!1;let l=o.node.type.contentMatch.defaultType?.createAndFill();if(!l)return!1;let u=t.doc.resolve(o.pos+1),d=c-1,f=o.node.child(d),p=u.posAtIndex(d,o.depth);if(!f.eq(l))return!1;let m=i.node(-3);if(!m)return!1;let h=i.indexAfter(-3),g=Ll(m.contentMatchAt(h));if(!g||!m.canReplaceWith(h,h,g))return!1;let _=g.createAndFill();if(!_)return!1;let{tr:v}=t,y=i.after(-2);v.replaceWith(y,y,_);let b=v.doc.resolve(y),x=w.near(b,1);v.setSelection(x);let S=p,C=p+f.nodeSize;return v.delete(S,C),v.scrollIntoView(),n.dispatch(v),!0}}},...Xf({nodeName:`detailsContent`})}),KJ=Jp.create({name:`detailsSummary`,content:`text*`,defining:!0,selectable:!1,isolating:!0,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`summary`}]},renderHTML({HTMLAttributes:e}){return[`summary`,A(this.options.HTMLAttributes,e),0]},...Xf({nodeName:`detailsSummary`,content:`inline`})});function qJ(e){return[WJ.configure({persist:!1,HTMLAttributes:{class:`dw-toggle`},renderToggleButton:({element:t,isOpen:n})=>{t.setAttribute(`aria-label`,n?e.blocks.collapse:e.blocks.expand),t.setAttribute(`aria-expanded`,String(n))}}),KJ,GJ]}function JJ(e={}){let t=e.labels??kR,n=null,r=Tp.create({name:`editorRef`,onCreate(){n=this.editor}}),i={host:e.files,labels:t,drawioUrl:e.drawioUrl,loadExcalidraw:e.loadExcalidraw,onError:e.onError},a=[r,Kk.configure({heading:{levels:[1,2,3,4,5,6]},codeBlock:!1,link:{openOnClick:!1,autolink:!0},undoRedo:e.collab||e.syncedDoc||e.rowBody||e.rowFragmentReadOnly?!1:void 0}),fT.configure({placeholder:e.placeholder??`Type '/' for commands…`}),KV.configure({host:e.files}),JV.configure({host:e.files,loadPdf:e.loadPdf,labels:t}),Pj.configure({lineNumbers:e.codeLineNumbers??!1}),kP,OP,FP,IP,...EP(),...DP(),IJ.configure({labels:t}),zP.configure({labels:t}),YV.configure({host:e.files,onError:e.onError}),bJ(t,e.mentions),KB.configure({labels:t,me:()=>e.mentions?.me,onOpen:e.onOpenDate}),AJ.configure({commands:OJ(t,e.files,e.onError,e.pages,!!e.loadExcalidraw,e.links),labels:t}),IB.configure({onSelect:e.onCommentSelect}),hJ(t,()=>n),EJ.configure({labels:t,load:e.loadMermaid}),BJ.configure({labels:t}),kV.configure(i),AV.configure(i),_V.configure({host:e.pages,labels:t,onNavigate:e.onNavigate}),yV.configure({host:e.syncedPages,pages:e.pages,labels:t,onNavigate:e.onNavigate,nested:t=>JJ({syncedDoc:t,files:e.files,links:e.links,onNavigate:e.onNavigate,drawioUrl:e.drawioUrl,loadMermaid:e.loadMermaid,loadPdf:e.loadPdf,codeLineNumbers:e.codeLineNumbers,labels:e.labels,placeholder:``})}),...qJ(t),VV.configure({labels:t}),HV.configure({labels:t}),tM.configure({labels:t,link:e.blockLink,onCopied:e.onBlockLinkCopied}),nH,DB.configure({labels:t,doc:e.collab?.provider.doc??e.syncedDoc??e.rowBody?.doc,readOnlyDoc:!!e.syncedDoc,undoScope:!e.rowBody,files:e.files,people:e.mentions,recordLink:e.blockLink,onLinkCopied:e.onBlockLinkCopied,me:()=>{let t=e.mentions?.me;return t?{id:t,name:e.collab?.user.name??``}:null},rowExtensions:n=>{let r=e.collab?.provider.doc??e.syncedDoc??e.rowBody?.doc;return JJ({rowBody:n&&r&&!e.syncedDoc?{doc:r,fragment:n}:void 0,files:e.files,mentions:e.mentions,pages:e.pages,links:e.links,onNavigate:e.onNavigate,drawioUrl:e.drawioUrl,loadMermaid:e.loadMermaid,loadExcalidraw:e.loadExcalidraw,loadPdf:e.loadPdf,codeLineNumbers:e.codeLineNumbers,labels:e.labels,placeholder:t.database.bodyPlaceholder,rowFragmentReadOnly:n&&e.syncedDoc?n:void 0})}})],o={trackedOrigins:[Dz]};return e.rowBody?a.push(Ow.configure({document:e.rowBody.doc,fragment:e.rowBody.fragment,yUndoOptions:o})):e.rowFragmentReadOnly?a.push(Ow.configure({fragment:e.rowFragmentReadOnly})):e.syncedDoc?a.push(Ow.configure({document:e.syncedDoc})):e.collab&&a.push(Ow.configure({document:e.collab.provider.doc,yUndoOptions:o}),Nw.configure({provider:e.collab.provider,user:e.collab.user,render:YJ})),a}function YJ(e){let t=typeof e.color==`string`&&/^#[0-9a-f]{3,8}$/i.test(e.color)?e.color:`#888`,n=document.createElement(`span`);n.classList.add(`collaboration-carets__caret`),n.style.borderColor=t;let r=document.createElement(`div`);return r.classList.add(`collaboration-carets__label`),r.setAttribute(`aria-hidden`,`true`),r.style.backgroundColor=t,r.textContent=typeof e.name==`string`?e.name:``,n.append(r),n}function XJ(e){let t=e??kR;return{...dF,...t.edgeless,colors:{...dF.colors,...t.colors}}}function ZJ(e){let t=e?.surface;return Array.isArray(t?.elements)?t.elements:[]}function QJ(e,t,n){let r={...n,placeholder:n.placeholder??``},i=new Vp({element:e,editable:t.kind!==`json`&&t.editable,content:t.kind===`json`?t.content:void 0,extensions:t.kind===`page`?JJ({...r,collab:{provider:t.provider,user:t.user}}):t.kind===`body`?JJ({...r,rowBody:{doc:t.doc,fragment:t.fragment}}):JJ(r),editorProps:{attributes:{class:`dw-prose`}}});return{destroy:()=>i.destroy(),focus:()=>i.commands.focus(`end`),setEditable:e=>i.setEditable(e&&t.kind!==`json`)}}function $J(e,t){let n=!!t.provider,r,i=null;if(t.provider)r=t.provider.doc;else{i=new bv,r=i;let e=t.content;i.transact(()=>JL(i.getXmlFragment(`default`),e?.content??[]));let n=ZJ(e);if(n.length){let e=new eR(i,{undo:!1});e.load(n),e.destroy()}}let a={...t};delete a.provider,delete a.content;let o=new vR(e,{doc:r,editable:n&&t.editable,notes:{mount:(e,r)=>{let i=n?r.page?{kind:`page`,provider:t.provider,user:t.user??{name:`?`,color:`#888`},editable:r.editable}:{kind:`body`,doc:r.doc,fragment:r.fragment,editable:r.editable}:{kind:`json`,content:r.page&&t.content?t.content:{type:`doc`,content:qL(r.fragment)}};return t.mountNote?t.mountNote(e,i):QJ(e,i,a)}},labels:XJ(t.labels),files:t.files,links:t.links,embedSource:PV,styles:t.styles,onStyles:t.onStyles,viewKey:t.viewKey,pageTitle:t.pageTitle,undo:n,onError:t.onError});return{view:o,setEditable:e=>o.setEditable(n&&e),destroy:()=>{o.destroy(),i?.destroy()}}}function eY(e,t,n){let r=Jj(t),i=vB(t);if(!r&&!i)return()=>{};let a=()=>i?bB(e,i.database,i.row):eM(e,r),o=!1,s,c=()=>{clearTimeout(s),s=setTimeout(()=>{o||e.isDestroyed||!a()||(o=!0,l(),n?.())},50)},l=()=>{e.off(`transaction`,c),clearTimeout(u)},u=setTimeout(l,5e3);return e.on(`transaction`,c),c(),()=>{l(),clearTimeout(s)}}var tY=3e4,nY=class extends um{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Mh();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&rY(this,t,`timeout`)},dm(tY/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Mh()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),Qh(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},rY=(e,t,n)=>{let r=[];for(let n=0;n0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},iY=(e,t,n=e.states)=>{let r=t.length,i=Mm();j(i,r);for(let a=0;a{let r=fh(t),i=Mh(),a=[],o=[],s=[],c=[],l=M(r);for(let t=0;t0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},oY=(e,t)=>{j(e,0),Wm(e,Gv(t))},sY=(e,t,n)=>{j(e,1),Wm(e,zv(t,n))},cY=(e,t,n)=>sY(t,n,hh(e)),lY=(e,t,n,r)=>{try{Iv(t,hh(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},uY=(e,t)=>{j(e,2),Wm(e,t)},dY=lY,fY=(e,t,n,r,i)=>{let a=M(e);switch(a){case 0:cY(e,t,n);break;case 1:lY(e,n,r,i);break;case 2:dY(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},pY=0,mY=1,hY=4401,gY=4404,_Y=4409,vY=class{opts;doc=new bv;awareness=new nY(this.doc);status=`connecting`;synced=!1;ws=null;retries=0;retryTimer;destroyed=!1;listeners=new Set;constructor(e){this.opts=e,this.doc.on(`update`,this.onDocUpdate),this.awareness.on(`update`,this.onAwarenessUpdate),e.readOnly&&this.awareness.setLocalState(null),window.addEventListener(`beforeunload`,this.onUnload),this.connect()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.destroyed||(this.destroyed=!0,this.listeners.clear(),clearTimeout(this.retryTimer),window.removeEventListener(`beforeunload`,this.onUnload),rY(this.awareness,[this.doc.clientID],`local`),this.doc.off(`update`,this.onDocUpdate),this.awareness.off(`update`,this.onAwarenessUpdate),this.ws?.close(),this.awareness.destroy(),this.doc.destroy(),this.listeners.clear())}set(e,t=this.synced){(e!==this.status||t!==this.synced)&&(this.status=e,this.synced=t,this.listeners.forEach(e=>e()))}connect(){let e=new WebSocket(`${this.opts.url}?page=${encodeURIComponent(this.opts.page)}`);e.binaryType=`arraybuffer`,this.ws=e,e.onopen=()=>{e.send(this.opts.token()??``);let t=Mm();j(t,pY),oY(t,this.doc),e.send(Fm(t)),this.awareness.getLocalState()!==null&&this.sendAwareness([this.doc.clientID])},e.onmessage=e=>this.onMessage(new Uint8Array(e.data)),e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=[...this.awareness.getStates().keys()].filter(e=>e!==this.doc.clientID);rY(this.awareness,n,this),this.destroyed||(t.code===hY||t.code===gY?this.set(`denied`,!1):t.code===_Y?this.set(`changed`):(this.set(`offline`),this.retryTimer=setTimeout(()=>this.connect(),Math.min(1e3*2**this.retries++,3e4))))}}onMessage(e){let t=fh(e),n=M(t);if(n===pY){let e=Mm();j(e,pY);let n=fY(t,e,this.doc,this);Pm(e)>1&&!this.opts.readOnly&&this.ws?.send(Fm(e)),n===1&&(this.retries=0,this.set(`connected`,!0))}else n===mY&&aY(this.awareness,hh(t),this)}onDocUpdate=(e,t)=>{if(t===this||this.opts.readOnly||this.ws?.readyState!==WebSocket.OPEN)return;let n=Mm();j(n,pY),uY(n,e),this.ws.send(Fm(n))};onAwarenessUpdate=({added:e,updated:t,removed:n},r)=>{r===this||this.opts.readOnly||this.sendAwareness([...e,...t,...n])};sendAwareness(e){if(this.ws?.readyState!==WebSocket.OPEN)return;let t=Mm();j(t,mY),Wm(t,iY(this.awareness,e)),this.ws.send(Fm(t))}onUnload=()=>rY(this.awareness,[this.doc.clientID],`unload`)},yY=`.dw-db-peek, .dw-db-pop, .dw-block-menu`,bY={bold:e=>e.chain().focus().toggleBold().run(),italic:e=>e.chain().focus().toggleItalic().run(),strike:e=>e.chain().focus().toggleStrike().run(),code:e=>e.chain().focus().toggleCode().run(),heading1:e=>e.chain().focus().toggleHeading({level:1}).run(),heading2:e=>e.chain().focus().toggleHeading({level:2}).run(),heading3:e=>e.chain().focus().toggleHeading({level:3}).run(),bulletList:e=>e.chain().focus().toggleBulletList().run(),orderedList:e=>e.chain().focus().toggleOrderedList().run(),blockquote:e=>e.chain().focus().toggleBlockquote().run(),codeBlock:e=>e.chain().focus().toggleCodeBlock().run(),underline:e=>e.chain().focus().toggleUnderline().run(),taskList:e=>e.chain().focus().toggleTaskList().run(),callout:e=>e.isActive(`callout`)?e.chain().focus().unsetCallout().run():e.chain().focus().setCallout().run(),table:e=>e.chain().focus().insertTable({rows:3,cols:3,withHeaderRow:!0}).run(),undo:e=>e.chain().focus().undo().run(),redo:e=>e.chain().focus().redo().run()},xY=[[`bold`,e=>e.isActive(`bold`)],[`italic`,e=>e.isActive(`italic`)],[`strike`,e=>e.isActive(`strike`)],[`code`,e=>e.isActive(`code`)],[`heading1`,e=>e.isActive(`heading`,{level:1})],[`heading2`,e=>e.isActive(`heading`,{level:2})],[`heading3`,e=>e.isActive(`heading`,{level:3})],[`bulletList`,e=>e.isActive(`bulletList`)],[`orderedList`,e=>e.isActive(`orderedList`)],[`blockquote`,e=>e.isActive(`blockquote`)],[`codeBlock`,e=>e.isActive(`codeBlock`)],[`underline`,e=>e.isActive(`underline`)],[`taskList`,e=>e.isActive(`taskList`)],[`callout`,e=>e.isActive(`callout`)],[`table`,e=>e.isActive(`table`)]],SY=class{el;send;editor;provider=null;lastState=``;editable=!0;overlay=!1;overlays=new MutationObserver(()=>this.reportOverlay());inner=null;onFocusIn=e=>this.track(e.target);canvas=null;canvasEl=null;mode=`page`;lastContent=null;constructor(e,t){this.el=e,this.send=t,this.editor=this.create({}),this.overlays.observe(document.body,{childList:!0}),document.addEventListener(`focusin`,this.onFocusIn),t({type:`ready`,version:3})}receive(e){try{let t=typeof e==`string`?JSON.parse(e):e;this.handle(t)}catch(e){this.send({type:`error`,message:e instanceof Error?e.message:String(e)})}}get content(){return this.editor.getJSON()}destroy(){this.overlays.disconnect(),document.removeEventListener(`focusin`,this.onFocusIn),this.setInner(null),this.closeCanvas(),this.editor.destroy(),this.provider?.destroy()}handle(e){switch(e.type){case`hello`:this.send({type:`ready`,version:3}),this.lastState=``,this.reportState();return;case`setContent`:this.lastContent=e.content,this.editor.commands.setContent(e.content??``,{emitUpdate:!1}),this.reportState(),this.mode===`edgeless`&&!this.provider&&this.openCanvas();return;case`setEditable`:this.editable=e.editable,this.editor.setEditable(e.editable);return;case`setTheme`:document.documentElement.classList.toggle(`dark`,e.dark);return;case`setLayout`:{let t=document.documentElement.classList;t.toggle(`dw-full-width`,e.fullWidth),t.toggle(`dw-font-serif`,e.font===`serif`),t.toggle(`dw-font-mono`,e.font===`mono`);return}case`command`:{let t=bY[e.command];if(!t)throw Error(`unknown command ${e.command}`);t(this.target);return}case`focus`:this.editor.commands.focus();return;case`blur`:this.editor.commands.blur();return;case`connect`:this.connect(e);return;case`follow`:eY(this.editor,e.hash);return;case`setMode`:this.mode=e.mode===`edgeless`?`edgeless`:`page`,this.mode===`edgeless`?this.openCanvas():this.closeCanvas();return;case`dismiss`:[...document.querySelectorAll(yY)].at(-1)?.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Escape`,bubbles:!0,cancelable:!0}));return;default:throw Error(`unknown message ${e.type}`)}}connect(e){this.provider?.destroy();let t=new vY({url:e.url,page:e.page,token:()=>e.token});t.onChange(()=>this.send({type:`collab`,status:t.status})),this.provider=t,this.editor.destroy(),this.editor=this.create({collab:{provider:t,user:e.user}}),this.mode===`edgeless`&&this.openCanvas()}openCanvas(){this.closeCanvas();let e=document.createElement(`div`);e.className=`dw-bridge-canvas`,document.body.append(e),this.canvasEl=e,this.el.hidden=!0,this.canvas=$J(e,{provider:this.provider??void 0,content:this.provider?void 0:this.lastContent??this.editor.getJSON(),editable:!1,onNavigate:e=>this.send({type:`navigate`,path:e}),onError:e=>this.send({type:`error`,message:e instanceof Error?e.message:String(e)})})}closeCanvas(){this.canvas?.destroy(),this.canvas=null,this.canvasEl?.remove(),this.canvasEl=null,this.el.hidden=!1}create(e){return this.el.replaceChildren(),new Vp({element:this.el,editable:this.editable,extensions:JJ({...e,onNavigate:e=>this.send({type:`navigate`,path:e})}),editorProps:{attributes:{class:`dw-prose`}},onUpdate:({editor:e})=>this.send({type:`change`,content:e.getJSON()}),onSelectionUpdate:()=>this.reportState(),onTransaction:()=>this.reportState(),onFocus:()=>this.reportState(),onBlur:()=>this.reportState()})}get target(){return this.inner&&!this.inner.isDestroyed?this.inner:this.editor}track(e){let t=(e instanceof Element?e.closest(`.ProseMirror`):null)?.editor;t&&(this.setInner(t===this.editor?null:t),this.reportState())}innerChanged=()=>this.reportState();innerGone=()=>{this.setInner(null),this.reportState()};setInner(e){if(e!==this.inner){if(this.inner){for(let e of[`selectionUpdate`,`transaction`,`focus`,`blur`])this.inner.off(e,this.innerChanged);this.inner.off(`destroy`,this.innerGone)}if(this.inner=e,e){for(let t of[`selectionUpdate`,`transaction`,`focus`,`blur`])e.on(t,this.innerChanged);e.on(`destroy`,this.innerGone)}}}reportOverlay(){let e=document.querySelector(yY)!==null;e!==this.overlay&&(this.overlay=e,this.send({type:`overlay`,open:e}))}reportState(){let e=this.target;if(e.isDestroyed)return;let t={active:xY.filter(([,t])=>t(e)).map(([e])=>e),canUndo:e.can().undo(),canRedo:e.can().redo(),focused:e.isFocused},n=JSON.stringify(t);n!==this.lastState&&(this.lastState=n,this.send({type:`state`,state:t}))}};function CY(e){let t=JSON.stringify(e);window.DocwellNative?window.DocwellNative.postMessage(t):(window.parent.postMessage(t,`*`),console.debug(`[docwell bridge]`,e))}var wY=new SY(document.getElementById(`editor`),CY);window.docwell={receive:e=>wY.receive(e)}; diff --git a/Packages/editor-bridge/src/bridge.test.ts b/Packages/editor-bridge/src/bridge.test.ts index 4a493c4..fd21c8c 100644 --- a/Packages/editor-bridge/src/bridge.test.ts +++ b/Packages/editor-bridge/src/bridge.test.ts @@ -36,6 +36,40 @@ describe("EditorBridge", () => { expect(sent.some((m) => m.type === "change")).toBe(false); }); + it("draws the canvas read-only in edgeless mode and goes back to the text", () => { + const { bridge, sent, el } = setup(); + const content = { + ...doc, + surface: { + elements: [ + { id: "s1", type: "shape", index: 1, x: 900, y: 0, w: 100, h: 60, text: "Idea" }, + { + id: "n1", + type: "note", + index: 2, + x: 0, + y: 300, + w: 200, + h: 80, + body: [{ type: "paragraph", content: [{ type: "text", text: "Sticky" }] }], + }, + ], + }, + }; + bridge.receive(JSON.stringify({ type: "setContent", content })); + bridge.receive(JSON.stringify({ type: "setMode", mode: "edgeless" })); + const canvas = document.querySelector(".dw-bridge-canvas")!; + expect(el.hidden).toBe(true); + expect(canvas.querySelector(".dw-cv-readonly")).not.toBeNull(); + expect(canvas.querySelector(".dw-cv-pagenote")?.textContent).toContain("Hello"); + expect(canvas.querySelector(".dw-cv-shape")?.textContent).toContain("Idea"); + expect(canvas.querySelector(".dw-cv-note:not(.dw-cv-pagenote)")?.textContent).toContain("Sticky"); + bridge.receive(JSON.stringify({ type: "setMode", mode: "page" })); + expect(document.querySelector(".dw-bridge-canvas")).toBeNull(); + expect(el.hidden).toBe(false); + expect(sent.some((m) => m.type === "error")).toBe(false); + }); + it("applies toolbar commands and reports the change and toolbar state", () => { const { bridge, sent } = setup(); bridge.receive({ type: "setContent", content: doc }); @@ -88,9 +122,25 @@ describe("EditorBridge", () => { title: "Tasks", columns: [{ id: "t", name: "Name", type: "title" }], rows: [{ id: "r1", cells: { t: "One" }, createdAt: 0, createdBy: null }], - views: [{ id: "v", name: "Table", type: "table", hidden: [], filters: [], filterMode: "and", sorts: [], groupBy: null, dateColumn: null, widths: {} }], + views: [ + { + id: "v", + name: "Table", + type: "table", + hidden: [], + filters: [], + filterMode: "and", + sorts: [], + groupBy: null, + dateColumn: null, + widths: {}, + }, + ], }; - bridge.receive({ type: "setContent", content: { type: "doc", content: [{ type: "database", attrs: { id: "db1", data } }] } }); + bridge.receive({ + type: "setContent", + content: { type: "doc", content: [{ type: "database", attrs: { id: "db1", data } }] }, + }); el.querySelector(".dw-db-t__open")!.click(); await Promise.resolve(); expect(document.querySelector(".dw-db-peek")).not.toBeNull(); diff --git a/Packages/editor-bridge/src/bridge.ts b/Packages/editor-bridge/src/bridge.ts index c726c43..483187d 100644 --- a/Packages/editor-bridge/src/bridge.ts +++ b/Packages/editor-bridge/src/bridge.ts @@ -2,6 +2,7 @@ import { Editor, type JSONContent } from "@tiptap/core"; import { docwellExtensions, type ExtensionOptions } from "@docwell/editor/extensions"; +import { mountEdgeless, type Edgeless } from "@docwell/editor/edgeless"; import { followLink } from "@docwell/editor/hashlinks"; import { CollabProvider } from "@docwell/editor/provider"; import { PROTOCOL_VERSION, type Command, type EditorMessage, type EditorState, type HostMessage } from "./protocol"; @@ -69,6 +70,12 @@ export class EditorBridge { */ private inner: Editor | null = null; private readonly onFocusIn = (e: FocusEvent) => this.track(e.target); + /** The canvas, while the page is shown in edgeless mode (read-only on phones). */ + private canvas: Edgeless | null = null; + private canvasEl: HTMLElement | null = null; + private mode: "page" | "edgeless" = "page"; + /** The content as the host sent it, with its canvas ("surface"). */ + private lastContent: JSONContent | null = null; constructor( private readonly el: HTMLElement, @@ -98,6 +105,7 @@ export class EditorBridge { this.overlays.disconnect(); document.removeEventListener("focusin", this.onFocusIn); this.setInner(null); + this.closeCanvas(); this.editor.destroy(); this.provider?.destroy(); } @@ -111,8 +119,10 @@ export class EditorBridge { return; case "setContent": // Not echoed back as a change: the host already has this content. + this.lastContent = msg.content; this.editor.commands.setContent(msg.content ?? "", { emitUpdate: false }); this.reportState(); + if (this.mode === "edgeless" && !this.provider) this.openCanvas(); return; case "setEditable": this.editable = msg.editable; @@ -147,6 +157,11 @@ export class EditorBridge { case "follow": followLink(this.editor, msg.hash); return; + case "setMode": + this.mode = msg.mode === "edgeless" ? "edgeless" : "page"; + if (this.mode === "edgeless") this.openCanvas(); + else this.closeCanvas(); + return; case "dismiss": { // Each overlay closes itself on Escape. const top = [...document.querySelectorAll(OVERLAYS)].at(-1); @@ -165,6 +180,32 @@ export class EditorBridge { this.provider = provider; this.editor.destroy(); this.editor = this.create({ collab: { provider, user: msg.user } }); + if (this.mode === "edgeless") this.openCanvas(); + } + + /** Draws the canvas over the text: the live page once connected, else the content. */ + private openCanvas(): void { + this.closeCanvas(); + const el = document.createElement("div"); + el.className = "dw-bridge-canvas"; + document.body.append(el); + this.canvasEl = el; + this.el.hidden = true; + this.canvas = mountEdgeless(el, { + provider: this.provider ?? undefined, + content: this.provider ? undefined : (this.lastContent ?? this.editor.getJSON()), + editable: false, + onNavigate: (path) => this.send({ type: "navigate", path }), + onError: (e) => this.send({ type: "error", message: e instanceof Error ? e.message : String(e) }), + }); + } + + private closeCanvas(): void { + this.canvas?.destroy(); + this.canvas = null; + this.canvasEl?.remove(); + this.canvasEl = null; + this.el.hidden = false; } private create(opts: ExtensionOptions): Editor { @@ -205,7 +246,8 @@ export class EditorBridge { private setInner(ed: Editor | null): void { if (ed === this.inner) return; if (this.inner) { - for (const ev of ["selectionUpdate", "transaction", "focus", "blur"] as const) this.inner.off(ev, this.innerChanged); + for (const ev of ["selectionUpdate", "transaction", "focus", "blur"] as const) + this.inner.off(ev, this.innerChanged); this.inner.off("destroy", this.innerGone); } this.inner = ed; diff --git a/Packages/editor-bridge/src/protocol.ts b/Packages/editor-bridge/src/protocol.ts index 18e52ad..6776c13 100644 --- a/Packages/editor-bridge/src/protocol.ts +++ b/Packages/editor-bridge/src/protocol.ts @@ -48,6 +48,8 @@ export type HostMessage = | { type: "dismiss" } /** Scrolls to a block ("#b-…") or opens a database record ("#r-…") of the page, once it shows it. */ | { type: "follow"; hash: string } + /** Shows the text, or the edgeless canvas read-only (ADR-14), of the content or live page. */ + | { type: "setMode"; mode: "page" | "edgeless" } /** Edit the live document over docwell-server's /collab WebSocket. */ | { type: "connect"; url: string; page: string; token: string; user: { name: string; color: string } }; @@ -75,4 +77,4 @@ export type EditorMessage = | { type: "error"; message: string }; /** Bumped when a message changes shape, so the app can refuse a stale bundle. */ -export const PROTOCOL_VERSION = 2; +export const PROTOCOL_VERSION = 3; diff --git a/Packages/editor-bridge/src/style.css b/Packages/editor-bridge/src/style.css index 6b56304..61d1839 100644 --- a/Packages/editor-bridge/src/style.css +++ b/Packages/editor-bridge/src/style.css @@ -4,6 +4,12 @@ @import "@docwell/ui/theme.css"; @import "@docwell/editor/editor.css"; +/* The canvas fills the WebView in edgeless mode. */ +.dw-bridge-canvas { + position: fixed; + inset: 0; +} + html, body { margin: 0; diff --git a/Packages/editor/package.json b/Packages/editor/package.json index 6ade34a..9b3a211 100644 --- a/Packages/editor/package.json +++ b/Packages/editor/package.json @@ -10,12 +10,14 @@ "./extensions": "./src/extensions.ts", "./provider": "./src/provider.ts", "./hashlinks": "./src/hashlinks.ts", - "./editor.css": "./src/editor.css" + "./editor.css": "./src/editor.css", + "./edgeless": "./src/edgeless.ts" }, "scripts": { "test": "vitest run" }, "dependencies": { + "@docwell/canvas": "*", "@docwell/ui": "*", "@excalidraw/excalidraw": "^0.18.1", "@floating-ui/dom": "^1.8.0", diff --git a/Packages/editor/src/DocwellEdgeless.vue b/Packages/editor/src/DocwellEdgeless.vue new file mode 100644 index 0000000..ce87c18 --- /dev/null +++ b/Packages/editor/src/DocwellEdgeless.vue @@ -0,0 +1,138 @@ + + + + diff --git a/Packages/editor/src/DocwellEditor.vue b/Packages/editor/src/DocwellEditor.vue index f688fb8..01bd857 100644 --- a/Packages/editor/src/DocwellEditor.vue +++ b/Packages/editor/src/DocwellEditor.vue @@ -17,6 +17,7 @@ import type { MentionHost } from "./mention"; import { createLinkedPage, type PageHost } from "./pagelinks"; import type { CollabProvider } from "./provider"; import type { SyncedPageHost } from "./syncedpage"; +import type * as Y from "yjs"; const props = withDefaults( defineProps<{ @@ -45,6 +46,8 @@ const props = withDefaults( journals?: boolean; /** Draws synced pages live; without it they show as links. */ syncedPages?: SyncedPageHost; + /** Edits this fragment of a document instead (a note on the canvas), without carets. */ + fragment?: { doc: Y.Doc; fragment: Y.XmlFragment }; }>(), { editable: true }, ); @@ -65,11 +68,12 @@ const emit = defineEmits<{ const labels = computed(() => props.labels ?? englishLabels); const editor = useEditor({ - content: props.provider ? undefined : props.content, + content: props.provider || props.fragment ? undefined : props.content, editable: props.editable, extensions: docwellExtensions({ placeholder: props.placeholder, collab: props.provider ? { provider: props.provider, user: props.user ?? { name: "?", color: "#888" } } : undefined, + rowBody: props.fragment, files: props.files, mentions: props.mentions, pages: props.pages, diff --git a/Packages/editor/src/edgeless.ts b/Packages/editor/src/edgeless.ts new file mode 100644 index 0000000..bb63c6a --- /dev/null +++ b/Packages/editor/src/edgeless.ts @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Edgeless mode (ADR-14): the page drawn as a canvas, its text as a note on +// it. The canvas comes from @docwell/canvas; this file gives it notes that +// are Docwell editors. The page's note is bound to the page's own text, so +// typing on the canvas is typing in the page. + +import { Editor, type JSONContent } from "@tiptap/core"; +import { + CanvasView, + SurfaceStore, + englishCanvasLabels, + fragmentToJSON, + writeJSON, + type CanvasLabels, + type ElementJSON, + type NoteHandle, + type NoteMount, + type StyleDefaults, +} from "@docwell/canvas"; +import * as Y from "yjs"; +import { embedSource, type LinkHost } from "./embeds"; +import { docwellExtensions, type CollabUser, type ExtensionOptions } from "./extensions"; +import { englishLabels, type EditorLabels } from "./labels"; +import type { CollabProvider } from "./provider"; + +/** What notes on the canvas are given, besides their text. */ +export type NoteOptions = Omit< + ExtensionOptions, + "collab" | "syncedDoc" | "rowBody" | "rowFragmentReadOnly" | "placeholder" +>; + +export interface EdgelessOptions extends NoteOptions { + /** The live page; without it the canvas shows content read-only. */ + provider?: CollabProvider; + user?: CollabUser; + /** A page as JSON (with its "surface"), for share links, history and the phone's offline copy. */ + content?: JSONContent | null; + editable: boolean; + placeholder?: string; + styles?: StyleDefaults; + onStyles?: (s: StyleDefaults) => void; + viewKey?: string; + pageTitle?: () => string; + /** + * Makes a note's editor. The web app mounts its full editor (with the + * selection toolbar); without it a plain Tiptap editor is used. + */ + mountNote?: (el: HTMLElement, note: NoteSpec) => NoteHandle; +} + +/** One note to mount: the live page, a live note body, or JSON read-only. */ +export type NoteSpec = + | { kind: "page"; provider: CollabProvider; user: CollabUser; editable: boolean } + | { kind: "body"; doc: Y.Doc; fragment: Y.XmlFragment; editable: boolean } + | { kind: "json"; content: JSONContent }; + +/** The canvas's words from the editor's labels (hosts translate the editor's). */ +export function canvasLabels(labels?: EditorLabels): CanvasLabels { + const l = labels ?? englishLabels; + return { ...englishCanvasLabels, ...l.edgeless, colors: { ...englishCanvasLabels.colors, ...l.colors } }; +} + +/** The canvas elements in a page's JSON (dw_to_json writes them as surface.elements). */ +export function surfaceOfJSON(content: JSONContent | null | undefined): ElementJSON[] { + const s = (content as { surface?: { elements?: unknown } } | null | undefined)?.surface; + return Array.isArray(s?.elements) ? (s.elements as ElementJSON[]) : []; +} + +/** Whether a page's JSON has anything on its canvas. */ +export const hasSurface = (content: JSONContent | null | undefined) => surfaceOfJSON(content).length > 0; + +/** A plain Tiptap editor for a note. */ +export function plainNote(el: HTMLElement, spec: NoteSpec, opts: NoteOptions & { placeholder?: string }): NoteHandle { + const base = { ...opts, placeholder: opts.placeholder ?? "" }; + const editor = new Editor({ + element: el, + editable: spec.kind !== "json" && spec.editable, + content: spec.kind === "json" ? spec.content : undefined, + extensions: + spec.kind === "page" + ? docwellExtensions({ ...base, collab: { provider: spec.provider, user: spec.user } }) + : spec.kind === "body" + ? docwellExtensions({ ...base, rowBody: { doc: spec.doc, fragment: spec.fragment } }) + : docwellExtensions(base), + editorProps: { attributes: { class: "dw-prose" } }, + }); + return { + destroy: () => editor.destroy(), + focus: () => editor.commands.focus("end"), + setEditable: (on) => editor.setEditable(on && spec.kind !== "json"), + }; +} + +export interface Edgeless { + view: CanvasView; + setEditable(editable: boolean): void; + destroy(): void; +} + +/** Draws a page as a canvas in el. */ +export function mountEdgeless(el: HTMLElement, opts: EdgelessOptions): Edgeless { + const live = !!opts.provider; + let doc: Y.Doc; + let local: Y.Doc | null = null; + if (opts.provider) doc = opts.provider.doc; + else { + // A snapshot: a document of its own, filled from the JSON, never sent anywhere. + local = new Y.Doc(); + doc = local; + const content = opts.content; + local.transact(() => writeJSON(local!.getXmlFragment("default"), (content?.content ?? []) as never)); + const list = surfaceOfJSON(content); + if (list.length) { + const store = new SurfaceStore(local, { undo: false }); + store.load(list); + store.destroy(); + } + } + const noteOpts: NoteOptions & { placeholder?: string } = { ...opts }; + delete (noteOpts as Partial).provider; + delete (noteOpts as Partial).content; + const mount = (target: HTMLElement, note: NoteMount): NoteHandle => { + const spec: NoteSpec = !live + ? { + kind: "json", + content: + note.page && opts.content + ? opts.content + : { type: "doc", content: fragmentToJSON(note.fragment) as JSONContent[] }, + } + : note.page + ? { + kind: "page", + provider: opts.provider!, + user: opts.user ?? { name: "?", color: "#888" }, + editable: note.editable, + } + : { kind: "body", doc: note.doc, fragment: note.fragment, editable: note.editable }; + return opts.mountNote ? opts.mountNote(target, spec) : plainNote(target, spec, noteOpts); + }; + const view = new CanvasView(el, { + doc, + editable: live && opts.editable, + notes: { mount }, + labels: canvasLabels(opts.labels), + files: opts.files, + links: opts.links as LinkHost | undefined, + embedSource, + styles: opts.styles, + onStyles: opts.onStyles, + viewKey: opts.viewKey, + pageTitle: opts.pageTitle, + undo: live, + onError: opts.onError, + }); + return { + view, + setEditable: (on) => view.setEditable(live && on), + destroy: () => { + view.destroy(); + local?.destroy(); + }, + }; +} diff --git a/Packages/editor/src/editor.css b/Packages/editor/src/editor.css index 8b21340..29c405b 100644 --- a/Packages/editor/src/editor.css +++ b/Packages/editor/src/editor.css @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: AGPL-3.0-or-later */ @import "katex/dist/katex.min.css"; +@import "@docwell/canvas/canvas.css"; /* Tailwind classes used by the editor's own components (menus, find bar). */ @source "./"; diff --git a/Packages/editor/src/index.ts b/Packages/editor/src/index.ts index 88d1f96..1dd4117 100644 --- a/Packages/editor/src/index.ts +++ b/Packages/editor/src/index.ts @@ -18,3 +18,12 @@ export { linkedRecord, openRecord, recordHash } from "./database/links"; export { followLink, isTargetHash } from "./hashlinks"; export { embedSource, type LinkHost, type LinkPreview } from "./embeds"; export { dateChoices, formatDate, type DateChoice } from "./dates"; +export { default as DocwellEdgeless } from "./DocwellEdgeless.vue"; +export { + canvasLabels, + hasSurface, + mountEdgeless, + surfaceOfJSON, + type Edgeless, + type EdgelessOptions, +} from "./edgeless"; diff --git a/Packages/editor/src/labels.ts b/Packages/editor/src/labels.ts index 84a1f42..c17fc84 100644 --- a/Packages/editor/src/labels.ts +++ b/Packages/editor/src/labels.ts @@ -1,7 +1,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later +import { englishCanvasLabels, type CanvasLabels } from "@docwell/canvas"; import { englishDatabaseLabels, type DatabaseLabels } from "./database/labels"; +/** The edgeless canvas's words; its colour names come from the editor's colours. */ +export type EdgelessLabels = Omit; + +const { colors: _canvasColors, ...englishEdgeless } = englishCanvasLabels; +void _canvasColors; + /** * The editor's own words (menus, buttons). The editor has no i18n of its own: * hosts pass translated labels, and English is the default. @@ -145,6 +152,7 @@ export interface EditorLabels { }; /** The database block (database/labels.ts). */ database: DatabaseLabels; + edgeless: EdgelessLabels; } export const englishLabels: EditorLabels = { @@ -313,4 +321,5 @@ export const englishLabels: EditorLabels = { openJournal: "Open journal", }, database: englishDatabaseLabels, + edgeless: englishEdgeless, }; diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts index 7aff16b..0243525 100644 --- a/Packages/ui/src/icons.ts +++ b/Packages/ui/src/icons.ts @@ -129,6 +129,52 @@ export const iconPaths = { sliders: ["M5 6h14", "M5 12h14", "M5 18h14", "M9 4v4", "M15 10v4", "M11 16v4"], sort: ["M7 4v16", "M4 7l3-3 3 3", "M17 20V4", "M14 17l3 3 3-3"], database: ["M4 5h16v14H4z", "M4 10h16", "M4 15h16", "M10 10v9"], + // Edgeless canvas. + edgeless: ["M4 5h16v14H4z", "M7 15l3-4 3 3 4-5", "M7 8.5h.01"], + cursor: ["M6 4l12 7-5.5 1.5L10 18z"], + hand: [ + "M8 13V6.5a1.5 1.5 0 0 1 3 0V12", + "M11 11V5a1.5 1.5 0 0 1 3 0v6", + "M14 11V6.5a1.5 1.5 0 0 1 3 0V14a6 6 0 0 1-6 6h-1a5 5 0 0 1-4.2-2.3L4.5 14a1.5 1.5 0 0 1 2.5-1.6L8 14", + ], + note: ["M5 4h14v10l-6 6H5z", "M13 20v-6h6"], + shapes: ["M4 13h7v7H4z", "M16.5 4a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7z", "M7.5 4l3.5 6H4z"], + connector: [ + "M5 19a2 2 0 1 0 0-4a2 2 0 1 0 0 4z", + "M19 9a2 2 0 1 0 0-4a2 2 0 1 0 0 4z", + "M6.5 15.5C9 10 13 13 17.5 8.5", + ], + pen: ["M4 20l1-4L16 5l3 3L8 19z", "M14 7l3 3"], + eraser: ["M8 20h12", "M4.5 15.5l9-9 6 6-7.5 7.5H9z", "M9 11l5 5"], + frame: ["M7 3v18", "M17 3v18", "M3 7h18", "M3 17h18"], + mindmap: [ + "M10 10h4v4h-4z", + "M3 4h4v3H3z", + "M17 4h4v3h-4z", + "M3 17h4v3H3z", + "M17 17h4v3h-4z", + "M7 6l3 4", + "M17 6l-3 4", + "M7 18l3-4", + "M17 18l-3-4", + ], + sticker: ["M12 3a9 9 0 1 0 9 9h-5a4 4 0 0 1-4-4z", "M12 3a9 9 0 0 1 9 9", "M9 14.5c1.5 1.5 4.5 1.5 6 0"], + present: ["M3 4h18", "M5 4v11h14V4", "M12 15v3", "M8 21l4-3 4 3"], + "zoom-in": ["M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z", "M16.5 16.5L20 20", "M8 11h6", "M11 8v6"], + "zoom-out": ["M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z", "M16.5 16.5L20 20", "M8 11h6"], + fit: ["M4 9V4h5", "M15 4h5v5", "M20 15v5h-5", "M9 20H4v-5"], + "send-back": ["M4 12h9v8H4z", "M11 4h9v8h-9z"], + group: [ + "M4 4h3", + "M10 4h4", + "M17 4h3v3", + "M20 10v4", + "M20 17v3h-3", + "M14 20h-4", + "M7 20H4v-3", + "M4 14v-4", + "M8 8h8v8H8z", + ], } as const; export type IconName = keyof typeof iconPaths; diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index d701852..ad9ec85 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -678,6 +678,7 @@ class Page { required this.pinnedAt, required this.fullWidth, required this.font, + required this.defaultMode, required this.tags, required this.properties, required this.journalDate, @@ -708,6 +709,7 @@ class Page { pinnedAt: json['pinnedAt'] as String, fullWidth: json['fullWidth'] as bool, font: PageFont.fromJson(json['font'] as String), + defaultMode: PageMode.fromJson(json['defaultMode'] as String), tags: (json['tags'] as List).map((e) => e as String).toList(), properties: json['properties'] as Map, journalDate: json['journalDate'] as String, @@ -768,6 +770,8 @@ class Page { final PageFont font; + final PageMode defaultMode; + /// Tag ids final List tags; @@ -802,6 +806,7 @@ class Page { 'pinnedAt': pinnedAt, 'fullWidth': fullWidth, 'font': font.toJson(), + 'defaultMode': defaultMode.toJson(), 'tags': tags.map((e) => e).toList(), 'properties': properties, 'journalDate': journalDate, @@ -810,6 +815,22 @@ class Page { }; } +/// The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it +enum PageMode { + page('page'), + edgeless('edgeless'); + + const PageMode(this.value); + final String value; + + static PageMode fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown PageMode', value), + ); + + String toJson() => value; +} + /// The body font for everyone reading the page; empty is the default sans enum PageFont { none(''), @@ -2896,6 +2917,7 @@ class SharedPage { required this.icon, required this.updated, required this.content, + required this.mode, required this.root, required this.pages, }); @@ -2908,6 +2930,7 @@ class SharedPage { content: json['content'] == null ? null : json['content'] as Map, + mode: PageMode.fromJson(json['mode'] as String), root: PageRef.fromJson(json['root'] as Map), pages: (json['pages'] as List) .map((e) => PageNode.fromJson(e as Map)) @@ -2922,9 +2945,11 @@ class SharedPage { final String updated; - /// Tiptap JSON; files load from /api/v1/share/{token}/files/{fileId} + /// Tiptap JSON (with "surface", the edgeless canvas, when it has one); files load from /api/v1/share/{token}/files/{fileId} final Map? content; + final PageMode mode; + final PageRef root; /// Pages under the shared page @@ -2936,6 +2961,7 @@ class SharedPage { 'icon': icon, 'updated': updated, 'content': content, + 'mode': mode.toJson(), 'root': root.toJson(), 'pages': pages.map((e) => e.toJson()).toList(), }; diff --git a/Phone-App/lib/editor/bridge.dart b/Phone-App/lib/editor/bridge.dart index 9b718f0..e150440 100644 --- a/Phone-App/lib/editor/bridge.dart +++ b/Phone-App/lib/editor/bridge.dart @@ -9,7 +9,7 @@ import 'dart:convert'; import 'package:flutter/foundation.dart'; /// Protocol version this app speaks. The page reports its own in "ready". -const editorProtocolVersion = 2; +const editorProtocolVersion = 3; /// Formatting the native toolbar can apply. enum EditorCommand { @@ -125,6 +125,10 @@ class EditorBridge extends ChangeNotifier { Future focus() => _post({'type': 'focus'}); + /// Shows the page's text, or its edgeless canvas (read-only), as the API's + /// PageMode names them: "page" or "edgeless". + Future setMode(String mode) => _post({'type': 'setMode', 'mode': mode}); + /// Closes the topmost panel or menu over the text. Future dismiss() => _post({'type': 'dismiss'}); diff --git a/Phone-App/lib/screens/page_screen.dart b/Phone-App/lib/screens/page_screen.dart index 0d50d56..c6c628e 100644 --- a/Phone-App/lib/screens/page_screen.dart +++ b/Phone-App/lib/screens/page_screen.dart @@ -58,6 +58,9 @@ class _PageScreenState extends State { bool _editing = false; bool _connected = false; + /// Showing the page as its edgeless canvas (read-only on phones). + bool _canvas = false; + bool get _canEdit { final p = _page; return p != null && @@ -112,6 +115,7 @@ class _PageScreenState extends State { _content = content.content; _offline = offline; _error = null; + _canvas = page.defaultMode == PageMode.edgeless; }); await _bridge.ready; await _bridge.setLayout( @@ -122,6 +126,7 @@ class _PageScreenState extends State { await _bridge.setEditable(false); await _bridge.setContent(_content); } + if (_canvas) await _bridge.setMode('edgeless'); if (widget.target case final target?) await _bridge.follow(target); if (widget.startEditing && _canEdit && !_editing) await _edit(); if (widget.openComment != null && mounted) _comments(); @@ -154,6 +159,13 @@ class _PageScreenState extends State { setState(() => _editing = false); } + Future _toggleCanvas() async { + if (_editing) await _done(); + final canvas = !_canvas; + await _bridge.setMode(canvas ? 'edgeless' : 'page'); + setState(() => _canvas = canvas); + } + void _follow(String route) { final m = RegExp(r'^/p/([A-Za-z0-9_-]+)').firstMatch(route); if (m == null) return; @@ -208,6 +220,15 @@ class _PageScreenState extends State { appBar: AppBar( title: Text(title, overflow: TextOverflow.ellipsis), actions: [ + if (page != null) + IconButton( + key: const Key('canvas'), + tooltip: _canvas ? 'Show as page' : 'Show as canvas', + icon: Icon( + _canvas ? Icons.article_outlined : Icons.dashboard_outlined, + ), + onPressed: _bridge.isReady ? _toggleCanvas : null, + ), if (page != null && !_offline) IconButton( tooltip: 'Comments', @@ -216,7 +237,7 @@ class _PageScreenState extends State { ), if (_editing) TextButton(onPressed: _done, child: const Text('Done')) - else if (_canEdit) + else if (_canEdit && !_canvas) IconButton( key: const Key('edit'), tooltip: 'Edit', diff --git a/Phone-App/test/editor_bridge_test.dart b/Phone-App/test/editor_bridge_test.dart index 8ebba5d..4a02045 100644 --- a/Phone-App/test/editor_bridge_test.dart +++ b/Phone-App/test/editor_bridge_test.dart @@ -71,7 +71,16 @@ void main() { test("sends the page's width and font", () async { await bridge.setLayout(fullWidth: true, font: 'serif'); - expect(sent.last, {'type': 'setLayout', 'fullWidth': true, 'font': 'serif'}); + expect(sent.last, { + 'type': 'setLayout', + 'fullWidth': true, + 'font': 'serif', + }); + }); + + test('switches between the text and the canvas', () async { + await bridge.setMode('edgeless'); + expect(sent.last, {'type': 'setMode', 'mode': 'edgeless'}); }); test('tracks panels over the text and dismisses them', () async { diff --git a/Phone-App/test/widget_test.dart b/Phone-App/test/widget_test.dart index ad518ec..84021df 100644 --- a/Phone-App/test/widget_test.dart +++ b/Phone-App/test/widget_test.dart @@ -273,12 +273,21 @@ void main() { 'favorite': false, 'pinnedAt': '', 'fullWidth': false, + 'defaultMode': 'page', 'font': '', 'tags': [], 'properties': {}, 'journalDate': '', - 'createdBy': {'id': 'u1', 'name': 'Ann', 'email': 'ann@docwell.test'}, - 'lastEditedBy': {'id': 'u1', 'name': 'Ann', 'email': 'ann@docwell.test'}, + 'createdBy': { + 'id': 'u1', + 'name': 'Ann', + 'email': 'ann@docwell.test', + }, + 'lastEditedBy': { + 'id': 'u1', + 'name': 'Ann', + 'email': 'ann@docwell.test', + }, }); await tester.pumpWidget( MaterialApp( diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index ca5a964..5c2849e 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -321,6 +321,24 @@ func (e PageGrantRole) Valid() bool { } } +// Defines values for PageMode. +const ( + PageModeEdgeless PageMode = "edgeless" + PageModePage PageMode = "page" +) + +// Valid indicates whether the value is a known member of the PageMode enum. +func (e PageMode) Valid() bool { + switch e { + case PageModeEdgeless: + return true + case PageModePage: + return true + default: + return false + } +} + // Defines values for PropertyType. const ( PropertyTypeCheckbox PropertyType = "checkbox" @@ -1293,6 +1311,9 @@ type Page struct { Created string `json:"created"` CreatedBy PageUser `json:"createdBy"` + // DefaultMode The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it + DefaultMode PageMode `json:"defaultMode"` + // DeletedAt When the page itself was trashed; empty otherwise DeletedAt string `json:"deletedAt"` @@ -1411,6 +1432,9 @@ type PageItem struct { Title string `json:"title"` } +// PageMode The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it +type PageMode string + // PageNode defines model for PageNode. type PageNode struct { Icon string `json:"icon"` @@ -1599,11 +1623,14 @@ type SharePageResult struct { // SharedPage defines model for SharedPage. type SharedPage struct { - // Content Tiptap JSON; files load from /api/v1/share/{token}/files/{fileId} + // Content Tiptap JSON (with "surface", the edgeless canvas, when it has one); files load from /api/v1/share/{token}/files/{fileId} Content *map[string]interface{} `json:"content"` Icon string `json:"icon"` Id string `json:"id"` + // Mode The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it + Mode PageMode `json:"mode"` + // Pages Pages under the shared page Pages []PageNode `json:"pages"` Root PageRef `json:"root"` @@ -2064,6 +2091,9 @@ type DeletePageParams struct { // UpdatePageJSONBody defines parameters for UpdatePage. type UpdatePageJSONBody struct { + // DefaultMode The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it + DefaultMode *PageMode `json:"defaultMode,omitempty"` + // Font The body font for everyone reading the page; empty is the default sans Font *PageFont `json:"font,omitempty"` diff --git a/Server/internal/directory/pages.go b/Server/internal/directory/pages.go index 081735a..b0c7a96 100644 --- a/Server/internal/directory/pages.go +++ b/Server/internal/directory/pages.go @@ -25,7 +25,7 @@ import ( // but stay readable (and read-only) until someone unarchives them. // pageFields skips the large content columns. -const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,pinned_at,full_width,font,tags,journal_date,created,updated" +const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,pinned_at,full_width,font,default_mode,tags,journal_date,created,updated" // pageDetailFields adds the page's property values. const pageDetailFields = pageFields + ",properties" @@ -47,6 +47,8 @@ type pageRecord struct { PinnedAt string `json:"pinned_at"` FullWidth bool `json:"full_width"` Font string `json:"font"` + // DefaultMode is "edgeless" for pages that open as a canvas; empty for text. + DefaultMode string `json:"default_mode"` // Tags are tag ids; Properties maps workspace property ids to values // (only loaded with pageDetailFields). Tags []string `json:"tags"` @@ -108,6 +110,8 @@ type Page struct { // FullWidth and Font are how the page is shown to everyone. FullWidth bool `json:"fullWidth"` Font string `json:"font"` + // DefaultMode is the view the page opens in: "page" or "edgeless". + DefaultMode string `json:"defaultMode"` // Tags are the page's tag ids, Properties its custom property values by // property id (see properties.go). Tags []string `json:"tags"` @@ -290,7 +294,7 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page ArchivedAt: p.ArchivedAt, Archived: p.ArchivedAt != "", Ancestors: []PageRef{}, Role: a.role, Restricted: p.Restricted, IsTemplate: p.IsTemplate, Favorite: s.isFavorite(ctx, c.ID, p.ID), PinnedAt: p.PinnedAt, - FullWidth: p.FullWidth, Font: p.Font, + FullWidth: p.FullWidth, Font: p.Font, DefaultMode: pageMode(p.DefaultMode), Tags: nonNil(p.Tags), Properties: p.Properties, JournalDate: p.JournalDate, CreatedBy: s.pageUser(ctx, p.Creator), LastEditedBy: s.pageUser(ctx, p.LastEditor), } @@ -442,6 +446,8 @@ type UpdatePageInput struct { IsTemplate *bool `json:"isTemplate"` FullWidth *bool `json:"fullWidth"` Font *string `json:"font"` + // DefaultMode is "page" or "edgeless". + DefaultMode *string `json:"defaultMode"` // Tags replaces the page's tags (ids of the workspace's tags). Tags *[]string `json:"tags"` // Properties sets the named property values; null clears one. @@ -492,6 +498,16 @@ func (s *Service) UpdatePage(ctx context.Context, c access.Caller, id string, in return Page{}, apperr.InvalidFields(map[string]string{"font": "Font must be empty, serif or mono."}) } } + if in.DefaultMode != nil { + switch *in.DefaultMode { + case "page": + patch["default_mode"] = "" + case "edgeless": + patch["default_mode"] = "edgeless" + default: + return Page{}, apperr.InvalidFields(map[string]string{"defaultMode": "Mode must be page or edgeless."}) + } + } if in.Tags != nil { tags, err := s.checkTags(ctx, p.Workspace, *in.Tags) if err != nil { @@ -782,3 +798,12 @@ func nonNil(list []string) []string { } return list } + +// pageMode is how the API names a page's default mode: "page" when the +// stored value is empty. +func pageMode(stored string) string { + if stored == "edgeless" { + return "edgeless" + } + return "page" +} diff --git a/Server/internal/directory/shares.go b/Server/internal/directory/shares.go index 79f54d9..a28cd07 100644 --- a/Server/internal/directory/shares.go +++ b/Server/internal/directory/shares.go @@ -123,6 +123,8 @@ type SharedPage struct { Icon string `json:"icon"` Updated string `json:"updated"` Content json.RawMessage `json:"content"` + // Mode is the view the page opens in: "page" or "edgeless". + Mode string `json:"mode"` // Root is the shared page; Pages lists the pages under it when the link // includes subpages (tree order, empty otherwise). Root PageRef `json:"root"` @@ -181,7 +183,7 @@ func (s *Service) GetSharedPage(ctx context.Context, token, pageID string) (Shar } root := t.byID[link.Page] out := SharedPage{ - ID: p.ID, Title: p.Title, Icon: p.Icon, Updated: p.Updated, Content: doc, + ID: p.ID, Title: p.Title, Icon: p.Icon, Updated: p.Updated, Content: doc, Mode: pageMode(p.DefaultMode), Root: PageRef{ID: root.ID, Title: root.Title, Icon: root.Icon}, Pages: []PageNode{}, } if link.IncludeSubpages { diff --git a/Server/internal/pbschema/schema.json b/Server/internal/pbschema/schema.json index 7e6e2c0..db5ddb1 100644 --- a/Server/internal/pbschema/schema.json +++ b/Server/internal/pbschema/schema.json @@ -1233,6 +1233,20 @@ "required": false, "system": false, "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "select3527113901", + "maxSelect": 1, + "name": "default_mode", + "presentable": false, + "required": false, + "system": false, + "type": "select", + "values": [ + "edgeless" + ] } ], "id": "pbc_3945946014", diff --git a/Server/internal/ycrdt/ycrdt_test.go b/Server/internal/ycrdt/ycrdt_test.go index 7ea17ca..c0f37d6 100644 --- a/Server/internal/ycrdt/ycrdt_test.go +++ b/Server/internal/ycrdt/ycrdt_test.go @@ -150,3 +150,60 @@ func TestDatabaseRoundTrip(t *testing.T) { t.Fatalf("text = %q, want %q", r.Text, want) } } + +// A page with an edgeless canvas: a shape, a note with a body of its own and +// a mind map, in drawing order (frames first). +const canvas = `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Page text"}]}],` + + `"surface":{"elements":[` + + `{"id":"f1","type":"frame","index":-1,"x":0,"y":0,"w":400,"h":300,"title":"Plan"},` + + `{"id":"s1","type":"shape","index":1,"x":10,"y":10,"w":100,"h":60,"shape":"ellipse","text":"Idea"},` + + `{"id":"n1","type":"note","index":2,"x":200,"y":10,"w":240,"h":80,"body":[{"type":"paragraph","content":[{"type":"text","text":"Sticky"}]}]},` + + `{"id":"m1","type":"mindmap","index":3,"x":0,"y":400,"nodes":{"r":{"parent":"","pos":0,"text":"Root"}}}]}}` + +func TestCanvasRoundTrip(t *testing.T) { + ctx := context.Background() + p := newPool(t) + seed, err := p.Replace(ctx, nil, []byte(canvas)) + if err != nil { + t.Fatal(err) + } + r, err := p.Read(ctx, seed) + if err != nil { + t.Fatal(err) + } + equalJSON(t, r.JSON, canvas) + for _, word := range []string{"Page text", "Plan", "Idea", "Sticky", "Root"} { + if !strings.Contains(r.Text, word) { + t.Fatalf("text %q is missing %q", r.Text, word) + } + } + // A document without a surface keeps the canvas; an empty one clears it. + keep, err := p.Replace(ctx, [][]byte{seed}, []byte(`{"type":"doc","content":[]}`)) + if err != nil { + t.Fatal(err) + } + merged, err := p.Merge(ctx, [][]byte{seed, keep}) + if err != nil { + t.Fatal(err) + } + r, err = p.Read(ctx, merged) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(r.JSON), `"Sticky"`) { + t.Fatalf("canvas lost: %s", r.JSON) + } + clear, err := p.Replace(ctx, [][]byte{merged}, []byte(`{"type":"doc","content":[],"surface":{"elements":[]}}`)) + if err != nil { + t.Fatal(err) + } + merged, err = p.Merge(ctx, [][]byte{merged, clear}) + if err != nil { + t.Fatal(err) + } + r, err = p.Read(ctx, merged) + if err != nil { + t.Fatal(err) + } + equalJSON(t, r.JSON, `{"type":"doc","content":[],"surface":{"elements":[]}}`) +} diff --git a/Server/ycrdt-wasm/src/lib.rs b/Server/ycrdt-wasm/src/lib.rs index 6cdceab..0c8f795 100644 --- a/Server/ycrdt-wasm/src/lib.rs +++ b/Server/ycrdt-wasm/src/lib.rs @@ -25,6 +25,9 @@ const FRAGMENT: &str = "default"; /// Database blocks keep their records in this map, keyed by the node's id (ADR-13). const BLOCKS: &str = "blocks"; +/// The edgeless canvas keeps its elements in this map, keyed by element id (ADR-14). +const SURFACE: &str = "surface"; + thread_local! { static OUT: RefCell> = const { RefCell::new(Vec::new()) }; } @@ -139,6 +142,9 @@ pub unsafe extern "C" fn dw_to_json(ptr: *const u8, len: u32) -> i32 { let mut root = Map::new(); root.insert("type".into(), "doc".into()); root.insert("content".into(), content.into()); + if let Some(surface) = surface_json(&txn) { + root.insert("surface".into(), surface); + } serde_json::to_vec(&Value::Object(root)).map_err(|e| e.to_string()) })) } @@ -155,6 +161,7 @@ pub unsafe extern "C" fn dw_to_text(ptr: *const u8, len: u32) -> i32 { node_text(&txn, node, &mut text); text.push('\n'); } + surface_text(&txn, &mut text); Ok(text.into_bytes()) })) } @@ -181,6 +188,10 @@ pub unsafe extern "C" fn dw_replace(ptr: *const u8, len: u32, json_ptr: *const u let n = fragment.len(&txn); fragment.remove_range(&mut txn, 0, n); fill(&mut txn, &fragment, content, 0)?; + // A document without "surface" leaves the canvas as it is (older versions had none). + if let Some(Value::Object(surface)) = root.get("surface") { + write_surface(&mut txn, surface)?; + } } let txn = doc.transact(); Ok(txn.encode_state_as_update_v1(&before)) @@ -560,3 +571,137 @@ fn write_database(txn: &mut TransactionMut, id: &str, data: &Value, depth: u32) } Ok(()) } + +// ---- The edgeless canvas (ADR-14) ---- + +/// The canvas as {elements: [...]}: each element's fields with its id, a note's +/// body as ProseMirror nodes, a mind map's nodes as an object. None when the +/// page never had a canvas; an empty list when everything was deleted. +fn surface_json(txn: &T) -> Option { + let surface = txn.get_map(SURFACE)?; + let mut elements: Vec<(bool, f64, String, Value)> = Vec::new(); + for (id, value) in surface.iter(txn) { + let Out::YMap(el) = value else { continue }; + let mut out = Map::new(); + out.insert("id".into(), id.into()); + for (key, v) in el.iter(txn) { + match (key, v) { + ("body", Out::YXmlFragment(f)) => { + let body: Vec = f.children(txn).flat_map(|n| node_json(txn, n)).collect(); + out.insert("body".into(), body.into()); + } + (key, v @ Out::YMap(_)) => { + out.insert(key.into(), any_json(&v.to_json(txn))); + } + (key, Out::Any(a)) => { + out.insert(key.into(), any_json(&a)); + } + _ => {} + } + } + let frame = out.get("type").and_then(Value::as_str) == Some("frame"); + let index = out.get("index").and_then(Value::as_f64).unwrap_or(0.0); + elements.push((!frame, index, id.to_owned(), Value::Object(out))); + } + // Drawing order: frames first, then by index, then by id. + elements.sort_by(|a, b| { + a.0.cmp(&b.0) + .then(a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)) + .then(a.2.cmp(&b.2)) + }); + let mut root = Map::new(); + root.insert("elements".into(), elements.into_iter().map(|e| e.3).collect::>().into()); + Some(Value::Object(root)) +} + +/// The canvas's words for search: shape and text boxes, frame titles, +/// connector labels, note bodies and mind map nodes, one element per line. +fn surface_text(txn: &T, buf: &mut String) { + let Some(surface) = txn.get_map(SURFACE) else { return }; + for (_, value) in surface.iter(txn) { + let Out::YMap(el) = value else { continue }; + let mut line = String::new(); + for key in ["text", "title", "label"] { + if let Some(Out::Any(Any::String(s))) = el.get(txn, key) { + if !s.is_empty() { + line.push_str(&s); + line.push(' '); + } + } + } + if let Some(Out::YXmlFragment(f)) = el.get(txn, "body") { + for node in f.children(txn) { + node_text(txn, node, &mut line); + line.push('\n'); + } + } + if let Some(nodes @ Out::YMap(_)) = el.get(txn, "nodes") { + if let Value::Object(m) = any_json(&nodes.to_json(txn)) { + for n in m.values() { + if let Some(t) = n.get("text").and_then(Value::as_str) { + line.push_str(t); + line.push(' '); + } + } + } + } + let line = line.trim(); + if !line.is_empty() { + buf.push_str(line); + buf.push('\n'); + } + } +} + +/// Writes the canvas from JSON ({elements: [...]}), replacing what was there, +/// the way the canvas's store.ts writes it. +fn write_surface(txn: &mut TransactionMut, surface: &Map) -> Result<(), String> { + let map = txn.get_or_insert_map(SURFACE); + let keys: Vec = map.keys(txn).map(str::to_owned).collect(); + for k in keys { + map.remove(txn, &k); + } + let elements = surface.get("elements").and_then(Value::as_array).cloned().unwrap_or_default(); + for el in elements { + let Value::Object(o) = el else { continue }; + let Some(id) = o.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned) else { + continue; + }; + let mut fields: Vec<(String, In)> = Vec::new(); + for (k, v) in &o { + if v.is_null() || k == "id" || k == "body" { + continue; + } + if k == "nodes" { + let mut nodes: Vec<(String, In)> = Vec::new(); + if let Value::Object(m) = v { + for (nid, n) in m { + let Value::Object(n) = n else { continue }; + let mut entries: Vec<(String, In)> = Vec::new(); + for (nk, nv) in n { + if !nv.is_null() { + entries.push((nk.clone(), In::Any(json_any(nv.clone())?))); + } + } + nodes.push((nid.clone(), In::Map(MapPrelim::from_iter(entries)))); + } + } + fields.push((k.clone(), In::Map(MapPrelim::from_iter(nodes)))); + continue; + } + fields.push((k.clone(), In::Any(json_any(v.clone())?))); + } + let item = map.insert(txn, id.as_str(), MapPrelim::from_iter(fields)); + let is_note = o.get("type").and_then(Value::as_str) == Some("note"); + let is_page = o.get("page").and_then(Value::as_bool) == Some(true); + if is_note && !is_page { + let body = match o.get("body") { + Some(Value::Array(b)) if !b.is_empty() => b.clone(), + _ => vec![serde_json::json!({ "type": "paragraph" })], + }; + let fragment = item.insert(txn, "body", XmlFragmentPrelim::default()); + fill(txn, &fragment, &body, 1)?; + } + } + Ok(()) +} diff --git a/Web-App/frontend/src/composables/useEditorHosts.ts b/Web-App/frontend/src/composables/useEditorHosts.ts index e896a57..f3a6f48 100644 --- a/Web-App/frontend/src/composables/useEditorHosts.ts +++ b/Web-App/frontend/src/composables/useEditorHosts.ts @@ -39,6 +39,7 @@ export function useEditorLabels() { find: group("find", "find"), dates: group("dates", "dates"), database: group("database", "database"), + edgeless: group("edgeless", "edgeless"), })); } diff --git a/Web-App/frontend/src/locales/de.json b/Web-App/frontend/src/locales/de.json index 378cf58..a7e2f0d 100644 --- a/Web-App/frontend/src/locales/de.json +++ b/Web-App/frontend/src/locales/de.json @@ -784,6 +784,108 @@ "resize": "Ziehen, um die Breite zu ändern", "groupAsDatabase": "Als Datenbank gruppieren", "done": "Erledigt" + }, + "edgeless": { + "toolbar": "Werkzeuge der Tafel", + "select": "Auswählen (V)", + "hand": "Hand (H)", + "note": "Notiz (N)", + "text": "Text (T)", + "shape": "Form (S)", + "connector": "Verbinder (C)", + "pen": "Stift (P)", + "eraser": "Radierer (E)", + "frame": "Rahmen (F)", + "mindmap": "Mindmap (M)", + "image": "Bild (I)", + "link": "Link (L)", + "library": "Sticker und Vorlagen", + "present": "Präsentieren", + "zoomIn": "Vergrößern", + "zoomOut": "Verkleinern", + "zoomFit": "An Bildschirm anpassen", + "zoomReset": "Auf 100 % zoomen", + "rect": "Quadrat", + "roundrect": "Abgerundetes Rechteck", + "ellipse": "Ellipse", + "diamond": "Raute", + "triangle": "Dreieck", + "general": "Normal", + "scribbled": "Skizziert", + "straight": "Gerade", + "curve": "Kurve", + "elbow": "Gewinkelt", + "stroke": "Linienfarbe", + "fill": "Füllung", + "textColor": "Textfarbe", + "background": "Hintergrund", + "thickness": "Stärke", + "lineStyle": "Linienart", + "solid": "Durchgezogen", + "dash": "Gestrichelt", + "noLine": "Keine Linie", + "startArrow": "Anfang", + "endArrow": "Ende", + "fontSize": "Größe", + "font": "Schrift", + "sans": "Serifenlos", + "serif": "Serifen", + "mono": "Monospace", + "alignLeft": "Links ausrichten", + "alignCenter": "Zentrieren", + "alignRight": "Rechts ausrichten", + "bold": "Fett", + "layout": "Anordnung", + "layoutRight": "Rechts", + "layoutLeft": "Links", + "layoutRadial": "Beide Seiten", + "addChild": "Zweig hinzufügen (Tab)", + "addSibling": "Geschwister hinzufügen (Enter)", + "bringFront": "In den Vordergrund", + "sendBack": "In den Hintergrund", + "group": "Gruppieren (Strg+G)", + "ungroup": "Gruppierung aufheben", + "duplicate": "Duplizieren (Strg+D)", + "delete": "Löschen", + "copy": "Kopieren", + "editText": "Text bearbeiten", + "openLink": "Link öffnen", + "frameTitle": "Rahmen", + "groupTitle": "Gruppe", + "linkPrompt": "Linkadresse", + "pageNote": "Seite", + "stickers": "Sticker", + "templates": "Vorlagen", + "presentNoFrames": "Füge Rahmen hinzu, um sie nacheinander zu zeigen.", + "presentExit": "Präsentation beenden", + "presentNext": "Nächster Rahmen", + "presentPrevious": "Vorheriger Rahmen", + "presentStep": "{n} / {total}", + "textPlaceholder": "Schreiben…", + "templateKanban": "Board", + "templateSwot": "SWOT", + "templateFlow": "Flussdiagramm", + "templateBrainstorm": "Brainstorming", + "templateRetro": "Retrospektive", + "todo": "Zu erledigen", + "doing": "In Arbeit", + "done": "Erledigt", + "strengths": "Stärken", + "weaknesses": "Schwächen", + "opportunities": "Chancen", + "threats": "Risiken", + "start": "Start", + "step": "Schritt", + "decision": "Entscheidung?", + "end": "Ende", + "centralIdea": "Kernidee", + "idea": "Idee", + "wentWell": "Lief gut", + "toImprove": "Zu verbessern", + "actions": "Maßnahmen", + "colorInk": "Standard", + "colorPaper": "Papier", + "colorNone": "Keine" } }, "comments": { @@ -898,7 +1000,15 @@ "dateTitles": "Neue Seiten mit dem heutigen Datum betiteln", "showProperties": "Eigenschaften unter dem Titel zeigen", "showBacklinks": "Seiten zeigen, die hierher verlinken", - "codeLineNumbers": "Zeilennummern in Codeblöcken" + "codeLineNumbers": "Zeilennummern in Codeblöcken", + "newPageMode": "Neue Seiten öffnen als", + "modes": { + "page": "Seite", + "edgeless": "Tafel" + }, + "edgelessStyles": "Stile der Tafel", + "edgelessStylesHint": "Neue Formen, Linien und Notizen sehen aus wie die zuletzt gestalteten.", + "resetStyles": "Zurücksetzen" } }, "webhooks": { @@ -1133,5 +1243,16 @@ "label": "Seite daneben", "openHere": "Als Hauptseite öffnen", "close": "Seite daneben schließen" + }, + "edgeless": { + "mode": "Ansicht", + "pageMode": "Seite", + "edgelessMode": "Randlos (Tafel)", + "canvas": "Tafel", + "present": "Rahmen präsentieren", + "exportPng": "Als PNG exportieren", + "exportSvg": "Als SVG exportieren", + "defaultEdgeless": "Für alle als Tafel öffnen", + "defaultPage": "Für alle als Seite öffnen" } } diff --git a/Web-App/frontend/src/locales/en.json b/Web-App/frontend/src/locales/en.json index 5e00595..168394f 100644 --- a/Web-App/frontend/src/locales/en.json +++ b/Web-App/frontend/src/locales/en.json @@ -784,6 +784,108 @@ "resize": "Drag to change the width", "groupAsDatabase": "Group as database", "done": "Done" + }, + "edgeless": { + "toolbar": "Canvas tools", + "select": "Select (V)", + "hand": "Hand (H)", + "note": "Note (N)", + "text": "Text (T)", + "shape": "Shape (S)", + "connector": "Connector (C)", + "pen": "Pen (P)", + "eraser": "Eraser (E)", + "frame": "Frame (F)", + "mindmap": "Mind map (M)", + "image": "Picture (I)", + "link": "Link (L)", + "library": "Stickers and templates", + "present": "Present", + "zoomIn": "Zoom in", + "zoomOut": "Zoom out", + "zoomFit": "Fit to screen", + "zoomReset": "Zoom to 100%", + "rect": "Square", + "roundrect": "Rounded rectangle", + "ellipse": "Ellipse", + "diamond": "Diamond", + "triangle": "Triangle", + "general": "General", + "scribbled": "Scribbled", + "straight": "Straight", + "curve": "Curve", + "elbow": "Elbowed", + "stroke": "Line colour", + "fill": "Fill", + "textColor": "Text colour", + "background": "Background", + "thickness": "Thickness", + "lineStyle": "Line style", + "solid": "Solid", + "dash": "Dashed", + "noLine": "No line", + "startArrow": "Start", + "endArrow": "End", + "fontSize": "Size", + "font": "Font", + "sans": "Sans", + "serif": "Serif", + "mono": "Mono", + "alignLeft": "Align left", + "alignCenter": "Align centre", + "alignRight": "Align right", + "bold": "Bold", + "layout": "Layout", + "layoutRight": "Right", + "layoutLeft": "Left", + "layoutRadial": "Both sides", + "addChild": "Add branch (Tab)", + "addSibling": "Add sibling (Enter)", + "bringFront": "Bring to front", + "sendBack": "Send to back", + "group": "Group (Ctrl+G)", + "ungroup": "Ungroup", + "duplicate": "Duplicate (Ctrl+D)", + "delete": "Delete", + "copy": "Copy", + "editText": "Edit text", + "openLink": "Open link", + "frameTitle": "Frame", + "groupTitle": "Group", + "linkPrompt": "Link address", + "pageNote": "Page", + "stickers": "Stickers", + "templates": "Templates", + "presentNoFrames": "Add frames to present them one by one.", + "presentExit": "Stop presenting", + "presentNext": "Next frame", + "presentPrevious": "Previous frame", + "presentStep": "{n} / {total}", + "textPlaceholder": "Type…", + "templateKanban": "Board", + "templateSwot": "SWOT", + "templateFlow": "Flowchart", + "templateBrainstorm": "Brainstorm", + "templateRetro": "Retrospective", + "todo": "To do", + "doing": "Doing", + "done": "Done", + "strengths": "Strengths", + "weaknesses": "Weaknesses", + "opportunities": "Opportunities", + "threats": "Threats", + "start": "Start", + "step": "Step", + "decision": "Decision?", + "end": "End", + "centralIdea": "Central idea", + "idea": "Idea", + "wentWell": "Went well", + "toImprove": "To improve", + "actions": "Actions", + "colorInk": "Default", + "colorPaper": "Paper", + "colorNone": "None" } }, "comments": { @@ -898,7 +1000,15 @@ "dateTitles": "Title new pages with today's date", "showProperties": "Show properties under the title", "showBacklinks": "Show the pages that link here", - "codeLineNumbers": "Line numbers in code blocks" + "codeLineNumbers": "Line numbers in code blocks", + "newPageMode": "New pages open as", + "modes": { + "page": "Page", + "edgeless": "Canvas" + }, + "edgelessStyles": "Canvas styles", + "edgelessStylesHint": "New shapes, lines and notes look like the ones you styled last.", + "resetStyles": "Reset" } }, "webhooks": { @@ -1133,5 +1243,16 @@ "label": "Page beside", "openHere": "Open as the main page", "close": "Close the side page" + }, + "edgeless": { + "mode": "View", + "pageMode": "Page", + "edgelessMode": "Edgeless (canvas)", + "canvas": "Canvas", + "present": "Present frames", + "exportPng": "Export as PNG", + "exportSvg": "Export as SVG", + "defaultEdgeless": "Open as canvas for everyone", + "defaultPage": "Open as page for everyone" } } diff --git a/Web-App/frontend/src/locales/es.json b/Web-App/frontend/src/locales/es.json index 47141f0..9d0d914 100644 --- a/Web-App/frontend/src/locales/es.json +++ b/Web-App/frontend/src/locales/es.json @@ -784,6 +784,108 @@ "resize": "Arrastra para cambiar el ancho", "groupAsDatabase": "Agrupar como base de datos", "done": "Hecho" + }, + "edgeless": { + "toolbar": "Herramientas del lienzo", + "select": "Seleccionar (V)", + "hand": "Mano (H)", + "note": "Nota (N)", + "text": "Texto (T)", + "shape": "Forma (S)", + "connector": "Conector (C)", + "pen": "Lápiz (P)", + "eraser": "Borrador (E)", + "frame": "Marco (F)", + "mindmap": "Mapa mental (M)", + "image": "Imagen (I)", + "link": "Enlace (L)", + "library": "Pegatinas y plantillas", + "present": "Presentar", + "zoomIn": "Acercar", + "zoomOut": "Alejar", + "zoomFit": "Ajustar a la pantalla", + "zoomReset": "Zoom al 100 %", + "rect": "Cuadrado", + "roundrect": "Rectángulo redondeado", + "ellipse": "Elipse", + "diamond": "Rombo", + "triangle": "Triángulo", + "general": "Normal", + "scribbled": "Boceto", + "straight": "Recto", + "curve": "Curvo", + "elbow": "En codo", + "stroke": "Color de línea", + "fill": "Relleno", + "textColor": "Color del texto", + "background": "Fondo", + "thickness": "Grosor", + "lineStyle": "Estilo de línea", + "solid": "Continua", + "dash": "Discontinua", + "noLine": "Sin línea", + "startArrow": "Inicio", + "endArrow": "Final", + "fontSize": "Tamaño", + "font": "Fuente", + "sans": "Sin serifa", + "serif": "Con serifa", + "mono": "Monoespaciada", + "alignLeft": "Alinear a la izquierda", + "alignCenter": "Centrar", + "alignRight": "Alinear a la derecha", + "bold": "Negrita", + "layout": "Disposición", + "layoutRight": "Derecha", + "layoutLeft": "Izquierda", + "layoutRadial": "Ambos lados", + "addChild": "Añadir rama (Tab)", + "addSibling": "Añadir al lado (Intro)", + "bringFront": "Traer al frente", + "sendBack": "Enviar al fondo", + "group": "Agrupar (Ctrl+G)", + "ungroup": "Desagrupar", + "duplicate": "Duplicar (Ctrl+D)", + "delete": "Eliminar", + "copy": "Copiar", + "editText": "Editar texto", + "openLink": "Abrir enlace", + "frameTitle": "Marco", + "groupTitle": "Grupo", + "linkPrompt": "Dirección del enlace", + "pageNote": "Página", + "stickers": "Pegatinas", + "templates": "Plantillas", + "presentNoFrames": "Añade marcos para presentarlos uno a uno.", + "presentExit": "Dejar de presentar", + "presentNext": "Marco siguiente", + "presentPrevious": "Marco anterior", + "presentStep": "{n} / {total}", + "textPlaceholder": "Escribe…", + "templateKanban": "Tablero", + "templateSwot": "DAFO", + "templateFlow": "Diagrama de flujo", + "templateBrainstorm": "Lluvia de ideas", + "templateRetro": "Retrospectiva", + "todo": "Pendiente", + "doing": "En curso", + "done": "Hecho", + "strengths": "Fortalezas", + "weaknesses": "Debilidades", + "opportunities": "Oportunidades", + "threats": "Amenazas", + "start": "Inicio", + "step": "Paso", + "decision": "¿Decisión?", + "end": "Fin", + "centralIdea": "Idea central", + "idea": "Idea", + "wentWell": "Lo que fue bien", + "toImprove": "A mejorar", + "actions": "Acciones", + "colorInk": "Predeterminado", + "colorPaper": "Papel", + "colorNone": "Ninguno" } }, "comments": { @@ -898,7 +1000,15 @@ "dateTitles": "Titular las páginas nuevas con la fecha de hoy", "showProperties": "Mostrar las propiedades bajo el título", "showBacklinks": "Mostrar las páginas que enlazan aquí", - "codeLineNumbers": "Números de línea en los bloques de código" + "codeLineNumbers": "Números de línea en los bloques de código", + "newPageMode": "Las páginas nuevas se abren como", + "modes": { + "page": "Página", + "edgeless": "Lienzo" + }, + "edgelessStyles": "Estilos del lienzo", + "edgelessStylesHint": "Las formas, líneas y notas nuevas se ven como las últimas que estilizaste.", + "resetStyles": "Restablecer" } }, "webhooks": { @@ -1133,5 +1243,16 @@ "label": "Página al lado", "openHere": "Abrir como página principal", "close": "Cerrar la página de al lado" + }, + "edgeless": { + "mode": "Vista", + "pageMode": "Página", + "edgelessMode": "Sin bordes (lienzo)", + "canvas": "Lienzo", + "present": "Presentar marcos", + "exportPng": "Exportar como PNG", + "exportSvg": "Exportar como SVG", + "defaultEdgeless": "Abrir como lienzo para todos", + "defaultPage": "Abrir como página para todos" } } diff --git a/Web-App/frontend/src/locales/fr.json b/Web-App/frontend/src/locales/fr.json index 82e18cf..0a13327 100644 --- a/Web-App/frontend/src/locales/fr.json +++ b/Web-App/frontend/src/locales/fr.json @@ -784,6 +784,108 @@ "resize": "Glisser pour changer la largeur", "groupAsDatabase": "Grouper en base de données", "done": "Terminé" + }, + "edgeless": { + "toolbar": "Outils du tableau", + "select": "Sélectionner (V)", + "hand": "Main (H)", + "note": "Note (N)", + "text": "Texte (T)", + "shape": "Forme (S)", + "connector": "Connecteur (C)", + "pen": "Stylo (P)", + "eraser": "Gomme (E)", + "frame": "Cadre (F)", + "mindmap": "Carte mentale (M)", + "image": "Image (I)", + "link": "Lien (L)", + "library": "Autocollants et modèles", + "present": "Présenter", + "zoomIn": "Zoom avant", + "zoomOut": "Zoom arrière", + "zoomFit": "Ajuster à l’écran", + "zoomReset": "Zoom à 100 %", + "rect": "Carré", + "roundrect": "Rectangle arrondi", + "ellipse": "Ellipse", + "diamond": "Losange", + "triangle": "Triangle", + "general": "Standard", + "scribbled": "Esquissé", + "straight": "Droit", + "curve": "Courbe", + "elbow": "Coudé", + "stroke": "Couleur du trait", + "fill": "Remplissage", + "textColor": "Couleur du texte", + "background": "Fond", + "thickness": "Épaisseur", + "lineStyle": "Style du trait", + "solid": "Plein", + "dash": "Tirets", + "noLine": "Sans trait", + "startArrow": "Début", + "endArrow": "Fin", + "fontSize": "Taille", + "font": "Police", + "sans": "Sans empattement", + "serif": "Avec empattement", + "mono": "Chasse fixe", + "alignLeft": "Aligner à gauche", + "alignCenter": "Centrer", + "alignRight": "Aligner à droite", + "bold": "Gras", + "layout": "Disposition", + "layoutRight": "À droite", + "layoutLeft": "À gauche", + "layoutRadial": "Des deux côtés", + "addChild": "Ajouter une branche (Tab)", + "addSibling": "Ajouter à côté (Entrée)", + "bringFront": "Mettre au premier plan", + "sendBack": "Mettre à l’arrière-plan", + "group": "Grouper (Ctrl+G)", + "ungroup": "Dégrouper", + "duplicate": "Dupliquer (Ctrl+D)", + "delete": "Supprimer", + "copy": "Copier", + "editText": "Modifier le texte", + "openLink": "Ouvrir le lien", + "frameTitle": "Cadre", + "groupTitle": "Groupe", + "linkPrompt": "Adresse du lien", + "pageNote": "Page", + "stickers": "Autocollants", + "templates": "Modèles", + "presentNoFrames": "Ajoutez des cadres pour les présenter un par un.", + "presentExit": "Arrêter la présentation", + "presentNext": "Cadre suivant", + "presentPrevious": "Cadre précédent", + "presentStep": "{n} / {total}", + "textPlaceholder": "Écrivez…", + "templateKanban": "Tableau", + "templateSwot": "SWOT", + "templateFlow": "Organigramme", + "templateBrainstorm": "Remue-méninges", + "templateRetro": "Rétrospective", + "todo": "À faire", + "doing": "En cours", + "done": "Terminé", + "strengths": "Forces", + "weaknesses": "Faiblesses", + "opportunities": "Opportunités", + "threats": "Menaces", + "start": "Début", + "step": "Étape", + "decision": "Décision ?", + "end": "Fin", + "centralIdea": "Idée centrale", + "idea": "Idée", + "wentWell": "Ce qui a bien marché", + "toImprove": "À améliorer", + "actions": "Actions", + "colorInk": "Par défaut", + "colorPaper": "Papier", + "colorNone": "Aucune" } }, "comments": { @@ -898,7 +1000,15 @@ "dateTitles": "Titrer les nouvelles pages avec la date du jour", "showProperties": "Afficher les propriétés sous le titre", "showBacklinks": "Afficher les pages qui pointent ici", - "codeLineNumbers": "Numéros de ligne dans les blocs de code" + "codeLineNumbers": "Numéros de ligne dans les blocs de code", + "newPageMode": "Les nouvelles pages s’ouvrent en", + "modes": { + "page": "Page", + "edgeless": "Tableau" + }, + "edgelessStyles": "Styles du tableau", + "edgelessStylesHint": "Les nouvelles formes, lignes et notes ressemblent aux dernières mises en forme.", + "resetStyles": "Réinitialiser" } }, "webhooks": { @@ -1133,5 +1243,16 @@ "label": "Page à côté", "openHere": "Ouvrir comme page principale", "close": "Fermer la page à côté" + }, + "edgeless": { + "mode": "Affichage", + "pageMode": "Page", + "edgelessMode": "Sans bords (tableau)", + "canvas": "Tableau", + "present": "Présenter les cadres", + "exportPng": "Exporter en PNG", + "exportSvg": "Exporter en SVG", + "defaultEdgeless": "Ouvrir en tableau pour tous", + "defaultPage": "Ouvrir en page pour tous" } } diff --git a/Web-App/frontend/src/locales/pl.json b/Web-App/frontend/src/locales/pl.json index 582f224..98b9a72 100644 --- a/Web-App/frontend/src/locales/pl.json +++ b/Web-App/frontend/src/locales/pl.json @@ -784,6 +784,108 @@ "resize": "Przeciągnij, aby zmienić szerokość", "groupAsDatabase": "Grupuj jako bazę danych", "done": "Gotowe" + }, + "edgeless": { + "toolbar": "Narzędzia tablicy", + "select": "Zaznacz (V)", + "hand": "Rączka (H)", + "note": "Notatka (N)", + "text": "Tekst (T)", + "shape": "Kształt (S)", + "connector": "Łącznik (C)", + "pen": "Pióro (P)", + "eraser": "Gumka (E)", + "frame": "Ramka (F)", + "mindmap": "Mapa myśli (M)", + "image": "Obraz (I)", + "link": "Link (L)", + "library": "Naklejki i szablony", + "present": "Prezentuj", + "zoomIn": "Powiększ", + "zoomOut": "Pomniejsz", + "zoomFit": "Dopasuj do ekranu", + "zoomReset": "Powiększenie 100%", + "rect": "Kwadrat", + "roundrect": "Zaokrąglony prostokąt", + "ellipse": "Elipsa", + "diamond": "Romb", + "triangle": "Trójkąt", + "general": "Zwykły", + "scribbled": "Szkic", + "straight": "Prosty", + "curve": "Łuk", + "elbow": "Łamany", + "stroke": "Kolor linii", + "fill": "Wypełnienie", + "textColor": "Kolor tekstu", + "background": "Tło", + "thickness": "Grubość", + "lineStyle": "Styl linii", + "solid": "Ciągła", + "dash": "Przerywana", + "noLine": "Bez linii", + "startArrow": "Początek", + "endArrow": "Koniec", + "fontSize": "Rozmiar", + "font": "Czcionka", + "sans": "Bezszeryfowa", + "serif": "Szeryfowa", + "mono": "Stała szerokość", + "alignLeft": "Do lewej", + "alignCenter": "Do środka", + "alignRight": "Do prawej", + "bold": "Pogrubienie", + "layout": "Układ", + "layoutRight": "W prawo", + "layoutLeft": "W lewo", + "layoutRadial": "Na obie strony", + "addChild": "Dodaj gałąź (Tab)", + "addSibling": "Dodaj obok (Enter)", + "bringFront": "Na wierzch", + "sendBack": "Na spód", + "group": "Grupuj (Ctrl+G)", + "ungroup": "Rozgrupuj", + "duplicate": "Duplikuj (Ctrl+D)", + "delete": "Usuń", + "copy": "Kopiuj", + "editText": "Edytuj tekst", + "openLink": "Otwórz link", + "frameTitle": "Ramka", + "groupTitle": "Grupa", + "linkPrompt": "Adres linku", + "pageNote": "Strona", + "stickers": "Naklejki", + "templates": "Szablony", + "presentNoFrames": "Dodaj ramki, aby pokazać je po kolei.", + "presentExit": "Zakończ prezentację", + "presentNext": "Następna ramka", + "presentPrevious": "Poprzednia ramka", + "presentStep": "{n} / {total}", + "textPlaceholder": "Pisz…", + "templateKanban": "Tablica zadań", + "templateSwot": "SWOT", + "templateFlow": "Schemat blokowy", + "templateBrainstorm": "Burza mózgów", + "templateRetro": "Retrospektywa", + "todo": "Do zrobienia", + "doing": "W toku", + "done": "Gotowe", + "strengths": "Mocne strony", + "weaknesses": "Słabe strony", + "opportunities": "Szanse", + "threats": "Zagrożenia", + "start": "Start", + "step": "Krok", + "decision": "Decyzja?", + "end": "Koniec", + "centralIdea": "Główna myśl", + "idea": "Pomysł", + "wentWell": "Co poszło dobrze", + "toImprove": "Do poprawy", + "actions": "Działania", + "colorInk": "Domyślny", + "colorPaper": "Papier", + "colorNone": "Brak" } }, "comments": { @@ -898,7 +1000,15 @@ "dateTitles": "Tytułuj nowe strony dzisiejszą datą", "showProperties": "Pokazuj właściwości pod tytułem", "showBacklinks": "Pokazuj strony, które tu linkują", - "codeLineNumbers": "Numery wierszy w blokach kodu" + "codeLineNumbers": "Numery wierszy w blokach kodu", + "newPageMode": "Nowe strony otwieraj jako", + "modes": { + "page": "Strona", + "edgeless": "Tablica" + }, + "edgelessStyles": "Style tablicy", + "edgelessStylesHint": "Nowe kształty, linie i notatki wyglądają jak ostatnio ostylowane.", + "resetStyles": "Przywróć" } }, "webhooks": { @@ -1133,5 +1243,16 @@ "label": "Strona obok", "openHere": "Otwórz jako główną", "close": "Zamknij stronę obok" + }, + "edgeless": { + "mode": "Widok", + "pageMode": "Strona", + "edgelessMode": "Tablica (bez krawędzi)", + "canvas": "Tablica", + "present": "Prezentuj ramki", + "exportPng": "Eksportuj jako PNG", + "exportSvg": "Eksportuj jako SVG", + "defaultEdgeless": "Otwieraj jako tablicę dla wszystkich", + "defaultPage": "Otwieraj jako stronę dla wszystkich" } } diff --git a/Web-App/frontend/src/stores/preferences.ts b/Web-App/frontend/src/stores/preferences.ts index 87afa72..c1141db 100644 --- a/Web-App/frontend/src/stores/preferences.ts +++ b/Web-App/frontend/src/stores/preferences.ts @@ -16,6 +16,10 @@ export interface EditorPrefs { showBacklinks: boolean; /** Code blocks show line numbers unless one was switched on or off itself. */ codeLineNumbers: boolean; + /** New pages open as text or as the edgeless canvas. */ + newPageMode: "page" | "edgeless"; + /** What new canvas elements look like: the style picked last for each kind (null = built in). */ + edgelessStyles: Record | null; } const key = "docwell.editorPrefs"; @@ -26,6 +30,8 @@ export const defaultEditorPrefs: EditorPrefs = { showProperties: true, showBacklinks: true, codeLineNumbers: false, + newPageMode: "page", + edgelessStyles: null, }; function read(): EditorPrefs { diff --git a/Web-App/frontend/src/stores/spaces.ts b/Web-App/frontend/src/stores/spaces.ts index 8072548..f541955 100644 --- a/Web-App/frontend/src/stores/spaces.ts +++ b/Web-App/frontend/src/stores/spaces.ts @@ -101,7 +101,7 @@ export const useSpacesStore = defineStore("spaces", () => { for (let p = parentOf.get(pageId); p; p = parentOf.get(p)) setExpanded(p, true); } - /** Makes a page; the editor preferences can title it with today's date and make it full width. */ + /** Makes a page; the editor preferences can title it with today's date, make it full width or a canvas. */ async function createPage(spaceId: string, parent = "", title?: string) { const prefs = useEditorPrefs(); if (!title && prefs.dateTitles) { @@ -109,7 +109,11 @@ export const useSpacesStore = defineStore("spaces", () => { title = new Intl.DateTimeFormat(lang, { dateStyle: "long" }).format(new Date()); } let page = await api.spaces.createPage(spaceId, title ? { parent, title } : { parent }); - if (prefs.newPageFullWidth) page = await api.pages.update(page.id, { fullWidth: true }); + if (prefs.newPageFullWidth || prefs.newPageMode === "edgeless") + page = await api.pages.update(page.id, { + ...(prefs.newPageFullWidth ? { fullWidth: true } : {}), + ...(prefs.newPageMode === "edgeless" ? { defaultMode: "edgeless" as const } : {}), + }); if (parent) setExpanded(parent, true); await loadTree(spaceId); return page; diff --git a/Web-App/frontend/src/views/ShareView.vue b/Web-App/frontend/src/views/ShareView.vue index f0d7dbe..4aa7274 100644 --- a/Web-App/frontend/src/views/ShareView.vue +++ b/Web-App/frontend/src/views/ShareView.vue @@ -1,11 +1,12 @@