(`[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 = `${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 @@