Add edgeless mode: pages as a canvas with their text as a live note
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / go (Server) (push) Failing after 8m12s
CI / go (Web-App) (push) Successful in 11m16s
CI / frontend (push) Failing after 7m33s
CI / desktop (ubuntu-latest) (push) Successful in 1h25m49s
CI / mobile (push) Failing after 5m48s
CI / docker (push) Successful in 41m19s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s

Phase D of docs/AFFINE.md (ADR-14).

The canvas lives in the page's Y.Doc next to its text, in
ydoc.getMap("surface"): one Y.Map per element, each field its own entry so
concurrent edits merge. The page's text is a note on the canvas bound to
the same "default" fragment, so typing on the canvas is typing in the page.
Canvas edits have their own undo history through a Y.UndoManager.

- New package @docwell/canvas: viewport with pan, zoom and pinch;
  selection, marquee, snapping, resize and rotate; notes, text, shapes
  (plain or scribbled), connectors (straight, curve, elbow, with arrowheads
  and labels), pen and eraser, frames, groups, pictures, embeds and link
  cards, and mind maps (right, left or both sides; Tab, Enter, arrows).
  A style bar over the selection; the last style per kind is the default.
- Presentation through frames, stickers and templates, PNG and SVG export.
- Page/Edgeless switch in the header, ?mode= in page and share links, a
  per-page default (pages.default_mode) and a per-device default for new
  pages; share links show the canvas read-only.
- Server: yrs writes the canvas into the document JSON as "surface",
  adds its text to search, and writes it back on restores and templates.
- Phone: the bridge draws the canvas read-only (protocol 3) and the page
  screen has a canvas button.

Strings are translated into all five languages and the user guide covers
edgeless mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-15 16:20:20 +01:00
1 parent aede10bd1a
commit e927653e4b
58 files changed
+7859 -97

No files matched your search

@@ -0,0 +1,19 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// Which view a page opens in for everyone: its text ("" = page) or the
// edgeless canvas (ADR-14).
migrate(
(app) => {
const pages = app.findCollectionByNameOrId("pages");
pages.fields.add(new SelectField({ name: "default_mode", maxSelect: 1, values: ["edgeless"] }));
app.save(pages);
},
(app) => {
const pages = app.findCollectionByNameOrId("pages");
pages.fields.removeByName("default_mode");
app.save(pages);
},
);
+28
View File
@@ -69,6 +69,34 @@ Exports (Markdown, HTML, PDF, Word) show a database as a table of its first view
record on its own, under the page that holds it, and opens it there. On a public link or in **History**, databases are
read-only.
## Edgeless mode (canvas)
Every page can also be shown as a whiteboard. The two buttons next to the page's title in the header switch between
**Page** and **Edgeless**; the page's text becomes a note on an endless canvas, and typing in that note is typing in the
page. To have a page open as a canvas for everyone, choose **Open as canvas for everyone** in the page's ⋯ menu; a link
with `?mode=edgeless` (or `?mode=page`) opens one view either way. **Account settings → Editor** can make new pages
start as canvases.
- **Tools** sit at the bottom: select (V), hand (H), note (N), text (T), shape (S: square, rounded rectangle,
ellipse, diamond or triangle, drawn plain or scribbled), connector (C: straight, curved or elbowed, stuck to what it
joins), pen (P), eraser (E), frame (F), mind map (M), picture (I), link (L), and stickers and templates.
- **Moving around:** scroll to pan, Ctrl+scroll or pinch to zoom, hold Space or the middle button to drag the view.
Ctrl+= and Ctrl+- zoom, Alt+0 goes to 100%, Alt+1 fits everything and Alt+2 fits the selection.
- **Editing:** click to select, Shift+click or drag a box for more; drag to move (edges line up with what is nearby;
hold Alt to stop that), drag the corners to resize and the round handle to turn. Double-click a shape, text, frame
title or line to type in it, and a note to write in it. The bar above the selection changes colours, line styles,
arrowheads, fonts and order. Ctrl+G groups, Ctrl+Shift+G ungroups, Ctrl+D duplicates, Ctrl+Z undoes, and copy and
paste work between canvases. The style you pick last for a kind of element is what the next one gets.
- **Mind maps:** pick a node and press Tab for a branch, Enter for a sibling, the arrow keys to move and Delete to
remove one. The bar above the map lays it out to the right, to the left or on both sides.
- **Frames** carry what is inside them when they move. **Present** (in the tools, or the ⋯ menu) shows the frames
one after another, full screen; the arrow keys step and Escape ends.
- **Export:** the ⋯ menu saves the canvas as a PNG or SVG picture.
Readers of a public link see the canvas read-only, and so does the mobile app: the canvas button in its title bar
switches between the text and the canvas. The canvas's text (shapes, notes, frames, mind maps) is found by search, and
**History** brings an old canvas back with the text.
## Comments
Select text and choose **Comment** to start a discussion; the text stays highlighted and the comment appears in
+2
View File
@@ -30,6 +30,7 @@ export type TrashedPage = Schemas["TrashedPage"];
export type ArchivedPage = Schemas["ArchivedPage"];
export type PinnedPage = Schemas["PinnedPage"];
export type PageFont = Schemas["PageFont"];
export type PageMode = Schemas["PageMode"];
export type LinkPreview = Schemas["LinkPreview"];
export type PageContent = Schemas["PageContent"];
export type PageVersion = Schemas["PageVersion"];
@@ -483,6 +484,7 @@ export function createClient(opts: ClientOptions) {
isTemplate?: boolean;
fullWidth?: boolean;
font?: PageFont;
defaultMode?: PageMode;
tags?: string[];
/** Property values by property id; null clears one. */
properties?: Record<string, unknown>;
+9 -1
View File
@@ -2630,6 +2630,7 @@ export interface components {
/** @description Shown across the whole window instead of the reading column */
fullWidth: boolean;
font: components["schemas"]["PageFont"];
defaultMode: components["schemas"]["PageMode"];
/** @description Tag ids */
tags: string[];
/** @description Custom property values by property id (see Property for their shapes) */
@@ -2641,6 +2642,11 @@ export interface components {
createdBy: components["schemas"]["PageUser"];
lastEditedBy: components["schemas"]["PageUser"];
};
/**
* @description The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it
* @enum {string}
*/
PageMode: "page" | "edgeless";
/**
* @description The body font for everyone reading the page; empty is the default sans
* @enum {string}
@@ -3088,10 +3094,11 @@ export interface components {
title: string;
icon: string;
updated: string;
/** @description Tiptap JSON; files load from /api/v1/share/{token}/files/{fileId} */
/** @description Tiptap JSON (with "surface", the edgeless canvas, when it has one); files load from /api/v1/share/{token}/files/{fileId} */
content: {
[key: string]: unknown;
} | null;
mode: components["schemas"]["PageMode"];
root: components["schemas"]["PageRef"];
/** @description Pages under the shared page */
pages: components["schemas"]["PageNode"][];
@@ -4831,6 +4838,7 @@ export interface operations {
/** @description Use the whole window instead of the reading column */
fullWidth?: boolean;
font?: components["schemas"]["PageFont"];
defaultMode?: components["schemas"]["PageMode"];
/** @description Replaces the page's tags (tag ids) */
tags?: string[];
/** @description Sets these custom property values by property id; null clears one */
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@docwell/canvas",
"version": "0.0.1",
"private": true,
"license": "AGPL-3.0-or-later",
"type": "module",
"description": "The edgeless canvas: shapes, connectors, drawings, frames and notes on an endless surface (ADR-14)",
"main": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./canvas.css": "./src/canvas.css"
},
"scripts": {
"test": "vitest run"
},
"dependencies": {
"@docwell/ui": "*",
"perfect-freehand": "^1.2.0",
"roughjs": "^4.6.4",
"yjs": "^13.6.33"
},
"devDependencies": {
"jsdom": "^30.1.3",
"vitest": "^5.0.5"
}
}
+616
View File
@@ -0,0 +1,616 @@
/* SPDX-License-Identifier: AGPL-3.0-or-later */
/* The edgeless canvas (ADR-14). Colours come from the design system's
variables, so the canvas follows the light and dark themes. */
.dw-cv {
position: relative;
overflow: hidden;
width: 100%;
height: 100%;
min-height: 320px;
background-color: var(--dw-surface-sunken);
background-image: radial-gradient(circle, color-mix(in srgb, var(--dw-ink) 16%, transparent) 1px, transparent 1.2px);
touch-action: none;
outline: none;
user-select: none;
-webkit-user-select: none;
cursor: default;
font-family: var(--font-sans, ui-sans-serif, system-ui, sans-serif);
color: var(--dw-ink);
}
.dw-cv[data-tool="hand"],
.dw-cv.dw-cv-panning,
.dw-cv.dw-cv-readonly {
cursor: grab;
}
.dw-cv.dw-cv-panning:active {
cursor: grabbing;
}
.dw-cv[data-tool="pen"],
.dw-cv[data-tool="shape"],
.dw-cv[data-tool="frame"],
.dw-cv[data-tool="connector"],
.dw-cv[data-tool="note"],
.dw-cv[data-tool="mindmap"] {
cursor: crosshair;
}
.dw-cv[data-tool="text"] {
cursor: text;
}
.dw-cv[data-tool="eraser"] {
cursor: cell;
}
.dw-cv-world {
position: absolute;
left: 0;
top: 0;
width: 0;
height: 0;
transform-origin: 0 0;
}
.dw-cv-el {
position: absolute;
left: 0;
top: 0;
transform-origin: center;
box-sizing: border-box;
}
.dw-cv-svg {
position: absolute;
left: 0;
top: 0;
overflow: visible;
pointer-events: none;
}
.dw-cv-erasing {
opacity: 0.25;
}
/* Shapes: the box takes the pointer; the label sits in the middle. */
.dw-cv-shape {
display: grid;
place-items: center;
}
.dw-cv-label {
position: relative;
max-width: calc(100% - 16px);
max-height: 100%;
overflow: hidden;
text-align: center;
white-space: pre-wrap;
overflow-wrap: anywhere;
line-height: 1.35;
outline: none;
}
.dw-cv-label:empty:not(.dw-cv-typing) {
display: none;
}
.dw-cv-label.dw-cv-typing {
min-width: 1ch;
cursor: text;
user-select: text;
-webkit-user-select: text;
}
/* Text boxes size themselves unless given a width. */
.dw-cv-textbody {
line-height: 1.35;
min-width: 2px;
min-height: 1em;
overflow-wrap: anywhere;
outline: none;
}
.dw-cv-textbody.dw-cv-typing {
cursor: text;
user-select: text;
-webkit-user-select: text;
}
.dw-cv-textbody:empty::before {
content: attr(data-placeholder);
color: var(--dw-ink-faint);
}
/* Connectors and pen strokes take the pointer on their line only. */
.dw-cv-connector,
.dw-cv-brush,
.dw-cv-frame,
.dw-cv-mindmap {
pointer-events: none;
}
.dw-cv-hit {
fill: none;
stroke: transparent;
pointer-events: stroke;
}
.dw-cv-hitfill {
stroke: transparent;
stroke-width: 8px;
pointer-events: all;
}
.dw-cv-connector .dw-cv-svg,
.dw-cv-brush .dw-cv-svg {
pointer-events: none;
}
.dw-cv-connector .dw-cv-hit,
.dw-cv-brush .dw-cv-hitfill {
pointer-events: all;
}
.dw-cv-connector .dw-cv-hit {
pointer-events: stroke;
}
.dw-cv-clabel {
position: absolute;
transform: translate(-50%, -50%);
padding: 2px 6px;
border-radius: 4px;
background: var(--dw-surface);
font-size: 13px;
line-height: 18px;
white-space: pre;
pointer-events: auto;
outline: none;
}
.dw-cv-clabel:empty:not(.dw-cv-typing) {
display: none;
}
/* Frames: a box underneath everything, picked by its edge or title. */
.dw-cv-framebox {
stroke: var(--dw-line-strong);
stroke-width: calc(1.5px / var(--dw-cv-zoom, 1));
pointer-events: stroke;
}
.dw-cv-frame .dw-cv-svg {
pointer-events: none;
}
.dw-cv-frame .dw-cv-framebox {
pointer-events: stroke;
stroke-width: calc(1.5px / var(--dw-cv-zoom, 1));
}
.dw-cv-frametitle {
position: absolute;
left: 0;
bottom: 100%;
margin-bottom: calc(4px / var(--dw-cv-zoom, 1));
padding: 0 4px;
max-width: 100%;
font-size: calc(13px / var(--dw-cv-zoom, 1));
line-height: 1.4;
font-weight: 600;
color: var(--dw-ink-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
border-radius: 4px;
pointer-events: auto;
outline: none;
}
.dw-cv-frametitle:hover {
background: var(--dw-surface-hover);
}
/* Notes: a card holding an editor. The text takes the pointer only while
someone types in it (double click), or always for readers. */
.dw-cv-note {
min-height: 48px;
padding: 18px 24px;
border-radius: 8px;
background: var(--dw-cv-note-bg, var(--dw-surface-raised));
border: 1px solid var(--dw-line);
box-shadow:
0 1px 2px rgb(0 0 0 / 0.06),
0 4px 14px rgb(0 0 0 / 0.06);
}
.dw-cv-notehead {
font-family: var(--font-serif, Georgia, serif);
font-size: 30px;
line-height: 1.25;
font-weight: 600;
margin-bottom: 8px;
}
.dw-cv-notehead:empty {
display: none;
}
.dw-cv-notebody {
pointer-events: none;
min-height: 24px;
}
.dw-cv-editing .dw-cv-notebody,
.dw-cv-readonly .dw-cv-notebody {
pointer-events: auto;
user-select: text;
-webkit-user-select: text;
}
.dw-cv-note .dw-prose {
outline: none;
min-height: 24px;
}
.dw-cv-note.dw-cv-editing {
box-shadow:
0 0 0 2px var(--dw-focus-ring),
0 4px 14px rgb(0 0 0 / 0.08);
}
/* Pictures, players and link cards. */
.dw-cv-image img {
display: block;
width: 100%;
height: 100%;
object-fit: contain;
pointer-events: none;
}
.dw-cv-embed iframe {
display: block;
width: 100%;
height: 100%;
border: 0;
border-radius: 8px;
background: #000;
pointer-events: none;
}
.dw-cv-embed.dw-cv-editing iframe,
.dw-cv-readonly .dw-cv-embed iframe {
pointer-events: auto;
}
.dw-cv-card {
display: flex;
gap: 12px;
height: 100%;
padding: 12px;
box-sizing: border-box;
overflow: hidden;
border: 1px solid var(--dw-line);
border-radius: 8px;
background: var(--dw-surface-raised);
color: inherit;
text-decoration: none;
-webkit-user-drag: none;
}
.dw-cv-card img {
width: 30%;
max-width: 140px;
height: 100%;
object-fit: cover;
border-radius: 4px;
pointer-events: none;
}
.dw-cv-cardtext {
display: flex;
min-width: 0;
flex-direction: column;
gap: 4px;
font-size: 13px;
line-height: 18px;
}
.dw-cv-cardtext strong {
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dw-cv-cardtext span {
color: var(--dw-ink-muted);
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.dw-cv-cardtext small {
color: var(--dw-ink-faint);
}
/* Mind maps: nodes take the pointer; lines do not. */
.dw-cv-node {
position: absolute;
box-sizing: border-box;
display: grid;
place-items: center;
padding: 0 10px;
border: 1.5px solid transparent;
border-radius: 8px;
background: var(--dw-surface-raised);
font-size: 15px;
line-height: 1.4;
text-align: center;
white-space: pre-wrap;
overflow-wrap: anywhere;
pointer-events: auto;
outline: none;
}
.dw-cv-root {
border-radius: 10px;
font-size: 18px;
font-weight: 600;
}
.dw-cv-node.dw-cv-active {
box-shadow:
0 0 0 2px var(--dw-surface),
0 0 0 4px var(--dw-focus-ring);
}
.dw-cv-node.dw-cv-typing {
cursor: text;
user-select: text;
-webkit-user-select: text;
}
.dw-cv-temp {
position: absolute;
left: 0;
top: 0;
overflow: visible;
pointer-events: none;
}
/* The overlay: selection, handles, guides, in screen units. */
.dw-cv-overlay {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
overflow: visible;
}
.dw-cv-sel,
.dw-cv-selline {
fill: none;
stroke: var(--dw-accent, #2f7d6d);
stroke-width: 1.5;
}
.dw-cv-selline {
stroke-width: 6;
stroke-opacity: 0.3;
stroke-linecap: round;
stroke-linejoin: round;
}
.dw-cv-selall {
stroke-dasharray: 4 3;
}
.dw-cv-groupbox {
fill: none;
stroke: var(--dw-ink-faint);
stroke-dasharray: 4 3;
}
.dw-cv-hover {
fill: color-mix(in srgb, var(--dw-accent, #2f7d6d) 8%, transparent);
stroke: var(--dw-accent, #2f7d6d);
stroke-width: 1;
}
.dw-cv-handle {
fill: var(--dw-surface);
stroke: var(--dw-accent, #2f7d6d);
stroke-width: 1.5;
pointer-events: all;
cursor: pointer;
}
.dw-cv-handle[data-handle="nw"],
.dw-cv-handle[data-handle="se"] {
cursor: nwse-resize;
}
.dw-cv-handle[data-handle="ne"],
.dw-cv-handle[data-handle="sw"] {
cursor: nesw-resize;
}
.dw-cv-handle[data-handle="n"],
.dw-cv-handle[data-handle="s"] {
cursor: ns-resize;
}
.dw-cv-handle[data-handle="e"],
.dw-cv-handle[data-handle="w"] {
cursor: ew-resize;
}
.dw-cv-rotate {
cursor: grab;
}
.dw-cv-marquee {
fill: color-mix(in srgb, var(--dw-accent, #2f7d6d) 10%, transparent);
stroke: var(--dw-accent, #2f7d6d);
stroke-width: 1;
}
.dw-cv-guide {
stroke: var(--dw-c-pink, #b8327a);
stroke-width: 1;
stroke-dasharray: 3 3;
}
/* Controls. */
.dw-cv-ui {
position: absolute;
z-index: 2;
display: flex;
align-items: center;
gap: 2px;
padding: 4px;
border: 1px solid var(--dw-line);
border-radius: 10px;
background: var(--dw-surface-raised);
box-shadow: 0 4px 16px rgb(0 0 0 / 0.12);
cursor: default;
font-size: 13px;
}
.dw-cv-ui[hidden] {
display: none;
}
.dw-cv-toolbar {
left: 50%;
bottom: 16px;
transform: translateX(-50%);
max-width: calc(100% - 32px);
overflow-x: auto;
scrollbar-width: none;
}
.dw-cv-zoom {
top: 12px;
right: 12px;
}
.dw-cv-props {
flex-wrap: wrap;
max-width: calc(100% - 16px);
}
.dw-cv-btn {
display: grid;
flex-shrink: 0;
place-items: center;
min-width: 32px;
height: 32px;
padding: 0 6px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--dw-ink-muted);
cursor: pointer;
font: inherit;
}
.dw-cv-btn:hover {
background: var(--dw-surface-hover);
color: var(--dw-ink);
}
.dw-cv-btn[aria-pressed="true"] {
background: var(--dw-accent-soft, var(--dw-surface-hover));
color: var(--dw-accent, var(--dw-ink));
}
.dw-cv-btn:focus-visible {
outline: 2px solid var(--dw-focus-ring);
outline-offset: -2px;
}
.dw-cv-danger:hover {
color: var(--dw-danger);
}
.dw-cv-wide {
justify-content: start;
width: 100%;
}
.dw-cv-zoomlabel {
min-width: 52px;
font-variant-numeric: tabular-nums;
}
.dw-cv-sep {
flex-shrink: 0;
width: 1px;
height: 20px;
margin: 0 4px;
background: var(--dw-line);
}
.dw-cv-pop {
flex-direction: column;
align-items: stretch;
gap: 4px;
padding: 6px;
}
.dw-cv-row {
display: flex;
flex-wrap: wrap;
gap: 2px;
}
.dw-cv-colors {
max-width: 220px;
}
.dw-cv-swatch {
display: block;
width: 18px;
height: 18px;
border-radius: 999px;
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--dw-ink) 18%, transparent);
}
.dw-cv-swatch-none {
background: linear-gradient(
135deg,
transparent 45%,
var(--dw-danger, #c0392b) 45%,
var(--dw-danger, #c0392b) 55%,
transparent 55%
) !important;
}
.dw-cv-dot {
display: block;
border-radius: 999px;
background: currentColor;
}
.dw-cv-bar {
display: block;
width: 18px;
border-radius: 2px;
background: currentColor;
}
.dw-cv-word {
font-size: 13px;
font-weight: 600;
white-space: nowrap;
}
.dw-cv-scribble {
font-style: italic;
}
.dw-cv-font-serif {
font-family: var(--font-serif, Georgia, serif);
}
.dw-cv-font-mono {
font-family: var(--font-mono, ui-monospace, monospace);
}
.dw-cv-flip svg {
transform: scaleX(-1);
}
.dw-cv-library {
width: 260px;
}
.dw-cv-poptitle {
padding: 4px 6px 0;
font-size: 12px;
font-weight: 600;
color: var(--dw-ink-muted);
}
.dw-cv-stickers {
display: grid;
grid-template-columns: repeat(8, 1fr);
gap: 2px;
}
.dw-cv-emoji {
font-size: 20px;
line-height: 1;
}
.dw-cv-templates {
display: flex;
flex-direction: column;
}
.dw-cv-toast {
left: 50%;
bottom: 72px;
transform: translateX(-50%);
padding: 8px 12px;
background: var(--dw-ink);
color: var(--dw-surface);
border-color: transparent;
}
/* Presenting: only the frames and the step bar. */
.dw-cv-presenting {
background-image: none;
cursor: default;
}
.dw-cv-presenting .dw-cv-toolbar,
.dw-cv-presenting .dw-cv-zoom,
.dw-cv-presenting .dw-cv-props,
.dw-cv-presenting .dw-cv-frametitle {
display: none;
}
.dw-cv-presentbar {
left: 50%;
bottom: 16px;
transform: translateX(-50%);
}
.dw-cv-step {
min-width: 56px;
text-align: center;
font-variant-numeric: tabular-nums;
}
@media (max-width: 640px) {
.dw-cv-zoom {
top: 8px;
right: 8px;
}
.dw-cv-toolbar {
bottom: 8px;
}
}
+227
View File
@@ -0,0 +1,227 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { describe, expect, it } from "vitest";
import * as Y from "yjs";
import { resolveEnds, route, snap } from "./geometry";
import { layoutMindmap, neighbour } from "./mindmap";
import { normalize, readStyles } from "./model";
import { SurfaceStore } from "./store";
import { fragmentToJSON, plainText, writeJSON } from "./yxml";
const size = (text: string) => ({ w: 40 + text.length * 8, h: 30 });
describe("SurfaceStore", () => {
it("lists the page note before anything is drawn and writes it on first change", () => {
const store = new SurfaceStore(new Y.Doc());
const [note] = store.elements();
expect(note).toMatchObject({ id: "page", type: "note", page: true, x: 0, y: 0 });
expect(store.isEmpty).toBe(true);
store.update("page", { x: 100 });
expect(store.isEmpty).toBe(false);
expect(store.get("page")).toMatchObject({ x: 100, w: 760 });
});
it("adds, restyles and removes elements, and undoes them", () => {
const store = new SurfaceStore(new Y.Doc());
const id = store.add({ type: "shape", shape: "ellipse", x: 1, y: 2, w: 30, h: 40 });
store.undo!.stopCapturing();
store.update(id, { fill: "red" });
expect(store.get(id)).toMatchObject({ type: "shape", shape: "ellipse", fill: "red" });
store.undo!.undo();
expect(store.get(id)).toMatchObject({ fill: "none" });
store.remove([id]);
expect(store.get(id)).toBeUndefined();
// The page's note is the page: it stays.
store.remove(["page"]);
expect(store.get("page")).toBeDefined();
});
it("keeps a connector's end where its element was when the element goes", () => {
const store = new SurfaceStore(new Y.Doc());
const a = store.add({ type: "shape", x: 0, y: 0, w: 100, h: 100 });
const c = store.add({ type: "connector", source: { id: a, pos: [1, 0.5] }, target: { x: 300, y: 50 } } as never);
store.remove([a]);
expect(store.get(c)).toMatchObject({ source: { x: 100, y: 50 } });
});
it("copies elements with new ids, keeping connectors, groups and note bodies", () => {
const store = new SurfaceStore(new Y.Doc());
const a = store.add({ type: "shape", x: 0, y: 0, w: 10, h: 10 });
const b = store.add({ type: "note", x: 50, y: 0, w: 200, h: 80 }, [
{ type: "paragraph", content: [{ type: "text", text: "Hello" }] },
]);
const c = store.add({ type: "connector", source: { id: a }, target: { id: b } } as never);
const g = store.groupOf([a, b])!;
const ids = store.insertJSON(store.toJSON([g, c]), 10, 10);
expect(ids).toHaveLength(4);
const copies = ids.map((id) => store.get(id)!);
const shape = copies.find((e) => e.type === "shape")!;
const note = copies.find((e) => e.type === "note")!;
const conn = copies.find((e) => e.type === "connector")!;
const group = copies.find((e) => e.type === "group")!;
expect(shape).toMatchObject({ x: 10, y: 10, group: group.id });
expect(conn).toMatchObject({ source: { id: shape.id }, target: { id: note.id } });
expect(fragmentToJSON(store.body(note.id)!)).toEqual([
{ type: "paragraph", content: [{ type: "text", text: "Hello" }] },
]);
});
it("adds and removes mind map branches", () => {
const store = new SurfaceStore(new Y.Doc());
const id = store.add({ type: "mindmap", x: 0, y: 0, nodes: { r: { text: "Root", parent: "", pos: 0 } } } as never);
const child = store.addNode(id, "r", 0, "A");
store.addNode(id, child, 0, "A1");
const el = store.get(id)!;
expect(el.type === "mindmap" && Object.keys(el.nodes)).toHaveLength(3);
store.removeNode(id, child);
const after = store.get(id)!;
expect(after.type === "mindmap" && Object.keys(after.nodes)).toEqual(["r"]);
store.removeNode(id, "r");
expect(store.get(id)).toBeUndefined();
});
it("orders frames underneath and moves elements to the front", () => {
const store = new SurfaceStore(new Y.Doc());
const a = store.add({ type: "shape", x: 0, y: 0, w: 1, h: 1 });
const b = store.add({ type: "shape", x: 0, y: 0, w: 1, h: 1 });
const f = store.add({ type: "frame", x: 0, y: 0, w: 1, h: 1 });
expect(store.elements()[0]!.id).toBe(f);
store.reorder([a], "front");
const order = store.elements().map((e) => e.id);
expect(order.indexOf(a)).toBeGreaterThan(order.indexOf(b));
});
it("replaces everything with a snapshot", () => {
const store = new SurfaceStore(new Y.Doc());
store.add({ type: "shape", x: 0, y: 0, w: 1, h: 1 });
store.load([{ id: "n1", type: "note", x: 5, y: 5, w: 100, h: 50, body: [{ type: "paragraph" }] }]);
expect(
store
.elements()
.map((e) => e.id)
.sort(),
).toEqual(["n1", "page"]);
});
});
describe("model", () => {
it("fills in defaults and drops unknown types", () => {
expect(normalize({ type: "nope" })).toBeNull();
expect(normalize({ type: "connector" })).toMatchObject({
mode: "curve",
endArrow: "arrow",
source: { x: 0, y: 0 },
});
expect(readStyles({ shape: { fill: "red", stroke: "purple-ish" } }).shape).toMatchObject({
fill: "red",
stroke: "blue",
});
});
});
describe("geometry", () => {
it("routes connectors between boxes", () => {
const boxes: Record<string, { box: { x: number; y: number; w: number; h: number }; ellipse: boolean }> = {
a: { box: { x: 0, y: 0, w: 100, h: 100 }, ellipse: false },
b: { box: { x: 300, y: 0, w: 100, h: 100 }, ellipse: false },
};
const ends = resolveEnds({ source: { id: "a" }, target: { id: "b" } }, (id) => boxes[id] ?? null);
expect(ends[0].at).toEqual([100, 50]);
expect(ends[1].at).toEqual([300, 50]);
const elbow = route("elbow", ends[0], ends[1]);
expect(elbow.points[0]).toEqual([100, 50]);
expect(elbow.points.at(-1)).toEqual([300, 50]);
expect(route("curve", ends[0], ends[1]).d).toMatch(/^M100 50 C/);
});
it("snaps edges that are close", () => {
const s = snap({ x: 103, y: 0, w: 50, h: 50 }, [{ x: 100, y: 200, w: 80, h: 40 }], 6);
expect(s.dx).toBe(-3);
expect(s.guides[0]).toMatchObject({ axis: "x", value: 100 });
});
});
describe("mind maps", () => {
const nodes = {
r: { text: "Root", parent: "", pos: 0 },
a: { text: "A", parent: "r", pos: 0 },
b: { text: "B", parent: "r", pos: 1 },
c: { text: "C", parent: "a", pos: 0 },
};
it("lays branches out to the right, left or both sides", () => {
const right = layoutMindmap(nodes, "right", size);
expect(right.boxes.get("a")!.x).toBeGreaterThan(right.boxes.get("r")!.w);
expect(right.boxes.get("c")!.x).toBeGreaterThan(right.boxes.get("a")!.x);
const left = layoutMindmap(nodes, "left", size);
expect(left.boxes.get("a")!.x).toBeLessThan(0);
const radial = layoutMindmap(nodes, "radial", size);
expect(radial.boxes.get("a")!.dir).toBe(1);
expect(radial.boxes.get("b")!.dir).toBe(-1);
expect(right.edges).toHaveLength(3);
});
it("moves between nodes with the arrow keys", () => {
const l = layoutMindmap(nodes, "right", size);
expect(neighbour(l, nodes, "r", "ArrowRight")).toBe("a");
expect(neighbour(l, nodes, "a", "ArrowDown")).toBe("b");
expect(neighbour(l, nodes, "a", "ArrowRight")).toBe("c");
expect(neighbour(l, nodes, "c", "ArrowLeft")).toBe("a");
});
});
describe("yxml", () => {
it("round-trips ProseMirror JSON through a fragment", () => {
const doc = new Y.Doc();
const f = doc.getXmlFragment("x");
const json = [
{ type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Title" }] },
{
type: "paragraph",
content: [
{ type: "text", text: "plain " },
{ type: "text", text: "bold", marks: [{ type: "bold", attrs: {} }] },
],
},
];
writeJSON(f, json);
expect(fragmentToJSON(f)).toEqual(json);
expect(plainText(json)).toEqual(["Title", "plain bold"]);
});
});
describe("CanvasView", () => {
it("draws a document's elements and exports them as SVG", async () => {
const { CanvasView } = await import("./view");
const doc = new Y.Doc();
writeJSON(doc.getXmlFragment("default"), [{ type: "paragraph", content: [{ type: "text", text: "Page body" }] }]);
const store = new SurfaceStore(doc);
store.add({ type: "shape", shape: "diamond", x: 900, y: 0, w: 120, h: 80, text: "Choose" } as never);
store.add({ type: "mindmap", x: 0, y: 500, nodes: { r: { text: "Root idea", parent: "", pos: 0 } } } as never);
store.destroy();
const host = document.createElement("div");
document.body.append(host);
const mounted: string[] = [];
const view = new CanvasView(host, {
doc,
editable: true,
pageTitle: () => "My page",
notes: {
mount: (el, note) => {
mounted.push(note.page ? "page" : note.id);
el.textContent = note.page ? "Page body" : "";
return { destroy: () => {}, focus: () => {}, setEditable: () => {} };
},
},
});
expect(mounted).toEqual(["page"]);
expect(host.querySelector(".dw-cv-shape")?.textContent).toBe("Choose");
expect(host.querySelector(".dw-cv-root")?.textContent).toBe("Root idea");
expect(host.querySelectorAll(".dw-cv-toolbar .dw-cv-btn").length).toBeGreaterThan(10);
const svg = await (await view.exportImage("svg")).text();
expect(svg).toMatch(/^<svg xmlns/);
for (const word of ["Choose", "Root idea", "My page", "Page body"]) expect(svg).toContain(word);
view.destroy();
expect(host.children).toHaveLength(0);
});
});
+277
View File
@@ -0,0 +1,277 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// The canvas as one standalone SVG (and from it a PNG): the same drawings as
// on screen with the theme's colours written out, notes as their text,
// pictures inlined so the file opens anywhere and the PNG can be read back.
import type * as Y from "yjs";
import { inflate, union, type Box, type Route } from "./geometry";
import { SANS, fontFamily, wrap } from "./measure";
import { edgePath, type MindmapLayoutResult } from "./mindmap";
import type { CanvasElement, Color, ConnectorElement, MindmapElement, NoteElement } from "./model";
import { brushSVG, connectorSVG, esc, shapeSVG, type Paint } from "./render";
import { fragmentToJSON, type PMNode } from "./yxml";
export type ExportKind = "svg" | "png";
export interface ExportContext {
root: HTMLElement;
elements: CanvasElement[];
boxOf(e: CanvasElement): Box;
routeOf(c: ConnectorElement): Route;
layoutOf(m: MindmapElement): MindmapLayoutResult;
noteBody(e: NoteElement): Y.XmlFragment | null;
pageTitle: string;
resolve(src: string): string;
}
/** Hex colours from the theme's variables, mixed for soft fills the way CSS color-mix would. */
function exportPaint(root: HTMLElement): Paint {
const css = getComputedStyle(root);
const v = (name: string, d: string) => css.getPropertyValue(name).trim() || d;
const surface = v("--dw-surface", "#ffffff");
const parse = (hex: string): number[] | null => {
const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex);
if (!m) return null;
const h = m[1]!.length === 3 ? [...m[1]!].map((c) => c + c).join("") : m[1]!;
return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
};
const mix = (a: string, b: string, t: number) => {
const x = parse(a);
const y = parse(b);
if (!x || !y) return a;
return `#${x
.map((c, i) =>
Math.round(c * t + y[i]! * (1 - t))
.toString(16)
.padStart(2, "0"),
)
.join("")}`;
};
return (c: Color, use) => {
if (c === "none") return "none";
if (c === "ink") return use === "fill" ? v("--dw-surface-sunken", "#f3f3f1") : v("--dw-ink", "#1d1f1e");
if (c === "paper") return use === "fill" ? v("--dw-surface-raised", "#ffffff") : surface;
const base = v(`--dw-c-${c}`, "#888888");
return use === "fill" ? mix(base, surface, 0.22) : base;
};
}
/** Text blocks of a note for drawing: headings bigger, list items with a bullet. */
function blocks(nodes: PMNode[]): { text: string; size: number; weight: number }[] {
const out: { text: string; size: number; weight: number }[] = [];
const inline = (n: PMNode): string =>
(n.content ?? [])
.map((c) => (c.type === "text" ? (c.text ?? "") : c.type === "hardBreak" ? "\n" : inline(c)))
.join("");
const walk = (list: PMNode[], bullet: string) => {
for (const n of list) {
if (n.type === "heading") {
const level = Number(n.attrs?.level) || 1;
out.push({ text: inline(n), size: [0, 26, 21, 18, 16, 16, 16][level] ?? 16, weight: 650 });
} else if (n.type === "paragraph") out.push({ text: bullet + inline(n), size: 15, weight: 400 });
else if (n.type === "listItem" || n.type === "taskItem") {
const mark = n.type === "taskItem" ? (n.attrs?.checked ? "☑ " : "☐ ") : "• ";
const [first, ...rest] = n.content ?? [];
if (first) out.push({ text: mark + inline(first), size: 15, weight: 400 });
walk(rest, " ");
} else if (n.type === "codeBlock") out.push({ text: inline(n), size: 13, weight: 400 });
else if (n.content?.length) walk(n.content, bullet);
}
};
walk(nodes, "");
return out;
}
function textLines(
x: number,
y: number,
lines: string[],
size: number,
color: string,
family: string,
weight = 400,
anchor = "start",
): string {
const lh = Math.round(size * 1.35);
return lines
.map(
(l, i) =>
`<text x="${x}" y="${y + size + i * lh}" font-size="${size}" font-family="${esc(family)}" font-weight="${weight}" fill="${color}" text-anchor="${anchor}" xml:space="preserve">${esc(l)}</text>`,
)
.join("");
}
async function inline(src: string): Promise<string | null> {
if (src.startsWith("data:")) return src;
try {
const res = await fetch(src, { credentials: "include" });
if (!res.ok) return null;
const blob = await res.blob();
return await new Promise((resolve) => {
const r = new FileReader();
r.onload = () => resolve(typeof r.result === "string" ? r.result : null);
r.onerror = () => resolve(null);
r.readAsDataURL(blob);
});
} catch {
return null;
}
}
/** The elements as SVG markup and the box it covers. */
export async function canvasSVG(ctx: ExportContext): Promise<{ svg: string; box: Box }> {
const paint = exportPaint(ctx.root);
const els = ctx.elements.filter((e) => e.type !== "group");
const box = inflate(union(els.map((e) => ctx.boxOf(e))) ?? { x: 0, y: 0, w: 400, h: 300 }, 32);
const ink = paint("ink", "line");
const parts: string[] = [];
for (const e of els) {
const b = ctx.boxOf(e);
const rot = e.rotate ? ` rotate(${e.rotate} ${b.w / 2} ${b.h / 2})` : "";
const g = (inner: string) => `<g transform="translate(${b.x} ${b.y})${rot}">${inner}</g>`;
switch (e.type) {
case "shape": {
const lines = wrap(e.text, e.fontSize, Math.max(20, b.w - 16));
const lh = Math.round(e.fontSize * 1.35);
const top = b.h / 2 - (lines.length * lh) / 2 - e.fontSize * 0.25;
parts.push(
g(
shapeSVG(e, paint) +
(e.text
? textLines(b.w / 2, top, lines, e.fontSize, paint(e.textColor, "line"), SANS, 400, "middle")
: ""),
),
);
break;
}
case "text": {
const family = fontFamily(e.font);
const lines = e.w ? wrap(e.text, e.fontSize, e.w, family) : e.text.split("\n");
const x = e.align === "center" ? b.w / 2 : e.align === "right" ? b.w : 0;
const anchor = e.align === "center" ? "middle" : e.align === "right" ? "end" : "start";
parts.push(g(textLines(x, 0, lines, e.fontSize, paint(e.color, "line"), family, e.bold ? 650 : 400, anchor)));
break;
}
case "connector": {
const r = ctx.routeOf(e);
parts.push(connectorSVG(e, r, paint));
if (e.label) {
const w = Math.min(240, e.label.length * 8 + 16);
parts.push(
`<rect x="${r.mid[0] - w / 2}" y="${r.mid[1] - 12}" width="${w}" height="24" rx="4" fill="${paint("paper", "line")}"/>` +
textLines(r.mid[0], r.mid[1] - 12 + 3, [e.label], 13, ink, SANS, 400, "middle"),
);
}
break;
}
case "brush":
parts.push(g(brushSVG(e, paint)));
break;
case "frame":
parts.push(
g(
`<rect width="${b.w}" height="${b.h}" rx="8" fill="${paint(e.background, "fill") === "none" ? "none" : paint(e.background, "fill")}" stroke="${paint("gray", "line")}" stroke-width="1.5"/>` +
textLines(4, -24, [e.title], 13, paint("gray", "line"), SANS, 600),
),
);
break;
case "note": {
const body = ctx.noteBody(e);
const content = body ? blocks(fragmentToJSON(body)) : [];
let y = 18;
let inner = `<rect width="${b.w}" height="${b.h}" rx="8" fill="${paint(e.background, "fill")}" stroke="${paint("gray", "fill")}"/>`;
if (e.page && ctx.pageTitle) {
const lines = wrap(ctx.pageTitle, 26, b.w - 48, SANS, 650);
inner += textLines(24, y - 4, lines, 26, ink, SANS, 650);
y += lines.length * 35 + 8;
}
for (const bl of content) {
const lines = wrap(bl.text, bl.size, b.w - 48, SANS, bl.weight);
inner += textLines(24, y, lines, bl.size, ink, SANS, bl.weight);
y += lines.length * Math.round(bl.size * 1.35) + 8;
if (y > b.h - 12) break;
}
parts.push(g(inner));
break;
}
case "image": {
const data = await inline(ctx.resolve(e.src));
parts.push(
g(
data
? `<image href="${esc(data)}" width="${b.w}" height="${b.h}" preserveAspectRatio="xMidYMid meet"/>`
: `<rect width="${b.w}" height="${b.h}" fill="${paint("ink", "fill")}"/>`,
),
);
break;
}
case "embed":
parts.push(
g(
`<rect width="${b.w}" height="${b.h}" rx="8" fill="${paint("paper", "fill")}" stroke="${paint("gray", "fill")}"/>` +
textLines(16, 16, wrap(e.url, 13, b.w - 32), 13, paint("blue", "line"), SANS),
),
);
break;
case "mindmap": {
const l = ctx.layoutOf(e);
const line = paint(e.color, "line");
const fill = paint(e.color, "fill");
let inner = l.edges
.map((ed) => `<path d="${edgePath(ed.from, ed.to)}" fill="none" stroke="${line}" stroke-width="2"/>`)
.join("");
for (const n of l.boxes.values()) {
const size = n.depth === 0 ? 18 : 15;
const weight = n.depth === 0 ? 600 : 400;
const bg = n.depth === 0 ? line : n.depth === 1 ? fill : paint("paper", "line");
const fg = n.depth === 0 ? paint("paper", "line") : ink;
inner += `<rect x="${n.x}" y="${n.y}" width="${n.w}" height="${n.h}" rx="${n.depth === 0 ? 10 : 8}" fill="${bg}" stroke="${line}" stroke-width="${n.depth === 0 ? 0 : 1.5}"/>`;
const lines = wrap(e.nodes[n.id]?.text || " ", size, 260, SANS, weight);
inner += textLines(
n.x + n.w / 2,
n.y + (n.h - lines.length * Math.round(size * 1.4)) / 2 - 2,
lines,
size,
fg,
SANS,
weight,
"middle",
);
}
parts.push(`<g transform="translate(${e.x} ${e.y})">${inner}</g>`);
break;
}
}
}
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${Math.ceil(box.w)}" height="${Math.ceil(box.h)}" viewBox="${box.x} ${box.y} ${box.w} ${box.h}"><rect x="${box.x}" y="${box.y}" width="${box.w}" height="${box.h}" fill="${paint("paper", "line")}"/>${parts.join("")}</svg>`;
return { svg, box };
}
export async function exportCanvas(kind: ExportKind, ctx: ExportContext): Promise<Blob> {
const { svg, box } = await canvasSVG(ctx);
const file = new Blob([svg], { type: "image/svg+xml" });
if (kind === "svg") return file;
// Twice the size for sharp text, within what browsers draw on one canvas.
const scale = Math.min(2, 8192 / Math.max(box.w, box.h, 1));
const url = URL.createObjectURL(file);
try {
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
const i = new Image();
i.onload = () => resolve(i);
i.onerror = () => reject(new Error("could not draw the canvas"));
i.src = url;
});
const c = document.createElement("canvas");
c.width = Math.ceil(box.w * scale);
c.height = Math.ceil(box.h * scale);
const g = c.getContext("2d");
if (!g) throw new Error("could not draw the canvas");
g.drawImage(img, 0, 0, c.width, c.height);
return await new Promise<Blob>((resolve, reject) =>
c.toBlob((b) => (b ? resolve(b) : reject(new Error("could not draw the canvas"))), "image/png"),
);
} finally {
URL.revokeObjectURL(url);
}
}
+368
View File
@@ -0,0 +1,368 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Boxes, points and connector routes. Everything is in canvas units.
import type { CanvasElement, ConnectorElement, End } from "./model";
export interface Box {
x: number;
y: number;
w: number;
h: number;
}
export type Point = [number, number];
export const center = (b: Box): Point => [b.x + b.w / 2, b.y + b.h / 2];
export function union(boxes: Box[]): Box | null {
if (!boxes.length) return null;
let x1 = Infinity;
let y1 = Infinity;
let x2 = -Infinity;
let y2 = -Infinity;
for (const b of boxes) {
x1 = Math.min(x1, b.x);
y1 = Math.min(y1, b.y);
x2 = Math.max(x2, b.x + b.w);
y2 = Math.max(y2, b.y + b.h);
}
return { x: x1, y: y1, w: x2 - x1, h: y2 - y1 };
}
export const inflate = (b: Box, d: number): Box => ({ x: b.x - d, y: b.y - d, w: b.w + 2 * d, h: b.h + 2 * d });
export const intersects = (a: Box, b: Box) =>
a.x <= b.x + b.w && b.x <= a.x + a.w && a.y <= b.y + b.h && b.y <= a.y + a.h;
export const containsBox = (outer: Box, inner: Box) =>
inner.x >= outer.x &&
inner.y >= outer.y &&
inner.x + inner.w <= outer.x + outer.w &&
inner.y + inner.h <= outer.y + outer.h;
export const containsPoint = (b: Box, [x, y]: Point) => x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h;
/** The box from two corners in any order. */
export function boxOf(a: Point, b: Point): Box {
return { x: Math.min(a[0], b[0]), y: Math.min(a[1], b[1]), w: Math.abs(a[0] - b[0]), h: Math.abs(a[1] - b[1]) };
}
export function rotatePoint([x, y]: Point, [cx, cy]: Point, deg: number): Point {
if (!deg) return [x, y];
const r = (deg * Math.PI) / 180;
const cos = Math.cos(r);
const sin = Math.sin(r);
return [cx + (x - cx) * cos - (y - cy) * sin, cy + (x - cx) * sin + (y - cy) * cos];
}
/** The axis-aligned box around a rotated box. */
export function rotatedBox(b: Box, deg: number): Box {
if (!deg) return b;
const c = center(b);
const corners: Point[] = [
[b.x, b.y],
[b.x + b.w, b.y],
[b.x + b.w, b.y + b.h],
[b.x, b.y + b.h],
].map((p) => rotatePoint(p as Point, c, deg));
return boxOf(
[Math.min(...corners.map((p) => p[0])), Math.min(...corners.map((p) => p[1]))],
[Math.max(...corners.map((p) => p[0])), Math.max(...corners.map((p) => p[1]))],
);
}
export function distToSegment([px, py]: Point, [ax, ay]: Point, [bx, by]: Point): number {
const dx = bx - ax;
const dy = by - ay;
const len = dx * dx + dy * dy;
const t = len ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / len)) : 0;
return Math.hypot(px - (ax + t * dx), py - (ay + t * dy));
}
export function distToPolyline(p: Point, pts: Point[]): number {
if (pts.length === 1) return Math.hypot(p[0] - pts[0]![0], p[1] - pts[0]![1]);
let d = Infinity;
for (let i = 1; i < pts.length; i++) d = Math.min(d, distToSegment(p, pts[i - 1]!, pts[i]!));
return d;
}
// ---- Connectors ----
/** Which side of a box a point is closest to. */
export type Side = "left" | "right" | "top" | "bottom";
export function nearestSide(b: Box, [x, y]: Point): Side {
const d: [Side, number][] = [
["left", Math.abs(x - b.x)],
["right", Math.abs(x - (b.x + b.w))],
["top", Math.abs(y - b.y)],
["bottom", Math.abs(y - (b.y + b.h))],
];
d.sort((a, z) => a[1] - z[1]);
return d[0]![0];
}
const normals: Record<Side, Point> = { left: [-1, 0], right: [1, 0], top: [0, -1], bottom: [0, 1] };
/** Where the line from the box's centre towards p leaves the box (or the ellipse inside it). */
export function edgeToward(b: Box, p: Point, ellipse = false): Point {
const [cx, cy] = center(b);
const dx = p[0] - cx;
const dy = p[1] - cy;
if (!dx && !dy) return [cx, cy];
const hw = Math.max(b.w / 2, 0.5);
const hh = Math.max(b.h / 2, 0.5);
const t = ellipse
? 1 / Math.sqrt((dx * dx) / (hw * hw) + (dy * dy) / (hh * hh))
: Math.min(Math.abs(hw / (dx || 1e-9)), Math.abs(hh / (dy || 1e-9)));
return [cx + dx * t, cy + dy * t];
}
/** The four side midpoints of a box, where a connector can snap to. */
export const anchors = (b: Box): [Side, Point][] => [
["top", [b.x + b.w / 2, b.y]],
["right", [b.x + b.w, b.y + b.h / 2]],
["bottom", [b.x + b.w / 2, b.y + b.h]],
["left", [b.x, b.y + b.h / 2]],
];
export interface Route {
points: Point[];
/** An SVG path in canvas units. */
d: string;
/** Where the label goes. */
mid: Point;
/** Directions the line leaves the source and enters the target, for arrowheads (radians). */
startAngle: number;
endAngle: number;
}
interface Resolved {
at: Point;
side: Side | null;
}
/**
* Where a connector's ends are: a free point, a point inside an element's
* box, or the point where the line towards the other end leaves the box.
*/
export function resolveEnds(
c: Pick<ConnectorElement, "source" | "target">,
boxOfId: (id: string) => { box: Box; ellipse: boolean } | null,
): [Resolved, Resolved] {
const loose = (e: End): Point | null => {
if (!e.id) return [e.x ?? 0, e.y ?? 0];
const t = boxOfId(e.id);
if (!t) return [e.x ?? 0, e.y ?? 0];
if (e.pos) return [t.box.x + t.box.w * e.pos[0], t.box.y + t.box.h * e.pos[1]];
return null;
};
const centreOf = (e: End): Point => {
const t = e.id ? boxOfId(e.id) : null;
return t ? center(t.box) : [e.x ?? 0, e.y ?? 0];
};
const one = (e: End, other: End): Resolved => {
const fixed = loose(e);
const t = e.id ? boxOfId(e.id) : null;
if (fixed) return { at: fixed, side: t ? nearestSide(t.box, fixed) : null };
const at = edgeToward(t!.box, loose(other) ?? centreOf(other), t!.ellipse);
return { at, side: nearestSide(t!.box, at) };
};
return [one(c.source, c.target), one(c.target, c.source)];
}
const fmt = (n: number) => Math.round(n * 100) / 100;
const pathOf = (pts: Point[]) => pts.map((p, i) => `${i ? "L" : "M"}${fmt(p[0])} ${fmt(p[1])}`).join(" ");
const angle = (from: Point, to: Point) => Math.atan2(to[1] - from[1], to[0] - from[0]);
/** A connector's line between its resolved ends. */
export function route(mode: ConnectorElement["mode"], a: Resolved, b: Resolved): Route {
const [ax, ay] = a.at;
const [bx, by] = b.at;
const dist = Math.hypot(bx - ax, by - ay);
if (mode === "straight" || dist < 1) {
return {
points: [a.at, b.at],
d: pathOf([a.at, b.at]),
mid: [(ax + bx) / 2, (ay + by) / 2],
startAngle: angle(b.at, a.at),
endAngle: angle(a.at, b.at),
};
}
if (mode === "curve") {
const k = Math.min(dist / 2, 160);
const na = a.side ? normals[a.side] : unit(a.at, b.at);
const nb = b.side ? normals[b.side] : unit(b.at, a.at);
const c1: Point = [ax + na[0] * k, ay + na[1] * k];
const c2: Point = [bx + nb[0] * k, by + nb[1] * k];
const pts: Point[] = [];
for (let i = 0; i <= 24; i++) pts.push(bezier(a.at, c1, c2, b.at, i / 24));
return {
points: pts,
d: `M${fmt(ax)} ${fmt(ay)} C${fmt(c1[0])} ${fmt(c1[1])} ${fmt(c2[0])} ${fmt(c2[1])} ${fmt(bx)} ${fmt(by)}`,
mid: bezier(a.at, c1, c2, b.at, 0.5),
startAngle: angle(c1, a.at),
endAngle: angle(c2, b.at),
};
}
// Elbow: leave and enter along the sides' normals with right angles between.
const gap = 24;
const sa =
a.side ?? (Math.abs(bx - ax) > Math.abs(by - ay) ? (bx > ax ? "right" : "left") : by > ay ? "bottom" : "top");
const sb =
b.side ?? (Math.abs(bx - ax) > Math.abs(by - ay) ? (bx > ax ? "left" : "right") : by > ay ? "top" : "bottom");
const pa: Point = [ax + normals[sa][0] * gap, ay + normals[sa][1] * gap];
const pb: Point = [bx + normals[sb][0] * gap, by + normals[sb][1] * gap];
const horizA = sa === "left" || sa === "right";
const horizB = sb === "left" || sb === "right";
let middle: Point[];
if (horizA && horizB) {
const mx = (pa[0] + pb[0]) / 2;
middle = [
[mx, pa[1]],
[mx, pb[1]],
];
} else if (!horizA && !horizB) {
const my = (pa[1] + pb[1]) / 2;
middle = [
[pa[0], my],
[pb[0], my],
];
} else if (horizA) middle = [[pb[0], pa[1]]];
else middle = [[pa[0], pb[1]]];
const pts = simplify([a.at, pa, ...middle, pb, b.at]);
return {
points: pts,
d: pathOf(pts),
mid: polylineMid(pts),
startAngle: angle(pts[1] ?? b.at, a.at),
endAngle: angle(pts[pts.length - 2] ?? a.at, b.at),
};
}
function unit(a: Point, b: Point): Point {
const d = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
return [(b[0] - a[0]) / d, (b[1] - a[1]) / d];
}
function bezier(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point {
const u = 1 - t;
const a = u * u * u;
const b = 3 * u * u * t;
const c = 3 * u * t * t;
const d = t * t * t;
return [a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]];
}
/** Drops points that lie on the line between their neighbours. */
function simplify(pts: Point[]): Point[] {
const out: Point[] = [];
for (const p of pts) {
const last = out[out.length - 1];
if (last && Math.abs(last[0] - p[0]) < 0.01 && Math.abs(last[1] - p[1]) < 0.01) continue;
const prev = out[out.length - 2];
if (prev && last) {
const cross = (last[0] - prev[0]) * (p[1] - prev[1]) - (last[1] - prev[1]) * (p[0] - prev[0]);
if (Math.abs(cross) < 0.01) out.pop();
}
out.push(p);
}
return out;
}
export function polylineMid(pts: Point[]): Point {
let total = 0;
for (let i = 1; i < pts.length; i++) total += Math.hypot(pts[i]![0] - pts[i - 1]![0], pts[i]![1] - pts[i - 1]![1]);
let left = total / 2;
for (let i = 1; i < pts.length; i++) {
const a = pts[i - 1]!;
const b = pts[i]!;
const len = Math.hypot(b[0] - a[0], b[1] - a[1]);
if (len >= left && len > 0) return [a[0] + ((b[0] - a[0]) * left) / len, a[1] + ((b[1] - a[1]) * left) / len];
left -= len;
}
return pts[0] ?? [0, 0];
}
// ---- Snapping ----
export interface Guide {
/** "x" draws a vertical line at value, "y" a horizontal one. */
axis: "x" | "y";
value: number;
from: number;
to: number;
}
/**
* Nudges a moving box so its edges or centre line up with another box's,
* when they are within threshold. Returns the shift and the lines to draw.
*/
export function snap(moving: Box, others: Box[], threshold: number): { dx: number; dy: number; guides: Guide[] } {
const xs = (b: Box) => [b.x, b.x + b.w / 2, b.x + b.w];
const ys = (b: Box) => [b.y, b.y + b.h / 2, b.y + b.h];
let best: { dx: number; ox: Box | null; vx: number } = { dx: 0, ox: null, vx: 0 };
let bestY: { dy: number; oy: Box | null; vy: number } = { dy: 0, oy: null, vy: 0 };
let minX = threshold + 1;
let minY = threshold + 1;
for (const o of others) {
for (const a of xs(moving))
for (const b of xs(o)) {
const d = Math.abs(b - a);
if (d < minX) {
minX = d;
best = { dx: b - a, ox: o, vx: b };
}
}
for (const a of ys(moving))
for (const b of ys(o)) {
const d = Math.abs(b - a);
if (d < minY) {
minY = d;
bestY = { dy: b - a, oy: o, vy: b };
}
}
}
const guides: Guide[] = [];
const dx = minX <= threshold ? best.dx : 0;
const dy = minY <= threshold ? bestY.dy : 0;
const moved = { ...moving, x: moving.x + dx, y: moving.y + dy };
if (minX <= threshold && best.ox) {
const o = best.ox;
guides.push({
axis: "x",
value: best.vx,
from: Math.min(o.y, moved.y),
to: Math.max(o.y + o.h, moved.y + moved.h),
});
}
if (minY <= threshold && bestY.oy) {
const o = bestY.oy;
guides.push({
axis: "y",
value: bestY.vy,
from: Math.min(o.x, moved.x),
to: Math.max(o.x + o.w, moved.x + moved.w),
});
}
return { dx, dy, guides };
}
/** Moves a free end onto the nearest side midpoint of a box when it is close. */
export function snapToAnchor(b: Box, p: Point, threshold: number): Point | null {
let best: Point | null = null;
let min = threshold;
for (const [, a] of anchors(b)) {
const d = Math.hypot(a[0] - p[0], a[1] - p[1]);
if (d < min) {
min = d;
best = a;
}
}
return best;
}
/** The box an element takes up, rotation included. */
export function outerBox(e: CanvasElement, box: Box): Box {
return rotatedBox(box, e.rotate);
}
+18
View File
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
export {
CanvasView,
type CanvasOptions,
type CanvasFiles,
type CanvasLinks,
type NoteHandle,
type NoteHost,
type NoteMount,
type Tool,
} from "./view";
export { SurfaceStore, CANVAS_ORIGIN, surfaceOf, type ElementJSON } from "./store";
export { englishCanvasLabels, type CanvasLabels } from "./labels";
export { defaultStyles, readStyles, normalize, PAGE_NOTE_ID, type CanvasElement, type StyleDefaults } from "./model";
export { fragmentToJSON, writeJSON, type PMNode } from "./yxml";
export { layoutMindmap } from "./mindmap";
export type { ExportKind } from "./export";
+222
View File
@@ -0,0 +1,222 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/** The canvas's own words; hosts pass translated ones, English is the default. */
export interface CanvasLabels {
toolbar: string;
select: string;
hand: string;
note: string;
text: string;
shape: string;
connector: string;
pen: string;
eraser: string;
frame: string;
mindmap: string;
image: string;
link: string;
library: string;
present: string;
zoomIn: string;
zoomOut: string;
zoomFit: string;
zoomReset: string;
rect: string;
roundrect: string;
ellipse: string;
diamond: string;
triangle: string;
general: string;
scribbled: string;
straight: string;
curve: string;
elbow: string;
stroke: string;
fill: string;
textColor: string;
background: string;
thickness: string;
lineStyle: string;
solid: string;
dash: string;
noLine: string;
startArrow: string;
endArrow: string;
fontSize: string;
font: string;
sans: string;
serif: string;
mono: string;
alignLeft: string;
alignCenter: string;
alignRight: string;
bold: string;
layout: string;
layoutRight: string;
layoutLeft: string;
layoutRadial: string;
addChild: string;
addSibling: string;
bringFront: string;
sendBack: string;
group: string;
ungroup: string;
duplicate: string;
delete: string;
copy: string;
editText: string;
openLink: string;
frameTitle: string;
groupTitle: string;
linkPrompt: string;
pageNote: string;
stickers: string;
templates: string;
presentNoFrames: string;
presentExit: string;
presentNext: string;
presentPrevious: string;
/** "{n} / {total}" while presenting. */
presentStep: string;
textPlaceholder: string;
templateKanban: string;
templateSwot: string;
templateFlow: string;
templateBrainstorm: string;
templateRetro: string;
todo: string;
doing: string;
done: string;
strengths: string;
weaknesses: string;
opportunities: string;
threats: string;
start: string;
step: string;
decision: string;
end: string;
centralIdea: string;
idea: string;
wentWell: string;
toImprove: string;
actions: string;
colorInk: string;
colorPaper: string;
colorNone: string;
/** Names of the palette colours, by name. */
colors: Record<string, string>;
}
export const englishCanvasLabels: CanvasLabels = {
toolbar: "Canvas tools",
select: "Select (V)",
hand: "Hand (H)",
note: "Note (N)",
text: "Text (T)",
shape: "Shape (S)",
connector: "Connector (C)",
pen: "Pen (P)",
eraser: "Eraser (E)",
frame: "Frame (F)",
mindmap: "Mind map (M)",
image: "Picture (I)",
link: "Link (L)",
library: "Stickers and templates",
present: "Present",
zoomIn: "Zoom in",
zoomOut: "Zoom out",
zoomFit: "Fit to screen",
zoomReset: "Zoom to 100%",
rect: "Square",
roundrect: "Rounded rectangle",
ellipse: "Ellipse",
diamond: "Diamond",
triangle: "Triangle",
general: "General",
scribbled: "Scribbled",
straight: "Straight",
curve: "Curve",
elbow: "Elbowed",
stroke: "Line colour",
fill: "Fill",
textColor: "Text colour",
background: "Background",
thickness: "Thickness",
lineStyle: "Line style",
solid: "Solid",
dash: "Dashed",
noLine: "No line",
startArrow: "Start",
endArrow: "End",
fontSize: "Size",
font: "Font",
sans: "Sans",
serif: "Serif",
mono: "Mono",
alignLeft: "Align left",
alignCenter: "Align centre",
alignRight: "Align right",
bold: "Bold",
layout: "Layout",
layoutRight: "Right",
layoutLeft: "Left",
layoutRadial: "Both sides",
addChild: "Add branch (Tab)",
addSibling: "Add sibling (Enter)",
bringFront: "Bring to front",
sendBack: "Send to back",
group: "Group (Ctrl+G)",
ungroup: "Ungroup",
duplicate: "Duplicate (Ctrl+D)",
delete: "Delete",
copy: "Copy",
editText: "Edit text",
openLink: "Open link",
frameTitle: "Frame",
groupTitle: "Group",
linkPrompt: "Link address",
pageNote: "Page",
stickers: "Stickers",
templates: "Templates",
presentNoFrames: "Add frames to present them one by one.",
presentExit: "Stop presenting",
presentNext: "Next frame",
presentPrevious: "Previous frame",
presentStep: "{n} / {total}",
textPlaceholder: "Type…",
templateKanban: "Board",
templateSwot: "SWOT",
templateFlow: "Flowchart",
templateBrainstorm: "Brainstorm",
templateRetro: "Retrospective",
todo: "To do",
doing: "Doing",
done: "Done",
strengths: "Strengths",
weaknesses: "Weaknesses",
opportunities: "Opportunities",
threats: "Threats",
start: "Start",
step: "Step",
decision: "Decision?",
end: "End",
centralIdea: "Central idea",
idea: "Idea",
wentWell: "Went well",
toImprove: "To improve",
actions: "Actions",
colorInk: "Default",
colorPaper: "Paper",
colorNone: "None",
colors: {
gray: "Gray",
red: "Red",
orange: "Orange",
yellow: "Yellow",
green: "Green",
teal: "Teal",
blue: "Blue",
purple: "Purple",
pink: "Pink",
},
};
+139
View File
@@ -0,0 +1,139 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Stickers and templates: ready-made elements dropped in the middle of the
// view. Everything is built from the canvas's own elements, so a template is
// editable like anything drawn by hand.
import type { CanvasLabels } from "./labels";
import { newId, type Color } from "./model";
import type { ElementJSON } from "./store";
import type { PMNode } from "./yxml";
/** Stickers are large emoji in a text box. */
export const stickers = [
"👍",
"⭐",
"❤️",
"✅",
"❌",
"💡",
"❓",
"❗",
"🎉",
"🔥",
"📌",
"🚀",
"👀",
"🎯",
"⚠️",
"🙂",
];
export function sticker(emoji: string): ElementJSON[] {
return [{ id: newId(), type: "text", text: emoji, fontSize: 64, x: 0, y: 0, w: 0, h: 0 }];
}
export type TemplateId = "kanban" | "swot" | "flow" | "brainstorm" | "retro";
export const templates: TemplateId[] = ["kanban", "swot", "flow", "brainstorm", "retro"];
const para = (text: string): PMNode[] => [{ type: "paragraph", content: text ? [{ type: "text", text }] : [] }];
const frame = (title: string, x: number, y: number, w: number, h: number, background: Color = "none"): ElementJSON => ({
id: newId(),
type: "frame",
title,
x,
y,
w,
h,
background,
});
const note = (text: string, x: number, y: number, background: Color, w = 220): ElementJSON => ({
id: newId(),
type: "note",
background,
x,
y,
w,
h: 90,
body: para(text),
});
const shape = (kind: string, text: string, x: number, y: number, w: number, h: number, color: Color): ElementJSON => ({
id: newId(),
type: "shape",
shape: kind,
text,
x,
y,
w,
h,
stroke: color,
fill: color,
strokeWidth: 2,
});
const arrow = (from: string, to: string, mode = "elbow"): ElementJSON => ({
id: newId(),
type: "connector",
source: { id: from },
target: { id: to },
mode,
stroke: "gray",
endArrow: "arrow",
});
export function template(id: TemplateId, l: CanvasLabels): ElementJSON[] {
switch (id) {
case "kanban": {
const cols: [string, Color][] = [
[l.todo, "gray"],
[l.doing, "blue"],
[l.done, "green"],
];
return cols.flatMap(([title, c], i) => [
frame(title, i * 300, 0, 280, 520),
note("", i * 300 + 30, 50, c),
note("", i * 300 + 30, 170, c),
]);
}
case "swot": {
const parts: [string, Color][] = [
[l.strengths, "green"],
[l.weaknesses, "red"],
[l.opportunities, "blue"],
[l.threats, "orange"],
];
return parts.flatMap(([title, c], i) => {
const x = (i % 2) * 380;
const y = Math.floor(i / 2) * 300;
return [shape("roundrect", title, x, y, 360, 280, c)];
});
}
case "flow": {
const a = shape("ellipse", l.start, 0, 0, 180, 70, "green");
const b = shape("rect", l.step, 0, 140, 180, 80, "blue");
const c = shape("diamond", l.decision, -10, 290, 200, 120, "orange");
const d = shape("rect", l.step, 280, 310, 180, 80, "blue");
const e = shape("ellipse", l.end, 0, 480, 180, 70, "red");
return [a, b, c, d, e, arrow(a.id, b.id), arrow(b.id, c.id), arrow(c.id, d.id), arrow(c.id, e.id)];
}
case "brainstorm": {
const root = newId();
const nodes: Record<string, { text: string; parent: string; pos: number }> = {
[root]: { text: l.centralIdea, parent: "", pos: 0 },
};
for (let i = 0; i < 4; i++) nodes[newId()] = { text: `${l.idea} ${i + 1}`, parent: root, pos: i };
return [{ id: newId(), type: "mindmap", layout: "radial", color: "purple", x: 0, y: 0, nodes }];
}
case "retro": {
const cols: [string, Color][] = [
[l.wentWell, "green"],
[l.toImprove, "orange"],
[l.actions, "blue"],
];
return cols.flatMap(([title, c], i) => [frame(title, i * 300, 0, 280, 420), note("", i * 300 + 30, 50, c)]);
}
}
}
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Text measuring for layouts that cannot wait for the DOM (mind maps,
// exports). Falls back to an estimate where there is no 2D canvas (tests).
let ctx: CanvasRenderingContext2D | null | undefined;
function context(): CanvasRenderingContext2D | null {
if (ctx !== undefined) return ctx;
try {
ctx = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : null;
} catch {
ctx = null;
}
return ctx;
}
export const SANS = '"Inter Variable", Inter, ui-sans-serif, system-ui, sans-serif';
export const SERIF = '"Source Serif 4 Variable", "Source Serif 4", Georgia, serif';
export const MONO = '"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, monospace';
export function fontFamily(font: "" | "serif" | "mono"): string {
return font === "serif" ? SERIF : font === "mono" ? MONO : SANS;
}
export function textWidth(text: string, size: number, family = SANS, weight = 400): number {
const c = context();
if (!c) return text.length * size * 0.56;
c.font = `${weight} ${size}px ${family}`;
return c.measureText(text).width;
}
/** Breaks text into lines no wider than max (words first, then characters). */
export function wrap(text: string, size: number, max: number, family = SANS, weight = 400): string[] {
const out: string[] = [];
for (const para of text.split("\n")) {
if (!para) {
out.push("");
continue;
}
let line = "";
for (const word of para.split(/(\s+)/)) {
const next = line + word;
if (!line || textWidth(next, size, family, weight) <= max) {
line = next;
continue;
}
out.push(line.trimEnd());
line = word.trimStart();
// A word longer than the line is broken where it must.
while (line && textWidth(line, size, family, weight) > max) {
let cut = line.length - 1;
while (cut > 1 && textWidth(line.slice(0, cut), size, family, weight) > max) cut--;
out.push(line.slice(0, cut));
line = line.slice(cut);
}
}
out.push(line);
}
return out;
}
/** The size of a mind map node: its text on one or more lines, with padding. */
export function nodeSize(text: string, depth: number): { w: number; h: number } {
const size = depth === 0 ? 18 : 15;
const weight = depth === 0 ? 600 : 400;
const lines = wrap(text || " ", size, 260, SANS, weight);
const w = Math.max(...lines.map((l) => textWidth(l, size, SANS, weight)), depth === 0 ? 60 : 40);
return {
w: Math.ceil(w) + (depth === 0 ? 32 : 24),
h: lines.length * Math.round(size * 1.4) + (depth === 0 ? 20 : 14),
};
}
+153
View File
@@ -0,0 +1,153 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Mind map layouts: the root on one side (right, left) or in the middle
// with branches on both sides (radial). Positions are relative to the
// root's top-left corner, which is the element's x, y.
import type { Box, Point } from "./geometry";
import type { MindmapLayout, MindmapNode } from "./model";
export interface NodeBox extends Box {
id: string;
depth: number;
/** Which way the branch grows from its parent. */
dir: 1 | -1;
parent: string;
}
export interface MindmapLayoutResult {
root: string;
boxes: Map<string, NodeBox>;
/** Parent → child lines, each as [from, to] points. */
edges: { from: Point; to: Point; child: string }[];
/** The whole map, relative to the root's corner. */
bounds: Box;
}
const H_GAP = 56;
const V_GAP = 14;
/** The root node's id: the one without a parent (the first, if several). */
export function rootOf(nodes: Record<string, MindmapNode>): string | null {
const roots = Object.entries(nodes).filter(([, n]) => !n.parent || !nodes[n.parent]);
roots.sort((a, b) => a[1].pos - b[1].pos || (a[0] < b[0] ? -1 : 1));
return roots[0]?.[0] ?? null;
}
/** A node's children in order. */
export function childrenOf(nodes: Record<string, MindmapNode>, id: string): string[] {
return Object.entries(nodes)
.filter(([cid, n]) => n.parent === id && cid !== id)
.sort((a, b) => a[1].pos - b[1].pos || (a[0] < b[0] ? -1 : 1))
.map(([cid]) => cid);
}
export function layoutMindmap(
nodes: Record<string, MindmapNode>,
layout: MindmapLayout,
measure: (text: string, depth: number) => { w: number; h: number },
): MindmapLayoutResult {
const root = rootOf(nodes);
const boxes = new Map<string, NodeBox>();
const edges: MindmapLayoutResult["edges"] = [];
if (!root) return { root: "", boxes, edges, bounds: { x: 0, y: 0, w: 0, h: 0 } };
const size = new Map<string, { w: number; h: number }>();
const seen = new Set<string>();
const measureAll = (id: string, depth: number) => {
if (seen.has(id) || depth > 50) return;
seen.add(id);
size.set(id, measure(nodes[id]!.text, depth));
for (const c of childrenOf(nodes, id)) measureAll(c, depth + 1);
};
measureAll(root, 0);
const kids = (id: string) => childrenOf(nodes, id).filter((c) => size.has(c));
// The height a branch needs: its node or its children stacked, whichever is taller.
const heights = new Map<string, number>();
const height = (id: string): number => {
const known = heights.get(id);
if (known !== undefined) return known;
const cs = kids(id);
const stack = cs.reduce((s, c) => s + height(c), 0) + V_GAP * Math.max(0, cs.length - 1);
const h = Math.max(size.get(id)!.h, stack);
heights.set(id, h);
return h;
};
const place = (id: string, x: number, centreY: number, depth: number, dir: 1 | -1, parent: string) => {
const s = size.get(id)!;
const bx = dir === 1 ? x : x - s.w;
boxes.set(id, { id, x: bx, y: centreY - s.h / 2, w: s.w, h: s.h, depth, dir, parent });
placeChildren(id, kids(id), dir === 1 ? bx + s.w + H_GAP : bx - H_GAP, centreY, depth + 1, dir);
};
const placeChildren = (parent: string, cs: string[], x: number, centreY: number, depth: number, dir: 1 | -1) => {
const total = cs.reduce((s, c) => s + height(c), 0) + V_GAP * Math.max(0, cs.length - 1);
let y = centreY - total / 2;
for (const c of cs) {
const h = height(c);
place(c, x, y + h / 2, depth, dir, parent);
y += h + V_GAP;
}
};
const rs = size.get(root)!;
boxes.set(root, { id: root, x: 0, y: 0, w: rs.w, h: rs.h, depth: 0, dir: 1, parent: "" });
const cy = rs.h / 2;
const cs = kids(root);
if (layout === "right") placeChildren(root, cs, rs.w + H_GAP, cy, 1, 1);
else if (layout === "left") placeChildren(root, cs, -H_GAP, cy, 1, -1);
else {
// Radial: the first half of the branches to the right, the rest to the left.
const half = Math.ceil(cs.length / 2);
placeChildren(root, cs.slice(0, half), rs.w + H_GAP, cy, 1, 1);
placeChildren(root, cs.slice(half), -H_GAP, cy, 1, -1);
}
for (const b of boxes.values()) {
if (!b.parent) continue;
const p = boxes.get(b.parent)!;
const from: Point = b.dir === 1 ? [p.x + p.w, p.y + p.h / 2] : [p.x, p.y + p.h / 2];
const to: Point = b.dir === 1 ? [b.x, b.y + b.h / 2] : [b.x + b.w, b.y + b.h / 2];
edges.push({ from, to, child: b.id });
}
let x1 = Infinity;
let y1 = Infinity;
let x2 = -Infinity;
let y2 = -Infinity;
for (const b of boxes.values()) {
x1 = Math.min(x1, b.x);
y1 = Math.min(y1, b.y);
x2 = Math.max(x2, b.x + b.w);
y2 = Math.max(y2, b.y + b.h);
}
return { root, boxes, edges, bounds: { x: x1, y: y1, w: x2 - x1, h: y2 - y1 } };
}
/** The node an arrow key moves to from id, or null. */
export function neighbour(
result: MindmapLayoutResult,
nodes: Record<string, MindmapNode>,
id: string,
key: "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight",
): string | null {
const b = result.boxes.get(id);
if (!b) return null;
if (key === "ArrowUp" || key === "ArrowDown") {
const siblings = b.parent ? childrenOf(nodes, b.parent).filter((c) => result.boxes.get(c)?.dir === b.dir) : [];
const i = siblings.indexOf(id);
return siblings[i + (key === "ArrowUp" ? -1 : 1)] ?? null;
}
const want = key === "ArrowRight" ? 1 : -1;
if (!b.parent) {
// From the root, go to the first branch on that side.
return childrenOf(nodes, id).find((c) => result.boxes.get(c)?.dir === want) ?? null;
}
if (want === b.dir) return childrenOf(nodes, id)[0] ?? null;
return b.parent;
}
/** Curved line from a parent to a child, as an SVG path. */
export function edgePath(from: Point, to: Point): string {
const mx = (from[0] + to[0]) / 2;
return `M${from[0]} ${from[1]} C${mx} ${from[1]} ${mx} ${to[1]} ${to[0]} ${to[1]}`;
}
+354
View File
@@ -0,0 +1,354 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// The elements of an edgeless canvas (ADR-14). Each one is a Y.Map in
// ydoc.getMap("surface") keyed by its id; these types are what the maps
// read as. Coordinates are canvas units; x, y is the top-left corner.
/** The theme colours elements use; documents store the name, not a value. */
export const palette = ["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"] as const;
/** A palette colour, "ink" (the text colour), "paper" (the page colour) or "none". */
export type Color = (typeof palette)[number] | "ink" | "paper" | "none";
export const colors: readonly Color[] = ["ink", ...palette, "paper", "none"];
export const isColor = (c: unknown): c is Color => typeof c === "string" && (colors as readonly string[]).includes(c);
export type ElementType =
"shape" | "text" | "connector" | "brush" | "note" | "frame" | "image" | "embed" | "group" | "mindmap";
export const shapeKinds = ["rect", "roundrect", "ellipse", "diamond", "triangle"] as const;
export type ShapeKind = (typeof shapeKinds)[number];
export type StrokeStyle = "solid" | "dash" | "none";
export const connectorModes = ["straight", "curve", "elbow"] as const;
export type ConnectorMode = (typeof connectorModes)[number];
export const arrowKinds = ["none", "arrow", "triangle", "circle", "diamond"] as const;
export type Arrow = (typeof arrowKinds)[number];
export type TextFont = "" | "serif" | "mono";
export type TextAlign = "left" | "center" | "right";
export const mindmapLayouts = ["right", "left", "radial"] as const;
export type MindmapLayout = (typeof mindmapLayouts)[number];
interface Base {
id: string;
type: ElementType;
/** Z-order: higher draws on top. Frames always draw below everything else. */
index: number;
x: number;
y: number;
w: number;
h: number;
/** Degrees clockwise around the centre. */
rotate: number;
/** The group the element belongs to, if any. */
group: string;
}
export interface ShapeElement extends Base {
type: "shape";
shape: ShapeKind;
stroke: Color;
fill: Color;
strokeWidth: number;
strokeStyle: StrokeStyle;
/** The hand-drawn ("scribbled") style. */
rough: boolean;
text: string;
textColor: Color;
fontSize: number;
}
export interface TextElement extends Base {
type: "text";
text: string;
color: Color;
fontSize: number;
font: TextFont;
align: TextAlign;
bold: boolean;
}
/** One end of a connector: stuck to an element (at pos inside its box, or the nearest side) or a free point. */
export interface End {
id?: string;
/** Where on the element, as fractions of its box; without it the end slides to the nearest side. */
pos?: [number, number];
x?: number;
y?: number;
}
export interface ConnectorElement extends Base {
type: "connector";
source: End;
target: End;
mode: ConnectorMode;
stroke: Color;
strokeWidth: number;
strokeStyle: StrokeStyle;
startArrow: Arrow;
endArrow: Arrow;
label: string;
rough: boolean;
}
export interface BrushElement extends Base {
type: "brush";
/** [x, y, pressure] relative to x, y. */
points: number[][];
color: Color;
size: number;
}
export interface NoteElement extends Base {
type: "note";
/** The page's own text (the "default" fragment) instead of a body of its own. */
page: boolean;
background: Color;
}
export interface FrameElement extends Base {
type: "frame";
title: string;
background: Color;
}
export interface ImageElement extends Base {
type: "image";
src: string;
alt: string;
}
/** A link: a player for the sites the editor embeds, a card for any other address. */
export interface EmbedElement extends Base {
type: "embed";
url: string;
}
/** Elements grouped with Ctrl+G; its box is its members' box. */
export interface GroupElement extends Base {
type: "group";
title: string;
}
export interface MindmapNode {
text: string;
/** The parent node's id; "" for the root. */
parent: string;
/** Order among siblings. */
pos: number;
}
/** A mind map; x, y is the root's top-left corner, the box follows the layout. */
export interface MindmapElement extends Base {
type: "mindmap";
layout: MindmapLayout;
color: Color;
nodes: Record<string, MindmapNode>;
}
export type CanvasElement =
| ShapeElement
| TextElement
| ConnectorElement
| BrushElement
| NoteElement
| FrameElement
| ImageElement
| EmbedElement
| GroupElement
| MindmapElement;
export type ElementOf<T extends ElementType> = Extract<CanvasElement, { type: T }>;
/** The default width of the page's note, about the reading column. */
export const PAGE_NOTE_WIDTH = 760;
/** The id of the page's note; it exists before anyone moves it (ADR-14). */
export const PAGE_NOTE_ID = "page";
const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) ? v : d);
const str = (v: unknown, d = "") => (typeof v === "string" ? v : d);
const bool = (v: unknown) => v === true;
const color = (v: unknown, d: Color): Color => (isColor(v) ? v : d);
const oneOf = <T extends string>(v: unknown, list: readonly T[], d: T): T =>
typeof v === "string" && (list as readonly string[]).includes(v) ? (v as T) : d;
function end(v: unknown): End {
if (!v || typeof v !== "object") return { x: 0, y: 0 };
const o = v as Record<string, unknown>;
const out: End = {};
if (typeof o.id === "string" && o.id) out.id = o.id;
if (Array.isArray(o.pos) && o.pos.length === 2) out.pos = [num(o.pos[0], 0.5), num(o.pos[1], 0.5)];
if (!out.id) {
out.x = num(o.x, 0);
out.y = num(o.y, 0);
}
return out;
}
function nodes(v: unknown): Record<string, MindmapNode> {
const out: Record<string, MindmapNode> = {};
if (!v || typeof v !== "object") return out;
for (const [id, n] of Object.entries(v as Record<string, unknown>)) {
if (!n || typeof n !== "object") continue;
const o = n as Record<string, unknown>;
out[id] = { text: str(o.text), parent: str(o.parent), pos: num(o.pos, 0) };
}
return out;
}
/** Reads an element from its stored fields, filling in what is missing; null for an unknown type. */
export function normalize(raw: Record<string, unknown>): CanvasElement | null {
const base = {
id: str(raw.id),
index: num(raw.index, 0),
x: num(raw.x, 0),
y: num(raw.y, 0),
w: Math.max(0, num(raw.w, 0)),
h: Math.max(0, num(raw.h, 0)),
rotate: num(raw.rotate, 0),
group: str(raw.group),
};
switch (raw.type) {
case "shape":
return {
...base,
type: "shape",
shape: oneOf(raw.shape, shapeKinds, "rect"),
stroke: color(raw.stroke, "ink"),
fill: color(raw.fill, "none"),
strokeWidth: num(raw.strokeWidth, 2),
strokeStyle: oneOf(raw.strokeStyle, ["solid", "dash", "none"] as const, "solid"),
rough: bool(raw.rough),
text: str(raw.text),
textColor: color(raw.textColor, "ink"),
fontSize: num(raw.fontSize, 18),
};
case "text":
return {
...base,
type: "text",
text: str(raw.text),
color: color(raw.color, "ink"),
fontSize: num(raw.fontSize, 24),
font: oneOf(raw.font, ["", "serif", "mono"] as const, ""),
align: oneOf(raw.align, ["left", "center", "right"] as const, "left"),
bold: bool(raw.bold),
};
case "connector":
return {
...base,
type: "connector",
source: end(raw.source),
target: end(raw.target),
mode: oneOf(raw.mode, connectorModes, "curve"),
stroke: color(raw.stroke, "ink"),
strokeWidth: num(raw.strokeWidth, 2),
strokeStyle: oneOf(raw.strokeStyle, ["solid", "dash", "none"] as const, "solid"),
startArrow: oneOf(raw.startArrow, arrowKinds, "none"),
endArrow: oneOf(raw.endArrow, arrowKinds, "arrow"),
label: str(raw.label),
rough: bool(raw.rough),
};
case "brush":
return {
...base,
type: "brush",
points: Array.isArray(raw.points)
? raw.points
.filter((p): p is number[] => Array.isArray(p) && p.length >= 2)
.map((p) => [num(p[0], 0), num(p[1], 0), num(p[2], 0.5)])
: [],
color: color(raw.color, "ink"),
size: num(raw.size, 4),
};
case "note":
return { ...base, type: "note", page: bool(raw.page), background: color(raw.background, "paper") };
case "frame":
return { ...base, type: "frame", title: str(raw.title), background: color(raw.background, "none") };
case "image":
return { ...base, type: "image", src: str(raw.src), alt: str(raw.alt) };
case "embed":
return { ...base, type: "embed", url: str(raw.url) };
case "group":
return { ...base, type: "group", title: str(raw.title) };
case "mindmap":
return {
...base,
type: "mindmap",
layout: oneOf(raw.layout, mindmapLayouts, "right"),
color: color(raw.color, "blue"),
nodes: nodes(raw.nodes),
};
default:
return null;
}
}
/** Elements whose box can be dragged by its corners. */
export const resizable = (e: CanvasElement) => !["connector", "group", "mindmap"].includes(e.type);
/** Elements that turn around their centre. */
export const rotatable = (e: CanvasElement) => ["shape", "text", "image", "brush"].includes(e.type);
/** Elements a connector can stick to. */
export const connectable = (e: CanvasElement) => !["connector", "brush", "group"].includes(e.type);
let counter = 0;
/** A new element or node id: short, random enough for one canvas. */
export function newId(): string {
counter = (counter + 1) % 1296;
return (
Date.now().toString(36).slice(-6) + counter.toString(36).padStart(2, "0") + Math.random().toString(36).slice(2, 8)
);
}
/** What new elements look like; the last style picked for a kind becomes its default. */
export interface StyleDefaults {
shape: Pick<ShapeElement, "shape" | "stroke" | "fill" | "strokeWidth" | "strokeStyle" | "rough" | "textColor">;
connector: Pick<ConnectorElement, "mode" | "stroke" | "strokeWidth" | "strokeStyle" | "startArrow" | "endArrow">;
brush: Pick<BrushElement, "color" | "size">;
text: Pick<TextElement, "color" | "fontSize" | "font">;
note: Pick<NoteElement, "background">;
frame: Pick<FrameElement, "background">;
mindmap: Pick<MindmapElement, "layout" | "color">;
}
export const defaultStyles: StyleDefaults = {
shape: {
shape: "rect",
stroke: "blue",
fill: "blue",
strokeWidth: 2,
strokeStyle: "solid",
rough: false,
textColor: "ink",
},
connector: {
mode: "curve",
stroke: "gray",
strokeWidth: 2,
strokeStyle: "solid",
startArrow: "none",
endArrow: "arrow",
},
brush: { color: "ink", size: 4 },
text: { color: "ink", fontSize: 24, font: "" },
note: { background: "yellow" },
frame: { background: "none" },
mindmap: { layout: "right", color: "blue" },
};
/** Merges stored defaults over the built-in ones, dropping anything that does not fit. */
export function readStyles(raw: unknown): StyleDefaults {
const out = structuredClone(defaultStyles);
if (!raw || typeof raw !== "object") return out;
for (const kind of Object.keys(out) as (keyof StyleDefaults)[]) {
const src = (raw as Record<string, unknown>)[kind];
if (!src || typeof src !== "object") continue;
const probe = normalize({ ...out[kind], ...(src as object), type: kind === "note" ? "note" : kind });
if (!probe) continue;
// A stored value counts only when it reads back as itself (it is valid).
for (const key of Object.keys(out[kind])) {
const v = (src as Record<string, unknown>)[key];
if (v !== undefined && (probe as unknown as Record<string, unknown>)[key] === v)
(out[kind] as Record<string, unknown>)[key] = v;
}
}
return out;
}
+199
View File
@@ -0,0 +1,199 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// SVG markup for the drawn elements. The live canvas and the exports share
// it; only the paint differs (CSS variables live, resolved colours in a
// file). Shapes draw in their own box (0..w, 0..h); connectors in canvas units.
import { getStroke } from "perfect-freehand";
import rough from "roughjs";
import type { Point, Route } from "./geometry";
import type { Arrow, BrushElement, Color, ShapeElement, StrokeStyle } from "./model";
/** Turns a colour name into a CSS colour: "line" for strokes and text, "fill" for soft backgrounds. */
export type Paint = (c: Color, use: "line" | "fill") => string;
export const livePaint: Paint = (c, use) => {
if (c === "none") return "none";
if (c === "ink") return use === "fill" ? "var(--dw-surface-sunken)" : "var(--dw-ink)";
if (c === "paper") return use === "fill" ? "var(--dw-surface-raised)" : "var(--dw-surface)";
return use === "fill" ? `color-mix(in srgb, var(--dw-c-${c}) 22%, var(--dw-surface))` : `var(--dw-c-${c})`;
};
export const esc = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const n = (v: number) => Math.round(v * 100) / 100;
const LINE = "#000001";
const FILL = "#000002";
function dash(style: StrokeStyle, width: number): string {
return style === "dash" ? `stroke-dasharray:${n(width * 4)} ${n(width * 3)};` : "";
}
/** A number from an id, so a scribbled shape looks the same on every screen. */
export function seedOf(id: string): number {
let h = 2166136261;
for (const ch of id) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
return (h >>> 0) % 2 ** 31 || 1;
}
/** The outline of a shape as points (for polygons) or null for curves. */
function polygon(kind: ShapeElement["shape"], w: number, h: number): Point[] | null {
switch (kind) {
case "diamond":
return [
[w / 2, 0],
[w, h / 2],
[w / 2, h],
[0, h / 2],
];
case "triangle":
return [
[w / 2, 0],
[w, h],
[0, h],
];
case "rect":
return [
[0, 0],
[w, 0],
[w, h],
[0, h],
];
default:
return null;
}
}
function roundRectPath(w: number, h: number): string {
const r = Math.min(16, w * 0.15, h * 0.15);
return `M${n(r)} 0 H${n(w - r)} Q${n(w)} 0 ${n(w)} ${n(r)} V${n(h - r)} Q${n(w)} ${n(h)} ${n(w - r)} ${n(h)} H${n(r)} Q0 ${n(h)} 0 ${n(h - r)} V${n(r)} Q0 0 ${n(r)} 0 Z`;
}
/** A shape's body (without its text) in its own box. */
export function shapeSVG(el: ShapeElement, paint: Paint): string {
const { w, h } = el;
const stroke = el.strokeStyle === "none" ? "none" : paint(el.stroke, "line");
const fill = paint(el.fill, "fill");
const sw = el.strokeStyle === "none" ? 0 : el.strokeWidth;
if (el.rough) {
const gen = rough.generator();
const opts = {
seed: seedOf(el.id),
roughness: 1.2,
bowing: 1,
strokeWidth: Math.max(sw, 1),
// Marker colours, swapped for the theme's below.
stroke: stroke === "none" ? "none" : LINE,
fill: fill === "none" ? undefined : FILL,
fillStyle: "hachure",
hachureGap: 8,
fillWeight: 1.4,
disableMultiStroke: sw === 0,
};
const pts = polygon(el.shape, w, h);
const drawable =
el.shape === "ellipse"
? gen.ellipse(w / 2, h / 2, w, h, opts)
: el.shape === "roundrect"
? gen.path(roundRectPath(w, h), opts)
: gen.polygon(pts!, opts);
return gen
.toPaths(drawable)
.map((p) => {
if (p.fill === FILL) return `<path d="${p.d}" style="fill:${fill};stroke:none"/>`;
// Hachure lines are drawn in the fill colour, a little stronger than a flat fill.
const hachure = p.stroke === FILL;
const color = hachure ? fill.replace("22%", "60%") : stroke;
if (color === "none" || p.stroke === "none") return "";
return `<path d="${p.d}" style="fill:none;stroke:${color};stroke-width:${n(p.strokeWidth)};${hachure ? "" : dash(el.strokeStyle, sw)}"/>`;
})
.join("");
}
const style = `fill:${fill};stroke:${stroke};stroke-width:${n(sw)};stroke-linejoin:round;${dash(el.strokeStyle, sw)}`;
if (el.shape === "ellipse")
return `<ellipse cx="${n(w / 2)}" cy="${n(h / 2)}" rx="${n(Math.max(0, w / 2))}" ry="${n(Math.max(0, h / 2))}" style="${style}"/>`;
if (el.shape === "roundrect") return `<path d="${roundRectPath(w, h)}" style="${style}"/>`;
const pts = polygon(el.shape, w, h)!;
return `<polygon points="${pts.map((p) => `${n(p[0])},${n(p[1])}`).join(" ")}" style="${style}"/>`;
}
/** Arrowhead at p pointing along angle (radians). */
function arrowHead(kind: Arrow, p: Point, angle: number, width: number, color: string): string {
if (kind === "none") return "";
const size = 6 + width * 2.5;
const at = (dx: number, dy: number): string => {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return `${n(p[0] + dx * cos - dy * sin)},${n(p[1] + dx * sin + dy * cos)}`;
};
switch (kind) {
case "arrow":
return `<polyline points="${at(-size, -size * 0.6)} ${at(0, 0)} ${at(-size, size * 0.6)}" style="fill:none;stroke:${color};stroke-width:${n(width)};stroke-linecap:round;stroke-linejoin:round"/>`;
case "triangle":
return `<polygon points="${at(0, 0)} ${at(-size, -size * 0.55)} ${at(-size, size * 0.55)}" style="fill:${color};stroke:${color};stroke-width:${n(width)};stroke-linejoin:round"/>`;
case "circle": {
const [cx, cy] = at(-size * 0.45, 0)
.split(",")
.map(Number);
return `<circle cx="${cx}" cy="${cy}" r="${n(size * 0.45)}" style="fill:${color}"/>`;
}
case "diamond":
return `<polygon points="${at(0, 0)} ${at(-size * 0.6, -size * 0.45)} ${at(-size * 1.2, 0)} ${at(-size * 0.6, size * 0.45)}" style="fill:${color}"/>`;
}
}
export interface ConnectorStyle {
id: string;
stroke: Color;
strokeWidth: number;
strokeStyle: StrokeStyle;
startArrow: Arrow;
endArrow: Arrow;
rough: boolean;
}
/** A connector's line and arrowheads, in canvas units. */
export function connectorSVG(c: ConnectorStyle, r: Route, paint: Paint): string {
const color = c.strokeStyle === "none" ? paint("gray", "line") : paint(c.stroke, "line");
const w = c.strokeWidth;
let line: string;
if (c.rough) {
const gen = rough.generator();
const d = gen.toPaths(gen.path(r.d, { seed: seedOf(c.id), roughness: 1, strokeWidth: w, stroke: "#000" }));
line = d.map((p) => `<path d="${p.d}" style="fill:none;stroke:${color};stroke-width:${n(w)}"/>`).join("");
} else {
line = `<path d="${r.d}" style="fill:none;stroke:${color};stroke-width:${n(w)};stroke-linecap:round;stroke-linejoin:round;${dash(c.strokeStyle, w)}"/>`;
}
const last = r.points[r.points.length - 1]!;
return (
line +
arrowHead(c.startArrow, r.points[0]!, r.startAngle, w, color) +
arrowHead(c.endArrow, last, r.endAngle, w, color)
);
}
/** A pen stroke's outline as an SVG path, relative to the element's corner. */
export function brushPath(points: number[][], size: number): string {
const outline = getStroke(points, {
size,
thinning: 0.55,
smoothing: 0.5,
streamline: 0.4,
simulatePressure: points.every((p) => p[2] === 0.5),
last: true,
});
if (!outline.length) return "";
const avg = (a: number, b: number) => (a + b) / 2;
let d = `M${n(outline[0]![0]!)} ${n(outline[0]![1]!)} Q`;
for (let i = 0; i < outline.length; i++) {
const [x0, y0] = outline[i]!;
const [x1, y1] = outline[(i + 1) % outline.length]!;
d += `${n(x0!)} ${n(y0!)} ${n(avg(x0!, x1!))} ${n(avg(y0!, y1!))} `;
}
return d + "Z";
}
export function brushSVG(el: BrushElement, paint: Paint): string {
return `<path d="${brushPath(el.points, el.size)}" style="fill:${paint(el.color, "line")};stroke:none"/>`;
}
+458
View File
@@ -0,0 +1,458 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// The canvas's live data in the page's Y.Doc (ADR-14):
// ydoc.getMap("surface") → id → Y.Map of the element's fields. A note's body
// is a Y.XmlFragment under "body"; a mind map's nodes a Y.Map under "nodes".
// Every edit runs in one transaction with CANVAS_ORIGIN, tracked by the
// canvas's undo manager.
import * as Y from "yjs";
import {
PAGE_NOTE_ID,
PAGE_NOTE_WIDTH,
newId,
normalize,
type CanvasElement,
type End,
type MindmapNode,
} from "./model";
import { fragmentToJSON, writeJSON, type PMNode } from "./yxml";
/** The transaction origin of canvas edits; the canvas's undo manager tracks it. */
export const CANVAS_ORIGIN = "docwell-canvas";
export const surfaceOf = (doc: Y.Doc) => doc.getMap<Y.Map<unknown>>("surface");
/** An element as copied, pasted or stored in JSON: its fields plus a note's body. */
export type ElementJSON = Record<string, unknown> & { id: string; type: string; body?: PMNode[] };
type YItem = Y.Map<unknown>;
/** Reads a stored element; nested types (a note body) are left out, a mind map's nodes read as JSON. */
function read(m: YItem): CanvasElement | null {
const raw: Record<string, unknown> = {};
for (const [k, v] of m.entries()) {
if (v instanceof Y.Map) raw[k] = v.toJSON();
else if (!(v instanceof Y.AbstractType)) raw[k] = v;
}
return normalize(raw);
}
/** Frames first (always underneath), then by index, then by id so every client agrees. */
export function zOrder(a: CanvasElement, b: CanvasElement): number {
const fa = a.type === "frame" ? 0 : 1;
const fb = b.type === "frame" ? 0 : 1;
return fa - fb || a.index - b.index || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
}
/** The page's note as it is drawn before anyone moved it. */
export function defaultPageNote(): CanvasElement {
return normalize({
id: PAGE_NOTE_ID,
type: "note",
page: true,
background: "paper",
x: 0,
y: 0,
w: PAGE_NOTE_WIDTH,
h: 400,
index: 0,
})!;
}
export class SurfaceStore {
readonly map: Y.Map<YItem>;
readonly undo: Y.UndoManager | null;
private cache: CanvasElement[] | null = null;
private byId = new Map<string, CanvasElement>();
private listeners = new Set<(changed: Set<string> | null) => void>();
private readonly observer = (events: Y.YEvent<Y.AbstractType<unknown>>[]) => {
this.cache = null;
// Which elements changed; null means the list itself changed.
let changed: Set<string> | null = new Set();
for (const ev of events) {
if (ev.target === this.map) {
changed = null;
break;
}
let t: Y.AbstractType<unknown> | null = ev.target;
while (t && t.parent !== this.map) t = t.parent as Y.AbstractType<unknown> | null;
const key = t && (t as unknown as { _item?: { parentSub?: string } })._item?.parentSub;
if (key) changed.add(key);
}
for (const fn of this.listeners) fn(changed);
};
constructor(
readonly doc: Y.Doc,
opts: { undo?: boolean } = {},
) {
this.map = surfaceOf(doc);
this.map.observeDeep(this.observer);
this.undo =
opts.undo === false
? null
: new Y.UndoManager(this.map, { trackedOrigins: new Set([CANVAS_ORIGIN]), captureTimeout: 400 });
}
destroy(): void {
this.map.unobserveDeep(this.observer);
this.undo?.destroy();
this.listeners.clear();
}
/** Calls fn after each change with the ids that changed, or null when elements came or went. */
onChange(fn: (changed: Set<string> | null) => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
/** Every element in drawing order, the page's note included. */
elements(): CanvasElement[] {
if (this.cache) return this.cache;
const list: CanvasElement[] = [];
for (const [id, m] of this.map.entries()) {
const el = m instanceof Y.Map ? read(m) : null;
if (el) list.push({ ...el, id });
}
if (!list.some((e) => e.type === "note" && e.page)) list.push(defaultPageNote());
list.sort(zOrder);
this.cache = list;
this.byId = new Map(list.map((e) => [e.id, e]));
return list;
}
get(id: string): CanvasElement | undefined {
this.elements();
return this.byId.get(id);
}
/** Whether the canvas has anything besides an unmoved page note. */
get isEmpty(): boolean {
return this.map.size === 0;
}
/** A note's body, made on first use (not for the page's note). */
body(id: string): Y.XmlFragment | null {
const m = this.map.get(id);
if (!(m instanceof Y.Map)) return null;
const b = m.get("body");
return b instanceof Y.XmlFragment ? b : null;
}
/** A mind map's nodes map. */
nodes(id: string): Y.Map<YItem> | null {
const n = this.map.get(id)?.get("nodes");
return n instanceof Y.Map ? (n as Y.Map<YItem>) : null;
}
transact(fn: () => void): void {
this.doc.transact(fn, CANVAS_ORIGIN);
}
private nextIndex(): number {
let max = 0;
for (const e of this.elements()) if (e.type !== "frame") max = Math.max(max, e.index);
return max + 1;
}
/** Writes the page's note at its default place, so it can be changed like any other element. */
private ensure(id: string): YItem | null {
const m = this.map.get(id);
if (m instanceof Y.Map) return m;
if (id !== PAGE_NOTE_ID) return null;
const note = this.get(id)!;
const y = new Y.Map<unknown>();
this.map.set(id, y);
for (const [k, v] of Object.entries(note)) if (k !== "id") y.set(k, v);
return y;
}
/** Adds an element; returns its id. Notes get an empty body, mind maps a root. */
add(fields: Partial<CanvasElement> & { type: CanvasElement["type"] }, body?: PMNode[]): string {
const id = fields.id || newId();
this.transact(() => {
const m = new Y.Map<unknown>();
this.map.set(id, m);
const { nodes, ...rest } = fields as Record<string, unknown> & { nodes?: Record<string, MindmapNode> };
for (const [k, v] of Object.entries(rest)) if (k !== "id" && v !== undefined) m.set(k, v);
if (!("index" in rest)) m.set("index", fields.type === "frame" ? -this.nextIndex() : this.nextIndex());
if (fields.type === "note" && !(fields as { page?: boolean }).page) {
const frag = new Y.XmlFragment();
m.set("body", frag);
writeJSON(frag, body?.length ? body : [{ type: "paragraph" }]);
}
if (fields.type === "mindmap") {
const n = new Y.Map<YItem>();
m.set("nodes", n);
const list = nodes && Object.keys(nodes).length ? nodes : { [newId()]: { text: "", parent: "", pos: 0 } };
for (const [nid, node] of Object.entries(list)) n.set(nid, nodeToY(node));
}
});
return id;
}
/** Changes fields of one element; undefined removes a field. */
update(id: string, patch: Record<string, unknown>): void {
this.updateMany([[id, patch]]);
}
updateMany(patches: [string, Record<string, unknown>][]): void {
if (!patches.length) return;
this.transact(() => {
for (const [id, patch] of patches) {
const m = this.ensure(id);
if (!m) continue;
for (const [k, v] of Object.entries(patch)) {
if (k === "id" || k === "type" || k === "body" || k === "nodes") continue;
if (v === undefined) m.delete(k);
else if (!sameValue(m.get(k), v)) m.set(k, v);
}
}
});
}
/**
* Deletes elements with their group members. Connectors stuck to a
* deleted element keep their end where it was.
*/
remove(ids: Iterable<string>): void {
const all = this.elements();
const gone = new Set<string>();
for (const id of ids) {
gone.add(id);
for (const e of all) if (e.group === id) gone.add(e.id);
}
// The page's note cannot be deleted: it is the page.
gone.delete(PAGE_NOTE_ID);
for (const e of all) if (e.type === "note" && e.page) gone.delete(e.id);
if (!gone.size) return;
this.transact(() => {
for (const e of all) {
if (e.type !== "connector" || gone.has(e.id)) continue;
for (const side of ["source", "target"] as const) {
const end = e[side];
if (end.id && gone.has(end.id)) {
const at = this.endPoint(end);
this.map.get(e.id)?.set(side, { x: at[0], y: at[1] });
}
}
}
for (const id of gone) this.map.delete(id);
// Groups left with fewer than two members dissolve.
const left = this.elements();
for (const g of left.filter((e) => e.type === "group")) {
const members = left.filter((e) => e.group === g.id);
if (members.length < 2) {
for (const m of members) this.map.get(m.id)?.delete("group");
this.map.delete(g.id);
}
}
});
}
/** Where an end attached to an element is, for when the element goes away. */
private endPoint(end: End): [number, number] {
const el = end.id ? this.get(end.id) : undefined;
if (!el) return [end.x ?? 0, end.y ?? 0];
const [px, py] = end.pos ?? [0.5, 0.5];
return [el.x + el.w * px, el.y + el.h * py];
}
/** Moves elements to the top or bottom of the drawing order, keeping their own order. */
reorder(ids: string[], to: "front" | "back" | "forward" | "backward"): void {
const all = this.elements().filter((e) => e.type !== "frame");
const chosen = new Set(ids);
const picked = all.filter((e) => chosen.has(e.id));
if (!picked.length) return;
const rest = all.filter((e) => !chosen.has(e.id));
let order: CanvasElement[];
if (to === "front") order = [...rest, ...picked];
else if (to === "back") order = [...picked, ...rest];
else {
// One step: past the next (or previous) element that is not chosen.
order = [...all];
const step = to === "forward" ? 1 : -1;
const idx = (e: CanvasElement) => order.indexOf(e);
const list = step === 1 ? [...picked].reverse() : picked;
for (const e of list) {
const i = idx(e);
const j = i + step;
if (j < 0 || j >= order.length || chosen.has(order[j]!.id)) continue;
[order[i], order[j]] = [order[j]!, order[i]!];
}
}
this.updateMany(
order
.map((e, i) => [e.id, { index: i + 1 }] as [string, Record<string, unknown>])
.filter(([id, p]) => this.get(id)?.index !== p.index),
);
}
/** Puts elements in a new group; returns its id. */
groupOf(ids: string[]): string | null {
const members = ids.filter((id) => {
const e = this.get(id);
return e && e.type !== "group" && !(e.type === "note" && e.page);
});
if (members.length < 2) return null;
const gid = newId();
this.transact(() => {
const g = new Y.Map<unknown>();
this.map.set(gid, g);
g.set("type", "group");
g.set("index", this.nextIndex());
for (const id of members) this.ensure(id)?.set("group", gid);
});
return gid;
}
ungroup(groupId: string): string[] {
const members = this.elements()
.filter((e) => e.group === groupId)
.map((e) => e.id);
this.transact(() => {
for (const id of members) this.map.get(id)?.delete("group");
this.map.delete(groupId);
});
return members;
}
// ---- Mind maps ----
addNode(mapId: string, parent: string, pos: number, text = ""): string {
const id = newId();
this.transact(() => this.nodes(mapId)?.set(id, nodeToY({ text, parent, pos })));
return id;
}
updateNode(mapId: string, nodeId: string, patch: Partial<MindmapNode>): void {
this.transact(() => {
const n = this.nodes(mapId)?.get(nodeId);
if (!n) return;
for (const [k, v] of Object.entries(patch)) if (n.get(k) !== v) n.set(k, v);
});
}
/** Removes a node and its branch. Removing the root removes the map. */
removeNode(mapId: string, nodeId: string): void {
const el = this.get(mapId);
if (el?.type !== "mindmap") return;
const root = Object.entries(el.nodes).find(([, n]) => !n.parent)?.[0];
if (nodeId === root) {
this.remove([mapId]);
return;
}
const gone = new Set([nodeId]);
let grew = true;
while (grew) {
grew = false;
for (const [id, n] of Object.entries(el.nodes)) {
if (!gone.has(id) && gone.has(n.parent)) {
gone.add(id);
grew = true;
}
}
}
this.transact(() => {
const nodes = this.nodes(mapId);
for (const id of gone) nodes?.delete(id);
});
}
// ---- JSON: copy, paste, templates, read-only snapshots ----
/** Elements as JSON (with group members and note bodies), for copying. */
toJSON(ids?: Iterable<string>): ElementJSON[] {
const all = this.elements();
let chosen: Set<string>;
if (ids) {
chosen = new Set(ids);
for (const e of all) if (chosen.has(e.group)) chosen.add(e.id);
} else chosen = new Set(all.map((e) => e.id));
return all
.filter((e) => chosen.has(e.id))
.map((e) => {
const out: ElementJSON = { ...(e as unknown as Record<string, unknown>), id: e.id, type: e.type };
const body = e.type === "note" && !e.page ? this.body(e.id) : null;
if (body) out.body = fragmentToJSON(body);
return out;
});
}
/**
* Adds copies of elements, moved by dx, dy, with new ids; connectors, groups
* and mind maps keep pointing at the copies. The page's note is never copied.
* Returns the new ids, in order.
*/
insertJSON(list: ElementJSON[], dx = 0, dy = 0): string[] {
const items = list.filter((e) => e && typeof e === "object" && !(e.type === "note" && e.page));
const ids = new Map(items.map((e) => [String(e.id), newId()]));
const out: string[] = [];
let index = this.nextIndex();
this.transact(() => {
for (const raw of items) {
const el = normalize(raw);
if (!el) continue;
const id = ids.get(String(raw.id))!;
const fields: Record<string, unknown> = { ...(el as unknown as Record<string, unknown>) };
delete fields.id;
fields.x = el.x + dx;
fields.y = el.y + dy;
fields.index = el.type === "frame" ? -index++ : index++;
fields.group = el.group && ids.has(el.group) ? ids.get(el.group) : undefined;
if (el.type === "connector") {
for (const side of ["source", "target"] as const) {
const end = el[side];
if (end.id && ids.has(end.id)) fields[side] = { id: ids.get(end.id), ...(end.pos ? { pos: end.pos } : {}) };
else if (end.id) {
// The other end was not copied: it becomes a free point near where it was.
const at = this.endPoint(end);
fields[side] = { x: at[0] + dx, y: at[1] + dy };
} else fields[side] = { x: (end.x ?? 0) + dx, y: (end.y ?? 0) + dy };
}
}
for (const k of Object.keys(fields)) if (fields[k] === undefined || fields[k] === "") delete fields[k];
this.add(
{ ...(fields as Partial<CanvasElement>), id, type: el.type },
Array.isArray(raw.body) ? raw.body : undefined,
);
out.push(id);
}
});
return out;
}
/** Replaces the whole canvas with a JSON snapshot (read-only views of a share link or the phone). */
load(list: ElementJSON[]): void {
this.transact(() => {
for (const k of [...this.map.keys()]) this.map.delete(k);
for (const raw of list) {
const el = normalize(raw);
if (!el || !raw.id) continue;
const fields: Record<string, unknown> = { ...(el as unknown as Record<string, unknown>) };
const id = String(raw.id);
delete fields.id;
for (const k of Object.keys(fields)) if (fields[k] === "") delete fields[k];
this.add(
{ ...(fields as Partial<CanvasElement>), id, type: el.type },
Array.isArray(raw.body) ? raw.body : undefined,
);
}
});
}
}
function nodeToY(n: MindmapNode): YItem {
const m = new Y.Map<unknown>();
m.set("text", n.text);
m.set("parent", n.parent);
m.set("pos", n.pos);
return m;
}
function sameValue(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
return JSON.stringify(a) === JSON.stringify(b);
}
+675
View File
@@ -0,0 +1,675 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// The canvas's controls: the tool bar at the bottom, the zoom buttons, and
// the style bar over the selection. Plain DOM, like the database block, so
// the phone's editor page can use the same canvas without Vue.
import { iconPaths, type IconName } from "@docwell/ui/icons";
import {
arrowKinds,
connectorModes,
mindmapLayouts,
palette,
shapeKinds,
type CanvasElement,
type Color,
} from "./model";
import { stickers, templates, type TemplateId } from "./library";
import type { CanvasView, Tool } from "./view";
const icon = (name: IconName, size = 18) =>
`<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${iconPaths[name].map((d) => `<path d="${d}"/>`).join("")}</svg>`;
const shapeIcons: Record<string, string> = {
rect: '<rect x="4" y="6" width="16" height="12"/>',
roundrect: '<rect x="4" y="6" width="16" height="12" rx="4"/>',
ellipse: '<ellipse cx="12" cy="12" rx="8" ry="6"/>',
diamond: '<path d="M12 4l8 8-8 8-8-8z"/>',
triangle: '<path d="M12 5l8 14H4z"/>',
straight: '<path d="M5 19L19 5"/>',
curve: '<path d="M5 19C5 9 19 15 19 5"/>',
elbow: '<path d="M5 19v-7h14V5"/>',
none: '<path d="M5 12h14"/>',
arrow: '<path d="M5 12h14M14 7l5 5-5 5"/>',
triangleEnd: '<path d="M5 12h10"/><path d="M14 7l6 5-6 5z" fill="currentColor"/>',
circle: '<path d="M5 12h10"/><circle cx="17" cy="12" r="3" fill="currentColor"/>',
diamondEnd: '<path d="M5 12h8"/><path d="M17 8l4 4-4 4-4-4z" fill="currentColor"/>',
solid: '<path d="M4 12h16"/>',
dash: '<path d="M4 12h4M10 12h4M16 12h4"/>',
noLine: '<path d="M4 12h16" stroke-opacity=".3"/><path d="M6 6l12 12"/>',
right:
'<rect x="3" y="10" width="6" height="4"/><path d="M9 12h3M12 7v10M12 7h3M12 17h3M12 12h3"/><rect x="15" y="5" width="6" height="4"/><rect x="15" y="15" width="6" height="4"/>',
left: '<rect x="15" y="10" width="6" height="4"/><path d="M15 12h-3M12 7v10M12 7H9M12 17H9M12 12H9"/><rect x="3" y="5" width="6" height="4"/><rect x="3" y="15" width="6" height="4"/>',
radial:
'<rect x="9" y="10" width="6" height="4"/><path d="M9 12H6M15 12h3"/><rect x="1" y="10" width="5" height="4"/><rect x="18" y="10" width="5" height="4"/>',
};
const drawn = (key: string) =>
`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${shapeIcons[key] ?? ""}</svg>`;
function swatchStyle(c: Color): string {
if (c === "none") return "background:transparent";
if (c === "ink") return "background:var(--dw-ink)";
if (c === "paper") return "background:var(--dw-surface)";
return `background:var(--dw-c-${c})`;
}
export class CanvasUI {
private readonly bar: HTMLElement;
private readonly zoomBox: HTMLElement;
private readonly props: HTMLElement;
private readonly zoomLabel: HTMLButtonElement;
private pop: HTMLElement | null = null;
private popFor = "";
private readonly fileInput: HTMLInputElement;
private lastProps = "";
private readonly closePop = (e: PointerEvent) => {
if (this.pop && !this.pop.contains(e.target as Node) && !(e.target as Element).closest?.("[data-pop]"))
this.hidePop();
};
constructor(private readonly v: CanvasView) {
const root = v.root;
this.bar = this.div("dw-cv-ui dw-cv-toolbar");
this.bar.setAttribute("role", "toolbar");
this.bar.setAttribute("aria-label", v.labels.toolbar);
this.zoomBox = this.div("dw-cv-ui dw-cv-zoom");
this.props = this.div("dw-cv-ui dw-cv-props");
this.props.setAttribute("role", "toolbar");
this.zoomLabel = document.createElement("button");
this.fileInput = document.createElement("input");
this.fileInput.type = "file";
this.fileInput.accept = "image/*";
this.fileInput.multiple = true;
this.fileInput.hidden = true;
this.fileInput.addEventListener("change", () => {
const files = [...(this.fileInput.files ?? [])];
this.fileInput.value = "";
if (files.length) void v.addImages(files);
});
root.append(this.bar, this.zoomBox, this.props, this.fileInput);
document.addEventListener("pointerdown", this.closePop, true);
this.buildZoom();
this.refresh();
}
destroy(): void {
document.removeEventListener("pointerdown", this.closePop, true);
}
private div(cls: string): HTMLElement {
const d = document.createElement("div");
d.className = cls;
return d;
}
private button(
html: string,
label: string,
run: () => void,
opts: { active?: boolean; pop?: string; cls?: string } = {},
): HTMLButtonElement {
const b = document.createElement("button");
b.type = "button";
b.className = `dw-cv-btn${opts.cls ? ` ${opts.cls}` : ""}`;
b.innerHTML = html;
b.title = label;
b.setAttribute("aria-label", label);
if (opts.active !== undefined) b.setAttribute("aria-pressed", String(opts.active));
if (opts.pop) b.dataset.pop = opts.pop;
b.addEventListener("pointerdown", (e) => e.stopPropagation());
b.addEventListener("click", (e) => {
e.stopPropagation();
run();
});
return b;
}
// ---- Tool bar ----
private buildBar(): void {
const v = this.v;
const l = v.labels;
this.bar.replaceChildren();
this.bar.hidden = v.isPresenting;
if (!v.editable) {
this.bar.append(
this.button(icon("cursor"), l.select, () => v.setTool("select"), { active: v.tool === "select" }),
this.button(icon("hand"), l.hand, () => v.setTool("hand"), { active: v.tool === "hand" }),
this.sep(),
this.button(icon("present"), l.present, () => v.present()),
);
return;
}
const tool = (t: Tool, name: IconName, label: string) =>
this.button(icon(name), label, () => v.setTool(t), { active: v.tool === t });
const shapeBtn = this.button(
drawn(v.shapeKind),
l.shape,
() => {
v.setTool("shape");
this.togglePop("shape", shapeBtn, () => this.shapePop());
},
{ active: v.tool === "shape", pop: "shape" },
);
const penBtn = this.button(
icon("pen"),
l.pen,
() => {
v.setTool("pen");
this.togglePop("pen", penBtn, () => this.penPop());
},
{ active: v.tool === "pen", pop: "pen" },
);
const conBtn = this.button(
icon("connector"),
l.connector,
() => {
v.setTool("connector");
this.togglePop("connector", conBtn, () => this.connectorPop());
},
{ active: v.tool === "connector", pop: "connector" },
);
const libBtn = this.button(
icon("sticker"),
l.library,
() => this.togglePop("library", libBtn, () => this.libraryPop()),
{
pop: "library",
},
);
this.bar.append(
tool("select", "cursor", l.select),
tool("hand", "hand", l.hand),
this.sep(),
tool("note", "note", l.note),
tool("text", "type", l.text),
shapeBtn,
conBtn,
penBtn,
tool("eraser", "eraser", l.eraser),
tool("frame", "frame", l.frame),
tool("mindmap", "mindmap", l.mindmap),
this.button(icon("image"), l.image, () => this.pickImage()),
this.button(icon("link"), l.link, () => void v.addLink()),
libBtn,
this.sep(),
this.button(icon("present"), l.present, () => v.present()),
);
}
private sep(): HTMLElement {
return this.div("dw-cv-sep");
}
pickImage(): void {
if (this.v.editable && this.v.opts.files?.upload) this.fileInput.click();
}
// ---- Pop-up panels ----
private togglePop(id: string, anchor: HTMLElement, build: () => HTMLElement): void {
if (this.pop && this.popFor === id) return this.hidePop();
this.hidePop();
const p = build();
p.classList.add("dw-cv-ui", "dw-cv-pop");
p.addEventListener("pointerdown", (e) => e.stopPropagation());
this.v.root.append(p);
this.pop = p;
this.popFor = id;
// Above the anchor, kept inside the canvas.
const r = this.v.root.getBoundingClientRect();
const a = anchor.getBoundingClientRect();
const w = p.offsetWidth;
const h = p.offsetHeight;
let x = a.left - r.left + a.width / 2 - w / 2;
x = Math.max(8, Math.min(r.width - w - 8, x));
let y = a.top - r.top - h - 8;
if (y < 8) y = a.bottom - r.top + 8;
p.style.left = `${x}px`;
p.style.top = `${y}px`;
}
private hidePop(): void {
this.pop?.remove();
this.pop = null;
this.popFor = "";
}
private row(...children: HTMLElement[]): HTMLElement {
const r = this.div("dw-cv-row");
r.append(...children);
return r;
}
private colorRow(current: Color, pick: (c: Color) => void, withNone: boolean, title: string): HTMLElement {
const r = this.div("dw-cv-row dw-cv-colors");
r.setAttribute("role", "group");
r.setAttribute("aria-label", title);
const l = this.v.labels;
const list: Color[] = ["ink", ...palette, ...(withNone ? (["paper", "none"] as Color[]) : [])];
for (const c of list) {
const name =
c === "ink" ? l.colorInk : c === "paper" ? l.colorPaper : c === "none" ? l.colorNone : (l.colors[c] ?? c);
const b = this.button(
`<span class="dw-cv-swatch${c === "none" ? " dw-cv-swatch-none" : ""}" style="${swatchStyle(c)}"></span>`,
name,
() => {
pick(c);
this.lastProps = "";
this.refresh();
},
{ active: c === current },
);
r.append(b);
}
return r;
}
private shapePop(): HTMLElement {
const v = this.v;
const l = v.labels;
const p = this.div("");
p.append(
this.row(
...shapeKinds.map((k) =>
this.button(
drawn(k),
l[k],
() => {
v.setShapeKind(k);
this.hidePop();
},
{ active: v.shapeKind === k },
),
),
),
this.row(
this.button(
`<span class="dw-cv-word">${l.general}</span>`,
l.general,
() => {
v.setStyle("shape", { rough: false });
this.hidePop();
},
{ active: !v.styles.shape.rough },
),
this.button(
`<span class="dw-cv-word dw-cv-scribble">${l.scribbled}</span>`,
l.scribbled,
() => {
v.setStyle("shape", { rough: true });
this.hidePop();
},
{ active: v.styles.shape.rough },
),
),
);
return p;
}
private penPop(): HTMLElement {
const v = this.v;
const p = this.div("");
p.append(
this.colorRow(v.styles.brush.color, (c) => v.setStyle("brush", { color: c }), false, v.labels.stroke),
this.row(
...[2, 4, 8, 14].map((s) =>
this.button(
`<span class="dw-cv-dot" style="width:${s + 2}px;height:${s + 2}px"></span>`,
`${v.labels.thickness} ${s}`,
() => {
v.setStyle("brush", { size: s });
this.hidePop();
},
{ active: v.styles.brush.size === s },
),
),
),
);
return p;
}
private connectorPop(): HTMLElement {
const v = this.v;
const p = this.div("");
p.append(
this.row(
...connectorModes.map((m) =>
this.button(
drawn(m),
v.labels[m],
() => {
v.setStyle("connector", { mode: m });
this.hidePop();
},
{ active: v.styles.connector.mode === m },
),
),
),
);
return p;
}
private libraryPop(): HTMLElement {
const v = this.v;
const l = v.labels;
const p = this.div("dw-cv-library");
const h1 = this.div("dw-cv-poptitle");
h1.textContent = l.stickers;
const grid = this.div("dw-cv-stickers");
for (const s of stickers) {
grid.append(
this.button(`<span class="dw-cv-emoji">${s}</span>`, s, () => {
v.insertSticker(s);
this.hidePop();
}),
);
}
const h2 = this.div("dw-cv-poptitle");
h2.textContent = l.templates;
const list = this.div("dw-cv-templates");
const names: Record<TemplateId, string> = {
kanban: l.templateKanban,
swot: l.templateSwot,
flow: l.templateFlow,
brainstorm: l.templateBrainstorm,
retro: l.templateRetro,
};
for (const t of templates) {
const b = this.button(
`<span class="dw-cv-word">${names[t]}</span>`,
names[t],
() => {
v.insertTemplate(t);
this.hidePop();
},
{ cls: "dw-cv-wide" },
);
list.append(b);
}
p.append(h1, grid, h2, list);
return p;
}
// ---- Zoom ----
private buildZoom(): void {
const v = this.v;
const l = v.labels;
this.zoomLabel.type = "button";
this.zoomLabel.className = "dw-cv-btn dw-cv-zoomlabel";
this.zoomLabel.title = l.zoomReset;
this.zoomLabel.addEventListener("pointerdown", (e) => e.stopPropagation());
this.zoomLabel.addEventListener("click", () => v.zoomAt(1));
this.zoomBox.append(
this.button(icon("zoom-out"), l.zoomOut, () => v.zoomBy(0.8)),
this.zoomLabel,
this.button(icon("zoom-in"), l.zoomIn, () => v.zoomBy(1.25)),
this.button(icon("fit"), l.zoomFit, () => v.fit()),
);
}
zoomChanged(): void {
this.zoomLabel.textContent = `${Math.round(this.v.zoom * 100)}%`;
}
// ---- The style bar over the selection ----
refresh(): void {
this.buildBar();
const sel = this.v.editable && !this.v.editing && !this.v.isPresenting ? this.v.selection() : [];
const key = JSON.stringify([sel, this.v.activeNode, this.v.styles.shape.rough]);
if (key !== this.lastProps) {
this.lastProps = key;
this.buildProps(sel);
}
this.place();
}
place(): void {
const p = this.props;
if (p.hidden) return;
const b = this.v.selectionScreenBox();
if (!b) {
p.hidden = true;
return;
}
const r = this.v.root.getBoundingClientRect();
const w = p.offsetWidth;
const h = p.offsetHeight;
let x = b.x + b.w / 2 - w / 2;
x = Math.max(8, Math.min(r.width - w - 8, x));
let y = b.y - h - 40;
if (y < 8) y = Math.min(r.height - h - 64, b.y + b.h + 16);
p.style.left = `${x}px`;
p.style.top = `${Math.max(8, y)}px`;
}
private buildProps(sel: CanvasElement[]): void {
const p = this.props;
p.replaceChildren();
if (!sel.length) {
p.hidden = true;
return;
}
p.hidden = false;
const v = this.v;
const l = v.labels;
const types = new Set(sel.map((e) => e.type));
const one = types.size === 1 ? sel[0]! : null;
const group: HTMLElement[] = [];
const menu = (id: string, html: string, label: string, build: () => HTMLElement) => {
const b: HTMLButtonElement = this.button(html, label, () => this.togglePop(id, b, build), { pop: id });
group.push(b);
};
const colorMenu = (id: string, label: string, current: Color, field: string, withNone: boolean) =>
menu(
id,
`<span class="dw-cv-swatch${current === "none" ? " dw-cv-swatch-none" : ""}" style="${swatchStyle(current)}"></span>`,
label,
() => {
const d = this.div("");
d.append(this.colorRow(current, (c) => v.restyle({ [field]: c }), withNone, label));
return d;
},
);
const choice = <T extends string>(
id: string,
label: string,
current: T,
list: readonly T[],
art: (x: T) => string,
field: string,
names: (x: T) => string,
parse: (x: T) => unknown = (x) => x,
) =>
menu(id, art(current), label, () => {
const d = this.div("");
d.append(
this.row(
...list.map((x) =>
this.button(
art(x),
names(x),
() => {
v.restyle({ [field]: parse(x) });
this.hidePop();
this.lastProps = "";
this.refresh();
},
{ active: x === current },
),
),
),
);
return d;
});
const toggle = (html: string, label: string, on: boolean, run: () => void) =>
group.push(this.button(html, label, run, { active: on }));
if (one?.type === "shape") {
choice("kind", l.shape, one.shape, shapeKinds, drawn, "shape", (k) => l[k]);
colorMenu("fill", l.fill, one.fill, "fill", true);
colorMenu("stroke", l.stroke, one.stroke, "stroke", true);
choice(
"style",
l.lineStyle,
one.strokeStyle,
["solid", "dash", "none"] as const,
(s) => drawn(s === "none" ? "noLine" : s),
"strokeStyle",
(s) => (s === "none" ? l.noLine : l[s]),
);
choice(
"width",
l.thickness,
String(one.strokeWidth) as "2",
["1", "2", "4", "6"] as const,
(s) => `<span class="dw-cv-bar" style="height:${Number(s) + 1}px"></span>`,
"strokeWidth",
(s) => `${l.thickness} ${s}`,
Number,
);
toggle(`<span class="dw-cv-word dw-cv-scribble">${l.scribbled}</span>`, l.scribbled, one.rough, () => {
v.restyle({ rough: !one.rough });
this.lastProps = "";
this.refresh();
});
colorMenu("textColor", l.textColor, one.textColor, "textColor", false);
} else if (one?.type === "connector") {
choice("mode", l.connector, one.mode, connectorModes, drawn, "mode", (m) => l[m]);
colorMenu("stroke", l.stroke, one.stroke, "stroke", false);
choice(
"style",
l.lineStyle,
one.strokeStyle === "none" ? "solid" : one.strokeStyle,
["solid", "dash"] as const,
drawn,
"strokeStyle",
(s) => l[s],
);
const art = (a: string) => drawn(a === "triangle" ? "triangleEnd" : a === "diamond" ? "diamondEnd" : a);
choice(
"start",
l.startArrow,
one.startArrow,
arrowKinds,
(a) => `<span class="dw-cv-flip">${art(a)}</span>`,
"startArrow",
(a) => a,
);
choice("end", l.endArrow, one.endArrow, arrowKinds, art, "endArrow", (a) => a);
} else if (one?.type === "brush") {
colorMenu("color", l.stroke, one.color, "color", false);
} else if (one?.type === "text") {
colorMenu("color", l.textColor, one.color, "color", false);
choice(
"size",
l.fontSize,
String(one.fontSize) as "24",
["16", "24", "32", "48", "64"] as const,
(s) => `<span class="dw-cv-word">${s}</span>`,
"fontSize",
(s) => `${l.fontSize} ${s}`,
Number,
);
choice(
"font",
l.font,
one.font || "sans",
["sans", "serif", "mono"] as const,
(f) => `<span class="dw-cv-word dw-cv-font-${f}">Aa</span>`,
"font",
(f) => l[f],
(f) => (f === "sans" ? "" : f),
);
choice(
"align",
l.alignLeft,
one.align,
["left", "center", "right"] as const,
(a) => icon(`align-${a}` as IconName),
"align",
(a) => l[a === "left" ? "alignLeft" : a === "center" ? "alignCenter" : "alignRight"],
);
toggle(icon("bold"), l.bold, one.bold, () => {
v.restyle({ bold: !one.bold });
this.lastProps = "";
this.refresh();
});
} else if (one?.type === "note") {
colorMenu("bg", l.background, one.background, "background", true);
} else if (one?.type === "frame") {
colorMenu("bg", l.background, one.background, "background", true);
} else if (one?.type === "mindmap") {
choice(
"layout",
l.layout,
one.layout,
mindmapLayouts,
(x) => drawn(x),
"layout",
(x) => l[x === "right" ? "layoutRight" : x === "left" ? "layoutLeft" : "layoutRadial"],
);
colorMenu("color", l.stroke, one.color, "color", false);
if (v.activeNode?.map === one.id) {
group.push(
this.button(`<span class="dw-cv-word">+ ${l.addChild}</span>`, l.addChild, () => v.mindmapAdd("child"), {
cls: "dw-cv-wide",
}),
);
}
} else if (one?.type === "embed" && sel.length === 1) {
group.push(this.button(icon("open"), l.openLink, () => window.open(one.url, "_blank", "noopener,noreferrer")));
}
p.append(...group);
if (group.length) p.append(this.sep());
const groups = sel.filter((e) => e.type === "group");
if (sel.length > 1 && !groups.length) p.append(this.button(icon("group"), l.group, () => v.group()));
if (groups.length) p.append(this.button(icon("layers"), l.ungroup, () => v.ungroup()));
const pageOnly = sel.every((e) => e.type === "note" && e.page);
p.append(
this.button(icon("arrow-up"), l.bringFront, () => v.reorder("front")),
this.button(icon("send-back"), l.sendBack, () => v.reorder("back")),
);
if (!pageOnly) {
p.append(
this.button(icon("copy"), l.duplicate, () => v.duplicate()),
this.button(icon("trash"), l.delete, () => v.deleteSelection(), { cls: "dw-cv-danger" }),
);
}
}
// ---- Messages and presenting ----
toast(text: string): void {
const t = this.div("dw-cv-ui dw-cv-toast");
t.setAttribute("role", "status");
t.textContent = text;
this.v.root.append(t);
setTimeout(() => t.remove(), 2600);
}
presentBar(): HTMLElement {
const v = this.v;
const l = v.labels;
const bar = this.div("dw-cv-ui dw-cv-presentbar");
const step = this.div("dw-cv-step");
step.setAttribute("aria-live", "polite");
bar.append(
this.button(icon("chevron-left"), l.presentPrevious, () => v.presentStep(-1)),
step,
this.button(icon("chevron-right"), l.presentNext, () => v.presentStep(1)),
this.button(icon("close"), l.presentExit, () => v.stopPresenting()),
);
v.root.append(bar);
this.hidePop();
this.refresh();
return bar;
}
presentStep(i: number, total: number): void {
const s = this.v.root.querySelector(".dw-cv-step");
if (s) s.textContent = this.v.labels.presentStep.replace("{n}", String(i + 1)).replace("{total}", String(total));
}
}
File diff suppressed because it is too large. Load diff
+104
View File
@@ -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<string, unknown>;
content?: PMNode[];
text?: string;
marks?: { type: string; attrs?: Record<string, unknown> }[];
}
/** 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<string, unknown> }[]) {
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<string, unknown>) : {},
}));
}
out.push(node);
}
} else if (child instanceof Y.XmlElement) {
const node: PMNode = { type: child.nodeName };
const attrs = child.getAttributes() as Record<string, unknown>;
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<string, unknown> = {};
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;
}
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { defineConfig } from "vitest/config";
export default defineConfig({
test: { environment: "jsdom" },
});
+66 -63
View File
@@ -5,18 +5,18 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Docwell editor</title>
<script type="module" crossorigin>(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};function n(e){this.content=e}n.prototype={constructor:n,find:function(e){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===e)return t;return-1},get:function(e){var t=this.find(e);return t==-1?void 0:this.content[t+1]},update:function(e,t,r){var i=r&&r!=e?this.remove(r):this,a=i.find(e),o=i.content.slice();return a==-1?o.push(r||e,t):(o[a+1]=t,r&&(o[a]=r)),new n(o)},remove:function(e){var t=this.find(e);if(t==-1)return this;var r=this.content.slice();return r.splice(t,2),new n(r)},addToStart:function(e,t){return new n([e,t].concat(this.remove(e).content))},addToEnd:function(e,t){var r=this.remove(e).content.slice();return r.push(e,t),new n(r)},addBefore:function(e,t,r){var i=this.remove(t),a=i.content.slice(),o=i.find(e);return a.splice(o==-1?a.length:o,0,t,r),new n(a)},forEach:function(e){for(var t=0;t<this.content.length;t+=2)e(this.content[t],this.content[t+1])},prepend:function(e){return e=n.from(e),e.size?new n(e.content.concat(this.subtract(e).content)):this},append:function(e){return e=n.from(e),e.size?new n(this.subtract(e).content.concat(e.content)):this},subtract:function(e){var t=this;e=n.from(e);for(var r=0;r<e.content.length;r+=2)t=t.remove(e.content[r]);return t},toObject:function(){var e={};return this.forEach(function(t,n){e[t]=n}),e},get size(){return this.content.length>>1}},n.from=function(e){if(e instanceof n)return e;var t=[];if(e)for(var r in e)t.push(r,e[r]);return new n(t)};function r(e,t,n){for(let i=0;;i++){if(i==e.childCount||i==t.childCount)return e.childCount==t.childCount?null:n;let s=e.child(i),c=t.child(i);if(s==c)n+=s.nodeSize;else{if(!s.sameMarkup(c))return n;if(s.isText&&s.text!=c.text){let e=s.text,t=c.text,r=0;for(;e[r]==t[r];r++)n++;return r&&r<e.length&&r<t.length&&o(e.charCodeAt(r-1))&&a(e.charCodeAt(r))&&n--,n}if(s.content.size||c.content.size){let e=r(s.content,c.content,n+1);if(e!=null)return e}n+=s.nodeSize}}}function i(e,t,n,r){for(let s=e.childCount,c=t.childCount;;){if(s==0||c==0)return s==c?null:{a:n,b:r};let l=e.child(--s),u=t.child(--c),d=l.nodeSize;if(l==u)n-=d,r-=d;else{if(!l.sameMarkup(u))return{a:n,b:r};if(l.isText&&l.text!=u.text){let e=l.text,t=u.text,i=e.length,s=t.length;for(;i>0&&s>0&&e[i-1]==t[s-1];)i--,s--,n--,r--;return i&&s&&i<e.length&&o(e.charCodeAt(i-1))&&a(e.charCodeAt(i))&&(n++,r++),{a:n,b:r}}if(l.content.size||u.content.size){let e=i(l.content,u.content,n-1,r-1);if(e)return e}n-=d,r-=d}}}function a(e){return e>=56320&&e<57344}function o(e){return e>=55296&&e<56320}var s=class e{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let t=0;t<e.length;t++)this.size+=e[t].nodeSize}nodesBetween(e,t,n,r=0,i){for(let a=0,o=0;o<t;a++){let s=this.content[a],c=o+s.nodeSize;if(c>e&&n(s,r+o,i||null,a)!==!1&&s.content.size){let i=o+1;s.nodesBetween(Math.max(0,e-i),Math.min(s.content.size,t-i),n,r+i)}o=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let i=``,a=!0;return this.nodesBetween(e,t,(o,s)=>{let c=o.isText?o.text.slice(Math.max(e,s)-s,t-s):o.isLeaf?r?typeof r==`function`?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):``:``;o.isBlock&&(o.isLeaf&&c||o.isTextblock)&&n&&(a?a=!1:i+=n),i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);a<t.content.length;a++)i.push(t.content[a]);return new e(i,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],i=0;if(n>t)for(let e=0,a=0;a<n;e++){let o=this.content[e],s=a+o.nodeSize;s>t&&((a<t||s>n)&&(o=o.isText?o.cut(Math.max(0,t-a),Math.min(o.text.length,n-a)):o.cut(Math.max(0,t-a-1),Math.min(o.content.size,n-a-1))),r.push(o),i+=o.nodeSize),a=s}return new e(r,i)}cutByIndex(t,n){return t==n?e.empty:t==0&&n==this.content.length?this:new e(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new e(i,a)}addToStart(t){return new e([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new e(this.content.concat(t),this.size+t.nodeSize)}eq(Line truncated
`)}};pe.empty=new pe(!0);var me=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw SyntaxError(e+` (in content expression '`+this.string+`')`)}};function he(e){let t=[];do t.push(ge(e));while(e.eat(`|`));return t.length==1?t[0]:{type:`choice`,exprs:t}}function ge(e){let t=[];do t.push(_e(e));while(e.next&&e.next!=`)`&&e.next!=`|`);return t.length==1?t[0]:{type:`seq`,exprs:t}}function _e(e){let t=xe(e);for(;;)if(e.eat(`+`))t={type:`plus`,expr:t};else if(e.eat(`*`))t={type:`star`,expr:t};else if(e.eat(`?`))t={type:`opt`,expr:t};else if(e.eat(`{`))t=ye(e,t);else break;return t}function ve(e){/\D/.test(e.next)&&e.err(`Expected number, got '`+e.next+`'`);let t=Number(e.next);return e.pos++,t}function ye(e,t){let n=ve(e),r=n;return e.eat(`,`)&&(r=e.next==`}`?-1:ve(e)),e.eat(`}`)||e.err(`Unclosed braced range`),{type:`range`,min:n,max:r,expr:t}}function be(e,t){let n=e.nodeTypes,r=n[t];if(r)return[r];let i=[];for(let e in n){let r=n[e];r.isInGroup(t)&&i.push(r)}return i.length==0&&e.err(`No node type or group '`+t+`' found`),i}function xe(e){if(e.eat(`(`)){let t=he(e);return e.eat(`)`)||e.err(`Missing closing paren`),t}if(/\W/.test(e.next))e.err(`Unexpected token '`+e.next+`'`);else{let t=be(e,e.next).map(t=>(e.inline==null?e.inline=t.isInline:e.inline!=t.isInline&&e.err(`Mixing inline and block content`),{type:`name`,value:t}));return e.pos++,t.length==1?t[0]:{type:`choice`,exprs:t}}}function Se(e){let t=[[]];return i(a(e,0),n()),t;function n(){return t.push([])-1}function r(e,n,r){let i={term:r,to:n};return t[e].push(i),i}function i(e,t){e.forEach(e=>e.to=t)}function a(e,t){if(e.type==`choice`)return e.exprs.reduce((e,n)=>e.concat(a(n,t)),[]);if(e.type==`seq`)for(let r=0;;r++){let o=a(e.exprs[r],t);if(r==e.exprs.length-1)return o;i(o,t=n())}else if(e.type==`star`){let o=n();return r(t,o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`plus`){let o=n();return i(a(e.expr,t),o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`opt`)return[r(t)].concat(a(e.expr,t));else if(e.type==`range`){let o=t;for(let t=0;t<e.min;t++){let t=n();i(a(e.expr,o),t),o=t}if(e.max==-1)i(a(e.expr,o),o);else for(let t=e.min;t<e.max;t++){let t=n();r(o,t),i(a(e.expr,o),t),o=t}return[r(o)]}else if(e.type==`name`)return[r(t,void 0,e.value)];else throw Error(`Unknown expr type`)}}function Ce(e,t){return t-e}function we(e,t){let n=[];return r(t),n.sort(Ce);function r(t){let i=e[t];if(i.length==1&&!i[0].term)return r(i[0].to);n.push(t);for(let e=0;e<i.length;e++){let{term:t,to:a}=i[e];!t&&n.indexOf(a)==-1&&r(a)}}}function Te(e){let t=Object.create(null);return n(we(e,0));function n(r){let i=[];r.forEach(t=>{e[t].forEach(({term:t,to:n})=>{if(!t)return;let r;for(let e=0;e<i.length;e++)i[e][0]==t&&(r=i[e][1]);we(e,n).forEach(e=>{r||i.push([t,r=[]]),r.indexOf(e)==-1&&r.push(e)})})});let a=t[r.join(`,`)]=new pe(r.indexOf(e.length-1)>-1);for(let e=0;e<i.length;e++){let r=i[e][1].sort(Ce);a.next.push({type:i[e][0],next:t[r.join(`,`)]||n(r)})}return a}}function Ee(e,t){for(let n=0,r=[e];n<r.length;n++){let e=r[n],i=!e.validEnd,a=[];for(let t=0;t<e.next.length;t++){let{type:n,next:o}=e.next[t];a.push(n.name),i&&!(n.isText||n.hasRequiredAttrs())&&(i=!1),r.indexOf(o)==-1&&r.push(o)}i&&t.err(`Only non-generatable nodes (`+a.join(`, `)+`) in a required position (see https://prosemirror.net/docs/guide/#generatable)`)}}function De(e){let t=Object.create(null);for(let n in e){let r=e[n];if(!r.hasDefault)return null;t[n]=r.default}return t}function Oe(e,t){let n=Object.create(null);for(let r in e){let i=e[r],a=t&&t[r];if(a===void 0){if(i.hasDefault)a=i.default;else throw RangeError(`No value supplied for attribute `+r)}else i.validate&&i.validate(a);n[r]=a}return n}function ke(e,t){let n=Object.create(null);if(t)for(let r in t)n[r]=new Me(e,r,t[r]);return n}var Ae=class e{constructor(e,t,n){this.name=e,this.schema=t,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(` `):[],this.attrs=ke(e,n.attrs),this.defaultAttrs=De(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||e==`text`),this.isText=e==`text`}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==pe.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?`pre`:`normal`)}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Oe(this.attrs,e)}create(e=null,t,n){if(this.isText)throw Error(`NodeType.create can't construct text nodes`);return new le(this,this.coLine truncated
`);else if(a.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(a.linebreakReplacement.create())){let e=n.split(/\r?\n|\r/);for(let n=0;n<e.length;n++)n&&this.insertNode(a.linebreakReplacement.create(),t,!0),e[n]&&this.insertNode(a.text(e[n]),t,!/\S/.test(e[n]));n=``}else n=n.replace(/\r?\n|\r/g,` `);n&&this.insertNode(a.text(n),t,!/\S/.test(n)),this.findInText(e)}else this.findInside(e)}addElement(e,t,n){let r=this.localPreserveWS,i=this.top;(e.tagName==`PRE`||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let a=e.nodeName.toLowerCase(),o;Ve.hasOwnProperty(a)&&this.parser.normalizeLists&&Je(e);let s=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(o=this.parser.matchTag(e,this,n));out:if(s?s.ignore:Be.hasOwnProperty(a))this.findInside(e),this.ignoreFallback(e,t);else if(!s||s.skip||s.closeParent){s&&s.closeParent?this.open=Math.max(0,this.open-1):s&&s.skip.nodeType&&(e=s.skip);let n,r=this.needsBlock;if(ze.hasOwnProperty(a))i.content.length&&i.content[0].isInline&&this.open&&(this.open--,i=this.top),n=!0,i.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break out}let o=s&&s.skip?t:this.readStyles(e,t);o&&this.addAll(e,o),n&&this.sync(i),this.needsBlock=r}else{let n=this.readStyles(e,t);n&&this.addElementByRule(e,s,n,s.consuming===!1?o:void 0)}this.localPreserveWS=r}leafFallback(e,t){e.nodeName==`BR`&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
`),t)}ignoreFallback(e,t){e.nodeName!=`BR`||this.top.type&&this.top.type.inlineContent||this.findPlace(this.parser.schema.text(`-`),t,!0)}readStyles(e,t){let n=e.style;if(n&&n.length)for(let e=0;e<this.parser.matchedStyles.length;e++){let r=this.parser.matchedStyles[e],i=n.getPropertyValue(r);if(i)for(let e;;){let n=this.parser.matchStyle(r,i,this,e);if(!n)break;if(n.ignore)return null;if(t=n.clearMark?t.filter(e=>!n.clearMark(e)):t.concat(this.parser.schema.marks[n.mark].create(n.attrs)),n.consuming===!1)e=n;else break}}return t}addElementByRule(e,t,n,r){let i,a;if(t.node){if(a=this.parser.schema.nodes[t.node],a.isLeaf)this.insertNode(a.create(t.attrs),n,e.nodeName==`BR`)||this.leafFallback(e,n);else{let e=this.enter(a,t.attrs||null,n,t.preserveWhitespace);e&&(i=!0,n=e)}}else{let e=this.parser.schema.marks[t.mark];n=n.concat(e.create(t.attrs))}let o=this.top;if(a&&a.isLeaf)this.findInside(e);else if(r)this.addElement(e,n,r);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(e=>this.insertNode(e,n,!1));else{let r=e;typeof t.contentElement==`string`?r=e.querySelector(t.contentElement):typeof t.contentElement==`function`?r=t.contentElement(e):t.contentElement&&(r=t.contentElement),this.findAround(e,r,!0),this.addAll(r,n),this.findAround(e,r,!1)}i&&this.sync(o)&&this.open--}addAll(e,t,n,r){let i=n||0;for(let a=n?e.childNodes[n]:e.firstChild,o=r==null?null:e.childNodes[r];a!=o;a=a.nextSibling,++i)this.findAtPoint(e,i),this.addDOM(a,t);this.findAtPoint(e,i)}findPlace(e,t,n){let r,i;for(let t=this.open,a=0;t>=0;t--){let o=this.nodes[t],s=o.findWrapping(e);if(s&&(!r||r.length>s.length+a)&&(r=s,i=o,!s.length))break;if(o.solid){if(n)break;a+=2}}if(!r)return null;this.sync(i);for(let e=0;e<r.length;e++)t=this.enterInner(r[e],null,t,!1);return t}insertNode(e,t,n){if(e.isInline&&this.needsBlock&&!this.top.type){let e=this.textblockFromContext();e&&(t=this.enterInner(e,null,t))}let r=this.findPlace(e,t,n);if(r){this.closeExtra();let t=this.top;t.match&&=t.match.matchType(e.type);let n=d.none;for(let i of r.concat(e.marks))(t.type?t.type.allowsMarkType(i.type):Ze(i.type,e.type))&&(n=i.addToSet(n));return t.content.push(e.mark(n)),!0}return!1}enter(e,t,n,r){let i=this.findPlace(e.create(t),n,!1);return i&&=this.enterInner(e,t,n,!0,r),i}enterInner(e,t,n,r=!1,i){this.closeExtra();let a=this.top;a.match=a.match&&a.match.matchType(e);let o=Ge(e,i,a.options);a.options&We&&a.content.length==0&&(o|=We);let s=d.none;return n=n.filter(t=>!(a.type?a.type.allowsMarkType(t.type):Ze(t.type,e))||(s=t.addToSet(s),!1)),this.nodes.push(new Ke(e,t,s,r,null,o)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--)if(this.nodes[t]==e)return this.open=t,!0;else this.localPreserveWS&&(this.nodes[t].options|=He);return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let t=n.length-1;t>=0;t--)e+=n[t].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&this.find[n].offset==t&&(this.find[n].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,n){if(e!=t&&this.find)for(let r=0;r<this.find.length;r++)this.find[r].pos==null&&e.nodeType==1&&e.contains(this.find[r].node)&&t.compareDocumentPosition(this.find[r].node)&(n?2:4)&&(this.find[r].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf(`|`)>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split(`/`),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+ +!r,a=(e,o)=>{for(;e>=0;e--){let s=t[e];if(s==``){if(e==t.length-1||e==0)continue;for(;o>=i;o--)if(a(e-1,o))return!0;return!1}{let e=o>0||o==0&&r?this.nodes[o].type:n&&o>=i?n.node(o-i).type:null;if(!e||e.name!=s&&!e.isInGroup(s))return!1;o--}}return!0};return a(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let t=this.parser.schema.nodes[e];if(t.isTextblock&&t.defaultAttrs)return t}}};function Je(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let e=t.nodeType==1?t.nodeName.toLowerCase():null;e&&Ve.hasOwnProperty(e)&&n?(n.appendChild(t),t=n):e==`li`?n=t:e&&(n=null)}}function Ye(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatcheLine truncated
`))}})}function Wt(e,t,n){let r=e.resolve(t),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function Gt(e,t,n,r,i){let a=e.doc.nodeAt(t);if(!a)throw RangeError(`No node at given position`);n||=a.type;let o=n.create(r,null,i||a.marks);if(a.isLeaf)return e.replaceWith(t,t+a.nodeSize,o);if(!n.validContent(a.content))throw RangeError(`Invalid content for node type `+n.name);e.step(new Ot(t,t+a.nodeSize,t+1,t+a.nodeSize-1,new p(s.from(o),0,0),1,!0))}function Kt(e,t,n=1,r){let i=e.resolve(t),a=i.depth-n,o=r&&r[r.length-1]||i.parent;if(a<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let e=i.depth-1,t=n-2;e>a;e--,t--){let n=i.node(e),a=i.index(e);if(n.type.spec.isolating)return!1;let o=n.content.cutByIndex(a,n.childCount),s=r&&r[t+1];s&&(o=o.replaceChild(0,s.type.create(s.attrs)));let c=r&&r[t]||n;if(!n.canReplace(a+1,n.childCount)||!c.type.validContent(o))return!1}let s=i.indexAfter(a),c=r&&r[0];return i.node(a).canReplaceWith(s,s,c?c.type:i.node(a+1).type)}function qt(e,t,n=1,r){let i=e.doc.resolve(t),a=s.empty,o=s.empty;for(let e=i.depth,t=i.depth-n,c=n-1;e>t;e--,c--){a=s.from(i.node(e).copy(a));let t=r&&r[c];o=s.from(t?t.type.create(t.attrs,o):i.node(e).copy(o))}e.step(new Dt(t,t,new p(a.append(o),n,n),!0))}function Jt(e,t){let n=e.resolve(t),r=n.index();return Xt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function Yt(e,t){t.content.size||e.type.compatibleContent(t.type);let n=e.contentMatchAt(e.childCount),{linebreakReplacement:r}=e.type.schema;for(let i=0;i<t.childCount;i++){let a=t.child(i),o=a.type==r?e.type.schema.nodes.text:a.type;if(n=n.matchType(o),!n||!e.type.allowsMarks(a.marks))return!1}return n.validEnd}function Xt(e,t){return!!(e&&t&&!e.isLeaf&&Yt(e,t))}function Zt(e,t,n=-1){let r=e.resolve(t);for(let e=r.depth;;e--){let i,a,o=r.index(e);if(e==r.depth?(i=r.nodeBefore,a=r.nodeAfter):n>0?(i=r.node(e+1),o++,a=r.node(e).maybeChild(o)):(i=r.node(e).maybeChild(o-1),a=r.node(e+1)),i&&!i.isTextblock&&Xt(i,a)&&r.node(e).canReplace(o,o+1))return t;if(e==0)break;t=n<0?r.before(e):r.after(e)}}function Qt(e,t,n){let r=null,{linebreakReplacement:i}=e.doc.type.schema,a=e.doc.resolve(t-n),o=a.node().type;if(i&&o.inlineContent){let e=o.whitespace==`pre`,t=!!o.contentMatch.matchType(i);e&&!t?r=!1:!e&&t&&(r=!0)}let s=e.steps.length;if(r===!1){let r=e.doc.resolve(t+n);Ut(e,r.node(),r.before(),s)}o.inlineContent&&Mt(e,t+n-1,o,a.node().contentMatchAt(a.index()),r==null);let c=e.mapping.slice(s),l=c.map(t-n);if(e.step(new Dt(l,c.map(t+n,-1),p.empty,!0)),r===!0){let t=e.doc.resolve(l);Ht(e,t.node(),t.before(),e.steps.length)}return e}function $t(e,t,n){let r=e.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let e=r.depth-1;e>=0;e--){let t=r.index(e);if(r.node(e).canReplaceWith(t,t,n))return r.before(e+1);if(t>0)return null}if(r.parentOffset==r.parent.content.size)for(let e=r.depth-1;e>=0;e--){let t=r.indexAfter(e);if(r.node(e).canReplaceWith(t,t,n))return r.after(e+1);if(t<r.node(e).childCount)return null}return null}function en(e,t,n){let r=e.resolve(t);if(!n.content.size)return t;let i=n.content;for(let e=0;e<n.openStart;e++)i=i.firstChild.content;for(let e=1;e<=(n.openStart==0&&n.size?2:1);e++)for(let t=r.depth;t>=0;t--){let n=t==r.depth?0:r.pos<=(r.start(t+1)+r.end(t+1))/2?-1:1,a=r.index(t)+ +(n>0),o=r.node(t),s=!1;if(e==1)s=o.canReplace(a,a,i);else{let e=o.contentMatchAt(a).findWrapping(i.firstChild.type);s=e&&o.canReplaceWith(a,a,e[0])}if(s)return n==0?r.pos:n<0?r.before(t+1):r.after(t+1)}return null}function tn(e,t,n=t,r=p.empty){if(t==n&&!r.size)return null;let i=e.resolve(t),a=e.resolve(n);return nn(i,a,r)?new Dt(t,n,r):new rn(i,a,r).fit()}function nn(e,t,n){return!n.openStart&&!n.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),n.content)}var rn=class{constructor(e,t,n){this.$from=e,this.$to=t,this.unplaced=n,this.frontier=[],this.placed=s.empty;for(let t=0;t<=e.depth;t++){let n=e.node(t);this.frontier.push({type:n.type,match:n.contentMatchAt(e.indexAfter(t))})}for(let t=e.depth;t>0;t--)this.placed=s.from(e.node(t).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let e=this.findFittable();e?this.placeNodes(e):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,n=this.$from,r=this.close(e<0?this.$to:n.doc.resolve(e));if(!r)return null;let i=this.placed,a=n.depth,o=r.depth;for(;a&&o&&i.childCount==1;)i=i.firstChild.content,a--,o--;let s=new p(i,a,o);return e>-1?new Ot(n.pos,e,this.$to.pos,this.$to.end(),s,t):s.size||n.pos!=this.$to.pos?new Dt(n.pos,r.pos,s):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,n=0,r=this.unplaced.openEnd;n<e;n++){let i=t.firstChild;if(t.childCount>1&&(r=0),i.type.spec.isolating&&r<=n){e=n;break}t=i.content}for(let t=1;t<=2;t++)for(let n=t=Line truncated
`).scrollIntoView()),!0)};function sr(e){for(let t=0;t<e.edgeCount;t++){let{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var cr=(e,t)=>{let{$head:n,$anchor:r}=e.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),a=n.indexAfter(-1),o=sr(i.contentMatchAt(a));if(!o||!i.canReplaceWith(a,a,o))return!1;if(t){let r=n.after(),i=e.tr.replaceWith(r,r,o.createAndFill());i.setSelection(C.near(i.doc.resolve(r),1)),t(i.scrollIntoView())}return!0},lr=(e,t)=>{let n=e.selection,{$from:r,$to:i}=n;if(n instanceof On||r.parent.inlineContent||i.parent.inlineContent)return!1;let a=sr(i.parent.contentMatchAt(i.indexAfter()));if(!a||!a.isTextblock)return!1;if(t){let n=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,o=e.tr.insert(n,a.createAndFill());o.setSelection(w.create(o.doc,n+1)),t(o.scrollIntoView())}return!0},ur=(e,t)=>{let{$cursor:n}=e.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let r=n.before();if(Kt(e.doc,r))return t&&t(e.tr.split(r).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Pt(r);return i!=null&&(t&&t(e.tr.lift(r,i).scrollIntoView()),!0)};function dr(e){return(t,n)=>{if(t.selection instanceof T&&t.selection.node.isBlock){let{$from:e}=t.selection;return!e.parentOffset||!Kt(t.doc,e.pos)?!1:(n&&n(t.tr.split(e.pos).scrollIntoView()),!0)}if(!t.selection.$from.depth)return!1;let r=t.tr;!t.selection.empty&&(t.selection instanceof w||t.selection instanceof On)&&r.deleteSelection();let{$from:i}=r.selection,a=r.steps.length,o=[],s,c,l=!1,u=!1;for(let t=i.depth;;t--)if(i.node(t).isBlock){l=i.end(t)==i.pos+(i.depth-t),u=i.start(t)==i.pos-(i.depth-t),c=sr(i.node(t-1).contentMatchAt(i.indexAfter(t-1)));let n=e&&e(i.parent,l,i);o.unshift(n||(l&&c?{type:c}:null)),s=t;break}else{if(t==1)return!1;o.unshift(null)}let d=i.pos,f=Kt(r.doc,d,o.length,o);if(f||=(o[0]=c?{type:c}:null,Kt(r.doc,d,o.length,o)),!f)return!1;if(r.split(d,o.length,o),!l&&u&&i.node(s).type!=c){let e=r.mapping.slice(a),t=e.map(i.before(s)),n=r.doc.resolve(t);c&&i.node(s-1).canReplaceWith(n.index(),n.index()+1,c)&&r.setNodeMarkup(e.map(i.before(s)),c)}return n&&n(r.scrollIntoView()),!0}}var fr=dr(),pr=(e,t)=>{let{$from:n,to:r}=e.selection,i,a=n.sharedDepth(r);return a!=0&&(i=n.before(a),t&&t(e.tr.setSelection(T.create(e.doc,i))),!0)},mr=(e,t)=>(t&&t(e.tr.setSelection(new On(e.doc))),!0);function hr(e,t,n){let r=t.nodeBefore,i=t.nodeAfter,a=t.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&t.parent.canReplace(a-1,a)?(n&&n(e.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(a,a+1)||!(i.isTextblock||Jt(e.doc,t.pos))?!1:(n&&n(e.tr.join(t.pos).scrollIntoView()),!0)}function gr(e,t,n,r){let i=t.nodeBefore,a=t.nodeAfter,o,c,l=i.type.spec.isolating||a.type.spec.isolating;if(!l&&hr(e,t,n))return!0;let u=!l&&t.parent.canReplace(t.index(),t.index()+1);if(u&&(o=(c=i.contentMatchAt(i.childCount)).findWrapping(a.type))&&c.matchType(o[0]||a.type).validEnd){if(n){let r=t.pos+a.nodeSize,c=s.empty;for(let e=o.length-1;e>=0;e--)c=s.from(o[e].create(null,c));c=s.from(i.copy(c));let l=e.tr.step(new Ot(t.pos-1,r,t.pos,r,new p(c,1,0),o.length,!0)),u=l.doc.resolve(r+2*o.length);u.nodeAfter&&u.nodeAfter.type==i.type&&Jt(l.doc,u.pos)&&l.join(u.pos),n(l.scrollIntoView())}return!0}let d=a.type.spec.isolating||r>0&&l?null:C.findFrom(t,1),f=d&&d.$from.blockRange(d.$to),m=f&&Pt(f);if(m!=null&&m>=t.depth)return n&&n(e.tr.lift(f,m).scrollIntoView()),!0;if(u&&Xn(a,`start`,!0)&&Xn(i,`end`)){let r=i,o=[];for(;o.push(r),!r.isTextblock;)r=r.lastChild;let c=a,l=1;for(;!c.isTextblock;c=c.firstChild)l++;if(r.canReplace(r.childCount,r.childCount,c.content)){if(n){let r=s.empty;for(let e=o.length-1;e>=0;e--)r=s.from(o[e].copy(r));n(e.tr.step(new Ot(t.pos-o.length,t.pos+a.nodeSize,t.pos+l,t.pos+a.nodeSize-l,new p(r,o.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function _r(e){return function(t,n){let r=t.selection,i=e<0?r.$from:r.$to,a=i.depth;for(;i.node(a).isInline;){if(!a)return!1;a--}return i.node(a).isTextblock?(n&&n(t.tr.setSelection(w.create(t.doc,e<0?i.start(a):i.end(a)))),!0):!1}}var vr=_r(-1),yr=_r(1);function br(e,t=null){return function(n,r){let{$from:i,$to:a}=n.selection,o=i.blockRange(a),s=o&&It(o,e,t);return s?(r&&r(n.tr.wrap(o,s).scrollIntoView()),!0):!1}}function xr(e,t=null){return function(n,r){let i=!1;for(let r=0;r<n.selection.ranges.length&&!i;r++){let{$from:{pos:a},$to:{pos:o}}=n.selection.ranges[r];n.doc.nodesBetween(a,o,(r,a)=>{if(i)return!1;if(r.isTextblock&&!r.hasMarkup(e,t)){if(r.type==e)i=!0;else{let t=n.doc.resolve(a),r=t.index();i=t.parent.canReplaceWith(r,r+1,e)}}})}if(!i)return!1;if(r){let i=n.tr;for(let r=0;r<n.selection.ranges.length;r++){let{$from:{pos:a},$to:{pos:o}}=n.selection.ranges[r];i.setBlockType(a,o,e,t)}r(i.scrollIntoView())}return!0}}function Sr(...e){return function(t,n,r){for(let i=0;i<e.length;i++)if(e[i](t,n,r))return!0;return!1}}var Cr=Sr(Wn,Kn,Zn),wr=Sr(Wn,er,tr),Tr={Enter:Sr(or,lrLine truncated
`),u&&t==e.nodeValue.length)for(let t=e,n;t;t=t.parentNode){if(n=t.nextSibling){n.nodeName==`BR`&&(o=s={node:n.parentNode,offset:Fr(n)+1});break}let e=t.pmViewDesc;if(e&&e.node&&e.node.isBlock)break}}else{let n=e.childNodes[t-1];u=n&&(n.nodeName==`BR`||n.contentEditable==`false`)}}if(ci&&l.focusNode&&l.focusNode!=s.node&&O(l.focusNode)){let e=l.focusNode.childNodes[l.focusOffset];e&&e.contentEditable==`false`&&(r=!0)}if(!(r||u&&fi)&&Br(o.node,o.offset,l.anchorNode,l.anchorOffset)&&Br(s.node,s.offset,l.focusNode,l.focusOffset))return;let d=!1;if((c.extend||e==t)&&!(u&&ci)){c.collapse(o.node,o.offset);try{e!=t&&c.extend(s.node,s.offset),d=!0}catch{}}if(!d){if(e>t){let e=o;o=s,s=e}let n=document.createRange();n.setEnd(s.node,s.offset),n.setStart(o.node,o.offset),c.removeAllRanges(),c.addRange(n)}}ignoreMutation(e){return!this.contentDOM&&e.type!=`selection`}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let n=0,r=0;r<this.children.length;r++){let i=this.children[r],a=n+i.size;if(n==a?e<=a&&t>=n:e<a&&t>n){let r=n+i.border,o=a-i.border;if(e>=r&&t<=o){this.dirty=e==n||t==a?$i:Qi,e==r&&t==o&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=ea:i.markDirty(e-r,t-r);return}i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?$i:ea}n=a}this.dirty=$i}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let n=e==1?$i:Qi;t.dirty<n&&(t.dirty=n)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}},na=class extends ta{constructor(e,t,n,r){let i,a=t.type.toDOM;if(typeof a==`function`&&(a=a(n,()=>{if(!i)return r;if(i.parent)return i.parent.posBeforeChild(i)})),!t.type.spec.raw){let e=O(a)?a:document.createElement(`span`);e!=a&&(e.appendChild(a),a=e),e.hasAttribute(`contenteditable`)||(e.contentEditable=`false`),e.classList.add(`ProseMirror-widget`)}super(e,[],a,null),this.widget=t,this.widget=t,i=this}matchesWidget(e){return this.dirty==Zi&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!=`selection`||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},ra=class extends ta{constructor(e,t,n,r){super(e,[],t,null),this.textDOM=n,this.text=r}get size(){return this.text.length}localPosFromDOM(e,t){return e==this.textDOM?this.posAtStart+t:this.posAtStart+(t?this.size:0)}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type===`characterData`&&e.target.nodeValue==e.oldValue}},ia=class e extends ta{constructor(e,t,n,r,i){super(e,[],n,r),this.mark=t,this.spec=i}static create(t,n,r,i){let a=i.nodeViews[n.type.name],o=a&&a(n,i,r);return o&&o.dom||(o=Qe.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new e(t,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&ea||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ea&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=Zi){let e=this.parent;for(;!e.node;)e=e.parent;e.dirty<this.dirty&&(e.dirty=this.dirty),this.dirty=Zi}}slice(t,n,r){let i=e.create(this.parent,this.mark,!0,r),a=this.children,o=this.size;n<o&&(a=Ta(a,n,o,r)),t>0&&(a=Ta(a,0,t,r));for(let e=0;e<a.length;e++)a[e].parent=i;return i.children=a,i}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}},aa=class e extends ta{constructor(e,t,n,r,i,a,o){super(e,[],i,a),this.node=t,this.outerDeco=n,this.innerDeco=r,this.nodeDOM=o}static create(t,n,r,i,a,o){let s=a.nodeViews[n.type.name],c,l=s&&s(n,a,()=>{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),u=l&&l.dom,d=l&&l.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(!Wr(u))throw RangeError(`Text must be rendered as a DOM text node`)}else if(!u){let e=Qe.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs);({dom:u,contentDOM:d}=e)}!d&&!n.isText&&u.nodeName!=`BR`&&(u.hasAttribute(`contenteditable`)||(u.contentEditable=`false`),n.type.spec.draggable&&(u.draggable=!0));let f=u;return u=ga(u,r,n),l?c=new la(t,n,r,i,u,d||null,f,l):n.isText?new sa(t,n,r,i,u,f):new e(t,n,r,i,u,d||null,f)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace==`pre`&&(t.preserveWhitespace=`full`),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let e=this.children.length-1;e>=0;e--){let n=this.children[e];if(this.dom.contains(n.dom.parentNode)){t.contentElement=n.dom.parentNode;Line truncated
<script type="module" crossorigin>(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};function n(e){this.content=e}n.prototype={constructor:n,find:function(e){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===e)return t;return-1},get:function(e){var t=this.find(e);return t==-1?void 0:this.content[t+1]},update:function(e,t,r){var i=r&&r!=e?this.remove(r):this,a=i.find(e),o=i.content.slice();return a==-1?o.push(r||e,t):(o[a+1]=t,r&&(o[a]=r)),new n(o)},remove:function(e){var t=this.find(e);if(t==-1)return this;var r=this.content.slice();return r.splice(t,2),new n(r)},addToStart:function(e,t){return new n([e,t].concat(this.remove(e).content))},addToEnd:function(e,t){var r=this.remove(e).content.slice();return r.push(e,t),new n(r)},addBefore:function(e,t,r){var i=this.remove(t),a=i.content.slice(),o=i.find(e);return a.splice(o==-1?a.length:o,0,t,r),new n(a)},forEach:function(e){for(var t=0;t<this.content.length;t+=2)e(this.content[t],this.content[t+1])},prepend:function(e){return e=n.from(e),e.size?new n(e.content.concat(this.subtract(e).content)):this},append:function(e){return e=n.from(e),e.size?new n(this.subtract(e).content.concat(e.content)):this},subtract:function(e){var t=this;e=n.from(e);for(var r=0;r<e.content.length;r+=2)t=t.remove(e.content[r]);return t},toObject:function(){var e={};return this.forEach(function(t,n){e[t]=n}),e},get size(){return this.content.length>>1}},n.from=function(e){if(e instanceof n)return e;var t=[];if(e)for(var r in e)t.push(r,e[r]);return new n(t)};function r(e,t,n){for(let i=0;;i++){if(i==e.childCount||i==t.childCount)return e.childCount==t.childCount?null:n;let s=e.child(i),c=t.child(i);if(s==c)n+=s.nodeSize;else{if(!s.sameMarkup(c))return n;if(s.isText&&s.text!=c.text){let e=s.text,t=c.text,r=0;for(;e[r]==t[r];r++)n++;return r&&r<e.length&&r<t.length&&o(e.charCodeAt(r-1))&&a(e.charCodeAt(r))&&n--,n}if(s.content.size||c.content.size){let e=r(s.content,c.content,n+1);if(e!=null)return e}n+=s.nodeSize}}}function i(e,t,n,r){for(let s=e.childCount,c=t.childCount;;){if(s==0||c==0)return s==c?null:{a:n,b:r};let l=e.child(--s),u=t.child(--c),d=l.nodeSize;if(l==u)n-=d,r-=d;else{if(!l.sameMarkup(u))return{a:n,b:r};if(l.isText&&l.text!=u.text){let e=l.text,t=u.text,i=e.length,s=t.length;for(;i>0&&s>0&&e[i-1]==t[s-1];)i--,s--,n--,r--;return i&&s&&i<e.length&&o(e.charCodeAt(i-1))&&a(e.charCodeAt(i))&&(n++,r++),{a:n,b:r}}if(l.content.size||u.content.size){let e=i(l.content,u.content,n-1,r-1);if(e)return e}n-=d,r-=d}}}function a(e){return e>=56320&&e<57344}function o(e){return e>=55296&&e<56320}var s=class e{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let t=0;t<e.length;t++)this.size+=e[t].nodeSize}nodesBetween(e,t,n,r=0,i){for(let a=0,o=0;o<t;a++){let s=this.content[a],c=o+s.nodeSize;if(c>e&&n(s,r+o,i||null,a)!==!1&&s.content.size){let i=o+1;s.nodesBetween(Math.max(0,e-i),Math.min(s.content.size,t-i),n,r+i)}o=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let i=``,a=!0;return this.nodesBetween(e,t,(o,s)=>{let c=o.isText?o.text.slice(Math.max(e,s)-s,t-s):o.isLeaf?r?typeof r==`function`?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):``:``;o.isBlock&&(o.isLeaf&&c||o.isTextblock)&&n&&(a?a=!1:i+=n),i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);a<t.content.length;a++)i.push(t.content[a]);return new e(i,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],i=0;if(n>t)for(let e=0,a=0;a<n;e++){let o=this.content[e],s=a+o.nodeSize;s>t&&((a<t||s>n)&&(o=o.isText?o.cut(Math.max(0,t-a),Math.min(o.text.length,n-a)):o.cut(Math.max(0,t-a-1),Math.min(o.content.size,n-a-1))),r.push(o),i+=o.nodeSize),a=s}return new e(r,i)}cutByIndex(t,n){return t==n?e.empty:t==0&&n==this.content.length?this:new e(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new e(i,a)}addToStart(t){return new e([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new e(this.content.concat(t),this.size+t.nodeSize)}eq(Line truncated
`)}};fe.empty=new fe(!0);var pe=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw SyntaxError(e+` (in content expression '`+this.string+`')`)}};function me(e){let t=[];do t.push(he(e));while(e.eat(`|`));return t.length==1?t[0]:{type:`choice`,exprs:t}}function he(e){let t=[];do t.push(ge(e));while(e.next&&e.next!=`)`&&e.next!=`|`);return t.length==1?t[0]:{type:`seq`,exprs:t}}function ge(e){let t=be(e);for(;;)if(e.eat(`+`))t={type:`plus`,expr:t};else if(e.eat(`*`))t={type:`star`,expr:t};else if(e.eat(`?`))t={type:`opt`,expr:t};else if(e.eat(`{`))t=ve(e,t);else break;return t}function _e(e){/\D/.test(e.next)&&e.err(`Expected number, got '`+e.next+`'`);let t=Number(e.next);return e.pos++,t}function ve(e,t){let n=_e(e),r=n;return e.eat(`,`)&&(r=e.next==`}`?-1:_e(e)),e.eat(`}`)||e.err(`Unclosed braced range`),{type:`range`,min:n,max:r,expr:t}}function ye(e,t){let n=e.nodeTypes,r=n[t];if(r)return[r];let i=[];for(let e in n){let r=n[e];r.isInGroup(t)&&i.push(r)}return i.length==0&&e.err(`No node type or group '`+t+`' found`),i}function be(e){if(e.eat(`(`)){let t=me(e);return e.eat(`)`)||e.err(`Missing closing paren`),t}if(/\W/.test(e.next))e.err(`Unexpected token '`+e.next+`'`);else{let t=ye(e,e.next).map(t=>(e.inline==null?e.inline=t.isInline:e.inline!=t.isInline&&e.err(`Mixing inline and block content`),{type:`name`,value:t}));return e.pos++,t.length==1?t[0]:{type:`choice`,exprs:t}}}function xe(e){let t=[[]];return i(a(e,0),n()),t;function n(){return t.push([])-1}function r(e,n,r){let i={term:r,to:n};return t[e].push(i),i}function i(e,t){e.forEach(e=>e.to=t)}function a(e,t){if(e.type==`choice`)return e.exprs.reduce((e,n)=>e.concat(a(n,t)),[]);if(e.type==`seq`)for(let r=0;;r++){let o=a(e.exprs[r],t);if(r==e.exprs.length-1)return o;i(o,t=n())}else if(e.type==`star`){let o=n();return r(t,o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`plus`){let o=n();return i(a(e.expr,t),o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`opt`)return[r(t)].concat(a(e.expr,t));else if(e.type==`range`){let o=t;for(let t=0;t<e.min;t++){let t=n();i(a(e.expr,o),t),o=t}if(e.max==-1)i(a(e.expr,o),o);else for(let t=e.min;t<e.max;t++){let t=n();r(o,t),i(a(e.expr,o),t),o=t}return[r(o)]}else if(e.type==`name`)return[r(t,void 0,e.value)];else throw Error(`Unknown expr type`)}}function Se(e,t){return t-e}function Ce(e,t){let n=[];return r(t),n.sort(Se);function r(t){let i=e[t];if(i.length==1&&!i[0].term)return r(i[0].to);n.push(t);for(let e=0;e<i.length;e++){let{term:t,to:a}=i[e];!t&&n.indexOf(a)==-1&&r(a)}}}function we(e){let t=Object.create(null);return n(Ce(e,0));function n(r){let i=[];r.forEach(t=>{e[t].forEach(({term:t,to:n})=>{if(!t)return;let r;for(let e=0;e<i.length;e++)i[e][0]==t&&(r=i[e][1]);Ce(e,n).forEach(e=>{r||i.push([t,r=[]]),r.indexOf(e)==-1&&r.push(e)})})});let a=t[r.join(`,`)]=new fe(r.indexOf(e.length-1)>-1);for(let e=0;e<i.length;e++){let r=i[e][1].sort(Se);a.next.push({type:i[e][0],next:t[r.join(`,`)]||n(r)})}return a}}function Te(e,t){for(let n=0,r=[e];n<r.length;n++){let e=r[n],i=!e.validEnd,a=[];for(let t=0;t<e.next.length;t++){let{type:n,next:o}=e.next[t];a.push(n.name),i&&!(n.isText||n.hasRequiredAttrs())&&(i=!1),r.indexOf(o)==-1&&r.push(o)}i&&t.err(`Only non-generatable nodes (`+a.join(`, `)+`) in a required position (see https://prosemirror.net/docs/guide/#generatable)`)}}function Ee(e){let t=Object.create(null);for(let n in e){let r=e[n];if(!r.hasDefault)return null;t[n]=r.default}return t}function De(e,t){let n=Object.create(null);for(let r in e){let i=e[r],a=t&&t[r];if(a===void 0){if(i.hasDefault)a=i.default;else throw RangeError(`No value supplied for attribute `+r)}else i.validate&&i.validate(a);n[r]=a}return n}function Oe(e,t){let n=Object.create(null);if(t)for(let r in t)n[r]=new je(e,r,t[r]);return n}var ke=class e{constructor(e,t,n){this.name=e,this.schema=t,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(` `):[],this.attrs=Oe(e,n.attrs),this.defaultAttrs=Ee(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||e==`text`),this.isText=e==`text`}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==fe.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?`pre`:`normal`)}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:De(this.attrs,e)}create(e=null,t,n){if(this.isText)throw Error(`NodeType.create can't construct text nodes`);return new ce(this,this.coLine truncated
`);else if(a.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(a.linebreakReplacement.create())){let e=n.split(/\r?\n|\r/);for(let n=0;n<e.length;n++)n&&this.insertNode(a.linebreakReplacement.create(),t,!0),e[n]&&this.insertNode(a.text(e[n]),t,!/\S/.test(e[n]));n=``}else n=n.replace(/\r?\n|\r/g,` `);n&&this.insertNode(a.text(n),t,!/\S/.test(n)),this.findInText(e)}else this.findInside(e)}addElement(e,t,n){let r=this.localPreserveWS,i=this.top;(e.tagName==`PRE`||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let a=e.nodeName.toLowerCase(),o;Be.hasOwnProperty(a)&&this.parser.normalizeLists&&qe(e);let s=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(o=this.parser.matchTag(e,this,n));out:if(s?s.ignore:ze.hasOwnProperty(a))this.findInside(e),this.ignoreFallback(e,t);else if(!s||s.skip||s.closeParent){s&&s.closeParent?this.open=Math.max(0,this.open-1):s&&s.skip.nodeType&&(e=s.skip);let n,r=this.needsBlock;if(Re.hasOwnProperty(a))i.content.length&&i.content[0].isInline&&this.open&&(this.open--,i=this.top),n=!0,i.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break out}let o=s&&s.skip?t:this.readStyles(e,t);o&&this.addAll(e,o),n&&this.sync(i),this.needsBlock=r}else{let n=this.readStyles(e,t);n&&this.addElementByRule(e,s,n,s.consuming===!1?o:void 0)}this.localPreserveWS=r}leafFallback(e,t){e.nodeName==`BR`&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
`),t)}ignoreFallback(e,t){e.nodeName!=`BR`||this.top.type&&this.top.type.inlineContent||this.findPlace(this.parser.schema.text(`-`),t,!0)}readStyles(e,t){let n=e.style;if(n&&n.length)for(let e=0;e<this.parser.matchedStyles.length;e++){let r=this.parser.matchedStyles[e],i=n.getPropertyValue(r);if(i)for(let e;;){let n=this.parser.matchStyle(r,i,this,e);if(!n)break;if(n.ignore)return null;if(t=n.clearMark?t.filter(e=>!n.clearMark(e)):t.concat(this.parser.schema.marks[n.mark].create(n.attrs)),n.consuming===!1)e=n;else break}}return t}addElementByRule(e,t,n,r){let i,a;if(t.node){if(a=this.parser.schema.nodes[t.node],a.isLeaf)this.insertNode(a.create(t.attrs),n,e.nodeName==`BR`)||this.leafFallback(e,n);else{let e=this.enter(a,t.attrs||null,n,t.preserveWhitespace);e&&(i=!0,n=e)}}else{let e=this.parser.schema.marks[t.mark];n=n.concat(e.create(t.attrs))}let o=this.top;if(a&&a.isLeaf)this.findInside(e);else if(r)this.addElement(e,n,r);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(e=>this.insertNode(e,n,!1));else{let r=e;typeof t.contentElement==`string`?r=e.querySelector(t.contentElement):typeof t.contentElement==`function`?r=t.contentElement(e):t.contentElement&&(r=t.contentElement),this.findAround(e,r,!0),this.addAll(r,n),this.findAround(e,r,!1)}i&&this.sync(o)&&this.open--}addAll(e,t,n,r){let i=n||0;for(let a=n?e.childNodes[n]:e.firstChild,o=r==null?null:e.childNodes[r];a!=o;a=a.nextSibling,++i)this.findAtPoint(e,i),this.addDOM(a,t);this.findAtPoint(e,i)}findPlace(e,t,n){let r,i;for(let t=this.open,a=0;t>=0;t--){let o=this.nodes[t],s=o.findWrapping(e);if(s&&(!r||r.length>s.length+a)&&(r=s,i=o,!s.length))break;if(o.solid){if(n)break;a+=2}}if(!r)return null;this.sync(i);for(let e=0;e<r.length;e++)t=this.enterInner(r[e],null,t,!1);return t}insertNode(e,t,n){if(e.isInline&&this.needsBlock&&!this.top.type){let e=this.textblockFromContext();e&&(t=this.enterInner(e,null,t))}let r=this.findPlace(e,t,n);if(r){this.closeExtra();let t=this.top;t.match&&=t.match.matchType(e.type);let n=d.none;for(let i of r.concat(e.marks))(t.type?t.type.allowsMarkType(i.type):Xe(i.type,e.type))&&(n=i.addToSet(n));return t.content.push(e.mark(n)),!0}return!1}enter(e,t,n,r){let i=this.findPlace(e.create(t),n,!1);return i&&=this.enterInner(e,t,n,!0,r),i}enterInner(e,t,n,r=!1,i){this.closeExtra();let a=this.top;a.match=a.match&&a.match.matchType(e);let o=We(e,i,a.options);a.options&Ue&&a.content.length==0&&(o|=Ue);let s=d.none;return n=n.filter(t=>!(a.type?a.type.allowsMarkType(t.type):Xe(t.type,e))||(s=t.addToSet(s),!1)),this.nodes.push(new Ge(e,t,s,r,null,o)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--)if(this.nodes[t]==e)return this.open=t,!0;else this.localPreserveWS&&(this.nodes[t].options|=Ve);return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let t=n.length-1;t>=0;t--)e+=n[t].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&this.find[n].offset==t&&(this.find[n].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,n){if(e!=t&&this.find)for(let r=0;r<this.find.length;r++)this.find[r].pos==null&&e.nodeType==1&&e.contains(this.find[r].node)&&t.compareDocumentPosition(this.find[r].node)&(n?2:4)&&(this.find[r].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf(`|`)>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split(`/`),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+ +!r,a=(e,o)=>{for(;e>=0;e--){let s=t[e];if(s==``){if(e==t.length-1||e==0)continue;for(;o>=i;o--)if(a(e-1,o))return!0;return!1}{let e=o>0||o==0&&r?this.nodes[o].type:n&&o>=i?n.node(o-i).type:null;if(!e||e.name!=s&&!e.isInGroup(s))return!1;o--}}return!0};return a(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let t=this.parser.schema.nodes[e];if(t.isTextblock&&t.defaultAttrs)return t}}};function qe(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let e=t.nodeType==1?t.nodeName.toLowerCase():null;e&&Be.hasOwnProperty(e)&&n?(n.appendChild(t),t=n):e==`li`?n=t:e&&(n=null)}}function Je(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatcheLine truncated
`))}})}function Ut(e,t,n){let r=e.resolve(t),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function Wt(e,t,n,r,i){let a=e.doc.nodeAt(t);if(!a)throw RangeError(`No node at given position`);n||=a.type;let o=n.create(r,null,i||a.marks);if(a.isLeaf)return e.replaceWith(t,t+a.nodeSize,o);if(!n.validContent(a.content))throw RangeError(`Invalid content for node type `+n.name);e.step(new Dt(t,t+a.nodeSize,t+1,t+a.nodeSize-1,new p(s.from(o),0,0),1,!0))}function Gt(e,t,n=1,r){let i=e.resolve(t),a=i.depth-n,o=r&&r[r.length-1]||i.parent;if(a<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let e=i.depth-1,t=n-2;e>a;e--,t--){let n=i.node(e),a=i.index(e);if(n.type.spec.isolating)return!1;let o=n.content.cutByIndex(a,n.childCount),s=r&&r[t+1];s&&(o=o.replaceChild(0,s.type.create(s.attrs)));let c=r&&r[t]||n;if(!n.canReplace(a+1,n.childCount)||!c.type.validContent(o))return!1}let s=i.indexAfter(a),c=r&&r[0];return i.node(a).canReplaceWith(s,s,c?c.type:i.node(a+1).type)}function Kt(e,t,n=1,r){let i=e.doc.resolve(t),a=s.empty,o=s.empty;for(let e=i.depth,t=i.depth-n,c=n-1;e>t;e--,c--){a=s.from(i.node(e).copy(a));let t=r&&r[c];o=s.from(t?t.type.create(t.attrs,o):i.node(e).copy(o))}e.step(new Et(t,t,new p(a.append(o),n,n),!0))}function qt(e,t){let n=e.resolve(t),r=n.index();return Yt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function Jt(e,t){t.content.size||e.type.compatibleContent(t.type);let n=e.contentMatchAt(e.childCount),{linebreakReplacement:r}=e.type.schema;for(let i=0;i<t.childCount;i++){let a=t.child(i),o=a.type==r?e.type.schema.nodes.text:a.type;if(n=n.matchType(o),!n||!e.type.allowsMarks(a.marks))return!1}return n.validEnd}function Yt(e,t){return!!(e&&t&&!e.isLeaf&&Jt(e,t))}function Xt(e,t,n=-1){let r=e.resolve(t);for(let e=r.depth;;e--){let i,a,o=r.index(e);if(e==r.depth?(i=r.nodeBefore,a=r.nodeAfter):n>0?(i=r.node(e+1),o++,a=r.node(e).maybeChild(o)):(i=r.node(e).maybeChild(o-1),a=r.node(e+1)),i&&!i.isTextblock&&Yt(i,a)&&r.node(e).canReplace(o,o+1))return t;if(e==0)break;t=n<0?r.before(e):r.after(e)}}function Zt(e,t,n){let r=null,{linebreakReplacement:i}=e.doc.type.schema,a=e.doc.resolve(t-n),o=a.node().type;if(i&&o.inlineContent){let e=o.whitespace==`pre`,t=!!o.contentMatch.matchType(i);e&&!t?r=!1:!e&&t&&(r=!0)}let s=e.steps.length;if(r===!1){let r=e.doc.resolve(t+n);Ht(e,r.node(),r.before(),s)}o.inlineContent&&jt(e,t+n-1,o,a.node().contentMatchAt(a.index()),r==null);let c=e.mapping.slice(s),l=c.map(t-n);if(e.step(new Et(l,c.map(t+n,-1),p.empty,!0)),r===!0){let t=e.doc.resolve(l);Vt(e,t.node(),t.before(),e.steps.length)}return e}function Qt(e,t,n){let r=e.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let e=r.depth-1;e>=0;e--){let t=r.index(e);if(r.node(e).canReplaceWith(t,t,n))return r.before(e+1);if(t>0)return null}if(r.parentOffset==r.parent.content.size)for(let e=r.depth-1;e>=0;e--){let t=r.indexAfter(e);if(r.node(e).canReplaceWith(t,t,n))return r.after(e+1);if(t<r.node(e).childCount)return null}return null}function $t(e,t,n){let r=e.resolve(t);if(!n.content.size)return t;let i=n.content;for(let e=0;e<n.openStart;e++)i=i.firstChild.content;for(let e=1;e<=(n.openStart==0&&n.size?2:1);e++)for(let t=r.depth;t>=0;t--){let n=t==r.depth?0:r.pos<=(r.start(t+1)+r.end(t+1))/2?-1:1,a=r.index(t)+ +(n>0),o=r.node(t),s=!1;if(e==1)s=o.canReplace(a,a,i);else{let e=o.contentMatchAt(a).findWrapping(i.firstChild.type);s=e&&o.canReplaceWith(a,a,e[0])}if(s)return n==0?r.pos:n<0?r.before(t+1):r.after(t+1)}return null}function en(e,t,n=t,r=p.empty){if(t==n&&!r.size)return null;let i=e.resolve(t),a=e.resolve(n);return tn(i,a,r)?new Et(t,n,r):new nn(i,a,r).fit()}function tn(e,t,n){return!n.openStart&&!n.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),n.content)}var nn=class{constructor(e,t,n){this.$from=e,this.$to=t,this.unplaced=n,this.frontier=[],this.placed=s.empty;for(let t=0;t<=e.depth;t++){let n=e.node(t);this.frontier.push({type:n.type,match:n.contentMatchAt(e.indexAfter(t))})}for(let t=e.depth;t>0;t--)this.placed=s.from(e.node(t).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let e=this.findFittable();e?this.placeNodes(e):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,n=this.$from,r=this.close(e<0?this.$to:n.doc.resolve(e));if(!r)return null;let i=this.placed,a=n.depth,o=r.depth;for(;a&&o&&i.childCount==1;)i=i.firstChild.content,a--,o--;let s=new p(i,a,o);return e>-1?new Dt(n.pos,e,this.$to.pos,this.$to.end(),s,t):s.size||n.pos!=this.$to.pos?new Et(n.pos,r.pos,s):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,n=0,r=this.unplaced.openEnd;n<e;n++){let i=t.firstChild;if(t.childCount>1&&(r=0),i.type.spec.isolating&&r<=n){e=n;break}t=i.content}for(let t=1;t<=2;t++)for(let n=t=Line truncated
`).scrollIntoView()),!0)};function sr(e){for(let t=0;t<e.edgeCount;t++){let{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var cr=(e,t)=>{let{$head:n,$anchor:r}=e.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),a=n.indexAfter(-1),o=sr(i.contentMatchAt(a));if(!o||!i.canReplaceWith(a,a,o))return!1;if(t){let r=n.after(),i=e.tr.replaceWith(r,r,o.createAndFill());i.setSelection(w.near(i.doc.resolve(r),1)),t(i.scrollIntoView())}return!0},lr=(e,t)=>{let n=e.selection,{$from:r,$to:i}=n;if(n instanceof Dn||r.parent.inlineContent||i.parent.inlineContent)return!1;let a=sr(i.parent.contentMatchAt(i.indexAfter()));if(!a||!a.isTextblock)return!1;if(t){let n=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,o=e.tr.insert(n,a.createAndFill());o.setSelection(T.create(o.doc,n+1)),t(o.scrollIntoView())}return!0},ur=(e,t)=>{let{$cursor:n}=e.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let r=n.before();if(Gt(e.doc,r))return t&&t(e.tr.split(r).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Nt(r);return i!=null&&(t&&t(e.tr.lift(r,i).scrollIntoView()),!0)};function dr(e){return(t,n)=>{if(t.selection instanceof E&&t.selection.node.isBlock){let{$from:e}=t.selection;return!e.parentOffset||!Gt(t.doc,e.pos)?!1:(n&&n(t.tr.split(e.pos).scrollIntoView()),!0)}if(!t.selection.$from.depth)return!1;let r=t.tr;!t.selection.empty&&(t.selection instanceof T||t.selection instanceof Dn)&&r.deleteSelection();let{$from:i}=r.selection,a=r.steps.length,o=[],s,c,l=!1,u=!1;for(let t=i.depth;;t--)if(i.node(t).isBlock){l=i.end(t)==i.pos+(i.depth-t),u=i.start(t)==i.pos-(i.depth-t),c=sr(i.node(t-1).contentMatchAt(i.indexAfter(t-1)));let n=e&&e(i.parent,l,i);o.unshift(n||(l&&c?{type:c}:null)),s=t;break}else{if(t==1)return!1;o.unshift(null)}let d=i.pos,f=Gt(r.doc,d,o.length,o);if(f||=(o[0]=c?{type:c}:null,Gt(r.doc,d,o.length,o)),!f)return!1;if(r.split(d,o.length,o),!l&&u&&i.node(s).type!=c){let e=r.mapping.slice(a),t=e.map(i.before(s)),n=r.doc.resolve(t);c&&i.node(s-1).canReplaceWith(n.index(),n.index()+1,c)&&r.setNodeMarkup(e.map(i.before(s)),c)}return n&&n(r.scrollIntoView()),!0}}var fr=dr(),pr=(e,t)=>{let{$from:n,to:r}=e.selection,i,a=n.sharedDepth(r);return a!=0&&(i=n.before(a),t&&t(e.tr.setSelection(E.create(e.doc,i))),!0)},mr=(e,t)=>(t&&t(e.tr.setSelection(new Dn(e.doc))),!0);function hr(e,t,n){let r=t.nodeBefore,i=t.nodeAfter,a=t.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&t.parent.canReplace(a-1,a)?(n&&n(e.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(a,a+1)||!(i.isTextblock||qt(e.doc,t.pos))?!1:(n&&n(e.tr.join(t.pos).scrollIntoView()),!0)}function gr(e,t,n,r){let i=t.nodeBefore,a=t.nodeAfter,o,c,l=i.type.spec.isolating||a.type.spec.isolating;if(!l&&hr(e,t,n))return!0;let u=!l&&t.parent.canReplace(t.index(),t.index()+1);if(u&&(o=(c=i.contentMatchAt(i.childCount)).findWrapping(a.type))&&c.matchType(o[0]||a.type).validEnd){if(n){let r=t.pos+a.nodeSize,c=s.empty;for(let e=o.length-1;e>=0;e--)c=s.from(o[e].create(null,c));c=s.from(i.copy(c));let l=e.tr.step(new Dt(t.pos-1,r,t.pos,r,new p(c,1,0),o.length,!0)),u=l.doc.resolve(r+2*o.length);u.nodeAfter&&u.nodeAfter.type==i.type&&qt(l.doc,u.pos)&&l.join(u.pos),n(l.scrollIntoView())}return!0}let d=a.type.spec.isolating||r>0&&l?null:w.findFrom(t,1),f=d&&d.$from.blockRange(d.$to),m=f&&Nt(f);if(m!=null&&m>=t.depth)return n&&n(e.tr.lift(f,m).scrollIntoView()),!0;if(u&&Xn(a,`start`,!0)&&Xn(i,`end`)){let r=i,o=[];for(;o.push(r),!r.isTextblock;)r=r.lastChild;let c=a,l=1;for(;!c.isTextblock;c=c.firstChild)l++;if(r.canReplace(r.childCount,r.childCount,c.content)){if(n){let r=s.empty;for(let e=o.length-1;e>=0;e--)r=s.from(o[e].copy(r));n(e.tr.step(new Dt(t.pos-o.length,t.pos+a.nodeSize,t.pos+l,t.pos+a.nodeSize-l,new p(r,o.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function _r(e){return function(t,n){let r=t.selection,i=e<0?r.$from:r.$to,a=i.depth;for(;i.node(a).isInline;){if(!a)return!1;a--}return i.node(a).isTextblock?(n&&n(t.tr.setSelection(T.create(t.doc,e<0?i.start(a):i.end(a)))),!0):!1}}var vr=_r(-1),yr=_r(1);function br(e,t=null){return function(n,r){let{$from:i,$to:a}=n.selection,o=i.blockRange(a),s=o&&Ft(o,e,t);return s?(r&&r(n.tr.wrap(o,s).scrollIntoView()),!0):!1}}function xr(e,t=null){return function(n,r){let i=!1;for(let r=0;r<n.selection.ranges.length&&!i;r++){let{$from:{pos:a},$to:{pos:o}}=n.selection.ranges[r];n.doc.nodesBetween(a,o,(r,a)=>{if(i)return!1;if(r.isTextblock&&!r.hasMarkup(e,t)){if(r.type==e)i=!0;else{let t=n.doc.resolve(a),r=t.index();i=t.parent.canReplaceWith(r,r+1,e)}}})}if(!i)return!1;if(r){let i=n.tr;for(let r=0;r<n.selection.ranges.length;r++){let{$from:{pos:a},$to:{pos:o}}=n.selection.ranges[r];i.setBlockType(a,o,e,t)}r(i.scrollIntoView())}return!0}}function Sr(...e){return function(t,n,r){for(let i=0;i<e.length;i++)if(e[i](t,n,r))return!0;return!1}}var Cr=Sr(Wn,Kn,Zn),wr=Sr(Wn,er,tr),Tr={Enter:Sr(or,lrLine truncated
`),u&&t==e.nodeValue.length)for(let t=e,n;t;t=t.parentNode){if(n=t.nextSibling){n.nodeName==`BR`&&(o=s={node:n.parentNode,offset:Fr(n)+1});break}let e=t.pmViewDesc;if(e&&e.node&&e.node.isBlock)break}}else{let n=e.childNodes[t-1];u=n&&(n.nodeName==`BR`||n.contentEditable==`false`)}}if(ci&&l.focusNode&&l.focusNode!=s.node&&O(l.focusNode)){let e=l.focusNode.childNodes[l.focusOffset];e&&e.contentEditable==`false`&&(r=!0)}if(!(r||u&&fi)&&Br(o.node,o.offset,l.anchorNode,l.anchorOffset)&&Br(s.node,s.offset,l.focusNode,l.focusOffset))return;let d=!1;if((c.extend||e==t)&&!(u&&ci)){c.collapse(o.node,o.offset);try{e!=t&&c.extend(s.node,s.offset),d=!0}catch{}}if(!d){if(e>t){let e=o;o=s,s=e}let n=document.createRange();n.setEnd(s.node,s.offset),n.setStart(o.node,o.offset),c.removeAllRanges(),c.addRange(n)}}ignoreMutation(e){return!this.contentDOM&&e.type!=`selection`}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let n=0,r=0;r<this.children.length;r++){let i=this.children[r],a=n+i.size;if(n==a?e<=a&&t>=n:e<a&&t>n){let r=n+i.border,o=a-i.border;if(e>=r&&t<=o){this.dirty=e==n||t==a?$i:Qi,e==r&&t==o&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=ea:i.markDirty(e-r,t-r);return}i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?$i:ea}n=a}this.dirty=$i}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let n=e==1?$i:Qi;t.dirty<n&&(t.dirty=n)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}},na=class extends ta{constructor(e,t,n,r){let i,a=t.type.toDOM;if(typeof a==`function`&&(a=a(n,()=>{if(!i)return r;if(i.parent)return i.parent.posBeforeChild(i)})),!t.type.spec.raw){let e=O(a)?a:document.createElement(`span`);e!=a&&(e.appendChild(a),a=e),e.hasAttribute(`contenteditable`)||(e.contentEditable=`false`),e.classList.add(`ProseMirror-widget`)}super(e,[],a,null),this.widget=t,this.widget=t,i=this}matchesWidget(e){return this.dirty==Zi&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!=`selection`||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},ra=class extends ta{constructor(e,t,n,r){super(e,[],t,null),this.textDOM=n,this.text=r}get size(){return this.text.length}localPosFromDOM(e,t){return e==this.textDOM?this.posAtStart+t:this.posAtStart+(t?this.size:0)}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type===`characterData`&&e.target.nodeValue==e.oldValue}},ia=class e extends ta{constructor(e,t,n,r,i){super(e,[],n,r),this.mark=t,this.spec=i}static create(t,n,r,i){let a=i.nodeViews[n.type.name],o=a&&a(n,i,r);return o&&o.dom||(o=Ze.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new e(t,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&ea||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ea&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=Zi){let e=this.parent;for(;!e.node;)e=e.parent;e.dirty<this.dirty&&(e.dirty=this.dirty),this.dirty=Zi}}slice(t,n,r){let i=e.create(this.parent,this.mark,!0,r),a=this.children,o=this.size;n<o&&(a=Ta(a,n,o,r)),t>0&&(a=Ta(a,0,t,r));for(let e=0;e<a.length;e++)a[e].parent=i;return i.children=a,i}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}},aa=class e extends ta{constructor(e,t,n,r,i,a,o){super(e,[],i,a),this.node=t,this.outerDeco=n,this.innerDeco=r,this.nodeDOM=o}static create(t,n,r,i,a,o){let s=a.nodeViews[n.type.name],c,l=s&&s(n,a,()=>{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),u=l&&l.dom,d=l&&l.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(!Wr(u))throw RangeError(`Text must be rendered as a DOM text node`)}else if(!u){let e=Ze.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs);({dom:u,contentDOM:d}=e)}!d&&!n.isText&&u.nodeName!=`BR`&&(u.hasAttribute(`contenteditable`)||(u.contentEditable=`false`),n.type.spec.draggable&&(u.draggable=!0));let f=u;return u=ga(u,r,n),l?c=new la(t,n,r,i,u,d||null,f,l):n.isText?new sa(t,n,r,i,u,f):new e(t,n,r,i,u,d||null,f)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace==`pre`&&(t.preserveWhitespace=`full`),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let e=this.children.length-1;e>=0;e--){let n=this.children[e];if(this.dom.contains(n.dom.parentNode)){t.contentElement=n.dom.parentNode;Line truncated
`),slice:t}}function oo(e,t,n,r,i){let a=i.parent.type.spec.code,o,c;if(!n&&!t)return null;let l=!!t&&(r||a||!n);if(l){if(e.someProp(`transformPastedText`,n=>{t=n(t,a||r,e)}),a)return c=new p(s.from(e.state.schema.text(t.replace(/\r\n?/g,`
`))),0,0),e.someProp(`transformPasted`,t=>{c=t(c,e,!0)}),c;let n=e.someProp(`clipboardTextParser`,n=>n(t,i,r,e));if(n)c=n;else{let n=i.marks(),{schema:r}=e.state,a=Qe.fromSchema(r);o=document.createElement(`div`),t.split(/(?:\r\n?|\n)+/).forEach(e=>{let t=o.appendChild(document.createElement(`p`));e&&t.appendChild(a.serializeNode(r.text(e,n)))})}}else e.someProp(`transformPastedHTML`,t=>{n=t(n,e)}),o=yo(n),_i&&bo(o);let u=o&&o.querySelector(`[data-pm-slice]`),d=u&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(u.getAttribute(`data-pm-slice`)||``);if(d&&d[3])for(let e=+d[3];e>0;e--){let e=o.firstChild;for(;e&&!O(e);)e=e.nextSibling;if(!e)break;o=e}if(c||=(e.someProp(`clipboardParser`)||e.someProp(`domParser`)||Re.fromSchema(e.state.schema)).parseSlice(o,{preserveWhitespace:!!(l||d),context:i,ruleFromNode(e){return e.nodeName==`BR`&&!e.nextSibling&&e.parentNode&&!so.test(e.parentNode.nodeName)?{ignore:!0}:null}}),d)c=xo(mo(c,+d[1],+d[2]),d[4]);else if(c=p.maxOpen(co(c.content,i),!0),c.openStart||c.openEnd){let e=0,t=0;for(let t=c.content.firstChild;e<c.openStart&&!t.type.spec.isolating;e++,t=t.firstChild);for(let e=c.content.lastChild;t<c.openEnd&&!e.type.spec.isolating;t++,e=e.lastChild);c=mo(c,e,t)}return e.someProp(`transformPasted`,t=>{c=t(c,e,l)}),c}var so=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function co(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.index(n)),i,a=[];if(e.forEach(e=>{if(!a)return;let t=r.findWrapping(e.type),n;if(!t)return a=null;if(n=a.length&&i.length&&uo(t,i,e,a[a.length-1],0))a[a.length-1]=n;else{a.length&&(a[a.length-1]=fo(a[a.length-1],i.length));let n=lo(e,t);a.push(n),r=r.matchType(n.type),i=t}}),a)return s.from(a)}return e}function lo(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,s.from(e));return e}function uo(e,t,n,r,i){if(i<e.length&&i<t.length&&e[i]==t[i]){let a=uo(e,t,n,r.lastChild,i+1);if(a)return r.copy(r.content.replaceChild(r.childCount-1,a));if(r.contentMatchAt(r.childCount).matchType(i==e.length-1?n.type:e[i+1]))return r.copy(r.content.append(s.from(lo(n,e,i+1))))}}function fo(e,t){if(t==0)return e;let n=e.content.replaceChild(e.childCount-1,fo(e.lastChild,t-1)),r=e.contentMatchAt(e.childCount).fillBefore(s.empty,!0);return e.copy(n.append(r))}function po(e,t,n,r,i,a){let o=t<0?e.firstChild:e.lastChild,c=o.content;return e.childCount>1&&(a=0),i<r-1&&(c=po(c,t,n,r,i+1,a)),i>=n&&(c=t<0?o.contentMatchAt(0).fillBefore(c,a<=i).append(c):c.append(o.contentMatchAt(o.childCount).fillBefore(s.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,o.copy(c))}function mo(e,t,n){return t<e.openStart&&(e=new p(po(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),n<e.openEnd&&(e=new p(po(e.content,1,n,e.openEnd,0,0),e.openStart,n)),e}var ho={thead:[`table`],tbody:[`table`],tfoot:[`table`],caption:[`table`],colgroup:[`table`],col:[`table`,`colgroup`],tr:[`table`,`tbody`],td:[`table`,`tbody`,`tr`],th:[`table`,`tbody`,`tr`]};function go(){return document.implementation.createHTMLDocument(`title`)}var _o=null;function vo(e){let t=window.trustedTypes;if(!t)return e;if(!_o){if(_o=t.defaultPolicy)try{return _o.createHTML(e)}catch{}_o=t.createPolicy(`ProseMirrorClipboard`,{createHTML:e=>e})}return _o.createHTML(e)}function yo(e){let t=/^(\s*<meta [^>]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let n=go(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(e),a;if((a=i&&ho[i[1].toLowerCase()])&&(e=a.map(e=>`<`+e+`>`).join(``)+e+a.map(e=>`</`+e+`>`).reverse().join(``)),r.innerHTML=vo(e),a)for(let e=0;e<a.length;e++)r=r.querySelector(a[e])||r;for(let e=0;e<n.styleSheets.length;e++){let t=n.styleSheets[e];for(let e=0;e<t.rules.length;e++){let n=t.rules[e];if(n instanceof CSSStyleRule){let e=r.querySelectorAll(n.selectorText);for(let t=0;t<e.length;t++)e[t].style.cssText+=n.style.cssText}}}return r}function bo(e){let t=e.querySelectorAll(ui?`span:not([class]):not([style])`:`span.Apple-converted-space`);for(let n=0;n<t.length;n++){let r=t[n];r.childNodes.length==1&&r.textContent==`\xA0`&&r.parentNode&&r.parentNode.replaceChild(e.ownerDocument.createTextNode(` `),r)}}function xo(e,t){if(!e.size)return e;let n=e.content.firstChild.type.schema,r;try{r=JSON.parse(t)}catch{return e}let{content:i,openStart:a,openEnd:o}=e;for(let e=r.length-2;e>=0;e-=2){let t=n.nodes[r[e]];if(!t||t.hasRequiredAttrs())break;try{i=s.from(t.create(r[e+1],i))}catch{break}a++,o++}return new p(i,a,o)}var So={},Co={},wo={touchstart:!0,touchmove:!0},To=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:``,button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariCompoLine truncated
`))),0,0),e.someProp(`transformPasted`,t=>{c=t(c,e,!0)}),c;let n=e.someProp(`clipboardTextParser`,n=>n(t,i,r,e));if(n)c=n;else{let n=i.marks(),{schema:r}=e.state,a=Ze.fromSchema(r);o=document.createElement(`div`),t.split(/(?:\r\n?|\n)+/).forEach(e=>{let t=o.appendChild(document.createElement(`p`));e&&t.appendChild(a.serializeNode(r.text(e,n)))})}}else e.someProp(`transformPastedHTML`,t=>{n=t(n,e)}),o=yo(n),_i&&bo(o);let u=o&&o.querySelector(`[data-pm-slice]`),d=u&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(u.getAttribute(`data-pm-slice`)||``);if(d&&d[3])for(let e=+d[3];e>0;e--){let e=o.firstChild;for(;e&&!O(e);)e=e.nextSibling;if(!e)break;o=e}if(c||=(e.someProp(`clipboardParser`)||e.someProp(`domParser`)||Le.fromSchema(e.state.schema)).parseSlice(o,{preserveWhitespace:!!(l||d),context:i,ruleFromNode(e){return e.nodeName==`BR`&&!e.nextSibling&&e.parentNode&&!so.test(e.parentNode.nodeName)?{ignore:!0}:null}}),d)c=xo(mo(c,+d[1],+d[2]),d[4]);else if(c=p.maxOpen(co(c.content,i),!0),c.openStart||c.openEnd){let e=0,t=0;for(let t=c.content.firstChild;e<c.openStart&&!t.type.spec.isolating;e++,t=t.firstChild);for(let e=c.content.lastChild;t<c.openEnd&&!e.type.spec.isolating;t++,e=e.lastChild);c=mo(c,e,t)}return e.someProp(`transformPasted`,t=>{c=t(c,e,l)}),c}var so=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function co(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.index(n)),i,a=[];if(e.forEach(e=>{if(!a)return;let t=r.findWrapping(e.type),n;if(!t)return a=null;if(n=a.length&&i.length&&uo(t,i,e,a[a.length-1],0))a[a.length-1]=n;else{a.length&&(a[a.length-1]=fo(a[a.length-1],i.length));let n=lo(e,t);a.push(n),r=r.matchType(n.type),i=t}}),a)return s.from(a)}return e}function lo(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,s.from(e));return e}function uo(e,t,n,r,i){if(i<e.length&&i<t.length&&e[i]==t[i]){let a=uo(e,t,n,r.lastChild,i+1);if(a)return r.copy(r.content.replaceChild(r.childCount-1,a));if(r.contentMatchAt(r.childCount).matchType(i==e.length-1?n.type:e[i+1]))return r.copy(r.content.append(s.from(lo(n,e,i+1))))}}function fo(e,t){if(t==0)return e;let n=e.content.replaceChild(e.childCount-1,fo(e.lastChild,t-1)),r=e.contentMatchAt(e.childCount).fillBefore(s.empty,!0);return e.copy(n.append(r))}function po(e,t,n,r,i,a){let o=t<0?e.firstChild:e.lastChild,c=o.content;return e.childCount>1&&(a=0),i<r-1&&(c=po(c,t,n,r,i+1,a)),i>=n&&(c=t<0?o.contentMatchAt(0).fillBefore(c,a<=i).append(c):c.append(o.contentMatchAt(o.childCount).fillBefore(s.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,o.copy(c))}function mo(e,t,n){return t<e.openStart&&(e=new p(po(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),n<e.openEnd&&(e=new p(po(e.content,1,n,e.openEnd,0,0),e.openStart,n)),e}var ho={thead:[`table`],tbody:[`table`],tfoot:[`table`],caption:[`table`],colgroup:[`table`],col:[`table`,`colgroup`],tr:[`table`,`tbody`],td:[`table`,`tbody`,`tr`],th:[`table`,`tbody`,`tr`]};function go(){return document.implementation.createHTMLDocument(`title`)}var _o=null;function vo(e){let t=window.trustedTypes;if(!t)return e;if(!_o){if(_o=t.defaultPolicy)try{return _o.createHTML(e)}catch{}_o=t.createPolicy(`ProseMirrorClipboard`,{createHTML:e=>e})}return _o.createHTML(e)}function yo(e){let t=/^(\s*<meta [^>]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let n=go(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(e),a;if((a=i&&ho[i[1].toLowerCase()])&&(e=a.map(e=>`<`+e+`>`).join(``)+e+a.map(e=>`</`+e+`>`).reverse().join(``)),r.innerHTML=vo(e),a)for(let e=0;e<a.length;e++)r=r.querySelector(a[e])||r;for(let e=0;e<n.styleSheets.length;e++){let t=n.styleSheets[e];for(let e=0;e<t.rules.length;e++){let n=t.rules[e];if(n instanceof CSSStyleRule){let e=r.querySelectorAll(n.selectorText);for(let t=0;t<e.length;t++)e[t].style.cssText+=n.style.cssText}}}return r}function bo(e){let t=e.querySelectorAll(ui?`span:not([class]):not([style])`:`span.Apple-converted-space`);for(let n=0;n<t.length;n++){let r=t[n];r.childNodes.length==1&&r.textContent==`\xA0`&&r.parentNode&&r.parentNode.replaceChild(e.ownerDocument.createTextNode(` `),r)}}function xo(e,t){if(!e.size)return e;let n=e.content.firstChild.type.schema,r;try{r=JSON.parse(t)}catch{return e}let{content:i,openStart:a,openEnd:o}=e;for(let e=r.length-2;e>=0;e-=2){let t=n.nodes[r[e]];if(!t||t.hasRequiredAttrs())break;try{i=s.from(t.create(r[e+1],i))}catch{break}a++,o++}return new p(i,a,o)}var So={},Co={},wo={touchstart:!0,touchmove:!0},To=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:``,button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariCompoLine truncated
`,textSerializers:o={}}=n||{},s=``;return e.nodesBetween(r,i,(e,n,c,l)=>{e.isBlock&&n>r&&(s+=a);let u=o?.[e.type.name];if(u)return c&&(s+=u({node:e,pos:n,parent:c,index:l,range:t})),!1;if(e.isText){var d;s+=e==null||(d=e.text)==null?void 0:d.slice(Math.max(r,n)-n,i-n)}}),s}function qu(e,t){return Ku(e,{from:0,to:e.content.size},t)}function Ju(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Yu(e,t){let n=il(t,e.schema),{from:r,to:i}=e.selection,a=[];e.doc.nodesBetween(r,i,e=>{a.push(e)});let o=a.reverse().find(e=>e.type.name===n.name);return o?{...o.attrs}:{}}function Xu(e,t){let n=nu(typeof t==`string`?t:t.name,e.schema);return n===`node`?Yu(e,t):n===`mark`?mu(e,t):{}}function Zu(e,t=JSON.stringify){let n={};return e.filter(e=>{let r=t(e);return Object.prototype.hasOwnProperty.call(n,r)?!1:n[r]=!0})}function Qu(e){let t=Zu(e);return t.length===1?t:t.filter((e,n)=>!t.filter((e,t)=>t!==n).some(t=>e.oldRange.from>=t.oldRange.from&&e.oldRange.to<=t.oldRange.to&&e.newRange.from>=t.newRange.from&&e.newRange.to<=t.newRange.to))}function $u(e){let{mapping:t,steps:n}=e,r=[],i=t.invert();return t.maps.forEach((e,a)=>{let o=[];if(e.ranges.length)e.forEach((e,t)=>{o.push({from:e,to:t})});else{let{from:e,to:t}=n[a];if(e===void 0||t===void 0)return;o.push({from:e,to:t})}let s=t.slice(a);o.forEach(({from:e,to:t})=>{let n=s.map(e,-1),a=s.map(t),o=i.map(n,-1),c=i.map(a);r.push({oldRange:{from:o,to:c},newRange:{from:n,to:a}})})}),Qu(r)}function ed(e,t,n){let r=[];return e===t?n.resolve(e).marks().forEach(t=>{let i=_l(n.resolve(e),t.type);i&&r.push({mark:t,...i})}):n.nodesBetween(e,t,(e,t)=>{e&&e?.nodeSize!==void 0&&r.push(...e.marks.map(n=>({from:t,to:t+e.nodeSize,mark:n})))}),r}var td=(e,t,n,r=20)=>{let i=e.doc.resolve(n),a=r,o=null;for(;a>0&&o===null;){let e=i.node(a);e?.type.name===t?o=e:--a}return[o,a]},nd=e=>{let t=e.depth-1;if(t<0)return null;let n=e.index(t);return n===0?null:e.node(t).child(n-1)};function rd(e,t){return t.nodes[e]||t.marks[e]||null}function id(e,t,n){return Object.fromEntries(Object.entries(n).filter(([n])=>{let r=e.find(e=>e.type===t&&e.name===n);return r?r.attribute.keepOnSplit:!1}))}var ad=(e,t=500)=>{let n=``,r=e.parentOffset;return e.parent.nodesBetween(Math.max(0,r-t),r,(e,t,i,a)=>{var o;let s=(o=e.type.spec).toText?.call(o,{node:e,pos:t,parent:i,index:a})||e.textContent||`%leaf%`;n+=e.isAtom&&!e.isText?s:s.slice(0,Math.max(0,r-t))}),n};function od(e,t,n={}){let{empty:r,ranges:i}=e.selection,a=t?vl(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(e=>!a||a.name===e.type.name).find(e=>ml(e.attrs,n,{strict:!1}));let o=0,s=[];if(i.forEach(({$from:t,$to:n})=>{let r=t.pos,i=n.pos;e.doc.nodesBetween(r,i,(e,t)=>{if(a&&e.inlineContent&&!e.type.allowsMarkType(a))return!1;if(!e.isText&&!e.marks.length)return;let n=Math.max(r,t),c=Math.min(i,t+e.nodeSize),l=c-n;o+=l,s.push(...e.marks.map(e=>({mark:e,from:n,to:c})))})}),o===0)return!1;let c=s.filter(e=>!a||a.name===e.mark.type.name).filter(e=>ml(e.mark.attrs,n,{strict:!1})).reduce((e,t)=>e+t.to-t.from,0),l=s.filter(e=>!a||e.mark.type!==a&&e.mark.type.excludes(a)).reduce((e,t)=>e+t.to-t.from,0);return(c>0?c+l:c)>=o}function sd(e,t,n={}){if(!t)return Zl(e,null,n)||od(e,null,n);let r=nu(t,e.schema);return r===`node`?Zl(e,t,n):r===`mark`&&od(e,t,n)}var cd=(e,t)=>{let{$from:n,$to:r,$anchor:i}=e.selection;if(t){let n=yu(e=>e.type.name===t)(e.selection);if(!n)return!1;let r=e.doc.resolve(n.pos+1);return i.pos+1===r.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)},ld=e=>{let{$from:t,$to:n}=e.selection;return!(t.parentOffset>0||t.pos!==n.pos)};function ud(e,t){return Array.isArray(t)?t.some(t=>(typeof t==`string`?t:t.name)===e.name):t}function dd(e,t){let{nodeExtensions:n}=Au(t),r=n.find(t=>t.name===e);if(!r)return!1;let i=Nu(k(r,`group`,{name:r.name,options:r.options,storage:r.storage}));return typeof i==`string`&&i.split(` `).includes(`list`)}function fd(e,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){if(n){if(e.type.name===`hardBreak`)return!0;if(e.isText)return!/\S/.test(e.text??``)}if(e.isText)return!e.text;if(e.isAtom||e.isLeaf)return!1;if(e.content.childCount===0)return!0;if(t){let r=!0;return e.content.forEach(e=>{r!==!1&&(fd(e,{ignoreWhitespace:n,checkChildren:t})||(r=!1))}),r}return!1}function pd(e){return e instanceof T}function md(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.apply==`function`&&typeof t.getMap==`function`&&typeof t.invert==`function`&&typeof t.map==`function`&&typeof t.merge==`function`&&typeof t.toJSON==`function`}function hd(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!md(t))return!1;let n=t.toJSON();return!(typeof n!=`object`||!n||n.stepType!==`replace`)}var gd=class e{constructor(e){this.position=e}static fromJSON(t){return new e(t.position)}toJSON(){return{position:this.position}}};function _d(e,t){let n=t.mapping.mapResult(e.position);return{position:new gd(n.pos),mapResult:n}}function Line truncated
`,textSerializers:o={}}=n||{},s=``;return e.nodesBetween(r,i,(e,n,c,l)=>{e.isBlock&&n>r&&(s+=a);let u=o?.[e.type.name];if(u)return c&&(s+=u({node:e,pos:n,parent:c,index:l,range:t})),!1;if(e.isText){var d;s+=e==null||(d=e.text)==null?void 0:d.slice(Math.max(r,n)-n,i-n)}}),s}function qu(e,t){return Ku(e,{from:0,to:e.content.size},t)}function Ju(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Yu(e,t){let n=il(t,e.schema),{from:r,to:i}=e.selection,a=[];e.doc.nodesBetween(r,i,e=>{a.push(e)});let o=a.reverse().find(e=>e.type.name===n.name);return o?{...o.attrs}:{}}function Xu(e,t){let n=nu(typeof t==`string`?t:t.name,e.schema);return n===`node`?Yu(e,t):n===`mark`?mu(e,t):{}}function Zu(e,t=JSON.stringify){let n={};return e.filter(e=>{let r=t(e);return Object.prototype.hasOwnProperty.call(n,r)?!1:n[r]=!0})}function Qu(e){let t=Zu(e);return t.length===1?t:t.filter((e,n)=>!t.filter((e,t)=>t!==n).some(t=>e.oldRange.from>=t.oldRange.from&&e.oldRange.to<=t.oldRange.to&&e.newRange.from>=t.newRange.from&&e.newRange.to<=t.newRange.to))}function $u(e){let{mapping:t,steps:n}=e,r=[],i=t.invert();return t.maps.forEach((e,a)=>{let o=[];if(e.ranges.length)e.forEach((e,t)=>{o.push({from:e,to:t})});else{let{from:e,to:t}=n[a];if(e===void 0||t===void 0)return;o.push({from:e,to:t})}let s=t.slice(a);o.forEach(({from:e,to:t})=>{let n=s.map(e,-1),a=s.map(t),o=i.map(n,-1),c=i.map(a);r.push({oldRange:{from:o,to:c},newRange:{from:n,to:a}})})}),Qu(r)}function ed(e,t,n){let r=[];return e===t?n.resolve(e).marks().forEach(t=>{let i=_l(n.resolve(e),t.type);i&&r.push({mark:t,...i})}):n.nodesBetween(e,t,(e,t)=>{e&&e?.nodeSize!==void 0&&r.push(...e.marks.map(n=>({from:t,to:t+e.nodeSize,mark:n})))}),r}var td=(e,t,n,r=20)=>{let i=e.doc.resolve(n),a=r,o=null;for(;a>0&&o===null;){let e=i.node(a);e?.type.name===t?o=e:--a}return[o,a]},nd=e=>{let t=e.depth-1;if(t<0)return null;let n=e.index(t);return n===0?null:e.node(t).child(n-1)};function rd(e,t){return t.nodes[e]||t.marks[e]||null}function id(e,t,n){return Object.fromEntries(Object.entries(n).filter(([n])=>{let r=e.find(e=>e.type===t&&e.name===n);return r?r.attribute.keepOnSplit:!1}))}var ad=(e,t=500)=>{let n=``,r=e.parentOffset;return e.parent.nodesBetween(Math.max(0,r-t),r,(e,t,i,a)=>{var o;let s=(o=e.type.spec).toText?.call(o,{node:e,pos:t,parent:i,index:a})||e.textContent||`%leaf%`;n+=e.isAtom&&!e.isText?s:s.slice(0,Math.max(0,r-t))}),n};function od(e,t,n={}){let{empty:r,ranges:i}=e.selection,a=t?vl(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(e=>!a||a.name===e.type.name).find(e=>ml(e.attrs,n,{strict:!1}));let o=0,s=[];if(i.forEach(({$from:t,$to:n})=>{let r=t.pos,i=n.pos;e.doc.nodesBetween(r,i,(e,t)=>{if(a&&e.inlineContent&&!e.type.allowsMarkType(a))return!1;if(!e.isText&&!e.marks.length)return;let n=Math.max(r,t),c=Math.min(i,t+e.nodeSize),l=c-n;o+=l,s.push(...e.marks.map(e=>({mark:e,from:n,to:c})))})}),o===0)return!1;let c=s.filter(e=>!a||a.name===e.mark.type.name).filter(e=>ml(e.mark.attrs,n,{strict:!1})).reduce((e,t)=>e+t.to-t.from,0),l=s.filter(e=>!a||e.mark.type!==a&&e.mark.type.excludes(a)).reduce((e,t)=>e+t.to-t.from,0);return(c>0?c+l:c)>=o}function sd(e,t,n={}){if(!t)return Zl(e,null,n)||od(e,null,n);let r=nu(t,e.schema);return r===`node`?Zl(e,t,n):r===`mark`&&od(e,t,n)}var cd=(e,t)=>{let{$from:n,$to:r,$anchor:i}=e.selection;if(t){let n=yu(e=>e.type.name===t)(e.selection);if(!n)return!1;let r=e.doc.resolve(n.pos+1);return i.pos+1===r.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)},ld=e=>{let{$from:t,$to:n}=e.selection;return!(t.parentOffset>0||t.pos!==n.pos)};function ud(e,t){return Array.isArray(t)?t.some(t=>(typeof t==`string`?t:t.name)===e.name):t}function dd(e,t){let{nodeExtensions:n}=Au(t),r=n.find(t=>t.name===e);if(!r)return!1;let i=Nu(k(r,`group`,{name:r.name,options:r.options,storage:r.storage}));return typeof i==`string`&&i.split(` `).includes(`list`)}function fd(e,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){if(n){if(e.type.name===`hardBreak`)return!0;if(e.isText)return!/\S/.test(e.text??``)}if(e.isText)return!e.text;if(e.isAtom||e.isLeaf)return!1;if(e.content.childCount===0)return!0;if(t){let r=!0;return e.content.forEach(e=>{r!==!1&&(fd(e,{ignoreWhitespace:n,checkChildren:t})||(r=!1))}),r}return!1}function pd(e){return e instanceof E}function md(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.apply==`function`&&typeof t.getMap==`function`&&typeof t.invert==`function`&&typeof t.map==`function`&&typeof t.merge==`function`&&typeof t.toJSON==`function`}function hd(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!md(t))return!1;let n=t.toJSON();return!(typeof n!=`object`||!n||n.stepType!==`replace`)}var gd=class e{constructor(e){this.position=e}static fromJSON(t){return new e(t.position)}toJSON(){return{position:this.position}}};function _d(e,t){let n=t.mapping.mapResult(e.position);return{position:new gd(n.pos),mapResult:n}}function Line truncated
`);return`:::${l}${i}\n\n${o}\n\n:::`}}}function Zf(e){let t={};return Kf(e,`shortcode`).forEach(e=>{e.type===`keyValue`&&(t[e.name]=e.value)}),t}function Qf(e){return Object.entries(e).filter(([,e])=>e!=null).map(([e,t])=>`${e}="${t}"`).join(` `)}function $f(e){let{nodeName:t,name:n,getContent:r,parseAttributes:i=Zf,serializeAttributes:a=Qf,defaultAttributes:o={},selfClosing:s=!1,allowedAttributes:c}=e,l=n||t,u=e=>{if(!c)return e;let t={};return c.forEach(n=>{let r=typeof n==`string`?n:n.name,i=typeof n==`string`?void 0:n.skipIfDefault;if(r in e){let n=e[r];if(i!==void 0&&n===i)return;t[r]=n}}),t},d=l.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return{parseMarkdown:(e,n)=>{let i={...o,...e.attributes};if(s)return n.createNode(t,i);let a=r?r(e):e.content||``;return a?n.createNode(t,i,[n.createTextNode(a)]):n.createNode(t,i,[])},markdownTokenizer:{name:t,level:`inline`,start(e){let t=RegExp(s?`\\[${d}\\s*[^\\]]*\\]`:`\\[${d}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${d}\\]`),n=e.match(t)?.index;return n===void 0?-1:n},tokenize(e,n,r){let a=RegExp(s?`^\\[${d}\\s*([^\\]]*)\\]`:`^\\[${d}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${d}\\]`),o=e.match(a);if(!o)return;let c=``,l=``;if(s){let[,e]=o;l=e}else{let[,e,t]=o;l=e,c=t||``}let u=i(l.trim());return{type:t,raw:o[0],content:c.trim(),attributes:u}}},renderMarkdown:e=>{let t=``;r?t=r(e):e.content&&e.content.length>0&&(t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``));let n=u(e.attrs||{}),i=a(n),o=i?` ${i}`:``;return s?`[${l}${o}]`:`[${l}${o}]${t}[/${l}]`}}}function ep(e,t){return e.replace(/^[ \t]*/,e=>{let n=0;for(let t of e)n+=t===` `?4-n%4:1;return` `.repeat(Math.max(0,n-t))})}function tp(e,t){let n=`text\n${e}\n`,r=t(n)[0];return(r?.type===`paragraph`||r?.type===`text`)&&r.raw===n}function np(e,t,n){let r=t.split(`
`),i=n.isParagraphContinuation??(e=>tp(e,n.blockTokens)),a=0;for(let e of r){if(!e.trim()||!i(e))break;a+=1}return{mainContent:[e,...r.slice(0,a).map(e=>e.trimStart())].join(`
@@ -27,10 +27,10 @@
`).map((e,n)=>n===0?e:t.indent(e)).join(`
`):c}`;return s&&s.length>0&&s.forEach((e,n)=>{let r=t.renderChild?.call(t,e,n+1)??t.renderChildren([e]);if(r!=null){let n=e=>{if(!i?.alignNestedToPrefix)return t.indent(e);let n=t.indent(``),r=ap(a);return(ap(n)>=r?n:` `.repeat(r))+e},o=r.split(`
`).map(e=>n(e||``)).join(`
`);l+=e.type===`paragraph`?`\n\n${o}`:`\n${o}`}}),l}function sp(e,t){let n={...e};return Nf(e)&&Nf(t)&&Object.keys(t).forEach(r=>{Nf(t[r])&&Nf(e[r])?n[r]=sp(e[r],t[r]):n[r]=t[r]}),n}function cp(e,t,n={}){let{state:r}=t,{doc:i,tr:a}=r,o=e;i.descendants((t,r)=>{let i=a.mapping.map(r),s=a.mapping.map(r)+t.nodeSize,c=null;if(t.marks.forEach(e=>{if(e!==o)return!1;c=e}),!c)return;let l=!1;if(Object.keys(n).forEach(e=>{n[e]!==c.attrs[e]&&(l=!0)}),l){let t=e.type.create({...e.attrs,...n});a.removeMark(i,s,e.type),a.addMark(i,s,t)}}),a.docChanged&&t.view.dispatch(a)}var lp=class{constructor(e){this.find=e.find,this.handler=e.handler,this.undoable=e.undoable??!0}},up=(e,t)=>{if(pl(t))return t.exec(e);let n=t(e);if(!n)return null;let r=[n.text];return r.index=n.index,r.input=e,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn(`[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".`),r.push(n.replaceWith)),r};function dp(e){let{editor:t,from:n,to:r,text:i,insertText:a}=e;if(!a)return{inputTransaction:null,tr:t.view.state.tr};let o=t.view.state.tr.insertText(i,n,r);return{inputTransaction:o,tr:Bn.create({doc:o.doc,selection:o.selection,storedMarks:o.storedMarks}).tr}}function fp(e){let{editor:t,from:n,to:r,text:i,rule:a,match:o,plugin:s,insertText:c}=e,{view:l}=t,{inputTransaction:u,tr:d}=dp({editor:t,from:n,to:r,text:i,insertText:c}),f=u?n+i.length:r,p=Yc({state:l.state,transaction:d}),m={from:n-(o[0].length-i.length),to:f},{commands:h,chain:g,can:_}=new Xc({editor:t,state:p});return a.handler({state:p,range:m,match:o,commands:h,chain:g,can:_})===null||!d.steps.length?!1:(u&&(l.dispatch(u),!l.state.doc.eq(u.doc))||(Vc(d),d.setMeta(`inputRule`,!0),a.undoable&&d.setMeta(s,{transform:d,from:n,to:f,text:i}),l.dispatch(d)),!0)}function pp(e,t,n){let r=t[0].length-n.length;if(r<=0)return!0;let i=e.parentOffset-r;return i>=0&&e.parent.textBetween(i,e.parentOffset)===t[0].slice(0,r)}function mp(e){let{editor:t,from:n,to:r,text:i,rules:a,plugin:o,insertText:s}=e,{view:c}=t;if(c.composing)return!1;let l=c.state.doc.resolve(n);if(l.parent.type.spec.code||(l.nodeBefore||l.nodeAfter)?.marks.find(e=>e.type.spec.code))return!1;let u=ad(l)+i;for(let e of a){let a=up(u,e.find);if(a&&pp(l,a,i)&&fp({editor:t,from:n,to:r,text:i,rule:e,match:a,plugin:o,insertText:s}))return!0}return!1}function hp(e){let{editor:t,rules:n}=e,r=new E({state:{init(){return null},apply(e,i,a){let o=e.getMeta(r);if(o)return o;let c=e.getMeta(`applyInputRules`);return c&&setTimeout(()=>{let{text:e}=c;e=typeof e==`string`?e:xu(s.from(e),a.schema);let{from:i}=c,o=i+e.length;mp({editor:t,from:i,to:o,text:e,rules:n,plugin:r})}),e.selectionSet||e.docChanged?null:i}},props:{handleTextInput(e,i,a,o){return mp({editor:t,from:i,to:a,text:o,rules:n,plugin:r,insertText:!0})},handleDOMEvents:{compositionend:e=>(setTimeout(()=>{let{$cursor:i}=e.state.selection;i&&mp({editor:t,from:i.pos,to:i.pos,text:``,rules:n,plugin:r})}),!1)},handleKeyDown(e,i){if(i.key!==`Enter`)return!1;let{$cursor:a}=e.state.selection;return a?mp({editor:t,from:a.pos,to:a.pos,text:`
`,rules:n,plugin:r}):!1}},isInputRules:!0});return r}var gp=class{constructor(e={}){this.type=`extendable`,this.parent=null,this.child=null,this.name=``,this.config={name:this.name},this.config={...this.config,...e},this.name=this.config.name}get options(){return{...Nu(k(this,`addOptions`,{name:this.name}))}}get storage(){return{...Nu(k(this,`addStorage`,{name:this.name,options:this.options}))}}configure(e={}){let t=this.extend({...this.config,addOptions:()=>sp(this.options,e)});return t.name=this.name,t.parent=this.parent,this.child=null,t}extend(e={}){let t=new this.constructor({...this.config,...e});return t.parent=this,this.child=t,t.name=`name`in e?e.name:t.parent.name,t}},_p=class e extends gp{constructor(...e){super(...e),this.type=`mark`}static create(t={}){let n=typeof t==`function`?t():t;return new e(n)}static handleExit({editor:e,mark:t}){let{tr:n}=e.state,r=e.state.selection.$from;if(r.pos===r.end()){let i=r.marks();if(!i.find(e=>e?.type.name===t.name))return!1;let a=i.find(e=>e?.type.name===t.name);return a&&n.removeStoredMark(a),n.insertText(` `,r.pos),e.view.dispatch(n),!0}return!1}configure(e){return super.configure(e)}extend(e){let t=typeof e==`function`?e():e;return super.extend(t)}},vp=class{constructor(e){this.find=e.find,this.handler=e.handler}},yp=(e,t,n)=>{if(pl(t))return[...e.matchAll(t)];let r=t(e,n);return r?r.map(t=>{let n=[t.text];return n.index=t.index,n.input=e,n.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn(`[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".`),n.push(t.replaceWith)),n}):[]};function bp(e){let{editor:t,state:n,from:r,to:i,rule:a,pasteEvent:o,dropEvent:s}=e,{commands:c,chain:l,can:u}=new Xc({editor:t,state:n}),d=[];return n.doc.nodesBetween(r,i,(e,t)=>{var f;if((f=e.type)!=null&&(f=f.spec)!=null&&f.code||!(e.isText||e.isTextblock||e.isInline))return;let p=e.content?.size??e.nodeSize??0,m=Math.max(r,t),h=Math.min(i,t+p);m>=h||yp(e.isText?e.text||``:e.textBetween(m-t,h-t,void 0,``),a.find,o).forEach(e=>{if(e.index===void 0)return;let t=m+e.index+1,r=t+e[0].length,i={from:n.tr.mapping.map(t),to:n.tr.mapping.map(r)},f=a.handler({state:n,range:i,match:e,commands:c,chain:l,can:u,pasteEvent:o,dropEvent:s});d.push(f)})}),d.every(e=>e!==null)}var xp=null,Sp=e=>{var t;let n=new ClipboardEvent(`paste`,{clipboardData:new DataTransfer});return(t=n.clipboardData)==null||t.setData(`text/html`,e),n};function Cp(e){let{editor:t,rules:n}=e,r=null,i=!1,a=!1,o=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,c;try{c=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{c=null}let l=({state:e,from:n,to:r,rule:i,pasteEvt:a})=>{let s=e.tr,l=Yc({state:e,transaction:s});if(bp({editor:t,state:l,from:Math.max(n-1,0),to:r.b-1,rule:i,pasteEvent:a,dropEvent:c})&&s.steps.length){try{c=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{c=null}return o=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,s}};return t.on(`destroy`,()=>{xp===t&&(xp=null)}),n.map(e=>new E({view(e){let n=n=>{r=e.dom.parentElement?.contains(n.target)?e.dom.parentElement:null,r&&(xp=t)},i=()=>{xp&&=null};return window.addEventListener(`dragstart`,n),window.addEventListener(`dragend`,i),{destroy(){window.removeEventListener(`dragstart`,n),window.removeEventListener(`dragend`,i)}}},props:{handleDOMEvents:{drop:(e,t)=>{if(a=r===e.dom.parentElement,c=t,!a){let e=xp;e?.isEditable&&setTimeout(()=>{if(e.isDestroyed)return;let t=e.state.selection;t&&e.commands.deleteRange({from:t.from,to:t.to})},10)}return!1},paste:(e,t)=>{let n=t.clipboardData?.getData(`text/html`);return o=t,i=!!n?.includes(`data-pm-slice`),!1}}},appendTransaction:(t,n,r)=>{let c=t[0],u=c.getMeta(`uiEvent`)===`paste`&&!i,d=c.getMeta(`uiEvent`)===`drop`&&!a,f=c.getMeta(`applyPasteRules`),p=!!f;if(!u&&!d&&!p)return;if(p){let{text:t}=f;t=typeof t==`string`?t:xu(s.from(t),r.schema);let{from:n}=f,i=n+t.length,a=Sp(t);return l({rule:e,state:r,from:n,to:{b:i},pasteEvt:a})}let m=n.doc.content.findDiffStart(r.doc.content),h=n.doc.content.findDiffEnd(r.doc.content);if(jf(m)&&h&&m!==h.b)return l({rule:e,state:r,from:m,to:h,pasteEvt:o})}}))}var wp=class{constructor(e,t){this.splittableMarks=[],this.nonClearableMarks=[],this.decorationManager=null,this.editor=t,this.baseExtensions=e,this.extensions=Gu(e),this.hasSchemaSpec=t.options.schemaSpec!==void 0,this.schema=Uu(this.extensions,t,t.options.schemaSpec),this.setupExtensions()}get commands(){return this.extensions.reduce((e,t)=>{let n=k(t,`addCommands`,{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:this.editor,type:rd(t.name,this.schema)});return n?{...e,...n()}:e},{})}get plugins(){let{editor:e}=this,t=Wu([...this.extensions].reverse()).flatMap(t=>{let n={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:e,type:rd(t.name,this.schema)},r=[],i=k(t,`addKeyboardShortcuts`,n),a={};if(t.type===`mark`&&k(t,`exitable`,n)&&(a.ArrowRight=()=>_p.handleExit({editor:e,mark:t})),i){Line truncated
`);l+=e.type===`paragraph`?`\n\n${o}`:`\n${o}`}}),l}function sp(e,t){let n={...e};return Nf(e)&&Nf(t)&&Object.keys(t).forEach(r=>{Nf(t[r])&&Nf(e[r])?n[r]=sp(e[r],t[r]):n[r]=t[r]}),n}function cp(e,t,n={}){let{state:r}=t,{doc:i,tr:a}=r,o=e;i.descendants((t,r)=>{let i=a.mapping.map(r),s=a.mapping.map(r)+t.nodeSize,c=null;if(t.marks.forEach(e=>{if(e!==o)return!1;c=e}),!c)return;let l=!1;if(Object.keys(n).forEach(e=>{n[e]!==c.attrs[e]&&(l=!0)}),l){let t=e.type.create({...e.attrs,...n});a.removeMark(i,s,e.type),a.addMark(i,s,t)}}),a.docChanged&&t.view.dispatch(a)}var lp=class{constructor(e){this.find=e.find,this.handler=e.handler,this.undoable=e.undoable??!0}},up=(e,t)=>{if(pl(t))return t.exec(e);let n=t(e);if(!n)return null;let r=[n.text];return r.index=n.index,r.input=e,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn(`[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".`),r.push(n.replaceWith)),r};function dp(e){let{editor:t,from:n,to:r,text:i,insertText:a}=e;if(!a)return{inputTransaction:null,tr:t.view.state.tr};let o=t.view.state.tr.insertText(i,n,r);return{inputTransaction:o,tr:zn.create({doc:o.doc,selection:o.selection,storedMarks:o.storedMarks}).tr}}function fp(e){let{editor:t,from:n,to:r,text:i,rule:a,match:o,plugin:s,insertText:c}=e,{view:l}=t,{inputTransaction:u,tr:d}=dp({editor:t,from:n,to:r,text:i,insertText:c}),f=u?n+i.length:r,p=Yc({state:l.state,transaction:d}),m={from:n-(o[0].length-i.length),to:f},{commands:h,chain:g,can:_}=new Xc({editor:t,state:p});return a.handler({state:p,range:m,match:o,commands:h,chain:g,can:_})===null||!d.steps.length?!1:(u&&(l.dispatch(u),!l.state.doc.eq(u.doc))||(Vc(d),d.setMeta(`inputRule`,!0),a.undoable&&d.setMeta(s,{transform:d,from:n,to:f,text:i}),l.dispatch(d)),!0)}function pp(e,t,n){let r=t[0].length-n.length;if(r<=0)return!0;let i=e.parentOffset-r;return i>=0&&e.parent.textBetween(i,e.parentOffset)===t[0].slice(0,r)}function mp(e){let{editor:t,from:n,to:r,text:i,rules:a,plugin:o,insertText:s}=e,{view:c}=t;if(c.composing)return!1;let l=c.state.doc.resolve(n);if(l.parent.type.spec.code||(l.nodeBefore||l.nodeAfter)?.marks.find(e=>e.type.spec.code))return!1;let u=ad(l)+i;for(let e of a){let a=up(u,e.find);if(a&&pp(l,a,i)&&fp({editor:t,from:n,to:r,text:i,rule:e,match:a,plugin:o,insertText:s}))return!0}return!1}function hp(e){let{editor:t,rules:n}=e,r=new D({state:{init(){return null},apply(e,i,a){let o=e.getMeta(r);if(o)return o;let c=e.getMeta(`applyInputRules`);return c&&setTimeout(()=>{let{text:e}=c;e=typeof e==`string`?e:xu(s.from(e),a.schema);let{from:i}=c,o=i+e.length;mp({editor:t,from:i,to:o,text:e,rules:n,plugin:r})}),e.selectionSet||e.docChanged?null:i}},props:{handleTextInput(e,i,a,o){return mp({editor:t,from:i,to:a,text:o,rules:n,plugin:r,insertText:!0})},handleDOMEvents:{compositionend:e=>(setTimeout(()=>{let{$cursor:i}=e.state.selection;i&&mp({editor:t,from:i.pos,to:i.pos,text:``,rules:n,plugin:r})}),!1)},handleKeyDown(e,i){if(i.key!==`Enter`)return!1;let{$cursor:a}=e.state.selection;return a?mp({editor:t,from:a.pos,to:a.pos,text:`
`,rules:n,plugin:r}):!1}},isInputRules:!0});return r}var gp=class{constructor(e={}){this.type=`extendable`,this.parent=null,this.child=null,this.name=``,this.config={name:this.name},this.config={...this.config,...e},this.name=this.config.name}get options(){return{...Nu(k(this,`addOptions`,{name:this.name}))}}get storage(){return{...Nu(k(this,`addStorage`,{name:this.name,options:this.options}))}}configure(e={}){let t=this.extend({...this.config,addOptions:()=>sp(this.options,e)});return t.name=this.name,t.parent=this.parent,this.child=null,t}extend(e={}){let t=new this.constructor({...this.config,...e});return t.parent=this,this.child=t,t.name=`name`in e?e.name:t.parent.name,t}},_p=class e extends gp{constructor(...e){super(...e),this.type=`mark`}static create(t={}){let n=typeof t==`function`?t():t;return new e(n)}static handleExit({editor:e,mark:t}){let{tr:n}=e.state,r=e.state.selection.$from;if(r.pos===r.end()){let i=r.marks();if(!i.find(e=>e?.type.name===t.name))return!1;let a=i.find(e=>e?.type.name===t.name);return a&&n.removeStoredMark(a),n.insertText(` `,r.pos),e.view.dispatch(n),!0}return!1}configure(e){return super.configure(e)}extend(e){let t=typeof e==`function`?e():e;return super.extend(t)}},vp=class{constructor(e){this.find=e.find,this.handler=e.handler}},yp=(e,t,n)=>{if(pl(t))return[...e.matchAll(t)];let r=t(e,n);return r?r.map(t=>{let n=[t.text];return n.index=t.index,n.input=e,n.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn(`[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".`),n.push(t.replaceWith)),n}):[]};function bp(e){let{editor:t,state:n,from:r,to:i,rule:a,pasteEvent:o,dropEvent:s}=e,{commands:c,chain:l,can:u}=new Xc({editor:t,state:n}),d=[];return n.doc.nodesBetween(r,i,(e,t)=>{var f;if((f=e.type)!=null&&(f=f.spec)!=null&&f.code||!(e.isText||e.isTextblock||e.isInline))return;let p=e.content?.size??e.nodeSize??0,m=Math.max(r,t),h=Math.min(i,t+p);m>=h||yp(e.isText?e.text||``:e.textBetween(m-t,h-t,void 0,``),a.find,o).forEach(e=>{if(e.index===void 0)return;let t=m+e.index+1,r=t+e[0].length,i={from:n.tr.mapping.map(t),to:n.tr.mapping.map(r)},f=a.handler({state:n,range:i,match:e,commands:c,chain:l,can:u,pasteEvent:o,dropEvent:s});d.push(f)})}),d.every(e=>e!==null)}var xp=null,Sp=e=>{var t;let n=new ClipboardEvent(`paste`,{clipboardData:new DataTransfer});return(t=n.clipboardData)==null||t.setData(`text/html`,e),n};function Cp(e){let{editor:t,rules:n}=e,r=null,i=!1,a=!1,o=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,c;try{c=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{c=null}let l=({state:e,from:n,to:r,rule:i,pasteEvt:a})=>{let s=e.tr,l=Yc({state:e,transaction:s});if(bp({editor:t,state:l,from:Math.max(n-1,0),to:r.b-1,rule:i,pasteEvent:a,dropEvent:c})&&s.steps.length){try{c=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{c=null}return o=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,s}};return t.on(`destroy`,()=>{xp===t&&(xp=null)}),n.map(e=>new D({view(e){let n=n=>{r=e.dom.parentElement?.contains(n.target)?e.dom.parentElement:null,r&&(xp=t)},i=()=>{xp&&=null};return window.addEventListener(`dragstart`,n),window.addEventListener(`dragend`,i),{destroy(){window.removeEventListener(`dragstart`,n),window.removeEventListener(`dragend`,i)}}},props:{handleDOMEvents:{drop:(e,t)=>{if(a=r===e.dom.parentElement,c=t,!a){let e=xp;e?.isEditable&&setTimeout(()=>{if(e.isDestroyed)return;let t=e.state.selection;t&&e.commands.deleteRange({from:t.from,to:t.to})},10)}return!1},paste:(e,t)=>{let n=t.clipboardData?.getData(`text/html`);return o=t,i=!!n?.includes(`data-pm-slice`),!1}}},appendTransaction:(t,n,r)=>{let c=t[0],u=c.getMeta(`uiEvent`)===`paste`&&!i,d=c.getMeta(`uiEvent`)===`drop`&&!a,f=c.getMeta(`applyPasteRules`),p=!!f;if(!u&&!d&&!p)return;if(p){let{text:t}=f;t=typeof t==`string`?t:xu(s.from(t),r.schema);let{from:n}=f,i=n+t.length,a=Sp(t);return l({rule:e,state:r,from:n,to:{b:i},pasteEvt:a})}let m=n.doc.content.findDiffStart(r.doc.content),h=n.doc.content.findDiffEnd(r.doc.content);if(jf(m)&&h&&m!==h.b)return l({rule:e,state:r,from:m,to:h,pasteEvt:o})}}))}var wp=class{constructor(e,t){this.splittableMarks=[],this.nonClearableMarks=[],this.decorationManager=null,this.editor=t,this.baseExtensions=e,this.extensions=Gu(e),this.hasSchemaSpec=t.options.schemaSpec!==void 0,this.schema=Uu(this.extensions,t,t.options.schemaSpec),this.setupExtensions()}get commands(){return this.extensions.reduce((e,t)=>{let n=k(t,`addCommands`,{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:this.editor,type:rd(t.name,this.schema)});return n?{...e,...n()}:e},{})}get plugins(){let{editor:e}=this,t=Wu([...this.extensions].reverse()).flatMap(t=>{let n={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:e,type:rd(t.name,this.schema)},r=[],i=k(t,`addKeyboardShortcuts`,n),a={};if(t.type===`mark`&&k(t,`exitable`,n)&&(a.ArrowRight=()=>_p.handleExit({editor:e,mark:t})),i){Line truncated
`)}}})]}}),Dp=Tp.create({name:`commands`,addCommands(){return{...tf}}}),Op=Tp.create({name:`delete`,onUpdate({transaction:e,appendedTransactions:t}){var n;let r=()=>{var n,r;if(((n=this.editor.options.coreExtensionOptions)==null||(n=n.delete)==null||(r=n.filterTransaction)==null?void 0:r.call(n,e))??e.getMeta(`y-sync$`))return;let i=hu(e.before,[e,...t]);$u(i).forEach(t=>{i.mapping.mapResult(t.oldRange.from).deletedAfter&&i.mapping.mapResult(t.oldRange.to).deletedBefore&&i.before.nodesBetween(t.oldRange.from,t.oldRange.to,(n,r)=>{let a=r+n.nodeSize-2,o=t.oldRange.from<=r&&a<=t.oldRange.to;this.editor.emit(`delete`,{type:`node`,node:n,from:r,to:a,newFrom:i.mapping.map(r),newTo:i.mapping.map(a),deletedRange:t.oldRange,newRange:t.newRange,partial:!o,editor:this.editor,transaction:e,combinedTransform:i})})});let a=i.mapping;i.steps.forEach((t,n)=>{if(t instanceof St){let r=a.slice(n).map(t.from,-1),o=a.slice(n).map(t.to),s=a.invert().map(r,-1),c=a.invert().map(o),l=r>0&&i.doc.nodeAt(r-1)?.marks.some(e=>e.eq(t.mark)),u=i.doc.nodeAt(o)?.marks.some(e=>e.eq(t.mark));this.editor.emit(`delete`,{type:`mark`,mark:t.mark,from:t.from,to:t.to,deletedRange:{from:s,to:c},newRange:{from:r,to:o},partial:!!(u||l),editor:this.editor,transaction:e,combinedTransform:i})}})};((n=this.editor.options.coreExtensionOptions)==null||(n=n.delete)==null?void 0:n.async)??!0?setTimeout(r,0):r()}}),kp=Tp.create({name:`drop`,addProseMirrorPlugins(){return[new E({key:new D(`tiptapDrop`),props:{handleDrop:(e,t,n,r)=>{this.editor.emit(`drop`,{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),Ap=Tp.create({name:`editable`,addProseMirrorPlugins(){return[new E({key:new D(`editable`),props:{editable:()=>this.editor.options.editable}})]}}),jp=new D(`focusEvents`),Mp=Tp.create({name:`focusEvents`,addProseMirrorPlugins(){let{editor:e}=this;return[new E({key:jp,props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;let r=e.state.tr.setMeta(`focus`,{event:n}).setMeta(`addToHistory`,!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;let r=e.state.tr.setMeta(`blur`,{event:n}).setMeta(`addToHistory`,!1);return t.dispatch(r),!1}}}})]}}),Np=Tp.create({name:`keymap`,addKeyboardShortcuts(){let e=()=>this.editor.commands.first(({commands:e})=>[()=>e.undoInputRule(),()=>e.command(({tr:t})=>{let{selection:n,doc:r}=t,{empty:i,$anchor:a}=n,{pos:o,parent:s}=a,c=a.parent.isTextblock&&o>0?t.doc.resolve(o-1):a,l=c.parent.type.spec.isolating,u=a.pos-a.parentOffset,d=l&&c.parent.childCount===1?u===a.pos:C.atStart(r).from===o;return!i||!s.type.isTextblock||s.textContent.length||!d||d&&a.parent.type.name===`paragraph`?!1:e.clearNodes()}),()=>e.deleteSelection(),()=>e.joinBackward(),()=>e.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:e})=>[()=>e.deleteSelection(),()=>e.deleteCurrentNode(),()=>e.joinForward(),()=>e.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:e})=>[()=>e.newlineInCode(),()=>e.createParagraphNear(),()=>e.liftEmptyBlock(),()=>e.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},r={...n},i={...n,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Tl()||Jl()?i:r},addProseMirrorPlugins(){return[new E({key:new D(`clearDocument`),appendTransaction:(e,t,n)=>{if(e.some(e=>e.getMeta(`composition`)))return;let r=e.some(e=>e.docChanged)&&!t.doc.eq(n.doc),i=e.some(e=>e.getMeta(`preventClearDocument`));if(!r||i)return;let{empty:a,from:o,to:s}=t.selection,c=C.atStart(t.doc).from,l=C.atEnd(t.doc).to;if(a||o!==c||s!==l||!fd(n.doc))return;let u=n.tr,d=Yc({state:n,transaction:u}),{commands:f}=new Xc({editor:this.editor,state:d});if(f.clearNodes(),u.steps.length)return u}})]}}),Pp=Tp.create({name:`paste`,addProseMirrorPlugins(){return[new E({key:new D(`tiptapPaste`),props:{handlePaste:(e,t,n)=>{this.editor.emit(`paste`,{editor:this.editor,event:t,slice:n})}}})]}}),Fp=Tp.create({name:`tabindex`,addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new E({key:new D(`tabindex`),props:{attributes:()=>!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:this.options.value??`0`}}})]}}),Ip=Tp.create({name:`textDirection`,addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];let{nodeExtensions:e}=Au(this.extensions);return[{types:e.filter(e=>e.name!==`text`).map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{let t=e.getAttribute(`dir`);return t&&(t===`ltr`||t===`rtl`||t===`auto`)?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new E({key:new D(`textDirection`),props:{attributes:()=>{let e=this.options.direction;return e?{dir:e}:{}}}})]}}),Lp=!1;function Rp(e){if(Lp)return;Lp=!0;let t;try{let n=Dt.fromJSON(e,Line truncated
`)}}})]}}),Dp=Tp.create({name:`commands`,addCommands(){return{...tf}}}),Op=Tp.create({name:`delete`,onUpdate({transaction:e,appendedTransactions:t}){var n;let r=()=>{var n,r;if(((n=this.editor.options.coreExtensionOptions)==null||(n=n.delete)==null||(r=n.filterTransaction)==null?void 0:r.call(n,e))??e.getMeta(`y-sync$`))return;let i=hu(e.before,[e,...t]);$u(i).forEach(t=>{i.mapping.mapResult(t.oldRange.from).deletedAfter&&i.mapping.mapResult(t.oldRange.to).deletedBefore&&i.before.nodesBetween(t.oldRange.from,t.oldRange.to,(n,r)=>{let a=r+n.nodeSize-2,o=t.oldRange.from<=r&&a<=t.oldRange.to;this.editor.emit(`delete`,{type:`node`,node:n,from:r,to:a,newFrom:i.mapping.map(r),newTo:i.mapping.map(a),deletedRange:t.oldRange,newRange:t.newRange,partial:!o,editor:this.editor,transaction:e,combinedTransform:i})})});let a=i.mapping;i.steps.forEach((t,n)=>{if(t instanceof xt){let r=a.slice(n).map(t.from,-1),o=a.slice(n).map(t.to),s=a.invert().map(r,-1),c=a.invert().map(o),l=r>0&&i.doc.nodeAt(r-1)?.marks.some(e=>e.eq(t.mark)),u=i.doc.nodeAt(o)?.marks.some(e=>e.eq(t.mark));this.editor.emit(`delete`,{type:`mark`,mark:t.mark,from:t.from,to:t.to,deletedRange:{from:s,to:c},newRange:{from:r,to:o},partial:!!(u||l),editor:this.editor,transaction:e,combinedTransform:i})}})};((n=this.editor.options.coreExtensionOptions)==null||(n=n.delete)==null?void 0:n.async)??!0?setTimeout(r,0):r()}}),kp=Tp.create({name:`drop`,addProseMirrorPlugins(){return[new D({key:new Un(`tiptapDrop`),props:{handleDrop:(e,t,n,r)=>{this.editor.emit(`drop`,{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),Ap=Tp.create({name:`editable`,addProseMirrorPlugins(){return[new D({key:new Un(`editable`),props:{editable:()=>this.editor.options.editable}})]}}),jp=new Un(`focusEvents`),Mp=Tp.create({name:`focusEvents`,addProseMirrorPlugins(){let{editor:e}=this;return[new D({key:jp,props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;let r=e.state.tr.setMeta(`focus`,{event:n}).setMeta(`addToHistory`,!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;let r=e.state.tr.setMeta(`blur`,{event:n}).setMeta(`addToHistory`,!1);return t.dispatch(r),!1}}}})]}}),Np=Tp.create({name:`keymap`,addKeyboardShortcuts(){let e=()=>this.editor.commands.first(({commands:e})=>[()=>e.undoInputRule(),()=>e.command(({tr:t})=>{let{selection:n,doc:r}=t,{empty:i,$anchor:a}=n,{pos:o,parent:s}=a,c=a.parent.isTextblock&&o>0?t.doc.resolve(o-1):a,l=c.parent.type.spec.isolating,u=a.pos-a.parentOffset,d=l&&c.parent.childCount===1?u===a.pos:w.atStart(r).from===o;return!i||!s.type.isTextblock||s.textContent.length||!d||d&&a.parent.type.name===`paragraph`?!1:e.clearNodes()}),()=>e.deleteSelection(),()=>e.joinBackward(),()=>e.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:e})=>[()=>e.deleteSelection(),()=>e.deleteCurrentNode(),()=>e.joinForward(),()=>e.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:e})=>[()=>e.newlineInCode(),()=>e.createParagraphNear(),()=>e.liftEmptyBlock(),()=>e.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},r={...n},i={...n,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Tl()||Jl()?i:r},addProseMirrorPlugins(){return[new D({key:new Un(`clearDocument`),appendTransaction:(e,t,n)=>{if(e.some(e=>e.getMeta(`composition`)))return;let r=e.some(e=>e.docChanged)&&!t.doc.eq(n.doc),i=e.some(e=>e.getMeta(`preventClearDocument`));if(!r||i)return;let{empty:a,from:o,to:s}=t.selection,c=w.atStart(t.doc).from,l=w.atEnd(t.doc).to;if(a||o!==c||s!==l||!fd(n.doc))return;let u=n.tr,d=Yc({state:n,transaction:u}),{commands:f}=new Xc({editor:this.editor,state:d});if(f.clearNodes(),u.steps.length)return u}})]}}),Pp=Tp.create({name:`paste`,addProseMirrorPlugins(){return[new D({key:new Un(`tiptapPaste`),props:{handlePaste:(e,t,n)=>{this.editor.emit(`paste`,{editor:this.editor,event:t,slice:n})}}})]}}),Fp=Tp.create({name:`tabindex`,addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new D({key:new Un(`tabindex`),props:{attributes:()=>!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:this.options.value??`0`}}})]}}),Ip=Tp.create({name:`textDirection`,addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];let{nodeExtensions:e}=Au(this.extensions);return[{types:e.filter(e=>e.name!==`text`).map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{let t=e.getAttribute(`dir`);return t&&(t===`ltr`||t===`rtl`||t===`auto`)?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new D({key:new Un(`textDirection`),props:{attributes:()=>{let e=this.options.direction;return e?{dir:e}:{}}}})]}}),Lp=!1;function Rp(e){if(Lp)return;Lp=!0;let t;try{let n=Et.fromLine truncated
position: relative;
}
@@ -100,12 +100,12 @@ img.ProseMirror-separator {
.ProseMirror-focused .ProseMirror-gapcursor {
display: block;
}`,Vp=class extends of{constructor(e={}){super(),this.css=null,this.className=`tiptap`,this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.hasWarnedStaleDecorationRead=!1,this.options={element:typeof document<`u`?document.createElement(`div`):null,content:``,injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:e})=>{throw e},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:_d,createMappablePosition:vd},this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on(`beforeCreate`,this.options.onBeforeCreate),this.emit(`beforeCreate`,{editor:this}),this.on(`mount`,this.options.onMount),this.on(`unmount`,this.options.onUnmount),this.on(`contentError`,this.options.onContentError),this.on(`create`,this.options.onCreate),this.on(`update`,this.options.onUpdate),this.on(`selectionUpdate`,this.options.onSelectionUpdate),this.on(`transaction`,this.options.onTransaction),this.on(`focus`,this.options.onFocus),this.on(`blur`,this.options.onBlur),this.on(`destroy`,this.options.onDestroy),this.on(`drop`,({event:e,slice:t,moved:n})=>this.options.onDrop(e,t,n)),this.on(`paste`,({event:e,slice:t})=>this.options.onPaste(e,t)),this.on(`delete`,this.options.onDelete);let t=this.createDoc();if(!this.editorState){let e=Cl(t,this.options.autofocus);this.editorState=Bn.create({doc:t,schema:this.schema,selection:e||void 0})}Rp(this.schema),this.options.element&&this.mount(this.options.element)}mount(e){if(typeof document>`u`)throw Error(`[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`);this.createView(e),this.emit(`mount`,{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit(`create`,{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){this.editorState=this.editorView.state;let e=this.editorView.dom;e?.editor&&delete e.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove==`function`?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(e){console.warn(`Failed to remove CSS element:`,e)}this.css=null,this.emit(`unmount`,{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager?this.commandManager.chain():Xc.createFakeChain()}can(){return this.commandManager?this.commandManager.can():Xc.createFallbackCan()}injectCSS(){this.options.injectCSS&&typeof document<`u`&&(this.css=Of(Bp,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},this.editorView&&this.state&&!this.isDestroyed&&(this.options.editorProps&&this.view.setProps({...this.options.editorProps,attributes:this.getEditorViewAttributes()}),this.view.updateState(this.state))}setEditable(e,t=!0){this.setOptions({editable:e}),t&&this.emit(`update`,{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:e=>{this.editorState=e},dispatch:e=>{this.dispatchTransaction(e)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(e,t)=>{if(this.editorView)return this.editorView[t];if(t===`state`)return this.editorState;if(t in e)return Reflect.get(e,t);throw Error(`[tiptap error]: The editor view is not available. Cannot access view['${t}']. The editor may not be mounted yet.`)}})}get state(){return sf&&!this.hasWarnedStaleDecorationRead&&af(this)&&(this.hasWarnedStaleDecorationRead=!0,console.warn("[tiptap warn]: `editor.state` was read while decoration `create()` was running. It returns the pre-transaction document. Use the `state` argument passed to `create()` instead. Helpers like `editor.isActive()` read `editor.state` too, so pass `state` to their standalone versions instead of calling them on the editor.")),this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(e,t){let n=Mu(t)?t(e,[...this.state.plugins]):[...this.state.plugins,e],r=this.state.recoLine truncated
}`,Vp=class extends of{constructor(e={}){super(),this.css=null,this.className=`tiptap`,this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.hasWarnedStaleDecorationRead=!1,this.options={element:typeof document<`u`?document.createElement(`div`):null,content:``,injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:e})=>{throw e},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:_d,createMappablePosition:vd},this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on(`beforeCreate`,this.options.onBeforeCreate),this.emit(`beforeCreate`,{editor:this}),this.on(`mount`,this.options.onMount),this.on(`unmount`,this.options.onUnmount),this.on(`contentError`,this.options.onContentError),this.on(`create`,this.options.onCreate),this.on(`update`,this.options.onUpdate),this.on(`selectionUpdate`,this.options.onSelectionUpdate),this.on(`transaction`,this.options.onTransaction),this.on(`focus`,this.options.onFocus),this.on(`blur`,this.options.onBlur),this.on(`destroy`,this.options.onDestroy),this.on(`drop`,({event:e,slice:t,moved:n})=>this.options.onDrop(e,t,n)),this.on(`paste`,({event:e,slice:t})=>this.options.onPaste(e,t)),this.on(`delete`,this.options.onDelete);let t=this.createDoc();if(!this.editorState){let e=Cl(t,this.options.autofocus);this.editorState=zn.create({doc:t,schema:this.schema,selection:e||void 0})}Rp(this.schema),this.options.element&&this.mount(this.options.element)}mount(e){if(typeof document>`u`)throw Error(`[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`);this.createView(e),this.emit(`mount`,{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit(`create`,{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){this.editorState=this.editorView.state;let e=this.editorView.dom;e?.editor&&delete e.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove==`function`?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(e){console.warn(`Failed to remove CSS element:`,e)}this.css=null,this.emit(`unmount`,{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager?this.commandManager.chain():Xc.createFakeChain()}can(){return this.commandManager?this.commandManager.can():Xc.createFallbackCan()}injectCSS(){this.options.injectCSS&&typeof document<`u`&&(this.css=Of(Bp,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},this.editorView&&this.state&&!this.isDestroyed&&(this.options.editorProps&&this.view.setProps({...this.options.editorProps,attributes:this.getEditorViewAttributes()}),this.view.updateState(this.state))}setEditable(e,t=!0){this.setOptions({editable:e}),t&&this.emit(`update`,{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:e=>{this.editorState=e},dispatch:e=>{this.dispatchTransaction(e)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(e,t)=>{if(this.editorView)return this.editorView[t];if(t===`state`)return this.editorState;if(t in e)return Reflect.get(e,t);throw Error(`[tiptap error]: The editor view is not available. Cannot access view['${t}']. The editor may not be mounted yet.`)}})}get state(){return sf&&!this.hasWarnedStaleDecorationRead&&af(this)&&(this.hasWarnedStaleDecorationRead=!0,console.warn("[tiptap warn]: `editor.state` was read while decoration `create()` was running. It returns the pre-transaction document. Use the `state` argument passed to `create()` instead. Helpers like `editor.isActive()` read `editor.state` too, so pass `state` to their standalone versions instead of calling them on the editor.")),this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(e,t){let n=Mu(t)?t(e,[...this.state.plugins]):[...this.state.plugins,e],r=this.state.recoLine truncated
`,textSerializers:n={}}=e||{};return qu(this.state.doc,{blockSeparator:t,textSerializers:{...Ju(this.schema),...n}})}get isEmpty(){return fd(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit(`destroy`),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){return this.editorView?.isDestroyed??!0}$node(e,t){return this.$doc?.querySelector(e,t)||null}$nodes(e,t){return this.$doc?.querySelectorAll(e,t)||null}$pos(e){let t=this.state.doc.resolve(e),n=e>0&&t.nodeAfter&&!t.nodeAfter.isText&&t.nodeAfter.isAtom?t.nodeAfter:null;return new zp(t,this,!1,n)}get $doc(){return this.$pos(0)}};function Hp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Nu(e.getAttributes,void 0,r);if(i===!1||i===null)return null;let{tr:a}=t,o=r[r.length-1],s=r[0];if(o){let r=s.search(/\S/),c=n.from+s.indexOf(o),l=c+o.length;if(ed(n.from,n.to,t.doc).filter(t=>t.mark.type.excluded.find(n=>n===e.type&&n!==t.mark.type)).filter(e=>e.to>c).length)return null;l<n.to&&a.delete(l,n.to),c>n.from&&a.delete(n.from+r,c);let u=n.from+r+o.length;a.addMark(n.from+r,u,e.type.create(i||{})),a.removeStoredMark(e.type)}},undoable:e.undoable})}function Up(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Nu(e.getAttributes,void 0,r)||{},{tr:a}=t,o=n.from,s=n.to,c=e.type.create(i);if(r[1]){let e=o+r[0].lastIndexOf(r[1]);e>s?e=s:s=e+r[1].length;let t=r[0][r[0].length-1];a.insertText(t,o+r[0].length-1),a.replaceWith(e,s,c)}else if(r[0]){let t=e.type.isInline?o:o-1;a.insert(t,e.type.create(i)).delete(a.mapping.map(o),a.mapping.map(s))}a.scrollIntoView()},undoable:e.undoable})}function Wp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=t.doc.resolve(n.from),a=Nu(e.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),e.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,e.type,a)},undoable:e.undoable})}function Gp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r,chain:i})=>{let a=Nu(e.getAttributes,void 0,r)||{},o=t.tr.delete(n.from,n.to),s=o.doc.resolve(n.from).blockRange(),c=s&&It(s,e.type,a);if(!c)return null;if(o.wrap(s,c),e.keepMarks&&e.editor){let{selection:n,storedMarks:r}=t,{splittableMarks:i}=e.editor.extensionManager,a=r||n.$to.parentOffset&&n.$from.marks();if(a){let e=a.filter(e=>i.includes(e.type.name));o.ensureMarks(e)}}if(e.keepAttributes){let t=e.type.name===`bulletList`||e.type.name===`orderedList`?`listItem`:`taskList`;i().updateAttributes(t,a).run()}let l=o.doc.resolve(n.from-1).nodeBefore;l&&l.type===e.type&&Jt(o.doc,n.from-1)&&(!e.joinPredicate||e.joinPredicate(r,l))&&o.join(n.from-1)},undoable:e.undoable})}var Kp=e=>`touches`in e,qp=class{constructor(e){var t;this.directions=[`bottom-left`,`bottom-right`,`top-left`,`top-right`],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:``,wrapper:``,handle:``,resizing:``},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.clientX-this.startX,n=e.clientY-this.startY;this.handleResize(t,n)},this.handleTouchMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.touches[0];if(!t)return;let n=t.clientX-this.startX,r=t.clientY-this.startY;this.handleResize(n,r)},this.handleMouseUp=()=>{if(!this.isResizing)return;let e=this.element.offsetWidth,t=this.element.offsetHeight;this.onCommit(e,t),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState=`false`,this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener(`mousemove`,this.handleMouseMove),document.removeEventListener(`mouseup`,this.handleMouseUp),document.removeEventListener(`keydown`,this.handleKeyDown),document.removeEventListener(`keyup`,this.handleKeyUp)},this.handleKeyDown=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!1)},this.node=e.node,this.editor=e.editor,this.element=e.element,this.element.draggable=!1,this.contentElement=e.contentElement,this.getPos=e.getPos,this.onResize=e.onResize,this.onCommit=e.onCommit,this.onUpdate=e.onUpdate,e.options?.min&&(this.minSize={...this.minSize,...e.options.min}),e.options?.max&&(this.maxSize=e.options.max),e!=null&&(t=e.options)!=null&&t.directions&&(this.directions=e.options.directions),e.options?.preserveAspectRatio&&(this.preserveAspectRatio=e.options.preserveAspectRatio),e.options?.className&&(this.classNames={container:e.options.className.container||``,wrapper:e.options.className.wrapper||``,handle:e.options.className.handle||``,resizing:e.options.className.resLine truncated
`,textSerializers:n={}}=e||{};return qu(this.state.doc,{blockSeparator:t,textSerializers:{...Ju(this.schema),...n}})}get isEmpty(){return fd(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit(`destroy`),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){return this.editorView?.isDestroyed??!0}$node(e,t){return this.$doc?.querySelector(e,t)||null}$nodes(e,t){return this.$doc?.querySelectorAll(e,t)||null}$pos(e){let t=this.state.doc.resolve(e),n=e>0&&t.nodeAfter&&!t.nodeAfter.isText&&t.nodeAfter.isAtom?t.nodeAfter:null;return new zp(t,this,!1,n)}get $doc(){return this.$pos(0)}};function Hp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Nu(e.getAttributes,void 0,r);if(i===!1||i===null)return null;let{tr:a}=t,o=r[r.length-1],s=r[0];if(o){let r=s.search(/\S/),c=n.from+s.indexOf(o),l=c+o.length;if(ed(n.from,n.to,t.doc).filter(t=>t.mark.type.excluded.find(n=>n===e.type&&n!==t.mark.type)).filter(e=>e.to>c).length)return null;l<n.to&&a.delete(l,n.to),c>n.from&&a.delete(n.from+r,c);let u=n.from+r+o.length;a.addMark(n.from+r,u,e.type.create(i||{})),a.removeStoredMark(e.type)}},undoable:e.undoable})}function Up(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Nu(e.getAttributes,void 0,r)||{},{tr:a}=t,o=n.from,s=n.to,c=e.type.create(i);if(r[1]){let e=o+r[0].lastIndexOf(r[1]);e>s?e=s:s=e+r[1].length;let t=r[0][r[0].length-1];a.insertText(t,o+r[0].length-1),a.replaceWith(e,s,c)}else if(r[0]){let t=e.type.isInline?o:o-1;a.insert(t,e.type.create(i)).delete(a.mapping.map(o),a.mapping.map(s))}a.scrollIntoView()},undoable:e.undoable})}function Wp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=t.doc.resolve(n.from),a=Nu(e.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),e.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,e.type,a)},undoable:e.undoable})}function Gp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r,chain:i})=>{let a=Nu(e.getAttributes,void 0,r)||{},o=t.tr.delete(n.from,n.to),s=o.doc.resolve(n.from).blockRange(),c=s&&Ft(s,e.type,a);if(!c)return null;if(o.wrap(s,c),e.keepMarks&&e.editor){let{selection:n,storedMarks:r}=t,{splittableMarks:i}=e.editor.extensionManager,a=r||n.$to.parentOffset&&n.$from.marks();if(a){let e=a.filter(e=>i.includes(e.type.name));o.ensureMarks(e)}}if(e.keepAttributes){let t=e.type.name===`bulletList`||e.type.name===`orderedList`?`listItem`:`taskList`;i().updateAttributes(t,a).run()}let l=o.doc.resolve(n.from-1).nodeBefore;l&&l.type===e.type&&qt(o.doc,n.from-1)&&(!e.joinPredicate||e.joinPredicate(r,l))&&o.join(n.from-1)},undoable:e.undoable})}var Kp=e=>`touches`in e,qp=class{constructor(e){var t;this.directions=[`bottom-left`,`bottom-right`,`top-left`,`top-right`],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:``,wrapper:``,handle:``,resizing:``},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.clientX-this.startX,n=e.clientY-this.startY;this.handleResize(t,n)},this.handleTouchMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.touches[0];if(!t)return;let n=t.clientX-this.startX,r=t.clientY-this.startY;this.handleResize(n,r)},this.handleMouseUp=()=>{if(!this.isResizing)return;let e=this.element.offsetWidth,t=this.element.offsetHeight;this.onCommit(e,t),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState=`false`,this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener(`mousemove`,this.handleMouseMove),document.removeEventListener(`mouseup`,this.handleMouseUp),document.removeEventListener(`keydown`,this.handleKeyDown),document.removeEventListener(`keyup`,this.handleKeyUp)},this.handleKeyDown=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!1)},this.node=e.node,this.editor=e.editor,this.element=e.element,this.element.draggable=!1,this.contentElement=e.contentElement,this.getPos=e.getPos,this.onResize=e.onResize,this.onCommit=e.onCommit,this.onUpdate=e.onUpdate,e.options?.min&&(this.minSize={...this.minSize,...e.options.min}),e.options?.max&&(this.maxSize=e.options.max),e!=null&&(t=e.options)!=null&&t.directions&&(this.directions=e.options.directions),e.options?.preserveAspectRatio&&(this.preserveAspectRatio=e.options.preserveAspectRatio),e.options?.className&&(this.classNames={container:e.options.className.container||``,wrapper:e.options.className.wrapper||``,handle:e.options.className.handle||``,resizing:e.options.className.resLine truncated
`)}},Ag=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Lh]?Rh(e,t):cm(e)?am(e,e=>om(t,t=>Ag(e,t))):zh(e)?Gh(e,(e,n)=>Ag(e,t[n])):!1,jg=class{static _dilutes=!1;extends(e){let[t,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,t]=[t,n]),Ag(t,n)}equals(e){return this.constructor===e.constructor&&Qh(this.shape,e.shape)}[Og](){return!0}[Lh](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){ah()}get nullable(){return u_(this,T_)}get optional(){return new Hg(this)}cast(e){return k_(e,this),e}expect(e){return k_(e,this),e}},Mg=class extends jg{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let n=e?.constructor===this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor===this.shape?`Check failed`:`Constructor match failed`),n}},Ng=(e,t=null)=>new Mg(e,t);Ng(Mg);var Pg=class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape(e);return!n&&t?.extend(null,`custom prop`,e?.constructor.name,`failed to check custom prop`),n}},Fg=e=>new Pg(e);Ng(Pg);var Ig=class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape.some(t=>t===e);return!n&&t?.extend(null,this.shape.join(` | `),e.toString()),n}},Lg=(...e)=>new Ig(e),Rg=Ng(Ig),zg=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,e=>`\\`+e)),Bg=e=>{if(b_.check(e))return[zg(e)];if(Rg.check(e))return e.shape.map(e=>e+``);if(y_.check(e))return[`[+-]?\\d+.?\\d*`];if(x_.check(e))return[`.*`];if(d_.check(e))return e.shape.map(Bg).flat(1);oh()};Ng(class extends jg{constructor(e){super(),this.shape=e,this._r=RegExp(`^`+e.map(Bg).map(e=>`(${e.join(`|`)})`).join(``)+`$`)}check(e,t){let n=this._r.exec(e)!=null;return!n&&t?.extend(null,this._r.toString(),e.toString(),`String doesn't match string template.`),n}});var Vg=Symbol(`optional`),Hg=class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=e===void 0||this.shape.check(e);return!n&&t?.extend(null,`undefined (optional)`,`()`),n}get[Vg](){return!0}},Ug=Ng(Hg),Wg=class extends jg{check(e,t){return t?.extend(null,`never`,typeof e),!1}};new Wg,Ng(Wg);var Gg=class e extends jg{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new e(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,`object`,`null`),!1):Gh(this.shape,(n,r)=>{let i=this._isPartial&&!Kh(e,r)||n.check(e[r],t);return!i&&t?.extend(r.toString(),n.toString(),typeof e[r],`Object property does not match`),i})}},Kg=e=>new Gg(e),qg=Ng(Gg),Jg=Fg(e=>e!=null&&(e.constructor===Object||e.constructor==null)),Yg=class extends jg{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&Gh(e,(n,r)=>{let i=this.shape.keys.check(r,t);return!i&&t?.extend(r+``,`Record`,typeof e,i?`Key doesn't match schema`:`Value doesn't match value`),i&&this.shape.values.check(n,t)})}},Xg=(e,t)=>new Yg(e,t),Zg=Ng(Yg),Qg=class extends jg{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&Gh(this.shape,(n,r)=>{let i=n.check(e[r],t);return!i&&t?.extend(r.toString(),`Tuple`,typeof n),i})}},$g=(...e)=>new Qg(e);Ng(Qg);var e_=class extends jg{constructor(e){super(),this.shape=e.length===1?e[0]:new l_(e)}check(e,t){let n=cm(e)&&am(e,e=>this.shape.check(e));return!n&&t?.extend(null,`Array`,``),n}},t_=(...e)=>new e_(e),n_=Ng(e_),r_=Fg(e=>cm(e)),i_=class extends jg{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name),n}},a_=(e,t=null)=>new i_(e,t);Ng(i_);var o_=a_(jg),s_=Ng(class extends jg{constructor(e){super(),this.len=e.length-1,this.args=$g(...e.slice(-1)),this.res=e[this.len]}check(e,t){let n=e.constructor===Function&&e.length<=this.len;return!n&&t?.extend(null,`function`,typeof e),n}}),c_=Fg(e=>typeof e==`function`);Ng(class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=am(this.shape,n=>n.check(e,t));return!n&&t?.extend(null,`Intersectinon`,typeof e),n}},e=>e.shape.length>0);var l_=class extends jg{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let n=om(this.shape,n=>n.check(e,t));return t?.extend(null,`Union`,typeof e),n}},u_=(...e)=>e.findIndex(e=>d_.check(e))>=0?u_(...e.map(e=>O_(e)).map(e=>d_.check(e)?e.shape:[e]).flat(1)):e.length===1?e[0]:new l_(e),d_=Ng(l_),f_=()=>!0,p_=Fg(f_),m_=Ng(Pg,e=>e.shape===f_),h_=Fg(e=>typeof e==`bigint`),g_=Fg(e=>e===h_),__=Fg(e=>typeof e==`symbol`);Fg(e=>e===__);var v_=Fg(e=>typeof e==`number`),y_=Fg(e=>e===v_),b_=Fg(e=>typeof e==`string`),x_=Fg(e=>e===b_),S_=Fg(e=>typeof e==`boolean`),C_=Fg(e=>e===S_),w_=Lg(void 0);Ng(Ig,e=>e.shape.length===1&&e.shape[0]===void 0),Lg(void 0);var T_=Lg(null),E_=Ng(Ig,e=>e.shape.length===1&&e.shape[0]===null);Ng(Uint8Array),Ng(Mg,e=>e.shape===Uint8Array);var D_=u_(v_,b_,T_,w_,h_,S_,__);(()=>{let e=t_(p_),t=Xg(b_,p_),n=u_(v_,b_,T_,S_,e,t);return e.shape=n,t.shape.values=n,n})();var O_=e=>{if(o_.check(e))return e;ifLine truncated
`;n.right=new Yx(N(o,xy(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Mx(i)),n.right.integrate(e,0),n.forward()}Ub(e,t,n,s)},Yb=(e,t,n,r,i)=>{let a=t,o=Xp();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===Tx){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case Tx:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Wb(i,n);break}}}t=t.right}return s},Xb=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Tx){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Zb=e=>{let t=0;return Ly(e.doc,n=>{let r=e._start,i=e._start,a=Xp(),o=Zp(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Tx:Wb(o,i.content);break;default:t+=Yb(n,r,i,a,o),a=Zp(o),r=i}i=i.right}}),t},Qb=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&ky(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===Tx&&e.constructor!==hx&&t.add(e.parent)})}Ly(n,n=>{cv(e,e.deleteSet,e=>{if(e instanceof hx||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===Tx?t.add(r):Xb(n,e)});for(let e of t)Zb(e)})},$b=(e,t,n)=>{let r=n,i=Zp(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Hx:case Cx:case Mx:n<t.right.length&&Ey(e,N(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}a&&Yb(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&db(o._searchMarker,t.index,-r+n),t},ex=class extends tb{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];Ly(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},Wh(o)||(e.attributes=Bh({},o))),c=0}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Hx:case Cx:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case Mx:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case Tx:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(zb(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),zb(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;zb(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(zb(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Wb(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},tx=class e extends pb{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??rb(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new ex(this,e,t);fb(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??rb();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Mx&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Ly(this.doc,n=>{let r=new Bb(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&qb(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&$b(n,r,a.delete):Jb(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??rb();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(_y(s,e)||t!==void 0&&_y(s,t))switch(s.content.constructor){case Mx:{let r=i.get(`ychange`);e!==void 0&&!_y(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!_y(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Hx:case Cx:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Tx:_y(s,e)&&(c(),Wb(i,s.content))}s=s.right}c()};return e||t?Ly(a,n=>{e&&vy(n,e),t&&vy(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),qb(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Ly(r,r=>{let i=Hb(r,this,e,!n);qb(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Ly(n,n=>{$b(n,Hb(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!1);i.right!==null&&Jb(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Ly(this.doc,t=>{Eb(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Ly(this.doc,n=>{Db(n,this,e,t)})}getAttribute(e){return Ob(this,e)}getAttributes(){return kb(this)}_write(e){e.writeTypeRef(Lx)}},nx=e=>new tx,rx=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??rb()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===ox||t.constructor===ix)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},ix=class e extends pb{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof pb?e.clone():e)),t}get length(){return this.doc??rb(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new rx(this,e)}querySelector(e){e=e.toUpperCase();let t=new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),im(new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){fb(this,e,new cx(this,t,e))}toString(){return vb(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),_b(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Ly(this.doc,n=>{Cb(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Ly(this.doc,n=>{let r=e&&e instanceof pb?e._item:e;xb(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw ih(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Ly(this.doc,n=>{Tb(n,this,e,t)})}toArray(){return hb(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return bb(this,e)}slice(e=0,t=this.length){return mb(this,e,t)}forEach(e){_b(this,e)}_write(e){e.writeTypeRef(zx)}},ax=e=>new ix,ox=class e extends ix{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return Hh(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>eLine truncated
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&qb(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&$b(n,r,a.delete):Jb(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??rb();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(_y(s,e)||t!==void 0&&_y(s,t))switch(s.content.constructor){case Mx:{let r=i.get(`ychange`);e!==void 0&&!_y(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!_y(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Hx:case Cx:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Tx:_y(s,e)&&(c(),Wb(i,s.content))}s=s.right}c()};return e||t?Ly(a,n=>{e&&vy(n,e),t&&vy(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),qb(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Ly(r,r=>{let i=Hb(r,this,e,!n);qb(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Ly(n,n=>{$b(n,Hb(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!1);i.right!==null&&Jb(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Ly(this.doc,t=>{Eb(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Ly(this.doc,n=>{Db(n,this,e,t)})}getAttribute(e){return Ob(this,e)}getAttributes(){return kb(this)}_write(e){e.writeTypeRef(Lx)}},nx=e=>new tx,rx=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??rb()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===ox||t.constructor===ix)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},ix=class e extends pb{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof pb?e.clone():e)),t}get length(){return this.doc??rb(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new rx(this,e)}querySelector(e){e=e.toUpperCase();let t=new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),im(new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){fb(this,e,new cx(this,t,e))}toString(){return vb(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),_b(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Ly(this.doc,n=>{Cb(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Ly(this.doc,n=>{let r=e&&e instanceof pb?e._item:e;xb(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw ih(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Ly(this.doc,n=>{Tb(n,this,e,t)})}toArray(){return hb(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return bb(this,e)}slice(e=0,t=this.length){return mb(this,e,t)}forEach(e){_b(this,e)}_write(e){e.writeTypeRef(zx)}},ax=e=>new ix,ox=class e extends ix{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return Hh(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>eLine truncated
`).map(e=>e.trim()===``?`>`:`> ${e}`);n.push(i.join(`
`))}),n.join(`
>
@@ -117,54 +117,57 @@ img.ProseMirror-separator {
`);return e.replaceWith(t,i,n.schema.text(a)),!0})},"Shift-Tab":({editor:e})=>{if(!this.options.enableTabIndentation)return!1;let t=this.options.tabSize??zT,{state:n}=e,{selection:r}=n,{$from:i,empty:a}=r;return i.parent.type===this.type?a?e.commands.command(({tr:e})=>{let{pos:r}=i,a=i.start(),o=i.end(),s=n.doc.textBetween(a,o,`
`,`
`).split(`
`),c=0,l=0,u=r-a;for(let e=0;e<s.length;e+=1){if(l+s[e].length>=u){c=e;break}l+=s[e].length+1}let d=s[c].match(/^ */)?.[0]||``,f=Math.min(d.length,t);if(f===0)return!0;let p=a;for(let e=0;e<c;e+=1)p+=s[e].length+1;return e.delete(p,p+f),r-p<=f&&e.setSelection(w.create(e.doc,p)),!0}):e.commands.command(({tr:e})=>{let{from:i,to:a}=r,o=n.doc.textBetween(i,a,`
`),c=0,l=0,u=r-a;for(let e=0;e<s.length;e+=1){if(l+s[e].length>=u){c=e;break}l+=s[e].length+1}let d=s[c].match(/^ */)?.[0]||``,f=Math.min(d.length,t);if(f===0)return!0;let p=a;for(let e=0;e<c;e+=1)p+=s[e].length+1;return e.delete(p,p+f),r-p<=f&&e.setSelection(T.create(e.doc,p)),!0}):e.commands.command(({tr:e})=>{let{from:i,to:a}=r,o=n.doc.textBetween(i,a,`
`,`
`).split(`
`).map(e=>{let n=e.match(/^ */)?.[0]||``,r=Math.min(n.length,t);return e.slice(r)}).join(`
`);return e.replaceWith(i,a,n.schema.text(o)),!0}):!1},Enter:({editor:e})=>{if(!this.options.exitOnTripleEnter)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type)return!1;let a=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(`
`);return!a||!o?!1:e.chain().command(({tr:e})=>(e.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowUp:({editor:e})=>{if(!this.options.exitOnArrowUp)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type||r.parentOffset!==0)return!1;let a=r.before();return a>0?!1:e.commands.insertDefaultBlock({pos:a})},ArrowDown:({editor:e})=>{if(!this.options.exitOnArrowDown)return!1;let{state:t}=e,{selection:n,doc:r}=t,{$from:i,empty:a}=n;if(!a||i.parent.type!==this.type||i.parentOffset!==i.parent.nodeSize-2)return!1;let o=i.after();return o===void 0?!1:r.nodeAt(o)?e.commands.command(({tr:e})=>(e.setSelection(C.near(r.resolve(o))),!0)):e.commands.exitCode()}}},addInputRules(){return[Wp({find:BT,type:this.type,getAttributes:e=>({language:e[1]})}),Wp({find:VT,type:this.type,getAttributes:e=>({language:e[1]})})]},addProseMirrorPlugins(){return[new E({key:new D(`codeBlockVSCodeHandler`),props:{handlePaste:(e,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;let n=t.clipboardData.getData(`text/plain`),r=t.clipboardData.getData(`vscode-editor-data`),i=(r?JSON.parse(r):void 0)?.mode;if(!n||!i)return!1;let{tr:a,schema:o}=e.state,s=o.text(n.replace(/\r\n?/g,`
`));return a.replaceSelectionWith(this.type.create({language:i},s)),a.selection.$from.parent.type!==this.type&&a.setSelection(w.near(a.doc.resolve(Math.max(0,a.selection.from-2)))),a.setMeta(`paste`,!0),e.dispatch(a),!0}}})]}}),UT=HT,WT=Jp.create({name:`doc`,topNode:!0,content:`block+`,renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
`);return!a||!o?!1:e.chain().command(({tr:e})=>(e.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowUp:({editor:e})=>{if(!this.options.exitOnArrowUp)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type||r.parentOffset!==0)return!1;let a=r.before();return a>0?!1:e.commands.insertDefaultBlock({pos:a})},ArrowDown:({editor:e})=>{if(!this.options.exitOnArrowDown)return!1;let{state:t}=e,{selection:n,doc:r}=t,{$from:i,empty:a}=n;if(!a||i.parent.type!==this.type||i.parentOffset!==i.parent.nodeSize-2)return!1;let o=i.after();return o===void 0?!1:r.nodeAt(o)?e.commands.command(({tr:e})=>(e.setSelection(w.near(r.resolve(o))),!0)):e.commands.exitCode()}}},addInputRules(){return[Wp({find:BT,type:this.type,getAttributes:e=>({language:e[1]})}),Wp({find:VT,type:this.type,getAttributes:e=>({language:e[1]})})]},addProseMirrorPlugins(){return[new D({key:new Un(`codeBlockVSCodeHandler`),props:{handlePaste:(e,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;let n=t.clipboardData.getData(`text/plain`),r=t.clipboardData.getData(`vscode-editor-data`),i=(r?JSON.parse(r):void 0)?.mode;if(!n||!i)return!1;let{tr:a,schema:o}=e.state,s=o.text(n.replace(/\r\n?/g,`
`));return a.replaceSelectionWith(this.type.create({language:i},s)),a.selection.$from.parent.type!==this.type&&a.setSelection(T.near(a.doc.resolve(Math.max(0,a.selection.from-2)))),a.setMeta(`paste`,!0),e.dispatch(a),!0}}})]}}),UT=HT,WT=Jp.create({name:`doc`,topNode:!0,content:`block+`,renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
`):``}),GT=Jp.create({name:`hardBreak`,markdownTokenName:`br`,addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:`inline`,selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:`br`}]},renderHTML({HTMLAttributes:e}){return[`br`,A(this.options.HTMLAttributes,e)]},renderText(){return`
`},renderMarkdown:()=>`
`,parseMarkdown:()=>({type:`hardBreak`}),addCommands(){return{setHardBreak:()=>({commands:e,chain:t,state:n,editor:r})=>e.first([()=>e.exitCode(),()=>e.command(()=>{let{selection:e,storedMarks:i}=n;if(e.$from.parent.type.spec.isolating)return!1;let{keepMarks:a}=this.options,{splittableMarks:o}=r.extensionManager,s=i||e.$to.parentOffset&&e.$from.marks();return t().insertContent({type:this.name}).command(({tr:e,dispatch:t})=>{if(t&&s&&a){let t=s.filter(e=>o.includes(e.type.name));e.ensureMarks(t)}return!0}).scrollIntoView().run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),KT=Jp.create({name:`heading`,addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:`inline*`,group:`block`,defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(e=>({tag:`h${e}`,attrs:{level:e}}))},renderHTML({node:e,HTMLAttributes:t}){return[`h${this.options.levels.includes(e.attrs.level)?e.attrs.level:this.options.levels[0]}`,A(this.options.HTMLAttributes,t),0]},parseMarkdown(e,t){let n=e.depth||1;return this.options.levels.includes(n)?t.createNode(`heading`,{level:n},t.parseInline(e.tokens||[])):t.createNode(`paragraph`,void 0,t.parseInline(e.tokens||[]))},renderMarkdown:(e,t)=>{let n=e.attrs?.level?parseInt(e.attrs.level,10):1,r=`#`.repeat(n);return e.content?`${r} ${t.renderChildren(e.content)}`:``},addCommands(){return{setHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.setNode(this.name,e):!1,toggleHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.toggleNode(this.name,`paragraph`,e):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((e,t)=>({...e,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(e=>Wp({find:RegExp(`^(#{${Math.min(...this.options.levels)},${e}})\\s$`),type:this.type,getAttributes:{level:e}}))}}),qT=Jp.create({name:`horizontalRule`,addOptions(){return{HTMLAttributes:{},nextNodeType:`paragraph`}},group:`block`,parseHTML(){return[{tag:`hr`}]},renderHTML({HTMLAttributes:e}){return[`hr`,A(this.options.HTMLAttributes,e)]},markdownTokenName:`hr`,parseMarkdown:(e,t)=>t.createNode(`horizontalRule`),renderMarkdown:()=>`---`,addCommands(){return{setHorizontalRule:()=>({chain:e,state:t})=>{if(!Df(t,t.schema.nodes[this.name]))return!1;let{selection:n}=t,{$to:r}=n,i=e();return pd(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:e,tr:t,dispatch:n})=>{if(n){let{$to:n}=t.selection,r=n.end();if(n.nodeAfter)n.nodeAfter.isTextblock?t.setSelection(w.create(t.doc,n.pos+1)):n.nodeAfter.isBlock?t.setSelection(T.create(t.doc,n.pos)):t.setSelection(w.create(t.doc,n.pos));else{let i=(e.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType)?.create();i&&(t.insert(r,i),t.setSelection(w.create(t.doc,r+1)))}t.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Up({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),JT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,YT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,XT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,ZT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,QT=_p.create({name:`italic`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`em`},{tag:`i`,getAttrs:e=>e.style.fontStyle!==`normal`&&null},{style:`font-style=normal`,clearMark:e=>e.type.name===this.name},{style:`font-style=italic`}]},renderHTML({HTMLAttributes:e}){return[`em`,A(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},markdownTokenName:`em`,parseMarkdown:(e,t)=>t.applyMark(`italic`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<em>`,close:`</em>`}},renderMarkdown:(e,t)=>`*${t.renderChildren(e)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Hp({find:JT,type:this.type}),Hp({find:XT,type:this.type})]},addPasteRules(){return[Yp({find:YT,type:this.type}),Yp({find:ZT,type:this.type})]}}),$T=`aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zLine truncated
`,ED=`️`,DD=`‍`,OD=``,kD=null,AD=null;function jD(e=[]){let t={};mE.groups=t;let n=new mE;kD??=FD($T),AD??=FD(eE),F(n,`'`,KE),F(n,`{`,kE),F(n,`}`,AE),F(n,`[`,jE),F(n,`]`,ME),F(n,`(`,NE),F(n,`)`,PE),F(n,`<`,FE),F(n,`>`,IE),F(n,`(`,LE),F(n,`)`,RE),F(n,`「`,zE),F(n,`」`,BE),F(n,`『`,VE),F(n,`』`,HE),F(n,`<`,UE),F(n,`>`,WE),F(n,`&`,GE),F(n,`*`,qE),F(n,`@`,JE),F(n,"`",XE),F(n,`^`,ZE),F(n,`:`,QE),F(n,`,`,$E),F(n,`$`,eD),F(n,`.`,tD),F(n,`=`,nD),F(n,`!`,rD),F(n,`-`,iD),F(n,`%`,aD),F(n,`|`,oD),F(n,`+`,sD),F(n,`#`,cD),F(n,`?`,lD),F(n,`"`,uD),F(n,`/`,pD),F(n,`;`,fD),F(n,`~`,mD),F(n,`_`,hD),F(n,`\\`,YE),F(n,`・`,dD);let r=hE(n,SD,EE,{[tE]:!0});hE(r,SD,r);let i=hE(r,yD,yE,{[iE]:!0}),a=hE(r,bD,bE,{[aE]:!0}),o=hE(n,yD,_E,{[nE]:!0});hE(o,SD,i),hE(o,yD,o),hE(i,SD,i),hE(i,yD,i);let s=hE(n,bD,vE,{[rE]:!0});hE(s,yD),hE(s,SD,a),hE(s,bD,s),hE(a,SD,a),hE(a,yD),hE(a,bD,a);let c=F(n,TD,OE,{[uE]:!0}),l=F(n,wD,DE,{[uE]:!0}),u=hE(n,CD,DE,{[uE]:!0});F(n,OD,u),F(l,TD,c),F(l,OD,u),hE(l,CD,u),F(u,wD),F(u,TD),hE(u,CD,u),F(u,OD,u);let d=hE(n,xD,gD,{[sE]:!0});F(d,`#`),hE(d,xD,d),F(d,ED,d);let f=F(d,DD);F(f,`#`),hE(f,xD,d);let p=[[yD,o],[SD,i]],m=[[yD,null],[bD,s],[SD,a]];for(let e=0;e<kD.length;e++)PD(n,kD[e],SE,_E,p);for(let e=0;e<AD.length;e++)PD(n,AD[e],CE,vE,m);fE(SE,{tld:!0,ascii:!0},t),fE(CE,{utld:!0,alpha:!0},t),PD(n,`file`,wE,_E,p),PD(n,`mailto`,wE,_E,p),PD(n,`http`,TE,_E,p),PD(n,`https`,TE,_E,p),PD(n,`ftp`,TE,_E,p),PD(n,`ftps`,TE,_E,p),fE(wE,{scheme:!0,ascii:!0},t),fE(TE,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){let r=e[t][0],i=e[t][1]?{[cE]:!0}:{[lE]:!0};r.indexOf(`-`)>=0?i[oE]=!0:yD.test(r)?SD.test(r)?i[iE]=!0:i[nE]=!0:i[tE]=!0,gE(n,r,r,i)}return gE(n,`localhost`,xE,{ascii:!0}),n.jd=new mE(_D),{start:n,tokens:Object.assign({groups:t},vD)}}function MD(e,t){let n=ND(t.replace(/[A-Z]/g,e=>e.toLowerCase())),r=n.length,i=[],a=0,o=0;for(;o<r;){let s=e,c=null,l=0,u=null,d=-1,f=-1;for(;o<r&&(c=s.go(n[o]));)s=c,s.accepts()?(d=0,f=0,u=s):d>=0&&(d+=n[o].length,f++),l+=n[o].length,a+=n[o].length,o++;a-=d,o-=f,l-=d,i.push({t:u.t,v:t.slice(a-l,a),s:a-l,e:a})}return i}function ND(e){let t=[],n=e.length,r=0;for(;r<n;){let i=e.charCodeAt(r),a,o=i<55296||i>56319||r+1===n||(a=e.charCodeAt(r+1))<56320||a>57343?e[r]:e.slice(r,r+2);t.push(o),r+=o.length}return t}function PD(e,t,n,r,i){let a,o=t.length;for(let n=0;n<o-1;n++){let o=t[n];e.j[o]?a=e.j[o]:(a=new mE(r),a.jr=i.slice(),e.j[o]=a),e=a}return a=new mE(n),a.jr=i.slice(),e.j[t[o-1]]=a,a}function FD(e){let t=[],n=[],r=0;for(;r<e.length;){let i=0;for(;`0123456789`.indexOf(e[r+i])>=0;)i++;if(i>0){t.push(n.join(``));for(let t=parseInt(e.substring(r,r+i),10);t>0;t--)n.pop();r+=i}else n.push(e[r]),r++}return t}var ID={defaultProtocol:`http`,events:null,format:RD,formatHref:RD,nl2br:!1,tagName:`a`,target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],ignoreClasses:[],render:null};function LD(e,t=null){let n=Object.assign({},ID);e&&(n=Object.assign(n,e instanceof LD?e.o:e));let r=n.ignoreTags,i=[];for(let e=0;e<r.length;e++)i.push(r[e].toUpperCase());this.o=n,t&&(this.defaultRender=t),this.ignoreTags=i,this.ignoreClasses=n.ignoreClasses.slice()}LD.prototype={o:ID,ignoreTags:[],ignoreClasses:[],isIgnoredClass(e){if(typeof e!=`string`||this.ignoreClasses.length===0)return!1;let t=e.split(/\s+/);for(let e=0;e<t.length;e++)if(this.ignoreClasses.indexOf(t[e])>=0)return!0;return!1},defaultRender(e){return e},check(e){return this.get(`validate`,e.toString(),e)},get(e,t,n){let r=t!=null,i=this.o[e];return i&&(typeof i==`object`?(i=n.t in i?i[n.t]:ID[e],typeof i==`function`&&r&&(i=i(t,n))):typeof i==`function`&&r&&(i=i(t,n.t,n)),i)},getObj(e,t,n){let r=this.o[e];return typeof r==`function`&&t!=null&&(r=r(t,n.t,n)),r},render(e){let t=e.render(this);return(this.get(`render`,null,e)||this.defaultRender)(t,e.t,e)}};function RD(e){return e}function zD(e,t){this.t=`token`,this.v=e,this.tk=t}zD.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){let t=this.toString(),n=e.get(`truncate`,t,this),r=e.get(`format`,t,this);return n&&r.length>n?r.substring(0,n)+`…`:r},toFormattedHref(e){return e.get(`formatHref`,this.toHref(e.get(`defaultProtocol`)),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=ID.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get(`validate`,this.toString(),this)},render(e){let t=this,n=this.toHref(e.get(`defaultProtocol`)),r=e.get(`formatHref`,n,this),i=e.get(`tagName`,n,t),a=this.toFormattedString(e),o={},s=e.get(`className`,n,t),c=e.get(`target`,n,t),l=e.get(`rel`,n,t),u=e.getObj(`attributes`,n,t),d=e.getObj(`events`,n,t);reLine truncated
`,parseMarkdown:()=>({type:`hardBreak`}),addCommands(){return{setHardBreak:()=>({commands:e,chain:t,state:n,editor:r})=>e.first([()=>e.exitCode(),()=>e.command(()=>{let{selection:e,storedMarks:i}=n;if(e.$from.parent.type.spec.isolating)return!1;let{keepMarks:a}=this.options,{splittableMarks:o}=r.extensionManager,s=i||e.$to.parentOffset&&e.$from.marks();return t().insertContent({type:this.name}).command(({tr:e,dispatch:t})=>{if(t&&s&&a){let t=s.filter(e=>o.includes(e.type.name));e.ensureMarks(t)}return!0}).scrollIntoView().run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),KT=Jp.create({name:`heading`,addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:`inline*`,group:`block`,defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(e=>({tag:`h${e}`,attrs:{level:e}}))},renderHTML({node:e,HTMLAttributes:t}){return[`h${this.options.levels.includes(e.attrs.level)?e.attrs.level:this.options.levels[0]}`,A(this.options.HTMLAttributes,t),0]},parseMarkdown(e,t){let n=e.depth||1;return this.options.levels.includes(n)?t.createNode(`heading`,{level:n},t.parseInline(e.tokens||[])):t.createNode(`paragraph`,void 0,t.parseInline(e.tokens||[]))},renderMarkdown:(e,t)=>{let n=e.attrs?.level?parseInt(e.attrs.level,10):1,r=`#`.repeat(n);return e.content?`${r} ${t.renderChildren(e.content)}`:``},addCommands(){return{setHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.setNode(this.name,e):!1,toggleHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.toggleNode(this.name,`paragraph`,e):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((e,t)=>({...e,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(e=>Wp({find:RegExp(`^(#{${Math.min(...this.options.levels)},${e}})\\s$`),type:this.type,getAttributes:{level:e}}))}}),qT=Jp.create({name:`horizontalRule`,addOptions(){return{HTMLAttributes:{},nextNodeType:`paragraph`}},group:`block`,parseHTML(){return[{tag:`hr`}]},renderHTML({HTMLAttributes:e}){return[`hr`,A(this.options.HTMLAttributes,e)]},markdownTokenName:`hr`,parseMarkdown:(e,t)=>t.createNode(`horizontalRule`),renderMarkdown:()=>`---`,addCommands(){return{setHorizontalRule:()=>({chain:e,state:t})=>{if(!Df(t,t.schema.nodes[this.name]))return!1;let{selection:n}=t,{$to:r}=n,i=e();return pd(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:e,tr:t,dispatch:n})=>{if(n){let{$to:n}=t.selection,r=n.end();if(n.nodeAfter)n.nodeAfter.isTextblock?t.setSelection(T.create(t.doc,n.pos+1)):n.nodeAfter.isBlock?t.setSelection(E.create(t.doc,n.pos)):t.setSelection(T.create(t.doc,n.pos));else{let i=(e.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType)?.create();i&&(t.insert(r,i),t.setSelection(T.create(t.doc,r+1)))}t.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Up({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),JT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,YT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,XT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,ZT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,QT=_p.create({name:`italic`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`em`},{tag:`i`,getAttrs:e=>e.style.fontStyle!==`normal`&&null},{style:`font-style=normal`,clearMark:e=>e.type.name===this.name},{style:`font-style=italic`}]},renderHTML({HTMLAttributes:e}){return[`em`,A(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},markdownTokenName:`em`,parseMarkdown:(e,t)=>t.applyMark(`italic`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<em>`,close:`</em>`}},renderMarkdown:(e,t)=>`*${t.renderChildren(e)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Hp({find:JT,type:this.type}),Hp({find:XT,type:this.type})]},addPasteRules(){return[Yp({find:YT,type:this.type}),Yp({find:ZT,type:this.type})]}}),$T=`aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zLine truncated
`,DD=`️`,OD=`‍`,kD=``,AD=null,jD=null;function MD(e=[]){let t={};mE.groups=t;let n=new mE;AD??=ID($T),jD??=ID(eE),P(n,`'`,qE),P(n,`{`,AE),P(n,`}`,jE),P(n,`[`,ME),P(n,`]`,NE),P(n,`(`,PE),P(n,`)`,FE),P(n,`<`,IE),P(n,`>`,LE),P(n,`(`,RE),P(n,`)`,zE),P(n,`「`,BE),P(n,`」`,VE),P(n,`『`,HE),P(n,`』`,UE),P(n,`<`,WE),P(n,`>`,GE),P(n,`&`,KE),P(n,`*`,JE),P(n,`@`,YE),P(n,"`",ZE),P(n,`^`,QE),P(n,`:`,$E),P(n,`,`,eD),P(n,`$`,tD),P(n,`.`,nD),P(n,`=`,rD),P(n,`!`,iD),P(n,`-`,aD),P(n,`%`,oD),P(n,`|`,sD),P(n,`+`,cD),P(n,`#`,lD),P(n,`?`,uD),P(n,`"`,dD),P(n,`/`,mD),P(n,`;`,pD),P(n,`~`,hD),P(n,`_`,gD),P(n,`\\`,XE),P(n,`・`,fD);let r=gE(n,CD,DE,{[tE]:!0});gE(r,CD,r);let i=gE(r,bD,bE,{[iE]:!0}),a=gE(r,xD,xE,{[aE]:!0}),o=gE(n,bD,vE,{[nE]:!0});gE(o,CD,i),gE(o,bD,o),gE(i,CD,i),gE(i,bD,i);let s=gE(n,xD,yE,{[rE]:!0});gE(s,bD),gE(s,CD,a),gE(s,xD,s),gE(a,CD,a),gE(a,bD),gE(a,xD,a);let c=P(n,ED,kE,{[uE]:!0}),l=P(n,TD,OE,{[uE]:!0}),u=gE(n,wD,OE,{[uE]:!0});P(n,kD,u),P(l,ED,c),P(l,kD,u),gE(l,wD,u),P(u,TD),P(u,ED),gE(u,wD,u),P(u,kD,u);let d=gE(n,SD,_D,{[sE]:!0});P(d,`#`),gE(d,SD,d),P(d,DD,d);let f=P(d,OD);P(f,`#`),gE(f,SD,d);let p=[[bD,o],[CD,i]],m=[[bD,null],[xD,s],[CD,a]];for(let e=0;e<AD.length;e++)FD(n,AD[e],CE,vE,p);for(let e=0;e<jD.length;e++)FD(n,jD[e],wE,yE,m);fE(CE,{tld:!0,ascii:!0},t),fE(wE,{utld:!0,alpha:!0},t),FD(n,`file`,TE,vE,p),FD(n,`mailto`,TE,vE,p),FD(n,`http`,EE,vE,p),FD(n,`https`,EE,vE,p),FD(n,`ftp`,EE,vE,p),FD(n,`ftps`,EE,vE,p),fE(TE,{scheme:!0,ascii:!0},t),fE(EE,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){let r=e[t][0],i=e[t][1]?{[cE]:!0}:{[lE]:!0};r.indexOf(`-`)>=0?i[oE]=!0:bD.test(r)?CD.test(r)?i[iE]=!0:i[nE]=!0:i[tE]=!0,_E(n,r,r,i)}return _E(n,`localhost`,SE,{ascii:!0}),n.jd=new mE(vD),{start:n,tokens:Object.assign({groups:t},yD)}}function ND(e,t){let n=PD(t.replace(/[A-Z]/g,e=>e.toLowerCase())),r=n.length,i=[],a=0,o=0;for(;o<r;){let s=e,c=null,l=0,u=null,d=-1,f=-1;for(;o<r&&(c=s.go(n[o]));)s=c,s.accepts()?(d=0,f=0,u=s):d>=0&&(d+=n[o].length,f++),l+=n[o].length,a+=n[o].length,o++;a-=d,o-=f,l-=d,i.push({t:u.t,v:t.slice(a-l,a),s:a-l,e:a})}return i}function PD(e){let t=[],n=e.length,r=0;for(;r<n;){let i=e.charCodeAt(r),a,o=i<55296||i>56319||r+1===n||(a=e.charCodeAt(r+1))<56320||a>57343?e[r]:e.slice(r,r+2);t.push(o),r+=o.length}return t}function FD(e,t,n,r,i){let a,o=t.length;for(let n=0;n<o-1;n++){let o=t[n];e.j[o]?a=e.j[o]:(a=new mE(r),a.jr=i.slice(),e.j[o]=a),e=a}return a=new mE(n),a.jr=i.slice(),e.j[t[o-1]]=a,a}function ID(e){let t=[],n=[],r=0;for(;r<e.length;){let i=0;for(;`0123456789`.indexOf(e[r+i])>=0;)i++;if(i>0){t.push(n.join(``));for(let t=parseInt(e.substring(r,r+i),10);t>0;t--)n.pop();r+=i}else n.push(e[r]),r++}return t}var LD={defaultProtocol:`http`,events:null,format:zD,formatHref:zD,nl2br:!1,tagName:`a`,target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],ignoreClasses:[],render:null};function RD(e,t=null){let n=Object.assign({},LD);e&&(n=Object.assign(n,e instanceof RD?e.o:e));let r=n.ignoreTags,i=[];for(let e=0;e<r.length;e++)i.push(r[e].toUpperCase());this.o=n,t&&(this.defaultRender=t),this.ignoreTags=i,this.ignoreClasses=n.ignoreClasses.slice()}RD.prototype={o:LD,ignoreTags:[],ignoreClasses:[],isIgnoredClass(e){if(typeof e!=`string`||this.ignoreClasses.length===0)return!1;let t=e.split(/\s+/);for(let e=0;e<t.length;e++)if(this.ignoreClasses.indexOf(t[e])>=0)return!0;return!1},defaultRender(e){return e},check(e){return this.get(`validate`,e.toString(),e)},get(e,t,n){let r=t!=null,i=this.o[e];return i&&(typeof i==`object`?(i=n.t in i?i[n.t]:LD[e],typeof i==`function`&&r&&(i=i(t,n))):typeof i==`function`&&r&&(i=i(t,n.t,n)),i)},getObj(e,t,n){let r=this.o[e];return typeof r==`function`&&t!=null&&(r=r(t,n.t,n)),r},render(e){let t=e.render(this);return(this.get(`render`,null,e)||this.defaultRender)(t,e.t,e)}};function zD(e){return e}function BD(e,t){this.t=`token`,this.v=e,this.tk=t}BD.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){let t=this.toString(),n=e.get(`truncate`,t,this),r=e.get(`format`,t,this);return n&&r.length>n?r.substring(0,n)+`…`:r},toFormattedHref(e){return e.get(`formatHref`,this.toHref(e.get(`defaultProtocol`)),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=LD.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get(`validate`,this.toString(),this)},render(e){let t=this,n=this.toHref(e.get(`defaultProtocol`)),r=e.get(`formatHref`,n,this),i=e.get(`tagName`,n,t),a=this.toFormattedString(e),o={},s=e.get(`className`,n,t),c=e.get(`target`,n,t),l=e.get(`rel`,n,t),u=e.getObj(`attributes`,n,t),d=e.getObj(`events`,n,t);reLine truncated
1. Must only contain digits, lowercase ASCII letters or "-"
2. Cannot start or end with "-"
3. "-" cannot repeat`);ZD.customSchemes.push([e,t])}function eO(){ZD.scanner=jD(ZD.customSchemes);for(let e=0;e<ZD.tokenQueue.length;e++)ZD.tokenQueue[e][1]({scanner:ZD.scanner});ZD.parser=KD(ZD.scanner.tokens);for(let e=0;e<ZD.pluginQueue.length;e++)ZD.pluginQueue[e][1]({scanner:ZD.scanner,parser:ZD.parser});return ZD.initialized=!0,ZD}function tO(e){return ZD.initialized||eO(),qD(ZD.parser.start,e,MD(ZD.scanner.start,e))}tO.scan=MD;function nO(e,t=null,n=null){if(t&&typeof t==`object`){if(n)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);n=t,t=null}let r=new LD(n),i=tO(e),a=[];for(let e=0;e<i.length;e++){let n=i[e];n.isLink&&(!t||n.t===t)&&r.check(n)&&a.push(n.toFormattedObject(r))}return a}var rO=`[\0- \xA0 ᠎ -\u2029  ]`,iO=new RegExp(rO),aO=RegExp(`${rO}$`),oO=RegExp(`${rO}+$`),sO=new RegExp(rO,`g`);function cO(e,t,n){let r=e.doc.resolve(t.to);if(!r.nodeBefore?.isText)return;let i=e.doc.textBetween(t.from,t.to,``,``).match(oO)?.[0];if(!i)return;let a=t.to-i.length,o=ed(a,t.to,e.doc).filter(e=>e.mark.type===n);if(!o.length)return;let{nodeAfter:s}=r;if(s&&o.some(e=>e.mark.isInSet(s.marks)))return;let c=e.storedMarks;e.removeMark(a,t.to,n),e.setStoredMarks(c),e.selection.empty&&e.selection.from===t.to&&e.removeStoredMark(n)}function lO(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?[`()`,`[]`].includes(e[0].value+e[2].value):!1}function uO(e){return new E({key:new D(`autolink`),appendTransaction:(t,n,r)=>{let i=t.some(e=>e.docChanged)&&!n.doc.eq(r.doc),a=t.some(e=>e.getMeta(`preventAutolink`));if(!i||a)return;let{tr:o}=r,s=hu(n.doc,[...t]);if(!t.some(Jc)){let t=[];s.steps.forEach((e,n)=>{if(!(e instanceof Dt)||!e.slice.size)return;let r=s.mapping.slice(n+1),i=r.map(e.from,1),a=r.map(e.from+e.slice.size,-1);i<a&&t.push({from:i,to:a})}),t.sort((e,t)=>t.to-e.to),t.forEach(t=>cO(o,t,e.type))}if($u(s).forEach(({newRange:t})=>{let n=_u(r.doc,t,e=>e.isTextblock),i,a;if(n.length>1)i=n[0],a=r.doc.textBetween(i.pos,i.pos+i.node.nodeSize,void 0,` `);else if(n.length){let e=r.doc.textBetween(t.from,t.to,` `,` `);if(!aO.test(e))return;i=n[0],a=r.doc.textBetween(i.pos,t.to,void 0,` `)}if(i&&a){let t=a.split(iO).filter(Boolean);if(t.length<=0)return!1;let n=t[t.length-1],s=i.pos+a.lastIndexOf(n);if(!n)return!1;let c=tO(n).map(t=>t.toObject(e.defaultProtocol));if(!lO(c))return!1;c.filter(e=>e.isLink).map(e=>({...e,from:s+e.start+1,to:s+e.end+1})).filter(e=>!r.schema.marks.code||!r.doc.rangeHasMark(e.from,e.to,r.schema.marks.code)).filter(t=>e.validate(t.value)).filter(t=>e.shouldAutoLink(t.value)).forEach(t=>{ed(t.from,t.to,r.doc).some(t=>t.mark.type===e.type)||o.addMark(t.from,t.to,e.type.create({href:t.href}))})}}),o.steps.length)return o}})}function dO(e){return new E({key:new D(`handleClickLink`),props:{handleClick:(t,n,r)=>{if(r.button!==0||!t.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{let t=r.target;if(!t)return!1;let n=e.editor.view.dom;i=t.closest(`a`),i&&!n.contains(i)&&(i=null)}if(!i)return!1;let a=!1;if(e.enableClickSelection&&(a=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){let n=Xu(t.state,e.type.name),r=i.href??n.href,o=i.target??n.target;r&&(window.open(r,o),a=!0)}return a}}})}var fO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)$/,pO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)/g;function mO(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function hO(e,t){let n=0,r=0;for(;r<t;){if(e[r]!=="`"||n===0&&mO(e,r)){r+=1;continue}let i=0;for(;r<t&&e[r]==="`";)i+=1,r+=1;n===0?n=i:i===n&&(n=0)}return n>0}function gO(e,t,n){let[,r,i]=t;return(t.index?e[t.index-1]:void 0)===`!`||mO(e,t.index??0)||hO(e,t.index??0)?!1:!!r.trim()&&n(i)}function _O(e){let[t,n,r,,i,a,o]=e,s=i??a??o;return{index:e.index??0,text:t,replaceWith:n,data:{href:r,title:s||null,markdown:!0}}}function vO(e,t){return e.index<t.index+t.text.length&&t.index<e.index+e.text.length}function yO(e){return{href:e.data?.href,title:e.data?.title??null}}function bO(e){let t=Hp({find:t=>{let n=fO.exec(t);return!n||!gO(t,n,e.isAllowedHref)?null:_O(n)},type:e.type,getAttributes:yO});return new lp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function xO(e){let t=Yp({find:t=>{let n=[];for(let r of t.matchAll(pO))gO(t,r,e.isAllowedHref)&&n.push(_O(r));let r=(e.findPlainUrls?.call(e,t)??[]).filter(e=>!n.some(t=>vO(t,e)));return[...n,...r]},type:e.type,getAttributes:yO});return new vp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.match.data?.markdown&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function SO(e){return new E({key:new D(`handlePasteLink`),props:{handlePaste:(t,n,r)=>{let{shouldAutoLink:i}=e,{state:a}=t,{selection:o}=a,{empty:s}=o;if(s)return!1;let c=``;r.content.forEach(e=>{c+=e.textContent});let l=nO(c,Line truncated
`):``,markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(TO,this.editor.getAttributes(EO)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let e=Gp({find:DO,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(e=Gp({find:DO,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(EO),editor:this.editor})),[e]}}),kO=(e,t,n)=>{let{selection:r}=e;if(!r.empty)return null;let{$from:i}=r;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let a=-1;for(let e=i.depth;e>0;--e)if(i.node(e).type.name===t){a=e;break}if(a<0)return null;let o=i.node(a),s=i.index(a);if(s+1>=o.childCount)return null;let c=o.child(s+1);if(!n.includes(c.type.name))return null;let l=e.schema.nodes[t],u=!1;if(c.forEach(e=>{e.type===l&&e.childCount>1&&(u=!0)}),!u)return null;let d=e.doc.resolve(i.after()).nodeAfter;if(!d||!n.includes(d.type.name))return null;let f=[];return d.forEach(e=>{f.push(e)}),f.length===0?null:{listItemDepth:a,nestedList:d,nestedListPos:i.after(),insertPos:i.after(a),items:f}},AO=(e,t,n,r)=>{let i=kO(e,n,r);if(!i)return!1;let{selection:a}=e,{nestedList:o,nestedListPos:c,insertPos:l,items:u}=i,d=e.tr;d.delete(c,c+o.nodeSize);let f=d.mapping.map(l);return d.insert(f,s.from(u)),d.setSelection(a.map(d.doc,d.mapping)),t&&t(d),!0},jO=(e,t,n)=>AO(e.state,e.view.dispatch,t,n),MO=(e,t)=>Tp.create({name:`${e}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){let n=()=>jO(this.editor,e,t);return{Delete:n,"Mod-Delete":n}}}),NO=[[1e3,`m`],[900,`cm`],[500,`d`],[400,`cd`],[100,`c`],[90,`xc`],[50,`l`],[40,`xl`],[10,`x`],[9,`ix`],[5,`v`],[4,`iv`],[1,`i`]],PO=`abcdefghijklmnopqrstuvwxyz`,FO=String.raw`\d+|[ivxlcdmIVXLCDM]+|${`[a-zA-Z]{1,2}`}`;function IO(e){let t=e,n=``;for(let[e,r]of NO)for(;t>=e;)n+=r,t-=e;return n}function LO(e){return IO(e).toUpperCase()}function RO(e){let t=e.toLowerCase(),n=0,r=0;for(;n<t.length;){let e=!1;for(let[i,a]of NO)if(t.startsWith(a,n)){r+=i,n+=a.length,e=!0;break}if(!e)return 0}return r}function zO(e){if(!/^[ivxlcdmIVXLCDM]+$/.test(e))return!1;let t=RO(e);return t<=0?!1:(e===e.toLowerCase()?IO(t):LO(t))===e}function BO(e){let t=e.toLowerCase();if(t.length===1)return t.charCodeAt(0)-97+1;if(t.length===2){let e=t.charCodeAt(0)-97,n=t.charCodeAt(1)-97;return(e+1)*26+n+1}return 0}function VO(e){if(e<=26)return PO[e-1];let t=Math.floor((e-1)/26)-1,n=(e-1)%26;return t<0?PO[n]:PO[t]+PO[n]}function HO(e){if(e&&!/^\d+$/.test(e)){if(zO(e))return e===e.toLowerCase()?`i`:`I`;if(/^[a-z]{1,2}$/.test(e))return`a`;if(/^[A-Z]{1,2}$/.test(e))return`A`}}function UO(e){if(/^\d+$/.test(e))return parseInt(e,10);let t=HO(e);if(t===`i`||t===`I`)return RO(e);if(t===`a`||t===`A`){let t=BO(e);return t>0?t:1}let n=parseInt(e,10);return Number.isNaN(n)?1:n}function WO(e,t){if(e===`numeric`)return String(t);switch(e){case`a`:return VO(t);case`A`:return VO(t).toUpperCase();case`i`:return IO(t);case`I`:return LO(t);default:return String(t)}}function GO(e){if(e.length===0)return!1;let t=HO(e[0])??`numeric`,n=UO(e[0]);if(n<1)return!1;for(let r=0;r<e.length;r++){let i=WO(t,n+r);if(e[r]!==i)return!1}return!0}function KO(e){return{type:HO(e),start:UO(e)}}function qO(e){let{type:t,start:n}=KO(e),r={};return t&&(r.type=t),n!==1&&(r.start=n),r}function JO(e,t,n=`. `){let r=t+1;if(!e||e===`1`)return`${r}${n}`;switch(e){case`a`:return`${VO(r)}${n}`;case`A`:return`${VO(r).toUpperCase()}${n}`;case`i`:return`${IO(r)}${n}`;case`I`:return`${LO(r)}${n}`;default:return`${r}${n}`}}function YO(e){return!e[0]||e[0].type===`paragraph`?e:[{type:`paragraph`,content:[]},...e]}function XO(e){let t=e.content?.[0];return t?.type===`paragraph`&&!t.content?.length}var ZO=`&nbsp;`,QO=1,$O=e=>(e?.level??QO)>QO;function ek(e){let t=e.tokens?.[0];return!!(e.text&&e.tokens?.length===1&&t?.type===`list`&&t.ordered&&t.raw===e.text)}function tk(e,t){return t.tokenizeInline?t.parseInline(t.tokenizeInline(e)):t.parseInline([{type:`text`,raw:e,text:e}])}var nk=Jp.create({name:`listItem`,addOptions(){return{HTMLAttributes:{},bulletListTypeName:`bulletList`,orderedListTypeName:`orderedList`}},content:`paragraph block*`,defining:!0,parseHTML(){return[{tag:`li`}]},renderHTML({HTMLAttributes:e}){return[`li`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`list_item`,parseMarkdown:(e,t)=>{if(e.type!==`list_item`)return[];let n=t.parseBlockChildren??t.parseChildren,r=[];if(e.tokens&&e.tokens.length>0){if(ek(e))return{type:`listItem`,content:[{type:`paragraph`,content:tk(e.text||``,t)}]};let[i,...a]=e.tokens;if(i.type===`heading`)return{type:`listItem`,content:[{type:`paragraph`,content:t.parseInline(i.tokens??[])},...a.length>0?n(a):[]]}Line truncated
3. "-" cannot repeat`);QD.customSchemes.push([e,t])}function tO(){QD.scanner=MD(QD.customSchemes);for(let e=0;e<QD.tokenQueue.length;e++)QD.tokenQueue[e][1]({scanner:QD.scanner});QD.parser=qD(QD.scanner.tokens);for(let e=0;e<QD.pluginQueue.length;e++)QD.pluginQueue[e][1]({scanner:QD.scanner,parser:QD.parser});return QD.initialized=!0,QD}function nO(e){return QD.initialized||tO(),JD(QD.parser.start,e,ND(QD.scanner.start,e))}nO.scan=ND;function rO(e,t=null,n=null){if(t&&typeof t==`object`){if(n)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);n=t,t=null}let r=new RD(n),i=nO(e),a=[];for(let e=0;e<i.length;e++){let n=i[e];n.isLink&&(!t||n.t===t)&&r.check(n)&&a.push(n.toFormattedObject(r))}return a}var iO=`[\0- \xA0 ᠎ -\u2029  ]`,aO=new RegExp(iO),oO=RegExp(`${iO}$`),sO=RegExp(`${iO}+$`),cO=new RegExp(iO,`g`);function lO(e,t,n){let r=e.doc.resolve(t.to);if(!r.nodeBefore?.isText)return;let i=e.doc.textBetween(t.from,t.to,``,``).match(sO)?.[0];if(!i)return;let a=t.to-i.length,o=ed(a,t.to,e.doc).filter(e=>e.mark.type===n);if(!o.length)return;let{nodeAfter:s}=r;if(s&&o.some(e=>e.mark.isInSet(s.marks)))return;let c=e.storedMarks;e.removeMark(a,t.to,n),e.setStoredMarks(c),e.selection.empty&&e.selection.from===t.to&&e.removeStoredMark(n)}function uO(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?[`()`,`[]`].includes(e[0].value+e[2].value):!1}function dO(e){return new D({key:new Un(`autolink`),appendTransaction:(t,n,r)=>{let i=t.some(e=>e.docChanged)&&!n.doc.eq(r.doc),a=t.some(e=>e.getMeta(`preventAutolink`));if(!i||a)return;let{tr:o}=r,s=hu(n.doc,[...t]);if(!t.some(Jc)){let t=[];s.steps.forEach((e,n)=>{if(!(e instanceof Et)||!e.slice.size)return;let r=s.mapping.slice(n+1),i=r.map(e.from,1),a=r.map(e.from+e.slice.size,-1);i<a&&t.push({from:i,to:a})}),t.sort((e,t)=>t.to-e.to),t.forEach(t=>lO(o,t,e.type))}if($u(s).forEach(({newRange:t})=>{let n=_u(r.doc,t,e=>e.isTextblock),i,a;if(n.length>1)i=n[0],a=r.doc.textBetween(i.pos,i.pos+i.node.nodeSize,void 0,` `);else if(n.length){let e=r.doc.textBetween(t.from,t.to,` `,` `);if(!oO.test(e))return;i=n[0],a=r.doc.textBetween(i.pos,t.to,void 0,` `)}if(i&&a){let t=a.split(aO).filter(Boolean);if(t.length<=0)return!1;let n=t[t.length-1],s=i.pos+a.lastIndexOf(n);if(!n)return!1;let c=nO(n).map(t=>t.toObject(e.defaultProtocol));if(!uO(c))return!1;c.filter(e=>e.isLink).map(e=>({...e,from:s+e.start+1,to:s+e.end+1})).filter(e=>!r.schema.marks.code||!r.doc.rangeHasMark(e.from,e.to,r.schema.marks.code)).filter(t=>e.validate(t.value)).filter(t=>e.shouldAutoLink(t.value)).forEach(t=>{ed(t.from,t.to,r.doc).some(t=>t.mark.type===e.type)||o.addMark(t.from,t.to,e.type.create({href:t.href}))})}}),o.steps.length)return o}})}function fO(e){return new D({key:new Un(`handleClickLink`),props:{handleClick:(t,n,r)=>{if(r.button!==0||!t.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{let t=r.target;if(!t)return!1;let n=e.editor.view.dom;i=t.closest(`a`),i&&!n.contains(i)&&(i=null)}if(!i)return!1;let a=!1;if(e.enableClickSelection&&(a=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){let n=Xu(t.state,e.type.name),r=i.href??n.href,o=i.target??n.target;r&&(window.open(r,o),a=!0)}return a}}})}var pO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)$/,mO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)/g;function hO(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function gO(e,t){let n=0,r=0;for(;r<t;){if(e[r]!=="`"||n===0&&hO(e,r)){r+=1;continue}let i=0;for(;r<t&&e[r]==="`";)i+=1,r+=1;n===0?n=i:i===n&&(n=0)}return n>0}function _O(e,t,n){let[,r,i]=t;return(t.index?e[t.index-1]:void 0)===`!`||hO(e,t.index??0)||gO(e,t.index??0)?!1:!!r.trim()&&n(i)}function vO(e){let[t,n,r,,i,a,o]=e,s=i??a??o;return{index:e.index??0,text:t,replaceWith:n,data:{href:r,title:s||null,markdown:!0}}}function yO(e,t){return e.index<t.index+t.text.length&&t.index<e.index+e.text.length}function bO(e){return{href:e.data?.href,title:e.data?.title??null}}function xO(e){let t=Hp({find:t=>{let n=pO.exec(t);return!n||!_O(t,n,e.isAllowedHref)?null:vO(n)},type:e.type,getAttributes:bO});return new lp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function SO(e){let t=Yp({find:t=>{let n=[];for(let r of t.matchAll(mO))_O(t,r,e.isAllowedHref)&&n.push(vO(r));let r=(e.findPlainUrls?.call(e,t)??[]).filter(e=>!n.some(t=>yO(t,e)));return[...n,...r]},type:e.type,getAttributes:bO});return new vp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.match.data?.markdown&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function CO(e){return new D({key:new Un(`handlePasteLink`),props:{handlePaste:(t,n,r)=>{let{shouldAutoLink:i}=e,{state:a}=t,{selection:o}=a,{empty:s}=o;if(s)return!1;let c=``;r.content.forEach(e=>{c+=e.textContent});let l=rOLine truncated
`):``,markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(EO,this.editor.getAttributes(DO)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let e=Gp({find:OO,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(e=Gp({find:OO,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(DO),editor:this.editor})),[e]}}),AO=(e,t,n)=>{let{selection:r}=e;if(!r.empty)return null;let{$from:i}=r;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let a=-1;for(let e=i.depth;e>0;--e)if(i.node(e).type.name===t){a=e;break}if(a<0)return null;let o=i.node(a),s=i.index(a);if(s+1>=o.childCount)return null;let c=o.child(s+1);if(!n.includes(c.type.name))return null;let l=e.schema.nodes[t],u=!1;if(c.forEach(e=>{e.type===l&&e.childCount>1&&(u=!0)}),!u)return null;let d=e.doc.resolve(i.after()).nodeAfter;if(!d||!n.includes(d.type.name))return null;let f=[];return d.forEach(e=>{f.push(e)}),f.length===0?null:{listItemDepth:a,nestedList:d,nestedListPos:i.after(),insertPos:i.after(a),items:f}},jO=(e,t,n,r)=>{let i=AO(e,n,r);if(!i)return!1;let{selection:a}=e,{nestedList:o,nestedListPos:c,insertPos:l,items:u}=i,d=e.tr;d.delete(c,c+o.nodeSize);let f=d.mapping.map(l);return d.insert(f,s.from(u)),d.setSelection(a.map(d.doc,d.mapping)),t&&t(d),!0},MO=(e,t,n)=>jO(e.state,e.view.dispatch,t,n),NO=(e,t)=>Tp.create({name:`${e}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){let n=()=>MO(this.editor,e,t);return{Delete:n,"Mod-Delete":n}}}),PO=[[1e3,`m`],[900,`cm`],[500,`d`],[400,`cd`],[100,`c`],[90,`xc`],[50,`l`],[40,`xl`],[10,`x`],[9,`ix`],[5,`v`],[4,`iv`],[1,`i`]],FO=`abcdefghijklmnopqrstuvwxyz`,IO=String.raw`\d+|[ivxlcdmIVXLCDM]+|${`[a-zA-Z]{1,2}`}`;function LO(e){let t=e,n=``;for(let[e,r]of PO)for(;t>=e;)n+=r,t-=e;return n}function RO(e){return LO(e).toUpperCase()}function zO(e){let t=e.toLowerCase(),n=0,r=0;for(;n<t.length;){let e=!1;for(let[i,a]of PO)if(t.startsWith(a,n)){r+=i,n+=a.length,e=!0;break}if(!e)return 0}return r}function BO(e){if(!/^[ivxlcdmIVXLCDM]+$/.test(e))return!1;let t=zO(e);return t<=0?!1:(e===e.toLowerCase()?LO(t):RO(t))===e}function VO(e){let t=e.toLowerCase();if(t.length===1)return t.charCodeAt(0)-97+1;if(t.length===2){let e=t.charCodeAt(0)-97,n=t.charCodeAt(1)-97;return(e+1)*26+n+1}return 0}function HO(e){if(e<=26)return FO[e-1];let t=Math.floor((e-1)/26)-1,n=(e-1)%26;return t<0?FO[n]:FO[t]+FO[n]}function UO(e){if(e&&!/^\d+$/.test(e)){if(BO(e))return e===e.toLowerCase()?`i`:`I`;if(/^[a-z]{1,2}$/.test(e))return`a`;if(/^[A-Z]{1,2}$/.test(e))return`A`}}function WO(e){if(/^\d+$/.test(e))return parseInt(e,10);let t=UO(e);if(t===`i`||t===`I`)return zO(e);if(t===`a`||t===`A`){let t=VO(e);return t>0?t:1}let n=parseInt(e,10);return Number.isNaN(n)?1:n}function GO(e,t){if(e===`numeric`)return String(t);switch(e){case`a`:return HO(t);case`A`:return HO(t).toUpperCase();case`i`:return LO(t);case`I`:return RO(t);default:return String(t)}}function KO(e){if(e.length===0)return!1;let t=UO(e[0])??`numeric`,n=WO(e[0]);if(n<1)return!1;for(let r=0;r<e.length;r++){let i=GO(t,n+r);if(e[r]!==i)return!1}return!0}function qO(e){return{type:UO(e),start:WO(e)}}function JO(e){let{type:t,start:n}=qO(e),r={};return t&&(r.type=t),n!==1&&(r.start=n),r}function YO(e,t,n=`. `){let r=t+1;if(!e||e===`1`)return`${r}${n}`;switch(e){case`a`:return`${HO(r)}${n}`;case`A`:return`${HO(r).toUpperCase()}${n}`;case`i`:return`${LO(r)}${n}`;case`I`:return`${RO(r)}${n}`;default:return`${r}${n}`}}function XO(e){return!e[0]||e[0].type===`paragraph`?e:[{type:`paragraph`,content:[]},...e]}function ZO(e){let t=e.content?.[0];return t?.type===`paragraph`&&!t.content?.length}var QO=`&nbsp;`,$O=1,ek=e=>(e?.level??$O)>$O;function tk(e){let t=e.tokens?.[0];return!!(e.text&&e.tokens?.length===1&&t?.type===`list`&&t.ordered&&t.raw===e.text)}function nk(e,t){return t.tokenizeInline?t.parseInline(t.tokenizeInline(e)):t.parseInline([{type:`text`,raw:e,text:e}])}var rk=Jp.create({name:`listItem`,addOptions(){return{HTMLAttributes:{},bulletListTypeName:`bulletList`,orderedListTypeName:`orderedList`}},content:`paragraph block*`,defining:!0,parseHTML(){return[{tag:`li`}]},renderHTML({HTMLAttributes:e}){return[`li`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`list_item`,parseMarkdown:(e,t)=>{if(e.type!==`list_item`)return[];let n=t.parseBlockChildren??t.parseChildren,r=[];if(e.tokens&&e.tokens.length>0){if(tk(e))return{type:`listItem`,content:[{type:`paragraph`,content:nk(e.text||``,t)}]};let[i,...a]=e.tokens;if(i.type===`heading`)return{type:`listItem`,content:[{type:`paragraph`,content:t.parseInline(i.tokens??[])},...a.length>0?n(a):[]]}Line truncated
`).trim(),contentLines:m,raw:g.join(`
`)}),r=h,n=h}return[t,r]}var bk=RegExp(`^(${FO})([.)])\\s+(.+)$`);function xk(e){let t=e.split(`
`).filter(e=>e.trim().length>0);if(t.length===0)return null;let n=[];for(let e of t){let t=e.trim().match(bk);if(!t)return null;n.push({marker:t[1],content:t[3]})}return GO(n.map(e=>e.marker))?{type:`orderedList`,attrs:qO(n[0].marker),content:n.map(e=>({type:`listItem`,content:[{type:`paragraph`,content:[{type:`text`,text:e.content}]}]}))}:null}function Sk(e,t,n){let r=[],i=0;for(;i<e.length;){let a=e[i];if(a.indent===t){let{paragraphLines:o,blockLines:s}=vk(a.contentLines),c=o.join(`
`)}),r=h,n=h}return[t,r]}var xk=RegExp(`^(${IO})([.)])\\s+(.+)$`);function Sk(e){let t=e.split(`
`).filter(e=>e.trim().length>0);if(t.length===0)return null;let n=[];for(let e of t){let t=e.trim().match(xk);if(!t)return null;n.push({marker:t[1],content:t[3]})}return KO(n.map(e=>e.marker))?{type:`orderedList`,attrs:JO(n[0].marker),content:n.map(e=>({type:`listItem`,content:[{type:`paragraph`,content:[{type:`text`,text:e.content}]}]}))}:null}function Ck(e,t,n){let r=[],i=0;for(;i<e.length;){let a=e[i];if(a.indent===t){let{paragraphLines:o,blockLines:s}=yk(a.contentLines),c=o.join(`
`).trim(),l=[];c&&l.push({type:`paragraph`,raw:c,tokens:n.inlineTokens(c)});let u=s.join(`
`).trim();if(u){let e=n.blockTokens(u);l.push(...e)}let d=i+1,f=[];for(;d<e.length&&e[d].indent>t;)f.push(e[d]),d+=1;if(f.length>0){let e=Sk(f,Math.min(...f.map(e=>e.indent)),n);l.push({type:`list`,ordered:!0,start:f[0].number,typeMarker:f[0].type,items:e,raw:f.map(e=>e.raw).join(`
`)})}r.push({type:`list_item`,raw:a.raw,tokens:l}),i=d}else i+=1}return r}function Ck(e,t){return e.map(e=>{if(e.type!==`list_item`)return t.parseChildren([e])[0];let n=[];return e.tokens&&e.tokens.length>0&&e.tokens.forEach(e=>{if(e.type===`paragraph`||e.type===`list`||e.type===`blockquote`||e.type===`code`)n.push(...t.parseChildren([e]));else if(e.type===`text`&&e.tokens){let r=t.parseChildren([e]);n.push({type:`paragraph`,content:r})}else{let r=t.parseChildren([e]);r.length>0&&n.push(...r)}}),{type:`listItem`,content:n}})}var wk=64;function Tk(e,t){let n=[],r=0;for(;n.length<t;){let t=e.indexOf(`
`,r);if(t===-1)return n.push(e.slice(r)),n;n.push(e.slice(r,t)),r=t+1}return n}function Ek(e){let t=e.indexOf(`
`),n=t===-1?e:e.slice(0,t);if(!fk.test(n))return[[],0,[]];let r=wk,i=Tk(e,r),a=yk(i);for(;a[1]===i.length&&i.length===r;)r*=2,i=Tk(e,r),a=yk(i);return[a[0],a[1],i]}var Dk=`listItem`,Ok=`textStyle`,kk=/^(\d+)\.\s$/;function Ak(e){let t=e.match(/list-style-type\s*:\s*([^;]+)/i);if(!t)return null;switch(t[1].trim().toLowerCase()){case`upper-roman`:return`I`;case`lower-roman`:return`i`;case`upper-alpha`:case`upper-latin`:return`A`;case`lower-alpha`:case`lower-latin`:return`a`;default:return null}}var jk=Jp.create({name:`orderedList`,addOptions(){return{itemTypeName:`listItem`,HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:`block list`,content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:e=>e.hasAttribute(`start`)?parseInt(e.getAttribute(`start`)||``,10):1},type:{default:null,parseHTML:e=>{let t=e.getAttribute(`type`);if(t)return t;let n=e.getAttribute(`style`);if(n){let e=Ak(n);if(e)return e}let r=e.querySelector(`li`);if(r){let e=r.getAttribute(`style`);if(e){let t=Ak(e);if(t)return t}}return null}}}},parseHTML(){return[{tag:`ol`}]},renderHTML({HTMLAttributes:e}){let{start:t,type:n,...r}=e,i=A(this.options.HTMLAttributes,r);return t!==1&&(i.start=t),n&&n!==`1`&&(i.type=n),[`ol`,i,0]},markdownTokenName:`list`,parseMarkdown:(e,t)=>{if(e.type!==`list`||!e.ordered)return[];let n=e.start||1,r=e.typeMarker,i=e.items?Ck(e.items,t):[],a={};return n!==1&&(a.start=n),r&&(a.type=r),Object.keys(a).length>0?{type:`orderedList`,attrs:a,content:i}:{type:`orderedList`,content:i}},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
`):``,markdownTokenizer:{name:`orderedList`,level:`block`,start:()=>-1,tokenize:(e,t,n)=>{let[r,i,a]=Ek(e);if(r.length===0)return;let o=Sk(r,r[0].indent,n);if(o.length!==0)return{type:`list`,ordered:!0,start:r[0]?.number||1,typeMarker:r[0]?.type,items:o,raw:a.slice(0,i).join(`
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(Dk,this.editor.getAttributes(Ok)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new E({props:{handlePaste:(e,t)=>{if((t.clipboardData?.getData(`text/html`))?.trim())return!1;let n=t.clipboardData?.getData(`text/plain`);if(!n)return!1;let r=xk(n);if(!r)return!1;try{let t=e.state.schema.nodeFromJSON(r),n=e.state.tr.replaceSelectionWith(t);return e.dispatch(n),!0}catch{return!1}}}})]},addInputRules(){let e=(e,t)=>(!t.attrs.type||t.attrs.type===`1`)&&t.childCount+t.attrs.start===+e[1],t=Gp({find:kk,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Gp({find:kk,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(Ok)}),joinPredicate:e,editor:this.editor})),[t]}}),Mk=/^\s*(\[([( |x])?\])\s$/,Nk=`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0`,Pk=(e,t,n)=>{var r;return(n==null||(r=n.checkboxLabel)==null?void 0:r.call(n,e,t))||`Task item checkbox for ${e.textContent||`empty task item`}`},Fk=Jp.create({name:`taskItem`,addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:`taskList`,a11y:void 0}},content(){return this.options.nested?`paragraph block*`:`paragraph+`},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-checked`);return t===``||t===`true`},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:e=>e.querySelector(`div`)??e}]},renderHTML({node:e,HTMLAttributes:t}){return[`li`,A(this.options.HTMLAttributes,t,{"data-type":this.name}),[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null}],[`span`]],[`div`,0]]},parseMarkdown:(e,t)=>{let n=[];if(e.tokens&&e.tokens.length>0?n.push(t.createNode(`paragraph`,{},t.parseInline(e.tokens))):e.text?n.push(t.createNode(`paragraph`,{},[t.createNode(`text`,{text:e.text})])):n.push(t.createNode(`paragraph`,{},[])),e.nestedTokens&&e.nestedTokens.length>0){let r=t.parseChildren(e.nestedTokens);n.push(...r)}return t.createNode(`taskItem`,{checked:e.checked||!1},n)},renderMarkdown:(e,t)=>op(e,t,`- [${e.attrs?.checked?`x`:` `}] `,void 0,{indentMainContent:!0}),addExtensions(){return this.options.nested?[MO(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:t,getPos:n,editor:r})=>{let i=document.createElement(`li`),a=document.createElement(`label`),o=document.createElement(`span`),s=document.createElement(`input`),c=document.createElement(`div`);o.style.cssText=Nk;let l=e=>{let t=Pk(e,e.attrs.checked,this.options.a11y);s.setAttribute(`aria-label`,t),o.textContent=t};l(e),a.contentEditable=`false`,s.type=`checkbox`,s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`change`,t=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){s.checked=!s.checked;return}let{checked:i}=t.target;r.isEditable&&typeof n==`function`&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:e})=>{let t=n();if(typeof t!=`number`)return!1;let r=e.doc.nodeAt(t);return e.setNodeMarkup(t,void 0,{...r?.attrs,checked:i}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,i)||(s.checked=!s.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([e,t])=>{i.setAttribute(e,t)}),i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,a.append(s,o),i.append(a,c),Object.entries(t).forEach(([e,t])=>{i.setAttribute(e,t)});let u=new Set(Object.keys(t));return{dom:i,contentDOM:c,update:e=>{if(e.type!==this.type)return!1;i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,l(e);let t=r.extensionManager.attributes,n=Lu(e,t),a=new Set(Object.keys(n)),o=this.options.HTMLAttributes;return u.forEach(e=>{a.has(e)||(e in o?i.setAttribute(e,o[e]):i.removeAttribute(e))}),Object.entries(n).forEach(([e,t])=>{t==null?e in o?i.setAttribute(e,o[e]):i.removeAttribute(e):i.setAttribute(e,t)}),u=a,!0}}}},addInputRules(){return[Gp({find:Mk,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),Ik=Jp.create({name:`taskList`,addOptions(){return{itemTypeName:`taskItem`,HTMLAttributes:{}}},group:`block list`,content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`uLine truncated
`):``,markdownTokenizer:{name:`taskList`,level:`block`,start(e){let t=e.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)?.index;return t===void 0?-1:t},tokenize(e,t,n){let r=e=>{let t=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(t){let r={type:`taskList`,raw:t.raw,items:t.items},i=e.slice(t.raw.length);return i.trim()?[r,...n.blockTokens(i)]:[r]}return n.blockTokens(e)},i=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(i)return{type:`taskList`,raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Tp.create({name:`listKit`,addExtensions(){let e=[];return this.options.bulletList!==!1&&e.push(OO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push(nk.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(dk.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(jk.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(Fk.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(Ik.configure(this.options.taskList)),e}});var Lk=`&nbsp;`,Rk=`\xA0`,zk=Jp.create({name:`paragraph`,priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:`block`,content:`inline*`,parseHTML(){return[{tag:`p`}]},renderHTML({HTMLAttributes:e}){return[`p`,A(this.options.HTMLAttributes,e),0]},parseMarkdown:(e,t)=>{let n=e.tokens||[];if(n.length===1&&n[0].type===`image`)return t.parseChildren([n[0]]);let r=t.parseInline(n);return n.length===1&&n[0].type===`text`&&(n[0].raw===Lk||n[0].text===Lk||n[0].raw===Rk||n[0].text===Rk)&&r.length===1&&r[0].type===`text`&&(r[0].text===Lk||r[0].text===Rk)?t.createNode(`paragraph`,void 0,[]):t.createNode(`paragraph`,void 0,r)},renderMarkdown:(e,t,n)=>{if(!e)return``;let r=Array.isArray(e.content)?e.content:[];if(r.length===0){var i,a;let e=Array.isArray(n==null||(i=n.previousNode)==null?void 0:i.content)?n.previousNode.content:[];return(n==null||(a=n.previousNode)==null?void 0:a.type)===`paragraph`&&e.length===0?Lk:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Bk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Vk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Hk=_p.create({name:`strike`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`s`},{tag:`del`},{tag:`strike`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`line-through`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`s`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`del`,parseMarkdown:(e,t)=>t.applyMark(`strike`,t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Hp({find:Bk,type:this.type})]},addPasteRules(){return[Yp({find:Vk,type:this.type})]}}),Uk=Jp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),Wk=_p.create({name:`underline`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`u`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`underline`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`u`,A(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||`underline`,t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`<u>${t.renderChildren(e)}</u>`},markdownTokenizer:{name:`underline`,level:`inline`,start(e){return e.toLowerCase().indexOf(`<u>`)},tokenize(e,t,n){if(!/^<u>/i.test(e))return;let r=/\\[\s\S]|`+|<\/u>/gi;r.lastIndex=3;let i=r.exec(e);for(;i;){if(i[0].startsWith("`")){let t=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/.exec(e.slice(i.index));t&&(r.lastIndex=i.index+t[0].length)}else if(!i[0].startsWith(`\\`)){let t=e.slice(3,i.index);return t?{type:`underline`,raw:e.slice(0,r.lastIndex),text:t,tokens:n.inlineTokens(t)}:void 0}i=r.exec(e)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleLine truncated
`).trim();if(u){let e=n.blockTokens(u);l.push(...e)}let d=i+1,f=[];for(;d<e.length&&e[d].indent>t;)f.push(e[d]),d+=1;if(f.length>0){let e=Ck(f,Math.min(...f.map(e=>e.indent)),n);l.push({type:`list`,ordered:!0,start:f[0].number,typeMarker:f[0].type,items:e,raw:f.map(e=>e.raw).join(`
`)})}r.push({type:`list_item`,raw:a.raw,tokens:l}),i=d}else i+=1}return r}function wk(e,t){return e.map(e=>{if(e.type!==`list_item`)return t.parseChildren([e])[0];let n=[];return e.tokens&&e.tokens.length>0&&e.tokens.forEach(e=>{if(e.type===`paragraph`||e.type===`list`||e.type===`blockquote`||e.type===`code`)n.push(...t.parseChildren([e]));else if(e.type===`text`&&e.tokens){let r=t.parseChildren([e]);n.push({type:`paragraph`,content:r})}else{let r=t.parseChildren([e]);r.length>0&&n.push(...r)}}),{type:`listItem`,content:n}})}var Tk=64;function Ek(e,t){let n=[],r=0;for(;n.length<t;){let t=e.indexOf(`
`,r);if(t===-1)return n.push(e.slice(r)),n;n.push(e.slice(r,t)),r=t+1}return n}function Dk(e){let t=e.indexOf(`
`),n=t===-1?e:e.slice(0,t);if(!pk.test(n))return[[],0,[]];let r=Tk,i=Ek(e,r),a=bk(i);for(;a[1]===i.length&&i.length===r;)r*=2,i=Ek(e,r),a=bk(i);return[a[0],a[1],i]}var Ok=`listItem`,kk=`textStyle`,Ak=/^(\d+)\.\s$/;function jk(e){let t=e.match(/list-style-type\s*:\s*([^;]+)/i);if(!t)return null;switch(t[1].trim().toLowerCase()){case`upper-roman`:return`I`;case`lower-roman`:return`i`;case`upper-alpha`:case`upper-latin`:return`A`;case`lower-alpha`:case`lower-latin`:return`a`;default:return null}}var Mk=Jp.create({name:`orderedList`,addOptions(){return{itemTypeName:`listItem`,HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:`block list`,content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:e=>e.hasAttribute(`start`)?parseInt(e.getAttribute(`start`)||``,10):1},type:{default:null,parseHTML:e=>{let t=e.getAttribute(`type`);if(t)return t;let n=e.getAttribute(`style`);if(n){let e=jk(n);if(e)return e}let r=e.querySelector(`li`);if(r){let e=r.getAttribute(`style`);if(e){let t=jk(e);if(t)return t}}return null}}}},parseHTML(){return[{tag:`ol`}]},renderHTML({HTMLAttributes:e}){let{start:t,type:n,...r}=e,i=A(this.options.HTMLAttributes,r);return t!==1&&(i.start=t),n&&n!==`1`&&(i.type=n),[`ol`,i,0]},markdownTokenName:`list`,parseMarkdown:(e,t)=>{if(e.type!==`list`||!e.ordered)return[];let n=e.start||1,r=e.typeMarker,i=e.items?wk(e.items,t):[],a={};return n!==1&&(a.start=n),r&&(a.type=r),Object.keys(a).length>0?{type:`orderedList`,attrs:a,content:i}:{type:`orderedList`,content:i}},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
`):``,markdownTokenizer:{name:`orderedList`,level:`block`,start:()=>-1,tokenize:(e,t,n)=>{let[r,i,a]=Dk(e);if(r.length===0)return;let o=Ck(r,r[0].indent,n);if(o.length!==0)return{type:`list`,ordered:!0,start:r[0]?.number||1,typeMarker:r[0]?.type,items:o,raw:a.slice(0,i).join(`
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(Ok,this.editor.getAttributes(kk)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new D({props:{handlePaste:(e,t)=>{if((t.clipboardData?.getData(`text/html`))?.trim())return!1;let n=t.clipboardData?.getData(`text/plain`);if(!n)return!1;let r=Sk(n);if(!r)return!1;try{let t=e.state.schema.nodeFromJSON(r),n=e.state.tr.replaceSelectionWith(t);return e.dispatch(n),!0}catch{return!1}}}})]},addInputRules(){let e=(e,t)=>(!t.attrs.type||t.attrs.type===`1`)&&t.childCount+t.attrs.start===+e[1],t=Gp({find:Ak,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Gp({find:Ak,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(kk)}),joinPredicate:e,editor:this.editor})),[t]}}),Nk=/^\s*(\[([( |x])?\])\s$/,Pk=`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0`,Fk=(e,t,n)=>{var r;return(n==null||(r=n.checkboxLabel)==null?void 0:r.call(n,e,t))||`Task item checkbox for ${e.textContent||`empty task item`}`},Ik=Jp.create({name:`taskItem`,addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:`taskList`,a11y:void 0}},content(){return this.options.nested?`paragraph block*`:`paragraph+`},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-checked`);return t===``||t===`true`},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:e=>e.querySelector(`div`)??e}]},renderHTML({node:e,HTMLAttributes:t}){return[`li`,A(this.options.HTMLAttributes,t,{"data-type":this.name}),[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null}],[`span`]],[`div`,0]]},parseMarkdown:(e,t)=>{let n=[];if(e.tokens&&e.tokens.length>0?n.push(t.createNode(`paragraph`,{},t.parseInline(e.tokens))):e.text?n.push(t.createNode(`paragraph`,{},[t.createNode(`text`,{text:e.text})])):n.push(t.createNode(`paragraph`,{},[])),e.nestedTokens&&e.nestedTokens.length>0){let r=t.parseChildren(e.nestedTokens);n.push(...r)}return t.createNode(`taskItem`,{checked:e.checked||!1},n)},renderMarkdown:(e,t)=>op(e,t,`- [${e.attrs?.checked?`x`:` `}] `,void 0,{indentMainContent:!0}),addExtensions(){return this.options.nested?[NO(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:t,getPos:n,editor:r})=>{let i=document.createElement(`li`),a=document.createElement(`label`),o=document.createElement(`span`),s=document.createElement(`input`),c=document.createElement(`div`);o.style.cssText=Pk;let l=e=>{let t=Fk(e,e.attrs.checked,this.options.a11y);s.setAttribute(`aria-label`,t),o.textContent=t};l(e),a.contentEditable=`false`,s.type=`checkbox`,s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`change`,t=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){s.checked=!s.checked;return}let{checked:i}=t.target;r.isEditable&&typeof n==`function`&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:e})=>{let t=n();if(typeof t!=`number`)return!1;let r=e.doc.nodeAt(t);return e.setNodeMarkup(t,void 0,{...r?.attrs,checked:i}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,i)||(s.checked=!s.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([e,t])=>{i.setAttribute(e,t)}),i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,a.append(s,o),i.append(a,c),Object.entries(t).forEach(([e,t])=>{i.setAttribute(e,t)});let u=new Set(Object.keys(t));return{dom:i,contentDOM:c,update:e=>{if(e.type!==this.type)return!1;i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,l(e);let t=r.extensionManager.attributes,n=Lu(e,t),a=new Set(Object.keys(n)),o=this.options.HTMLAttributes;return u.forEach(e=>{a.has(e)||(e in o?i.setAttribute(e,o[e]):i.removeAttribute(e))}),Object.entries(n).forEach(([e,t])=>{t==null?e in o?i.setAttribute(e,o[e]):i.removeAttribute(e):i.setAttribute(e,t)}),u=a,!0}}}},addInputRules(){return[Gp({find:Nk,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),Lk=Jp.create({name:`taskList`,addOptions(){return{itemTypeName:`taskItem`,HTMLAttributes:{}}},group:`block list`,content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`uLine truncated
`):``,markdownTokenizer:{name:`taskList`,level:`block`,start(e){let t=e.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)?.index;return t===void 0?-1:t},tokenize(e,t,n){let r=e=>{let t=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(t){let r={type:`taskList`,raw:t.raw,items:t.items},i=e.slice(t.raw.length);return i.trim()?[r,...n.blockTokens(i)]:[r]}return n.blockTokens(e)},i=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(i)return{type:`taskList`,raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Tp.create({name:`listKit`,addExtensions(){let e=[];return this.options.bulletList!==!1&&e.push(kO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push(rk.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(fk.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(Mk.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(Ik.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(Lk.configure(this.options.taskList)),e}});var Rk=`&nbsp;`,zk=`\xA0`,Bk=Jp.create({name:`paragraph`,priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:`block`,content:`inline*`,parseHTML(){return[{tag:`p`}]},renderHTML({HTMLAttributes:e}){return[`p`,A(this.options.HTMLAttributes,e),0]},parseMarkdown:(e,t)=>{let n=e.tokens||[];if(n.length===1&&n[0].type===`image`)return t.parseChildren([n[0]]);let r=t.parseInline(n);return n.length===1&&n[0].type===`text`&&(n[0].raw===Rk||n[0].text===Rk||n[0].raw===zk||n[0].text===zk)&&r.length===1&&r[0].type===`text`&&(r[0].text===Rk||r[0].text===zk)?t.createNode(`paragraph`,void 0,[]):t.createNode(`paragraph`,void 0,r)},renderMarkdown:(e,t,n)=>{if(!e)return``;let r=Array.isArray(e.content)?e.content:[];if(r.length===0){var i,a;let e=Array.isArray(n==null||(i=n.previousNode)==null?void 0:i.content)?n.previousNode.content:[];return(n==null||(a=n.previousNode)==null?void 0:a.type)===`paragraph`&&e.length===0?Rk:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Vk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Hk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Uk=_p.create({name:`strike`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`s`},{tag:`del`},{tag:`strike`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`line-through`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`s`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`del`,parseMarkdown:(e,t)=>t.applyMark(`strike`,t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Hp({find:Vk,type:this.type})]},addPasteRules(){return[Yp({find:Hk,type:this.type})]}}),Wk=Jp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),Gk=_p.create({name:`underline`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`u`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`underline`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`u`,A(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||`underline`,t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`<u>${t.renderChildren(e)}</u>`},markdownTokenizer:{name:`underline`,level:`inline`,start(e){return e.toLowerCase().indexOf(`<u>`)},tokenize(e,t,n){if(!/^<u>/i.test(e))return;let r=/\\[\s\S]|`+|<\/u>/gi;r.lastIndex=3;let i=r.exec(e);for(;i;){if(i[0].startsWith("`")){let t=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/.exec(e.slice(i.index));t&&(r.lastIndex=i.index+t[0].length)}else if(!i[0].startsWith(`\\`)){let t=e.slice(3,i.index);return t?{type:`underline`,raw:e.slice(0,r.lastIndex),text:t,tokens:n.inlineTokens(t)}:void 0}i=r.exec(e)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleLine truncated
`).length:0;c!==o&&(o=c,i.textContent=Array.from({length:c},(e,t)=>t+1).join(`
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),Pj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Fj(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Ij={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-left":[`M14 6l-6 6 6 6`],"chevron-down":[`M6 10l6 6 6-6`],"chevron-up":[`M6 14l6-6 6 6`],plus:[`M12 5v14`,`M5 12h14`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z`,`M16.5 16.5L20 20`],more:[`M6 12h.01`,`M12 12h.01`,`M18 12h.01`],drop:[`M12 4h7v7a7 7 0 1 1-7-7z`],info:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 11v5`,`M12 8h.01`],check:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8 12.5l2.5 2.5L16 9.5`],alert:[`M12 4l9 16H3z`,`M12 10v4`,`M12 17h.01`],error:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M9 9l6 6`,`M15 9l-6 6`],text:[`M5 6h14`,`M12 6v13`],heading:[`M6 5v14`,`M18 5v14`,`M6 12h12`],list:[`M9 6h11`,`M9 12h11`,`M9 18h11`,`M4.5 6h.01`,`M4.5 12h.01`,`M4.5 18h.01`],todo:[`M4 4h7v7H4z`,`M5.5 7.5l1.5 1.5 2.5-2.5`,`M14 7h6`,`M4 14h7v7H4z`,`M14 17h6`],code:[`M9 7l-5 5 5 5`,`M15 7l5 5-5 5`],quote:[`M6 6v12`,`M10 8h9`,`M10 12h9`,`M10 16h6`],image:[`M4 5h16v14H4z`,`M4 16l5-5 4 4 2-2 5 5`,`M15.5 8.5h.01`],table:[`M4 5h16v14H4z`,`M4 10h16`,`M4 15h16`,`M10 5v14`],lock:[`M6 11h12v9H6z`,`M8.5 11V8a3.5 3.5 0 0 1 7 0v3`],trash:[`M4 7h16`,`M10 4h4`,`M6 7l1 13h10l1-13`,`M10 11v6`,`M14 11v6`],settings:[`M4 7h9`,`M17 7h3`,`M15 5v4`,`M4 17h3`,`M11 17h9`,`M9 15v4`],menu:[`M4 7h16`,`M4 12h16`,`M4 17h16`],close:[`M6 6l12 12`,`M18 6L6 18`],open:[`M8 16L16 8`,`M9 8h7v7`],restore:[`M4.5 13a7.5 7.5 0 1 0 2.2-6.3`,`M5 4v4h4`],"sign-out":[`M14 4h5v16h-5`,`M10 8l-4 4 4 4`,`M6 12h9`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8Line truncated
`).map(e=>!e.includes(`|`)||!e.includes("`")?e:fP(e)).join(`
`)}function mP(e){return(e||``).replaceAll(``,` `).replace(/\s+/g,` `).trim()}function hP(e,t){return t?e.split(t).join(`
`):e}function gP(e){return e.replace(/\\.|\|/g,e=>e===`|`?`\\|`:e)}function _P(e,t,n={}){if(!e||!e.content||e.content.length===0)return``;let r=[];e.content.forEach(e=>{let i=[];e.content&&e.content.forEach(e=>{let r=``;r=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>hP(t.renderChildren(e),n.cellLineSeparator)).join(`
`):hP(e.content?t.renderChildren(e.content):``,n.cellLineSeparator);let a=gP(mP(r.replace(/[ \t]*\r?\n[ \t]*/g,`<br>`))),o=e.type===`tableHeader`,s=GN(e.attrs);i.push({text:a,isHeader:o,align:s})}),r.push(i)});let i=r.reduce((e,t)=>Math.max(e,t.length),0);if(i===0)return``;let a=Array.from({length:i}).fill(0);r.forEach(e=>{for(let t=0;t<i;t+=1){let n=(e[t]?.text||``).length;n>a[t]&&(a[t]=n),a[t]<3&&(a[t]=3)}});let o=(e,t)=>e+` `.repeat(Math.max(0,t-e.length)),s=r[0],c=s.some(e=>e.isHeader),l=Array.from({length:i}).fill(null);r.forEach(e=>{for(let t=0;t<i;t+=1)!l[t]&&e[t]?.align&&(l[t]=e[t].align)});let u=`
`,d=Array.from({length:i}).map((e,t)=>c&&s[t]&&s[t].text||``);return u+=`| ${d.map((e,t)=>o(e,a[t])).join(` | `)} |\n`,u+=`| ${a.map((e,t)=>{let n=Math.max(3,e),r=l[t];return r===`left`?`:${`-`.repeat(n)}`:r===`right`?`${`-`.repeat(n)}:`:r===`center`?`:${`-`.repeat(n)}:`:`-`.repeat(n)}).join(` | `)} |\n`,(c?r.slice(1):r).forEach(e=>{u+=`| ${Array.from({length:i}).fill(0).map((t,n)=>o(e[n]&&e[n].text||``,a[n])).join(` | `)} |\n`}),u}var vP=new D(`preserveCellSelectionOnContextMenu`);function yP(e,t){let n=e.posAtCoords({left:t.clientX,top:t.clientY});if(n)return n.pos;if(!(t.target instanceof Node))return null;try{return e.posAtDOM(t.target,0)}catch{return null}}function bP(e,t){let n=!1;return e.forEachCell((e,r)=>{t>=r&&t<r+e.nodeSize&&(n=!0)}),n}function xP(){return new E({key:vP,props:{handleDOMEvents:{mousedown(e,t){if(t.button!==2)return!1;let{selection:n}=e.state;if(!lP(n)||n.ranges.length<2)return!1;let r=yP(e,t);return r==null||!bP(n,r)?!1:(t.preventDefault(),!0)}}}})}var SP=Jp.create({name:`table`,addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:iP,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:`tableRow+`,tableRole:`table`,isolating:!0,group:`block`,parseHTML(){return[{tag:`table`}]},renderHTML({node:e,HTMLAttributes:t}){let{colgroup:n,tableWidth:r,tableMinWidth:i}=aP(e,this.options.cellMinWidth),a=t.style;function o(){return a||(r?`width: ${r}`:`min-width: ${i}`)}let s=[`table`,A(this.options.HTMLAttributes,t,{style:o()}),n,[`tbody`,0]];return this.options.renderWrapper?[`div`,{class:`tableWrapper`},s]:s},parseMarkdown:(e,t)=>{let n=[],r=Array.isArray(e.align)?e.align:[];if(e.header){let i=[];e.header.forEach((e,n)=>{let a=UN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableHeader`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}return e.rows&&e.rows.forEach(e=>{let i=[];e.forEach((e,n)=>{let a=UN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableCell`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}),t.createNode(`table`,void 0,n)},renderMarkdown:(e,t)=>_P(e,t),markdownTokenizer:{name:`table`,level:`block`,start:e=>{let t=e.split(`
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),Fj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Ij(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Lj={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-left":[`M14 6l-6 6 6 6`],"chevron-down":[`M6 10l6 6 6-6`],"chevron-up":[`M6 14l6-6 6 6`],plus:[`M12 5v14`,`M5 12h14`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z`,`M16.5 16.5L20 20`],more:[`M6 12h.01`,`M12 12h.01`,`M18 12h.01`],drop:[`M12 4h7v7a7 7 0 1 1-7-7z`],info:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 11v5`,`M12 8h.01`],check:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8 12.5l2.5 2.5L16 9.5`],alert:[`M12 4l9 16H3z`,`M12 10v4`,`M12 17h.01`],error:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M9 9l6 6`,`M15 9l-6 6`],text:[`M5 6h14`,`M12 6v13`],heading:[`M6 5v14`,`M18 5v14`,`M6 12h12`],list:[`M9 6h11`,`M9 12h11`,`M9 18h11`,`M4.5 6h.01`,`M4.5 12h.01`,`M4.5 18h.01`],todo:[`M4 4h7v7H4z`,`M5.5 7.5l1.5 1.5 2.5-2.5`,`M14 7h6`,`M4 14h7v7H4z`,`M14 17h6`],code:[`M9 7l-5 5 5 5`,`M15 7l5 5-5 5`],quote:[`M6 6v12`,`M10 8h9`,`M10 12h9`,`M10 16h6`],image:[`M4 5h16v14H4z`,`M4 16l5-5 4 4 2-2 5 5`,`M15.5 8.5h.01`],table:[`M4 5h16v14H4z`,`M4 10h16`,`M4 15h16`,`M10 5v14`],lock:[`M6 11h12v9H6z`,`M8.5 11V8a3.5 3.5 0 0 1 7 0v3`],trash:[`M4 7h16`,`M10 4h4`,`M6 7l1 13h10l1-13`,`M10 11v6`,`M14 11v6`],settings:[`M4 7h9`,`M17 7h3`,`M15 5v4`,`M4 17h3`,`M11 17h9`,`M9 15v4`],menu:[`M4 7h16`,`M4 12h16`,`M4 17h16`],close:[`M6 6l12 12`,`M18 6L6 18`],open:[`M8 16L16 8`,`M9 8h7v7`],restore:[`M4.5 13a7.5 7.5 0 1 0 2.2-6.3`,`M5 4v4h4`],"sign-out":[`M14 4h5v16h-5`,`M10 8l-4 4 4 4`,`M6 12h9`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8Line truncated
`).map(e=>!e.includes(`|`)||!e.includes("`")?e:pP(e)).join(`
`)}function hP(e){return(e||``).replaceAll(``,` `).replace(/\s+/g,` `).trim()}function gP(e,t){return t?e.split(t).join(`
`):e}function _P(e){return e.replace(/\\.|\|/g,e=>e===`|`?`\\|`:e)}function vP(e,t,n={}){if(!e||!e.content||e.content.length===0)return``;let r=[];e.content.forEach(e=>{let i=[];e.content&&e.content.forEach(e=>{let r=``;r=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>gP(t.renderChildren(e),n.cellLineSeparator)).join(`
`):gP(e.content?t.renderChildren(e.content):``,n.cellLineSeparator);let a=_P(hP(r.replace(/[ \t]*\r?\n[ \t]*/g,`<br>`))),o=e.type===`tableHeader`,s=KN(e.attrs);i.push({text:a,isHeader:o,align:s})}),r.push(i)});let i=r.reduce((e,t)=>Math.max(e,t.length),0);if(i===0)return``;let a=Array.from({length:i}).fill(0);r.forEach(e=>{for(let t=0;t<i;t+=1){let n=(e[t]?.text||``).length;n>a[t]&&(a[t]=n),a[t]<3&&(a[t]=3)}});let o=(e,t)=>e+` `.repeat(Math.max(0,t-e.length)),s=r[0],c=s.some(e=>e.isHeader),l=Array.from({length:i}).fill(null);r.forEach(e=>{for(let t=0;t<i;t+=1)!l[t]&&e[t]?.align&&(l[t]=e[t].align)});let u=`
`,d=Array.from({length:i}).map((e,t)=>c&&s[t]&&s[t].text||``);return u+=`| ${d.map((e,t)=>o(e,a[t])).join(` | `)} |\n`,u+=`| ${a.map((e,t)=>{let n=Math.max(3,e),r=l[t];return r===`left`?`:${`-`.repeat(n)}`:r===`right`?`${`-`.repeat(n)}:`:r===`center`?`:${`-`.repeat(n)}:`:`-`.repeat(n)}).join(` | `)} |\n`,(c?r.slice(1):r).forEach(e=>{u+=`| ${Array.from({length:i}).fill(0).map((t,n)=>o(e[n]&&e[n].text||``,a[n])).join(` | `)} |\n`}),u}var yP=new Un(`preserveCellSelectionOnContextMenu`);function bP(e,t){let n=e.posAtCoords({left:t.clientX,top:t.clientY});if(n)return n.pos;if(!(t.target instanceof Node))return null;try{return e.posAtDOM(t.target,0)}catch{return null}}function xP(e,t){let n=!1;return e.forEachCell((e,r)=>{t>=r&&t<r+e.nodeSize&&(n=!0)}),n}function SP(){return new D({key:yP,props:{handleDOMEvents:{mousedown(e,t){if(t.button!==2)return!1;let{selection:n}=e.state;if(!uP(n)||n.ranges.length<2)return!1;let r=bP(e,t);return r==null||!xP(n,r)?!1:(t.preventDefault(),!0)}}}})}var CP=Jp.create({name:`table`,addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:aP,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:`tableRow+`,tableRole:`table`,isolating:!0,group:`block`,parseHTML(){return[{tag:`table`}]},renderHTML({node:e,HTMLAttributes:t}){let{colgroup:n,tableWidth:r,tableMinWidth:i}=oP(e,this.options.cellMinWidth),a=t.style;function o(){return a||(r?`width: ${r}`:`min-width: ${i}`)}let s=[`table`,A(this.options.HTMLAttributes,t,{style:o()}),n,[`tbody`,0]];return this.options.renderWrapper?[`div`,{class:`tableWrapper`},s]:s},parseMarkdown:(e,t)=>{let n=[],r=Array.isArray(e.align)?e.align:[];if(e.header){let i=[];e.header.forEach((e,n)=>{let a=WN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableHeader`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}return e.rows&&e.rows.forEach(e=>{let i=[];e.forEach((e,n)=>{let a=WN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableCell`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}),t.createNode(`table`,void 0,n)},renderMarkdown:(e,t)=>vP(e,t),markdownTokenizer:{name:`table`,level:`block`,start:e=>{let t=e.split(`
`);if(t.length<2)return-1;let n=t[1];return!/^[ \t|:]*-[ \t|:-]*$/.test(n)||!n.includes(`|`)?-1:t[0].includes(`|`)?0:-1},tokenize(e,t,n){let r=e.indexOf(`
`),i=r>=0?e.slice(0,r):e,a=i.split(`
`);if(a.length<2)return;let o=a[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(o)||!o.includes(`|`))return;let s=pP(i);if(s===i)return;let c=n.blockTokens(s)[0];if(c?.type!==`table`||!c.raw)return;let l=c.raw.split(`
`);if(a.length<2)return;let o=a[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(o)||!o.includes(`|`))return;let s=mP(i);if(s===i)return;let c=n.blockTokens(s)[0];if(c?.type!==`table`||!c.raw)return;let l=c.raw.split(`
`).length,u=e.split(`
`).slice(0,l).join(`
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=cP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(w.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>LM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>RM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return BM(e,t&&(e=>{n&&dP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>UM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>WM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return KM(e,t&&(e=>{n&&dP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>aN(e,t),mergeCells:()=>({state:e,dispatch:t})=>YM(e,t),splitCell:()=>({state:e,dispatch:t})=>XM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>tN(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>tN(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>nN(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>YM(e,t)?!0:XM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>QM(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>iN(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>iN(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&NM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=TM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:uP,"Mod-Backspace":uP,Delete:uP,"Mod-Delete":uP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[ON({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],HN({allowTableNodeSelection:this.options.allowTableNodeSelection}),xP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),CP=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(SP.configure(this.options.table)),this.options.tableCell!==!1&&e.push($N.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(eP.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(tP.configure(this.options.tableRow)),e}}),wP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function TP(){return[Ik.configure({HTMLAttributes:{class:`dw-tasks`}}),Fk.configure({nested:!0})]}function EP(){return[CP.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var DP=wP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),OP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),kP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,AP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,jP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=lP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(T.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>RM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>zM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return VM(e,t&&(e=>{n&&fP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>WM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>GM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return qM(e,t&&(e=>{n&&fP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>oN(e,t),mergeCells:()=>({state:e,dispatch:t})=>XM(e,t),splitCell:()=>({state:e,dispatch:t})=>ZM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>nN(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>nN(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>rN(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>XM(e,t)?!0:ZM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>$M(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>aN(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>aN(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&PM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=EM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:dP,"Mod-Backspace":dP,Delete:dP,"Mod-Delete":dP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[kN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],UN({allowTableNodeSelection:this.options.allowTableNodeSelection}),SP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),wP=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(CP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(eP.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(tP.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(nP.configure(this.options.tableRow)),e}}),TP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function EP(){return[Lk.configure({HTMLAttributes:{class:`dw-tasks`}}),Ik.configure({nested:!0})]}function DP(){return[wP.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var OP=TP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),kP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),AP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,jP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,MP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`)){if(!o){a.push(``);continue}let e=``;for(let s of o.split(/(\s+)/)){let o=e+s;if(!e||XF(o,t,r,i)<=n)e=o;else for(a.push(e.trimEnd()),e=s.trimStart();e&&XF(e,t,r,i)>n;){let o=e.length-1;for(;o>1&&XF(e.slice(0,o),t,r,i)>n;)o--;a.push(e.slice(0,o)),e=e.slice(o)}}a.push(e)}return a}function QF(e,t){let n=t===0?18:15,r=t===0?600:400,i=ZF(e||` `,n,260,KF,r),a=Math.max(...i.map(e=>XF(e,n,KF,r)),t===0?60:40);return{w:Math.ceil(a)+(t===0?32:24),h:i.length*Math.round(n*1.4)+(t===0?20:14)}}var $F=56,eI=14;function tI(e){let t=Object.entries(e).filter(([,t])=>!t.parent||!e[t.parent]);return t.sort((e,t)=>e[1].pos-t[1].pos||(e[0]<t[0]?-1:1)),t[0]?.[0]??null}function nI(e,t){return Object.entries(e).filter(([e,n])=>n.parent===t&&e!==t).sort((e,t)=>e[1].pos-t[1].pos||(e[0]<t[0]?-1:1)).map(([e])=>e)}function rI(e,t,n){let r=tI(e),i=new Map,a=[];if(!r)return{root:``,boxes:i,edges:a,bounds:{x:0,y:0,w:0,h:0}};let o=new Map,s=new Set,c=(t,r)=>{if(!(s.has(t)||r>50)){s.add(t),o.set(t,n(e[t].text,r));for(let n of nI(e,t))c(n,r+1)}};c(r,0);let l=t=>nI(e,t).filter(e=>o.has(e)),u=new Map,d=e=>{let t=u.get(e);if(t!==void 0)return t;let n=l(e),r=n.reduce((e,t)=>e+d(t),0)+eI*Math.max(0,n.length-1),i=Math.max(o.get(e).h,r);return u.set(e,i),i},f=(e,t,n,r,a,s)=>{let c=o.get(e),u=a===1?t:t-c.w;i.set(e,{id:e,x:u,y:n-c.h/2,w:c.w,h:c.h,depth:r,dir:a,parent:s}),p(e,l(e),a===1?u+c.w+$F:u-$F,n,r+1,a)},p=(e,t,n,r,i,a)=>{let o=r-(t.reduce((e,t)=>e+d(t),0)+eI*Math.max(0,t.length-1))/2;for(let r of t){let t=d(r);f(r,n,o+t/2,i,a,e),o+=t+eI}},m=o.get(r);i.set(r,{id:r,x:0,y:0,w:m.w,h:m.h,depth:0,dir:1,parent:``});let h=m.h/2,g=l(r);if(t===`right`)p(r,g,m.w+$F,h,1,1);else if(t===`left`)p(r,g,-56,h,1,-1);else{let e=Math.ceil(g.length/2);p(r,g.slice(0,e),m.w+$F,h,1,1),p(r,g.slice(e),-56,h,1,-1)}for(let e of i.values()){if(!e.parent)continue;let t=i.get(e.parent),n=e.dir===1?[t.x+t.w,t.y+t.h/2]:[t.x,t.y+t.h/2],r=e.dir===1?[e.x,e.y+e.h/2]:[e.x+e.w,e.y+e.h/2];a.push({from:n,to:r,child:e.id})}let _=1/0,v=1/0,y=-1/0,b=-1/0;for(let e of i.values())_=Math.min(_,e.x),v=Math.min(v,e.y),y=Math.max(y,e.x+e.w),b=Math.max(b,e.y+e.h);return{root:r,boxes:i,edges:a,bounds:{x:_,y:v,w:y-_,h:b-v}}}function iI(e,t,n,r){let i=e.boxes.get(n);if(!i)return null;if(r===`ArrowUp`||r===`ArrowDown`){let a=i.parent?nI(t,i.parent).filter(t=>e.boxes.get(t)?.dir===i.dir):[];return a[a.indexOf(n)+(r===`ArrowUp`?-1:1)]??null}let a=r===`ArrowRight`?1:-1;return i.parent?a===i.dir?nI(t,n)[0]??null:i.parent:nI(t,n).find(t=>e.boxes.get(t)?.dir===a)??null}function aI(e,t){let n=(e[0]+t[0])/2;return`M${e[0]} ${e[1]} C${n} ${e[1]} ${n} ${t[1]} ${t[0]} ${t[1]}`}function oI(e,t,n,r=e=>e){return e*r(.5-t*(.5-n))}function sI(e){return[-e[0],-e[1]]}function cI(e,t){return[e[0]+t[0],e[1]+t[1]]}function lI(e,t){return[e[0]-t[0],e[1]-t[1]]}function uI(e,t){return[e[0]*t,e[1]*t]}function dI(e,t){return[e[0]/t,e[1]/t]}function fI(e){return[e[1],-e[0]]}function pI(e,t){return e[0]*t[0]+e[1]*t[1]}function mI(e,t){return e[0]===t[0]&&e[1]===t[1]}function hI(e){return Math.hypot(e[0],e[1])}function gI(e){return e[0]*e[0]+e[1]*e[1]}function _I(e,t){return gI(lI(e,t))}function vI(e){return dI(e,hI(e))}function yI(e,t){return Math.hypot(e[1]-t[1],e[0]-t[0])}function bI(e,t,n){let r=Math.sin(n),i=Math.cos(n),a=e[0]-t[0],o=e[1]-t[1],s=a*i-o*r,c=a*r+o*i;return[s+t[0],c+t[1]]}function xI(e,t,n){return cI(e,uI(lI(t,e),n))}function SI(e,t,n){return cI(e,uI(t,n))}var{min:CI,PI:wI}=Math,TI=.275,EI=wI+1e-4;function DI(e,t={}){let{size:n=16,smoothing:r=.5,thinning:i=.5,simulatePressure:a=!0,easing:o=e=>e,start:s={},end:c={},last:l=!1}=t,{cap:u=!0,easing:d=e=>e*(2-e)}=s,{cap:f=!0,easing:p=e=>--e*e*e+1}=c;if(e.length===0||n<=0)return[];let m=e[e.length-1].runningLength,h=s.taper===!1?0:s.taper===!0?Math.max(n,m):s.taper,g=c.taper===!1?0:c.taper===!0?Math.max(n,m):c.taper,_=(n*r)**2,v=[],y=[],b=e.slice(0,10).reduce((e,t)=>{let r=t.pressure;if(a){let i=CI(1,t.distance/n);r=CI(1,e+(CI(1,1-i)-e)*(i*TI))}return(e+r)/2},e[0].pressure),x=oI(n,i,e[e.length-1].pressure,o),S,C=e[0].vector,ee=e[0].point,te=ee,ne=ee,re=te,ie=!1;for(let t=0;t<e.length;t++){let{pressure:r}=e[t],{point:s,vector:c,distance:l,runningLength:u}=e[t];if(t<e.length-1&&m-u<3)continue;if(i){if(a){let e=CI(1,l/n),t=CI(1,1-e);r=CI(1,b+(t-b)*(e*TI))}x=oI(n,i,r,o)}else x=n/2;S===void 0&&(S=x);let f=u<h?d(u/h):1,ae=m-u<g?p((m-u)/g):1;x=Math.max(.01,x*Math.min(f,ae));let oe=(t<e.length-1?e[t+1]:e[t]).vector,se=t<e.length-1?pI(c,oe):1,ce=pI(c,C)<0&&!ie,le=se!==null&&se<0;if(ce||le){let e=uI(fI(C),x);for(let t=0;t<=1;t+=.07692307692307693)ne=bI(lI(s,e),s,EI*t),v.push(ne),re=bI(cI(s,e),s,EI*-t),y.push(re);ee=ne,te=re,le&&(ie=!0);continue}if(ie=!1,t===e.length-1){let e=uI(fI(c),x);v.push(lI(s,e)),y.push(cI(s,e));continue}let ue=uI(fI(xI(oe,c,se)),x);ne=lI(s,ue),(t<=1||_I(ee,ne)>_)&&(v.push(ne),ee=ne),re=cI(s,ue),(t<=1||_I(te,re)>_)&&(y.push(re),te=re),b=r,C=c}let ae=e[0].point.slice(0,2),oe=e.length>1?e[e.length-1].point.slice(0,2):cI(e[0].point,[1,1]),se=[],ce=[];if(eLine truncated
`:n(e)).join(``),r=(e,i)=>{for(let a of e)if(a.type===`heading`){let e=Number(a.attrs?.level)||1;t.push({text:n(a),size:[0,26,21,18,16,16,16][e]??16,weight:650})}else if(a.type===`paragraph`)t.push({text:i+n(a),size:15,weight:400});else if(a.type===`listItem`||a.type===`taskItem`){let e=a.type===`taskItem`?a.attrs?.checked?`☑ `:`☐ `:`• `,[i,...o]=a.content??[];i&&t.push({text:e+n(i),size:15,weight:400}),r(o,` `)}else a.type===`codeBlock`?t.push({text:n(a),size:13,weight:400}):a.content?.length&&r(a.content,i)};return r(e,``),t}function uR(e,t,n,r,i,a,o=400,s=`start`){let c=Math.round(r*1.35);return n.map((n,l)=>`<text x="${e}" y="${t+r+l*c}" font-size="${r}" font-family="${PL(a)}" font-weight="${o}" fill="${i}" text-anchor="${s}" xml:space="preserve">${PL(n)}</text>`).join(``)}async function dR(e){if(e.startsWith(`data:`))return e;try{let t=await fetch(e,{credentials:`include`});if(!t.ok)return null;let n=await t.blob();return await new Promise(e=>{let t=new FileReader;t.onload=()=>e(typeof t.result==`string`?t.result:null),t.onerror=()=>e(null),t.readAsDataURL(n)})}catch{return null}}async function fR(e){let t=cR(e.root),n=e.elements.filter(e=>e.type!==`group`),r=HP(VP(n.map(t=>e.boxOf(t)))??{x:0,y:0,w:400,h:300},32),i=t(`ink`,`line`),a=[];for(let r of n){let n=e.boxOf(r),o=r.rotate?` rotate(${r.rotate} ${n.w/2} ${n.h/2})`:``,s=e=>`<g transform="translate(${n.x} ${n.y})${o}">${e}</g>`;switch(r.type){case`shape`:{let e=ZF(r.text,r.fontSize,Math.max(20,n.w-16)),i=Math.round(r.fontSize*1.35),o=n.h/2-e.length*i/2-r.fontSize*.25;a.push(s(HL(r,t)+(r.text?uR(n.w/2,o,e,r.fontSize,t(r.textColor,`line`),KF,400,`middle`):``)));break}case`text`:{let e=YF(r.font),i=r.w?ZF(r.text,r.fontSize,r.w,e):r.text.split(`
`),o=r.align===`center`?n.w/2:r.align===`right`?n.w:0,c=r.align===`center`?`middle`:r.align===`right`?`end`:`start`;a.push(s(uR(o,0,i,r.fontSize,t(r.color,`line`),e,r.bold?650:400,c)));break}case`connector`:{let n=e.routeOf(r);if(a.push(WL(r,n,t)),r.label){let e=Math.min(240,r.label.length*8+16);a.push(`<rect x="${n.mid[0]-e/2}" y="${n.mid[1]-12}" width="${e}" height="24" rx="4" fill="${t(`paper`,`line`)}"/>`+uR(n.mid[0],n.mid[1]-12+3,[r.label],13,i,KF,400,`middle`))}break}case`brush`:a.push(s(KL(r,t)));break;case`frame`:a.push(s(`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(r.background,`fill`)===`none`?`none`:t(r.background,`fill`)}" stroke="${t(`gray`,`line`)}" stroke-width="1.5"/>`+uR(4,-24,[r.title],13,t(`gray`,`line`),KF,600)));break;case`note`:{let o=e.noteBody(r),c=o?lR(qL(o)):[],l=18,u=`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(r.background,`fill`)}" stroke="${t(`gray`,`fill`)}"/>`;if(r.page&&e.pageTitle){let t=ZF(e.pageTitle,26,n.w-48,KF,650);u+=uR(24,l-4,t,26,i,KF,650),l+=t.length*35+8}for(let e of c){let t=ZF(e.text,e.size,n.w-48,KF,e.weight);if(u+=uR(24,l,t,e.size,i,KF,e.weight),l+=t.length*Math.round(e.size*1.35)+8,l>n.h-12)break}a.push(s(u));break}case`image`:{let i=await dR(e.resolve(r.src));a.push(s(i?`<image href="${PL(i)}" width="${n.w}" height="${n.h}" preserveAspectRatio="xMidYMid meet"/>`:`<rect width="${n.w}" height="${n.h}" fill="${t(`ink`,`fill`)}"/>`));break}case`embed`:a.push(s(`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(`paper`,`fill`)}" stroke="${t(`gray`,`fill`)}"/>`+uR(16,16,ZF(r.url,13,n.w-32),13,t(`blue`,`line`),KF)));break;case`mindmap`:{let n=e.layoutOf(r),o=t(r.color,`line`),s=t(r.color,`fill`),c=n.edges.map(e=>`<path d="${aI(e.from,e.to)}" fill="none" stroke="${o}" stroke-width="2"/>`).join(``);for(let e of n.boxes.values()){let n=e.depth===0?18:15,a=e.depth===0?600:400,l=e.depth===0?o:e.depth===1?s:t(`paper`,`line`),u=e.depth===0?t(`paper`,`line`):i;c+=`<rect x="${e.x}" y="${e.y}" width="${e.w}" height="${e.h}" rx="${e.depth===0?10:8}" fill="${l}" stroke="${o}" stroke-width="${e.depth===0?0:1.5}"/>`;let d=ZF(r.nodes[e.id]?.text||` `,n,260,KF,a);c+=uR(e.x+e.w/2,e.y+(e.h-d.length*Math.round(n*1.4))/2-2,d,n,u,KF,a,`middle`)}a.push(`<g transform="translate(${r.x} ${r.y})">${c}</g>`);break}}}return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${Math.ceil(r.w)}" height="${Math.ceil(r.h)}" viewBox="${r.x} ${r.y} ${r.w} ${r.h}"><rect x="${r.x}" y="${r.y}" width="${r.w}" height="${r.h}" fill="${t(`paper`,`line`)}"/>${a.join(``)}</svg>`,box:r}}async function pR(e,t){let{svg:n,box:r}=await fR(t),i=new Blob([n],{type:`image/svg+xml`});if(e===`svg`)return i;let a=Math.min(2,8192/Math.max(r.w,r.h,1)),o=URL.createObjectURL(i);try{let e=await new Promise((e,t)=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>t(Error(`could not draw the canvas`)),n.src=o}),t=document.createElement(`canvas`);t.width=Math.ceil(r.w*a),t.height=Math.ceil(r.h*a);let n=t.getContext(`2d`);if(!n)throw Error(`could not draw the canvas`);return n.drawImage(e,0,0,t.width,t.height),await new Promise((e,n)=>t.toBlob(t=>t?e(t):n(Error(`could not draw the canvas`)),`image/png`))}finally{URL.revokeObjectURL(o)}}var mR=.1,hR=4,gR=`http://www.w3.org/2000/svg`,_R=e=>e instanceof HTMLElement&&(e.isContentEditable||e.tagName===`INPUT`||e.tagName===`TEXTAREA`),vR=class{opts;store;labels;root;styles;editable;tool=`select`;shapeKind;selected=new Set;activeNode=null;editing=null;entered=null;world;overlay;ui;view={x:0,y:0,zoom:1};rendered=new Map;measured=new Map;layouts=new Map;routes=new Map;previews=new Map;drag=null;guides=[];marquee=null;hover=null;raf=0;spaceDown=!1;pointers=new Map;pinch=null;presenting=null;resize=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>this.onResize(e));unsub;cleanups=[];saveTimer;constructor(e,t){this.opts=t,this.labels=t.labels??dF,this.editable=t.editable,this.styles=PF(t.styles),this.shapeKind=this.styles.shape.shape,this.store=new eR(t.doc,{undo:t.undo!==!1}),this.root=document.createElement(`div`),this.root.className=`dw-cv`,this.root.tabIndex=0,this.root.setAttribute(`role`,`application`),this.root.dataset.testid=`edgeless-canvas`,this.world=document.createElement(`div`),this.world.className=`dw-cv-world`,this.overlay=document.createElementNS(gR,`svg`),this.overlay.classList.add(`dw-cv-overlay`),this.root.append(this.world,this.overlay),e.append(this.root),this.ui=new sR(this),this.root.classList.toggle(`dw-cv-readonly`,!this.editable),this.unsub=this.store.onChange(()=>this.schedule()),this.listen(),this.render(),this.restoreView()||this.fit(void 0,!1),this.applyView()}destroy(){cancelAnimationFrame(this.raf),clearTimeout(this.saveTimer),this.saveView(),this.unsub(),this.resize?.disconnect();for(let e of this.cleanups)e();for(let e of this.rendered.values())e.note?.destroy();this.rendered.clear(),this.ui.destroy(),this.store.destroy(),this.root.remove()}setEditable(e){if(e!==this.editable){this.editable=e,this.root.classList.toggle(`dw-cv-reLine truncated
`||e===`\r`?(r.push(i),n.push(r),r=[],i=``,e===`\r`&&s[o+1]===`
`&&o++):i+=e,o++}return(i!==``||r.length)&&(r.push(i),n.push(r)),n}function cI(e,t){return e.includes(t)||/["\r\n]/.test(e)||/^\s|\s$/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function lI(e,t=`,`){return e.map(e=>e.map(e=>cI(e,t)).join(t)).join(`\r
`)}function uI(e,t,n){return lI([t.map(e=>e.name),...n.map(e=>t.map(t=>vF(e,t)))])}function dI(e){let t=e.map(e=>e.trim()).filter(Boolean);if(!t.length)return`text`;if(t.every(e=>gF(e)!==null))return`number`;if(t.every(e=>/^\d{4}-\d{2}-\d{2}/.test(e)))return`date`;if(t.every(e=>/^(true|false|yes|no)$/i.test(e)))return`checkbox`;if(t.every(e=>/^https?:\/\/\S+$/.test(e)))return`link`;let n=new Set(t.map(e=>e.toLowerCase()));return t.length>=4&&n.size<=Math.max(2,t.length/3)&&t.every(e=>e.length<=40)?`select`:`text`}function fI(e,t,n){let r=e.trim();if(!r)return null;let i=e=>{let t=n.find(t=>t.name.toLowerCase()===e.toLowerCase());return t||(t={id:iF(),name:e,color:kF(n)},n.push(t)),t.id};switch(t.type){case`number`:return gF(r);case`progress`:{let e=gF(r.replace(`%`,``));return e===null?null:Math.max(0,Math.min(100,Math.round(e)))}case`checkbox`:return/^(true|yes|1|x|✓|done)$/i.test(r);case`date`:return mF(r)||null;case`select`:return i(r);case`multiSelect`:return[...new Set(r.split(/[,;]/).map(e=>e.trim()).filter(Boolean).map(i))];case`member`:case`attachment`:case`createdBy`:case`createdTime`:return null;default:return r}}function pI(e,t=`,`){let n=sI(e,t).filter(e=>e.some(e=>e.trim())),r=n[0]??[],i=n.slice(1),a=r.map((e,t)=>({id:iF(),name:e.trim()||`${t+1}`,type:t===0?`title`:dI(i.map(e=>e[t]??``))}));for(let e of a)e.type===`select`&&(e.options=[]);return{columns:a,rows:i.map(e=>{let t={};return a.forEach((n,r)=>{let i=fI(e[r]??``,n,n.options??[]);i!==null&&(!Array.isArray(i)||i.length)&&(t[n.id]=i)}),t})}}function mI(e,t){let n=[];return{index:e.map(e=>{let r=t.find(t=>t.name.trim().toLowerCase()===e.trim().toLowerCase());return!r&&e.trim()&&n.push(e.trim()),r??null}),missing:n}}function hI(e,t,n,r){let i=I(`select`,{class:`dw-db-select`,"aria-label":n});for(let n of t){let t=I(`option`,{value:n.value},n.label);n.value===e&&(t.selected=!0),i.append(t)}return i.addEventListener(`change`,()=>r(i.value)),i.addEventListener(`keydown`,e=>e.stopPropagation()),i}var gI=e=>e.map(e=>({value:e.id,label:e.name||`…`}));function _I(e,t,n,r){let i=e.labels;if(!bF(n.op))return null;if(t.type===`select`||t.type===`multiSelect`)return hI(typeof n.value==`string`?n.value:``,[{value:``,label:`—`},...(t.options??[]).map(e=>({value:e.id,label:e.name}))],i.value,r);let a=t.type===`date`||t.type===`createdTime`?`date`:t.type===`number`||t.type===`progress`?`number`:`text`,o=I(`input`,{class:`dw-db-input dw-db-input--small`,type:a,"aria-label":i.value,placeholder:i.value});return o.value=n.value===void 0||n.value===null?``:String(n.value),o.addEventListener(`keydown`,e=>e.stopPropagation()),o.addEventListener(`change`,()=>r(a===`number`?o.value===``?null:Number(o.value):o.value)),o}function vI(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.filters),s=()=>r?.updateView(n.id,{filters:o}),c=()=>{t.replaceChildren(),o.length>1&&t.append(hI(n.filterMode,[{value:`and`,label:i.matchAll},{value:`or`,label:i.matchAny}],i.filter,e=>{n.filterMode=e,r?.updateView(n.id,{filterMode:n.filterMode})})),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noFilters)),o.forEach((n,r)=>{let l=a.find(e=>e.id===n.column);if(!l)return;let u=yF(l.type),d=I(`div`,{class:`dw-db-pop__line`},hI(n.column,gI(a),i.filter,e=>{let t=a.find(t=>t.id===e);o[r]={column:e,op:yF(t.type)[0]},s(),c()}),hI(n.op,u.map(e=>({value:e,label:UP(i,e)})),i.filter,e=>{o[r]={...n,op:e},bF(e)||delete o[r].value,s(),c()}),_I(e,l,n,e=>{o[r]={...o[r],value:e},s()}),CI(i.remove,()=>{o.splice(r,1),s(),c()}));t.append(d)}),r&&t.append(wI(i.addFilter,()=>{let e=a.find(e=>e.type!==`title`)??a[0];o.push({column:e.id,op:yF(e.type)[0]}),s(),c()}))};c()}function yI(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.sorts),s=()=>r?.updateView(n.id,{sorts:o}),c=()=>{t.replaceChildren(),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noSorts)),o.forEach((e,n)=>{t.append(I(`div`,{class:`dw-db-pop__line`},hI(e.column,gI(a),i.sort,t=>{o[n]={...e,column:t},s()}),hI(e.desc?`desc`:`asc`,[{value:`asc`,label:i.ascending},{value:`desc`,label:i.descending}],i.sort,t=>{o[n]={...e,desc:t===`desc`},s()}),CI(i.remove,()=>{o.splice(n,1),s(),c()})))}),r&&t.append(wI(i.addSort,()=>{let e=new Set(o.map(e=>e.column)),t=a.find(t=>!e.has(t.id))??a[0];o.push({column:t.id,desc:!1}),s(),c()}))};c()}function bI(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>oF.includes(e.type)),o=a.map(e=>({value:e.id,label:e.name||VP(i,e.type)}));n.type!==`kanban`&&o.unshift({value:``,label:i.noGrouping}),t.append(I(`label`,{class:`dw-db-pop__label`},i.groupBy),a.length||n.type!==`kanban`?hI(n.groupBy??``,o,i.groupBy,e=>r?.updateView(n.id,{groupBy:e||null})):I(`p`,{class:`dw-db-pop__empty`},i.noGroupColumn))}function xI(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>e.type===`date`||e.type===`createdTime`);t.append(I(`label`,{class:`dw-db-pop__label`},i.dateColumn),a.length?hI(n.dateColumn??``,[{value:``,label:`—`},...a.map(e=>({value:e.id,label:e.name||VP(i,e.tyLine truncated
`)},onCreate(){let{doc:e,readOnlyDoc:t,undoScope:n}=this.options;e&&!t&&n&&(NS.getState(this.editor.state)?.undoManager)?.addToScope(GF(e))},addCommands(){let e=e=>{let t=iF(),{doc:n,readOnlyDoc:r}=this.options;return!n||r?{id:t,data:e}:(oI(n,t,e,(e,t)=>GI(this.editor,e,t)),{id:t,data:null})};return{insertDatabase:t=>({commands:n})=>n.insertContent([{type:this.name,attrs:e(t??tI(BI(this.options.labels)))},{type:`paragraph`}]),groupAsDatabase:()=>({state:t,dispatch:n,commands:r})=>{let i=JI(t.selection.$from,t.selection.$to);if(!i)return!1;if(!n)return!0;let a=zI(this.options.labels),o={id:iF(),name:a.typeTitle,type:`title`},s=[o],c=i.checks?{id:iF(),name:a.done,type:`checkbox`}:null;c&&s.push(c);let l=Date.now(),u={title:``,columns:s,rows:i.items.map((e,t)=>({id:iF(),cells:{[o.id]:e.text,...c&&e.checked?{[c.id]:!0}:{}},createdAt:l+t,createdBy:this.options.me?.()??null,body:e.rest.length?e.rest:void 0})),views:[aF(`table`,a.viewTable,s)]},d=this.type.create(e(u));return r.command(({tr:e})=>(e.replaceWith(i.from,i.to,d),e.setSelection(T.create(e.doc,i.from)),!0))}}},addKeyboardShortcuts(){return{"Mod-g":()=>this.editor.commands.groupAsDatabase()}},addProseMirrorPlugins(){let{doc:e,readOnlyDoc:t}=this.options,n=e&&!t?e:null,r=this.editor;return[new E({key:new D(`databaseClipboard`),props:{transformCopied:t=>!e||!UI(t.content)?t:new p(HI(t.content,t=>{let n=GF(e).get(String(t.attrs.id));return n instanceof Lb?t.type.create({...t.attrs,data:aI(n,VI)}):t}),t.openStart,t.openEnd),transformPasted:e=>UI(e.content)?new p(HI(e.content,e=>{let t=iF();if(!n)return e.type.create({...e.attrs,id:t});let i=e.attrs.data?sF(e.attrs.data):null,a=GF(n).get(String(e.attrs.id)),o=i??(a instanceof Lb?aI(a,VI):tI(BI(this.options.labels)));return oI(n,t,qI(o),(e,t)=>GI(r,e,t)),e.type.create({id:t,data:null})}),e.openStart,e.openEnd):e},appendTransaction:(e,t,i)=>{if(!n||!e.some(e=>e.docChanged&&!e.getMeta(MS))||!e.some(e=>e.steps.some(e=>UI(e.slice?.content??s.empty))))return null;let a=new Set,o=[];if(i.doc.descendants((e,t)=>{if(e.type.name!==`database`)return;let n=String(e.attrs.id);return n&&a.has(n)&&o.push({pos:t,node:e}),a.add(n),!1}),!o.length)return null;let c=i.tr;for(let{pos:e,node:t}of o){let i=GF(n).get(String(t.attrs.id)),a=iF();i instanceof Lb&&oI(n,a,qI(aI(i,VI)),(e,t)=>GI(r,e,t)),c.setNodeMarkup(e,void 0,{...t.attrs,id:a,data:null})}return c}})]},addNodeView(){let e=this.options;return({node:t,editor:n,getPos:r})=>{let i=t,a=e.labels??KP,o=e.doc,s=()=>n.isEditable&&!!o&&!e.readOnlyDoc,c=null,l=null,u=null,d=null,f=I(`div`,{class:`dw-db-node`}),p=()=>String(i.attrs.id),m=()=>{let e=o?GF(o).get(p()):void 0;return e instanceof Lb?e:null},h=()=>{let t=m();return t?eI(t):i.attrs.data?sF(i.attrs.data):tI(BI(e.labels))},g=()=>({labels:a.database,colorNames:a.colors,locale:a.locale,files:e.files,people:e.people,store:c}),_=(t,n)=>{let r=e.rowExtensions;if(!r)return null;let i=m(),o=null;if(i&&(o=c?c.rowBody(n.id):KI(i,n.id),!o))return t.append(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),null;let s=new Vp({element:t,editable:!!c,extensions:r(o),content:o?void 0:{type:`doc`,content:n.body??[{type:`paragraph`}]},editorProps:{attributes:{class:`dw-prose dw-db-peek__prose`}}});return!o&&!n.body?.length&&t.replaceChildren(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),()=>s.destroy()},v=e.recordLink,y=v?t=>{let n=v(PI(p(),t));RI(n).then(t=>t&&e.onLinkCopied?.(n))}:void 0;f.addEventListener(II,e=>{let t=e.detail,n=h();n.rows.some(e=>e.id===t.row)&&(t.found=!0,f.scrollIntoView?.({block:`start`}),b(t.row,n.rows.map(e=>e.id)))});let b=(e,t)=>{u?.close(),u=new UF({ctx:{...g()},mountBody:_,copyLink:y},h(),e,t,()=>u=null)},x=()=>{let e=h();d?.update(e,{store:c}),u?.update(e,{store:c})},S=()=>{if(l?.(),l=null,c=null,!o)return;let t=m();if(!t&&s()){let a=i.attrs.data?sF(i.attrs.data):tI(BI(e.labels)),s=p()?p():iF();oI(o,s,a,(e,t)=>GI(n,e,t)),queueMicrotask(()=>{let e=typeof r==`function`?r():void 0;e!==void 0&&n.state.doc.nodeAt(e)?.type.name===`database`&&n.view.dispatch(n.state.tr.setNodeMarkup(e,void 0,{...i.attrs,id:s,data:null}).setMeta(`addToHistory`,!1))}),t=GF(o).get(s)}let a=GF(o),d=e=>{if(!e.keysChanged.has(p()))return;S(),x();let t=u?.row;t&&h().rows.some(e=>e.id===t)&&b(t,[t])};if(a.observe(d),t){s()&&(c=new rI(o,t,()=>e.me?.()??null));let n=t,r=()=>x();n.observeDeep(r),l=()=>{a.unobserve(d),n.unobserveDeep(r)}}else l=()=>a.unobserve(d)};S(),d=new AI({...g(),openRow:b,undo:()=>n.commands.undo?.(),redo:()=>n.commands.redo?.(),notify:e.notify,copyLink:y},h()),f.append(d.dom);let ee=s(),te=()=>{s()!==ee&&(ee=s(),S(),x())};return n.on(`update`,te),n.on(`transaction`,te),{dom:f,update(e){if(e.type!==i.type)return!1;let t=e.attrs.id!==i.attrs.id;return i=e,t&&S(),x(),!0},ignoreMutation:()=>!0,stopEvent:e=>e.type!==`dragstart`||e.target!==f,destroy(){l?.(),u?.close(),d?.destroy(),n.off(`update`,te),n.off(`transaction`,te)}}}}});function GI(e,t,n){try{yw(e.schema,{type:`doc`,content:t},n)}catch{}}function Line truncated
`);return/\s/.test(n)}):!1}function hL(e){return()=>{let t=e.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=e.view.coordsAtPos(t);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}}}function gL(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:hL(e)}function _L({match:e,dismissedRange:t,state:n,transaction:r,editor:i,shouldResetDismissed:a,effectiveAllowSpaces:o}){return a?.({editor:i,state:n,range:t,match:e,transaction:r,allowSpaces:o})?!1:o?e.range.from===t.from:e.range.from===t.from&&!mL(r)}function vL({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function yL({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function bL({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function xL({editor:e,items:t}){let n=null,r=null,i=null,a=()=>{r!==null&&(clearTimeout(r),r=null),i?.(),i=null},o=e=>new Promise(t=>{i=t,r=setTimeout(()=>{r=null;let e=i;i=null,e?.()},e)}),s=()=>{n?.abort(),a(),n=null};return{abort:s,fetch:async(r,i)=>{s(),n=new AbortController;let a=n;if(i>0&&await o(i),n!==a||a.signal.aborted)return{status:`aborted`};try{let i=await t({editor:e,query:r,signal:a.signal});return n!==a||a.signal.aborted?{status:`aborted`}:{status:`resolved`,items:i}}catch{return n!==a||a.signal.aborted?{status:`aborted`}:{status:`error`}}}}}function SL({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[Oj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(Aj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function CL(e){if(e instanceof HTMLElement)return e;if(typeof e==`string`)try{let t=document.querySelector(e);if(t)return t}catch{return document.body}return document.body}function wL({getReferenceRect:e,contextElement:t,config:n,container:r,dismissOnOutsideClick:i,dismiss:a}){return(o,s={})=>{let c={getBoundingClientRect:()=>e()??new DOMRect,contextElement:t},l=!1,u=!o.isConnected;u&&CL(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=Dj(c,o,()=>{jj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function TL({editor:e,pluginKey:t,items:n,renderer:r,minQueryLength:i,debounce:a,initialItems:o,placement:s,offset:c,container:l,flip:u,floatingUi:d,dismissOnOutsideClick:f,command:p,clientRectFor:m,dispatchExit:h}){let g,_=xL({editor:e,items:n}),v=SL({placLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=Dj(e.anchor,t,()=>{jj(e.anchor,t,{placement:`bottom-start`,middleware:[Oj(6),Aj(),kj({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),JL===d&&(JL=null),n||e.onCancel?.())}let d=()=>u();return JL=d,n.focus(),e.multiline||n.select(),d}var XL=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function ZL(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of XL){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function QL(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var $L=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function eR(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;YL({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(QL(t)),onCancel:()=>e(``)})})}async function tR(e,t,n,r){let i=await eR(e,t,t.blocks.embedUrl);i&&(ZL(i)?e.chain().focus().insertEmbed(i).run():await rR(e,i,n,r))}async function nR(e,t,n,r){let i=await eR(e,t,t.blocks.linkUrl);i&&await rR(e,i,n,r)}async function rR(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var iR=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=QL(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=QL(e),i=ZL(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${$L(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
`&&o++):i+=e,o++}return(i!==``||r.length)&&(r.push(i),n.push(r)),n}function Gz(e,t){return e.includes(t)||/["\r\n]/.test(e)||/^\s|\s$/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function Kz(e,t=`,`){return e.map(e=>e.map(e=>Gz(e,t)).join(t)).join(`\r
`)}function qz(e,t,n){return Kz([t.map(e=>e.name),...n.map(e=>t.map(t=>tz(e,t)))])}function Jz(e){let t=e.map(e=>e.trim()).filter(Boolean);if(!t.length)return`text`;if(t.every(e=>$R(e)!==null))return`number`;if(t.every(e=>/^\d{4}-\d{2}-\d{2}/.test(e)))return`date`;if(t.every(e=>/^(true|false|yes|no)$/i.test(e)))return`checkbox`;if(t.every(e=>/^https?:\/\/\S+$/.test(e)))return`link`;let n=new Set(t.map(e=>e.toLowerCase()));return t.length>=4&&n.size<=Math.max(2,t.length/3)&&t.every(e=>e.length<=40)?`select`:`text`}function Yz(e,t,n){let r=e.trim();if(!r)return null;let i=e=>{let t=n.find(t=>t.name.toLowerCase()===e.toLowerCase());return t||(t={id:VR(),name:e,color:fz(n)},n.push(t)),t.id};switch(t.type){case`number`:return $R(r);case`progress`:{let e=$R(r.replace(`%`,``));return e===null?null:Math.max(0,Math.min(100,Math.round(e)))}case`checkbox`:return/^(true|yes|1|x|✓|done)$/i.test(r);case`date`:return ZR(r)||null;case`select`:return i(r);case`multiSelect`:return[...new Set(r.split(/[,;]/).map(e=>e.trim()).filter(Boolean).map(i))];case`member`:case`attachment`:case`createdBy`:case`createdTime`:return null;default:return r}}function Xz(e,t=`,`){let n=Wz(e,t).filter(e=>e.some(e=>e.trim())),r=n[0]??[],i=n.slice(1),a=r.map((e,t)=>({id:VR(),name:e.trim()||`${t+1}`,type:t===0?`title`:Jz(i.map(e=>e[t]??``))}));for(let e of a)e.type===`select`&&(e.options=[]);return{columns:a,rows:i.map(e=>{let t={};return a.forEach((n,r)=>{let i=Yz(e[r]??``,n,n.options??[]);i!==null&&(!Array.isArray(i)||i.length)&&(t[n.id]=i)}),t})}}function Zz(e,t){let n=[];return{index:e.map(e=>{let r=t.find(t=>t.name.trim().toLowerCase()===e.trim().toLowerCase());return!r&&e.trim()&&n.push(e.trim()),r??null}),missing:n}}function Qz(e,t,n,r){let i=I(`select`,{class:`dw-db-select`,"aria-label":n});for(let n of t){let t=I(`option`,{value:n.value},n.label);n.value===e&&(t.selected=!0),i.append(t)}return i.addEventListener(`change`,()=>r(i.value)),i.addEventListener(`keydown`,e=>e.stopPropagation()),i}var $z=e=>e.map(e=>({value:e.id,label:e.name||`…`}));function eB(e,t,n,r){let i=e.labels;if(!rz(n.op))return null;if(t.type===`select`||t.type===`multiSelect`)return Qz(typeof n.value==`string`?n.value:``,[{value:``,label:`—`},...(t.options??[]).map(e=>({value:e.id,label:e.name}))],i.value,r);let a=t.type===`date`||t.type===`createdTime`?`date`:t.type===`number`||t.type===`progress`?`number`:`text`,o=I(`input`,{class:`dw-db-input dw-db-input--small`,type:a,"aria-label":i.value,placeholder:i.value});return o.value=n.value===void 0||n.value===null?``:String(n.value),o.addEventListener(`keydown`,e=>e.stopPropagation()),o.addEventListener(`change`,()=>r(a===`number`?o.value===``?null:Number(o.value):o.value)),o}function tB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.filters),s=()=>r?.updateView(n.id,{filters:o}),c=()=>{t.replaceChildren(),o.length>1&&t.append(Qz(n.filterMode,[{value:`and`,label:i.matchAll},{value:`or`,label:i.matchAny}],i.filter,e=>{n.filterMode=e,r?.updateView(n.id,{filterMode:n.filterMode})})),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noFilters)),o.forEach((n,r)=>{let l=a.find(e=>e.id===n.column);if(!l)return;let u=nz(l.type),d=I(`div`,{class:`dw-db-pop__line`},Qz(n.column,$z(a),i.filter,e=>{let t=a.find(t=>t.id===e);o[r]={column:e,op:nz(t.type)[0]},s(),c()}),Qz(n.op,u.map(e=>({value:e,label:wR(i,e)})),i.filter,e=>{o[r]={...n,op:e},rz(e)||delete o[r].value,s(),c()}),eB(e,l,n,e=>{o[r]={...o[r],value:e},s()}),oB(i.remove,()=>{o.splice(r,1),s(),c()}));t.append(d)}),r&&t.append(sB(i.addFilter,()=>{let e=a.find(e=>e.type!==`title`)??a[0];o.push({column:e.id,op:nz(e.type)[0]}),s(),c()}))};c()}function nB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.sorts),s=()=>r?.updateView(n.id,{sorts:o}),c=()=>{t.replaceChildren(),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noSorts)),o.forEach((e,n)=>{t.append(I(`div`,{class:`dw-db-pop__line`},Qz(e.column,$z(a),i.sort,t=>{o[n]={...e,column:t},s()}),Qz(e.desc?`desc`:`asc`,[{value:`asc`,label:i.ascending},{value:`desc`,label:i.descending}],i.sort,t=>{o[n]={...e,desc:t===`desc`},s()}),oB(i.remove,()=>{o.splice(n,1),s(),c()})))}),r&&t.append(sB(i.addSort,()=>{let e=new Set(o.map(e=>e.column)),t=a.find(t=>!e.has(t.id))??a[0];o.push({column:t.id,desc:!1}),s(),c()}))};c()}function rB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>UR.includes(e.type)),o=a.map(e=>({value:e.id,label:e.name||SR(i,e.type)}));n.type!==`kanban`&&o.unshift({value:``,label:i.noGrouping}),t.append(I(`label`,{class:`dw-db-pop__label`},i.groupBy),a.length||n.type!==`kanban`?Qz(n.groupBy??``,o,i.groupBy,e=>r?.updateView(n.id,{groupBy:e||null})):I(`p`,{class:`dw-db-pop__empty`},i.noGroupColumn))}function iB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>e.type===`date`||e.type===`createdTime`);t.append(I(`label`,{class:`dw-db-pop__label`},i.dateColumn),a.length?Qz(n.dateColumn??``,[{value:``,label:`—`},...a.map(e=>({value:e.id,label:e.name||SR(i,e.tyLine truncated
`)},onCreate(){let{doc:e,readOnlyDoc:t,undoScope:n}=this.options;e&&!t&&n&&(NS.getState(this.editor.state)?.undoManager)?.addToScope(Oz(e))},addCommands(){let e=e=>{let t=VR(),{doc:n,readOnlyDoc:r}=this.options;return!n||r?{id:t,data:e}:(Uz(n,t,e,(e,t)=>OB(this.editor,e,t)),{id:t,data:null})};return{insertDatabase:t=>({commands:n})=>n.insertContent([{type:this.name,attrs:e(t??Rz(CB(this.options.labels)))},{type:`paragraph`}]),groupAsDatabase:()=>({state:t,dispatch:n,commands:r})=>{let i=jB(t.selection.$from,t.selection.$to);if(!i)return!1;if(!n)return!0;let a=SB(this.options.labels),o={id:VR(),name:a.typeTitle,type:`title`},s=[o],c=i.checks?{id:VR(),name:a.done,type:`checkbox`}:null;c&&s.push(c);let l=Date.now(),u={title:``,columns:s,rows:i.items.map((e,t)=>({id:VR(),cells:{[o.id]:e.text,...c&&e.checked?{[c.id]:!0}:{}},createdAt:l+t,createdBy:this.options.me?.()??null,body:e.rest.length?e.rest:void 0})),views:[HR(`table`,a.viewTable,s)]},d=this.type.create(e(u));return r.command(({tr:e})=>(e.replaceWith(i.from,i.to,d),e.setSelection(E.create(e.doc,i.from)),!0))}}},addKeyboardShortcuts(){return{"Mod-g":()=>this.editor.commands.groupAsDatabase()}},addProseMirrorPlugins(){let{doc:e,readOnlyDoc:t}=this.options,n=e&&!t?e:null,r=this.editor;return[new D({key:new Un(`databaseClipboard`),props:{transformCopied:t=>!e||!EB(t.content)?t:new p(TB(t.content,t=>{let n=Oz(e).get(String(t.attrs.id));return n instanceof Lb?t.type.create({...t.attrs,data:Hz(n,wB)}):t}),t.openStart,t.openEnd),transformPasted:e=>EB(e.content)?new p(TB(e.content,e=>{let t=VR();if(!n)return e.type.create({...e.attrs,id:t});let i=e.attrs.data?WR(e.attrs.data):null,a=Oz(n).get(String(e.attrs.id)),o=i??(a instanceof Lb?Hz(a,wB):Rz(CB(this.options.labels)));return Uz(n,t,AB(o),(e,t)=>OB(r,e,t)),e.type.create({id:t,data:null})}),e.openStart,e.openEnd):e},appendTransaction:(e,t,i)=>{if(!n||!e.some(e=>e.docChanged&&!e.getMeta(MS))||!e.some(e=>e.steps.some(e=>EB(e.slice?.content??s.empty))))return null;let a=new Set,o=[];if(i.doc.descendants((e,t)=>{if(e.type.name!==`database`)return;let n=String(e.attrs.id);return n&&a.has(n)&&o.push({pos:t,node:e}),a.add(n),!1}),!o.length)return null;let c=i.tr;for(let{pos:e,node:t}of o){let i=Oz(n).get(String(t.attrs.id)),a=VR();i instanceof Lb&&Uz(n,a,AB(Hz(i,wB)),(e,t)=>OB(r,e,t)),c.setNodeMarkup(e,void 0,{...t.attrs,id:a,data:null})}return c}})]},addNodeView(){let e=this.options;return({node:t,editor:n,getPos:r})=>{let i=t,a=e.labels??kR,o=e.doc,s=()=>n.isEditable&&!!o&&!e.readOnlyDoc,c=null,l=null,u=null,d=null,f=I(`div`,{class:`dw-db-node`}),p=()=>String(i.attrs.id),m=()=>{let e=o?Oz(o).get(p()):void 0;return e instanceof Lb?e:null},h=()=>{let t=m();return t?Lz(t):i.attrs.data?WR(i.attrs.data):Rz(CB(e.labels))},g=()=>({labels:a.database,colorNames:a.colors,locale:a.locale,files:e.files,people:e.people,store:c}),_=(t,n)=>{let r=e.rowExtensions;if(!r)return null;let i=m(),o=null;if(i&&(o=c?c.rowBody(n.id):kB(i,n.id),!o))return t.append(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),null;let s=new Vp({element:t,editable:!!c,extensions:r(o),content:o?void 0:{type:`doc`,content:n.body??[{type:`paragraph`}]},editorProps:{attributes:{class:`dw-prose dw-db-peek__prose`}}});return!o&&!n.body?.length&&t.replaceChildren(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),()=>s.destroy()},v=e.recordLink,y=v?t=>{let n=v(_B(p(),t));xB(n).then(t=>t&&e.onLinkCopied?.(n))}:void 0;f.addEventListener(yB,e=>{let t=e.detail,n=h();n.rows.some(e=>e.id===t.row)&&(t.found=!0,f.scrollIntoView?.({block:`start`}),b(t.row,n.rows.map(e=>e.id)))});let b=(e,t)=>{u?.close(),u=new Ez({ctx:{...g()},mountBody:_,copyLink:y},h(),e,t,()=>u=null)},x=()=>{let e=h();d?.update(e,{store:c}),u?.update(e,{store:c})},S=()=>{if(l?.(),l=null,c=null,!o)return;let t=m();if(!t&&s()){let a=i.attrs.data?WR(i.attrs.data):Rz(CB(e.labels)),s=p()?p():VR();Uz(o,s,a,(e,t)=>OB(n,e,t)),queueMicrotask(()=>{let e=typeof r==`function`?r():void 0;e!==void 0&&n.state.doc.nodeAt(e)?.type.name===`database`&&n.view.dispatch(n.state.tr.setNodeMarkup(e,void 0,{...i.attrs,id:s,data:null}).setMeta(`addToHistory`,!1))}),t=Oz(o).get(s)}let a=Oz(o),d=e=>{if(!e.keysChanged.has(p()))return;S(),x();let t=u?.row;t&&h().rows.some(e=>e.id===t)&&b(t,[t])};if(a.observe(d),t){s()&&(c=new Bz(o,t,()=>e.me?.()??null));let n=t,r=()=>x();n.observeDeep(r),l=()=>{a.unobserve(d),n.unobserveDeep(r)}}else l=()=>a.unobserve(d)};S(),d=new pB({...g(),openRow:b,undo:()=>n.commands.undo?.(),redo:()=>n.commands.redo?.(),notify:e.notify,copyLink:y},h()),f.append(d.dom);let C=s(),ee=()=>{s()!==C&&(C=s(),S(),x())};return n.on(`update`,ee),n.on(`transaction`,ee),{dom:f,update(e){if(e.type!==i.type)return!1;let t=e.attrs.id!==i.attrs.id;return i=e,t&&S(),x(),!0},ignoreMutation:()=>!0,stopEvent:e=>e.type!==`dragstart`||e.target!==f,destroy(){l?.(),u?.close(),d?.destroy(),n.off(`update`,ee),n.off(`transaction`,ee)}}}}});function OB(e,t,n){try{yw(e.schema,{type:`doc`,content:t},n)}catch{}}function kBLine truncated
`);return/\s/.test(n)}):!1}function QB(e){return()=>{let t=e.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=e.view.coordsAtPos(t);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}}}function $B(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:QB(e)}function eV({match:e,dismissedRange:t,state:n,transaction:r,editor:i,shouldResetDismissed:a,effectiveAllowSpaces:o}){return a?.({editor:i,state:n,range:t,match:e,transaction:r,allowSpaces:o})?!1:o?e.range.from===t.from:e.range.from===t.from&&!ZB(r)}function tV({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function nV({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function rV({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function iV({editor:e,items:t}){let n=null,r=null,i=null,a=()=>{r!==null&&(clearTimeout(r),r=null),i?.(),i=null},o=e=>new Promise(t=>{i=t,r=setTimeout(()=>{r=null;let e=i;i=null,e?.()},e)}),s=()=>{n?.abort(),a(),n=null};return{abort:s,fetch:async(r,i)=>{s(),n=new AbortController;let a=n;if(i>0&&await o(i),n!==a||a.signal.aborted)return{status:`aborted`};try{let i=await t({editor:e,query:r,signal:a.signal});return n!==a||a.signal.aborted?{status:`aborted`}:{status:`resolved`,items:i}}catch{return n!==a||a.signal.aborted?{status:`aborted`}:{status:`error`}}}}}function aV({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[kj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(jj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function oV(e){if(e instanceof HTMLElement)return e;if(typeof e==`string`)try{let t=document.querySelector(e);if(t)return t}catch{return document.body}return document.body}function sV({getReferenceRect:e,contextElement:t,config:n,container:r,dismissOnOutsideClick:i,dismiss:a}){return(o,s={})=>{let c={getBoundingClientRect:()=>e()??new DOMRect,contextElement:t},l=!1,u=!o.isConnected;u&&oV(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=Oj(c,o,()=>{Mj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function cV({editor:e,pluginKey:t,items:n,renderer:r,minQueryLength:i,debounce:a,initialItems:o,placement:s,offset:c,container:l,flip:u,floatingUi:d,dismissOnOutsideClick:f,command:p,clientRectFor:m,dispatchExit:h}){let g,_=iV({editor:e,items:n}),v=aV({placLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=Oj(e.anchor,t,()=>{Mj(e.anchor,t,{placement:`bottom-start`,middleware:[kj(6),jj(),Aj({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),jV===d&&(jV=null),n||e.onCancel?.())}let d=()=>u();return jV=d,n.focus(),e.multiline||n.select(),d}var NV=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function PV(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of NV){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function FV(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var IV=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function LV(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;MV({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(FV(t)),onCancel:()=>e(``)})})}async function RV(e,t,n,r){let i=await LV(e,t,t.blocks.embedUrl);i&&(PV(i)?e.chain().focus().insertEmbed(i).run():await BV(e,i,n,r))}async function zV(e,t,n,r){let i=await LV(e,t,t.blocks.linkUrl);i&&await BV(e,i,n,r)}async function BV(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var VV=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=FV(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=FV(e),i=PV(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${IV(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
@@ -175,7 +178,7 @@ c5.3,-9.3,12,-14,20,-14
H400000v`+(40+e)+`H845.2724
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},rz=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},BH=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120
c340,-704.7,510.7,-1060.3,512,-1067
l`+e/2.084+` -`+e+`
@@ -185,7 +188,7 @@ s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,
c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1
s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26
c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},iz=function(e,t){return`M983 `+(10+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},VH=function(e,t){return`M983 `+(10+e+t)+`
l`+e/3.13+` -`+e+`
c4,-6.7,10,-10,18,-10 H400000v`+(40+e)+`
H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7
@@ -194,7 +197,7 @@ c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30
c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722
c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5
c53.7,-170.3,84.5,-266.8,92.5,-289.5z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},az=function(e,t){return`M424,`+(2398+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},HH=function(e,t){return`M424,`+(2398+e+t)+`
c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514
c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20
s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121
@@ -204,18 +207,18 @@ v`+(40+e)+`H1014.6
s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185
c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2z M`+(1001+e)+` `+t+`
h400000v`+(40+e)+`h-400000z`},oz=function(e,t){return`M473,`+(2713+e+t)+`
h400000v`+(40+e)+`h-400000z`},UH=function(e,t){return`M473,`+(2713+e+t)+`
c339.3,-1799.3,509.3,-2700,510,-2702 l`+e/5.298+` -`+e+`
c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+e)+`H1017.7
s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200
c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26
s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},sz=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},cz=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},WH=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},GH=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
H742v`+r+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1
h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170
c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},lz=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=nz(t,tz);break;case`sqrtSize1`:r=rz(t,tz);break;case`sqrtSize2`:r=iz(t,tz);break;case`sqrtSize3`:r=az(t,tz);break;case`sqrtSize4`:r=oz(t,tz);break;case`sqrtTall`:r=cz(t,tz,n)}return r},uz=function(e,t){switch(e){case`⎜`:return ez(`M291 0 H417 V`+t+` H291z`);case`∣`:return ez(`M145 0 H188 V`+t+` H145z`);case`∥`:return ez(`M145 0 H188 V`+t+` H145z`)+ez(`M367 0 H410 V`+t+` H367z`);case`⎟`:return ez(`M457 0 H583 V`+t+` H457z`);case`⎢`:return ez(`M319 0 H403 V`+t+` H319z`);case`⎥`:return ez(`M263 0 H347 V`+t+` H263z`);case`⎪`:return ez(`M384 0 H504 V`+t+` H384z`);case`⏐`:return ez(`M312 0 H355 V`+t+` H312z`);case`‖`:return ez(`M257 0 H300 V`+t+` H257z`)+ez(`M478 0 H521 V`+t+` H478z`);default:return``}},dz={doubleleftarrow:`M262 157
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},KH=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=zH(t,RH);break;case`sqrtSize1`:r=BH(t,RH);break;case`sqrtSize2`:r=VH(t,RH);break;case`sqrtSize3`:r=HH(t,RH);break;case`sqrtSize4`:r=UH(t,RH);break;case`sqrtTall`:r=GH(t,RH,n)}return r},qH=function(e,t){switch(e){case`⎜`:return LH(`M291 0 H417 V`+t+` H291z`);case`∣`:return LH(`M145 0 H188 V`+t+` H145z`);case`∥`:return LH(`M145 0 H188 V`+t+` H145z`)+LH(`M367 0 H410 V`+t+` H367z`);case`⎟`:return LH(`M457 0 H583 V`+t+` H457z`);case`⎢`:return LH(`M319 0 H403 V`+t+` H319z`);case`⎥`:return LH(`M263 0 H347 V`+t+` H263z`);case`⎪`:return LH(`M384 0 H504 V`+t+` H384z`);case`⏐`:return LH(`M312 0 H355 V`+t+` H312z`);case`‖`:return LH(`M257 0 H300 V`+t+` H257z`)+LH(`M478 0 H521 V`+t+` H478z`);default:return``}},JH={doubleleftarrow:`M262 157
l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3
0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28
14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5
@@ -261,10 +264,10 @@ m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9
v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5
-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3
-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:ez(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:ez(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:ez(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:ez(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:LH(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:LH(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:LH(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:LH(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8
c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:ez(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:LH(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14
-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7
311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11
@@ -313,7 +316,7 @@ m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown
m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3
15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0
-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:ez(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:ez(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:ez(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:LH(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:LH(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:LH(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32
-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142
-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40
@@ -386,7 +389,7 @@ M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`
c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,
-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6
c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},fz=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},YH=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
H403z M403 1759 V0 H319 V1759 v`+t+` v1759 v84 h84z`;case`rbrack`:return`M347 1759 V0 H0 V84 H263 V1759 v`+t+` v1759 H0 v84 H347z
M347 1759 V0 H263 V1759 v`+t+` v1759 h84z`;case`vert`:return`M145 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15
c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15
@@ -414,17 +417,17 @@ c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6
c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17
c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558
l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function pz(e){return`toText`in e}var mz=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(pz(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},hz={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},gz={ex:!0,em:!0,mu:!0},_z=function(e){return typeof e!=`string`&&(e=e.unit),e in hz||e in gz||e===`ex`},vz=function(e,t){var n;if(e.unit in hz)n=hz[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new L(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},z=function(e){return+e.toFixed(4)+`em`},yz=function(e){return e.filter(e=>e).join(` `)},bz=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=xR(n)+`:`+r+`;`)}return t},xz=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},Sz=function(e){var t=document.createElement(e);t.className=yz(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},Cz=/[\s"'>/=\x00-\x1f]/,wz=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+wR(yz(this.classes))+`"`);var n=bz(this.style);n&&(t+=` style="`+wR(n)+`"`);for(var r of Object.keys(this.attributes)){if(Cz.test(r))throw new L(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+wR(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},Tz=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,xz.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return Sz.call(this,`span`)}toMarkup(){return wz.call(this,`span`)}},Ez=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,xz.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return Sz.call(this,`a`)}toMarkup(){return wz.call(this,`a`)}},Dz=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+wR(this.src)+`"`+(` alt="`+wR(this.alt)+`"`),t=bz(this.style);return t&&(e+=` style="`+wR(t)+`"`),e+=`'/>`,e}},Oz={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},kz=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=ZR(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=Oz[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=z(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=yz(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=wR(yz(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new Az([new jz(d[v])],{width:`400em`,height:z(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=LB([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=z(m),l.push(b)}return{span:X([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=z(o),a>0&&(i.style.minWidth=z(a)),i},KV=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=X([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new Mz({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new Mz({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=LB([],[new Az(c,{width:`100%`,height:z(o)})],i)}return a.height=o,a.style.height=z(o),a},qV=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],JV=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],YV=new Set(qV),XV=new Set(JV);function ZV(e){return YV.has(e)}function QV(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function $V(e){var t=eH(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function eH(e){return e.type===`atom`||XV.has(e.type)?e:null}function tH(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new L(t,e);return r}var nH=e=>{if(e instanceof kz)return e;if(Fz(e)&&e.children.length===1)return nH(e.children[0])},rH=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=QV(e.base,`accent`),n=r.base,e.base=n,i=Pz(gV(e,t)),e.base=r):(r=QV(e,`accent`),n=r.base);var a=gV(n,t.havingCrampedStyle()),o=r.isShifty&&DR(n),s=0;o&&(s=nH(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=GV(r,t),u=UB({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+z(2*s)+`)`,marginLeft:z(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=JB(`vec`,t),f=qB.vec[1]):(d=NB({type:`textord`,mode:r.mode,text:r.label},t),d=Nz(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=X([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=z(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=UB({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=X([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},iH=(e,t)=>{var n=e.isStretchy?HV(e.label):new Q(`mo`,[wV(e.label,e.mode)]),r=new Q(`mover`,[jV(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},aH=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));Z({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=iV(t[0]),r=!aH.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:rH,mathmlBuilder:iH}),Z({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),Z({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=gV(e.base,t),r=GV(e,t),i=e.label===`\\utilde`?.12:0;return X([`mord`,`accentunder`],[UB({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=HV(e.label),r=new Q(`munder`,[jV(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var oH=e=>{var t=new Q(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};Z({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrighLine truncated
]`,ZU=`\\\\[a-zA-Z@]+`,QU=`\\\\[^\ud800-\udfff]`,$U=`(`+ZU+`)`+XU+`*`,eW=`\\\\(
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function XH(e){return`toText`in e}var ZH=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(XH(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},QH={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},$H={ex:!0,em:!0,mu:!0},eU=function(e){return typeof e!=`string`&&(e=e.unit),e in QH||e in $H||e===`ex`},tU=function(e,t){var n;if(e.unit in QH)n=QH[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new L(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},z=function(e){return+e.toFixed(4)+`em`},nU=function(e){return e.filter(e=>e).join(` `)},rU=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=iH(n)+`:`+r+`;`)}return t},iU=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},aU=function(e){var t=document.createElement(e);t.className=nU(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},oU=/[\s"'>/=\x00-\x1f]/,sU=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+sH(nU(this.classes))+`"`);var n=rU(this.style);n&&(t+=` style="`+sH(n)+`"`);for(var r of Object.keys(this.attributes)){if(oU.test(r))throw new L(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+sH(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},cU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,iU.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return aU.call(this,`span`)}toMarkup(){return sU.call(this,`span`)}},lU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,iU.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return aU.call(this,`a`)}toMarkup(){return sU.call(this,`a`)}},uU=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+sH(this.src)+`"`+(` alt="`+sH(this.alt)+`"`),t=rU(this.style);return t&&(e+=` style="`+sH(t)+`"`),e+=`'/>`,e}},dU={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},fU=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=PH(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=dU[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=z(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=nU(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=sH(nU(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new pU([new mU(d[v])],{width:`400em`,height:z(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=bW([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=z(m),l.push(b)}return{span:X([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=z(o),a>0&&(i.style.minWidth=z(a)),i},kG=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=X([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new hU({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new hU({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=bW([],[new pU(c,{width:`100%`,height:z(o)})],i)}return a.height=o,a.style.height=z(o),a},AG=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],jG=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],MG=new Set(AG),NG=new Set(jG);function PG(e){return MG.has(e)}function FG(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function IG(e){var t=LG(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function LG(e){return e.type===`atom`||NG.has(e.type)?e:null}function RG(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new L(t,e);return r}var zG=e=>{if(e instanceof fU)return e;if(vU(e)&&e.children.length===1)return zG(e.children[0])},BG=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=FG(e.base,`accent`),n=r.base,e.base=n,i=_U($W(e,t)),e.base=r):(r=FG(e,`accent`),n=r.base);var a=$W(n,t.havingCrampedStyle()),o=r.isShifty&&uH(n),s=0;o&&(s=zG(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=OG(r,t),u=EW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+z(2*s)+`)`,marginLeft:z(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=jW(`vec`,t),f=AW.vec[1]):(d=gW({type:`textord`,mode:r.mode,text:r.label},t),d=gU(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=X([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=z(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=EW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=X([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},VG=(e,t)=>{var n=e.isStretchy?TG(e.label):new Q(`mo`,[sG(e.label,e.mode)]),r=new Q(`mover`,[mG(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},HG=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));Z({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=VW(t[0]),r=!HG.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:BG,mathmlBuilder:VG}),Z({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),Z({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=$W(e.base,t),r=OG(e,t),i=e.label===`\\utilde`?.12:0;return X([`mord`,`accentunder`],[EW({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=TG(e.label),r=new Q(`munder`,[mG(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var UG=e=>{var t=new Q(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};Z({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrighLine truncated
]`,Pq=`\\\\[a-zA-Z@]+`,Fq=`\\\\[^\ud800-\udfff]`,Iq=`(`+Pq+`)`+Nq+`*`,Lq=`\\\\(
|[ \r ]+
?)[ \r ]*`,tW=`[̀-ͯ]`,nW=RegExp(tW+`+$`),rW=`(`+XU+`+)|`+(eW+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(tW+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(tW+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+$U)+(`|`+QU+`)`),iW=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(rW,`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 iU(`EOF`,new rU(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new L(`Unexpected character: '`+e[t]+`'`,new iU(e[t],new rU(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 iU(r,new rU(this,t,this.tokenRegex.lastIndex))}},aW=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;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(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}},oW=nU;$(`\\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 sW={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=sW[t.text],r==null||r>=n)throw new L(`Invalid base-`+n+` digit `+t.text);for(var i;(i=sW[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var cW=(e,t,n,r)=>{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=>cW(e,!1,!0,!1)),$(`\\renewcommand`,e=>cW(e,!0,!1,!1)),$(`\\providecommand`,e=>cW(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),YU[n],Uz.math[n],Uz.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{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(yW,t[0])&&!Uz[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=yW[t[0]]+t.slice(1));var i=nW.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(Uz[this.mode][t]){this.settings.strict&&this.mode===`math`&&dB.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=Uz[this.mode][t].group,s=rU.range(e);a=ZV(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&($R(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:rU.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!vW[l])throw new L(`Unknown accent ' `+l+`'`,e);var u=vW[l][this.mode]||vW[l].text;if(!u)throw new L(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:rU.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};bW.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var xW=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new bW(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new L(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new iU(`\\df@tag`)])}]}return r},SW=function(e,t,n){t.textContent=``;var r=EW(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),SW=function(){throw new L(`KaTeX doesn't work in quirks mode.`)});var CW=function(e,t){return EW(e,t).toMarkup()},wW=function(e,t){return xW(e,new NR(t))},TW=function(e,t,n){if(n.throwOnError||!(e instanceof L))throw e;var r=X([`katex-error`],[new kz(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},EW=function(e,t){var n=new NR(t);try{return zV(xW(e,n),e,n)}catch(t){return TW(t,e,n)}},DW={version:`0.18.10`,render:SW,renderToString:CW,ParseError:L,SETTINGS_SCHEMA:kR,__parse:wW,__renderToDomTree:EW,__renderToHTMLTree:function(e,t){var n=new NR(t);try{return BV(xW(e,n),e,n)}catch(t){return TW(t,e,n)}},__setFontMetrics:zz,__defineSymbol:B,__defineFunction:Z,__defineMacro:$,__domTree:{Span:Tz,Anchor:Ez,SymbolNode:kz,SvgNode:Az,PathNode:jz,LineNode:Mz}},OW=Jp.create({name:`blockMath`,group:`block`,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{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{DW.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)}}}}}),kW=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},AW=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:kW,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{DW.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)}}}}}),jW=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[OW.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),AW.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function MW(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;YL({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 jW.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function NW({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new D,command:({editor:e,range:t,props:i})=>{var a,o;let s=Line truncated
Idea --> Draft --> Review --> Published`,zW=null;function BW(e){return zW??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),zW}var VW=0;async function HW(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 BW(r)).render(`dw-mermaid-${++VW}`,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 UW=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=RW)=>({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 HW(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;YL({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void HW(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),HW(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void HW(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),HW(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function WW(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 GW(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().Line truncated
?)[ \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;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(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<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var Gq=(e,t,n,r)=>{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{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(nJ,t[0])&&!EU[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=nJ[t[0]]+t.slice(1));var i=zq.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(EU[this.mode][t]){this.settings.strict&&this.mode===`math`&&JU.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=EU[this.mode][t].group,s=BK.range(e);a=PG(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=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;c<i[0].length;c++){var l=i[0][c];if(!tJ[l])throw new L(`Unknown accent ' `+l+`'`,e);var u=tJ[l][this.mode]||tJ[l].text;if(!u)throw new L(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:BK.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};rJ.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var iJ=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new rJ(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new L(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new VK(`\\df@tag`)])}]}return r},aJ=function(e,t,n){t.textContent=``;var r=lJ(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),aJ=function(){throw new L(`KaTeX doesn't work in quirks mode.`)});var oJ=function(e,t){return lJ(e,t).toMarkup()},sJ=function(e,t){return iJ(e,new gH(t))},cJ=function(e,t,n){if(n.throwOnError||!(e instanceof L))throw e;var r=X([`katex-error`],[new fU(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},lJ=function(e,t){var n=new gH(t);try{return SG(iJ(e,n),e,n)}catch(t){return cJ(t,e,n)}},uJ={version:`0.18.10`,render:aJ,renderToString:oJ,ParseError:L,SETTINGS_SCHEMA:fH,__parse:sJ,__renderToDomTree:lJ,__renderToHTMLTree:function(e,t){var n=new gH(t);try{return CG(iJ(e,n),e,n)}catch(t){return cJ(t,e,n)}},__setFontMetrics:SU,__defineSymbol:B,__defineFunction:Z,__defineMacro:$,__domTree:{Span:cU,Anchor:lU,SymbolNode:fU,SvgNode:pU,PathNode:mU,LineNode:hU}},dJ=Jp.create({name:`blockMath`,group:`block`,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{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 sLine truncated
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().Line truncated
<style rel="stylesheet" crossorigin>/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--shadow-dialog:var(--dw-shadow-dialog);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-varLine truncated
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--shadow-dialog:var(--dw-shadow-dialog);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-varLine truncated
/*$vite$:1*/</style>
</head>
<body>
+52 -2
View File
@@ -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<HTMLElement>(".dw-db-t__open")!.click();
await Promise.resolve();
expect(document.querySelector(".dw-db-peek")).not.toBeNull();
+43 -1
View File
@@ -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<HTMLElement>(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;
+3 -1
View File
@@ -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;
+6
View File
@@ -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;
+3 -1
View File
@@ -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",
+138
View File
@@ -0,0 +1,138 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
// Edgeless mode for the web and desktop apps: the canvas, with every note a
// full Docwell editor (selection toolbar, tables, find) mounted in it.
import type { JSONContent } from "@tiptap/core";
import type { NoteHandle, StyleDefaults } from "@docwell/canvas";
import { createApp, h, onBeforeUnmount, onMounted, ref, shallowRef, watch, type App } from "vue";
import DocwellEditor from "./DocwellEditor.vue";
import { mountEdgeless, type Edgeless, type NoteSpec } from "./edgeless";
import type { LinkHost } from "./embeds";
import type { CollabUser } from "./extensions";
import type { FileHost } from "./files";
import type { EditorLabels } from "./labels";
import type { MentionHost } from "./mention";
import type { PageHost } from "./pagelinks";
import type { CollabProvider } from "./provider";
import type { SyncedPageHost } from "./syncedpage";
const props = withDefaults(
defineProps<{
provider?: CollabProvider;
user?: CollabUser;
/** The page as JSON, shown read-only when there is no provider. */
content?: JSONContent | null;
editable?: boolean;
files?: FileHost;
mentions?: MentionHost;
pages?: PageHost;
links?: LinkHost;
blockLink?: (hash: string) => string;
drawioUrl?: string;
labels?: EditorLabels;
codeLineNumbers?: boolean;
journals?: boolean;
syncedPages?: SyncedPageHost;
placeholder?: string;
styles?: StyleDefaults;
/** Keeps pan and zoom on this device under this key. */
viewKey?: string;
pageTitle?: string;
}>(),
{ editable: true },
);
const emit = defineEmits<{
navigate: [path: string];
error: [err: unknown];
"block-link-copied": [url: string];
styles: [styles: StyleDefaults];
}>();
const host = ref<HTMLElement | null>(null);
const edgeless = shallowRef<Edgeless | null>(null);
/** Each note is a small Vue app of its own around the editor component. */
function mountNote(el: HTMLElement, spec: NoteSpec): NoteHandle {
const editable = ref(spec.kind !== "json" && spec.editable);
const editorRef = shallowRef<InstanceType<typeof DocwellEditor> | null>(null);
const shared = {
files: props.files,
mentions: props.mentions,
pages: props.pages,
links: props.links,
blockLink: props.blockLink,
drawioUrl: props.drawioUrl,
labels: props.labels,
codeLineNumbers: props.codeLineNumbers,
journals: props.journals,
syncedPages: props.syncedPages,
onNavigate: (p: string) => emit("navigate", p),
onError: (e: unknown) => emit("error", e),
"onBlock-link-copied": (u: string) => emit("block-link-copied", u),
};
const app: App = createApp({
render: () =>
h(DocwellEditor, {
...shared,
ref: editorRef,
editable: editable.value,
placeholder: spec.kind === "page" ? (props.placeholder ?? "") : "",
...(spec.kind === "page"
? { provider: spec.provider, user: spec.user }
: spec.kind === "body"
? { fragment: { doc: spec.doc, fragment: spec.fragment } }
: { content: spec.content }),
}),
});
app.mount(el);
return {
destroy: () => app.unmount(),
focus: () => editorRef.value?.editor?.commands.focus("end"),
setEditable: (on) => (editable.value = on && spec.kind !== "json"),
};
}
onMounted(() => {
if (!host.value) return;
edgeless.value = mountEdgeless(host.value, {
provider: props.provider,
user: props.user,
content: props.content,
editable: props.editable,
files: props.files,
links: props.links,
labels: props.labels,
styles: props.styles,
onStyles: (s) => emit("styles", s),
viewKey: props.viewKey,
pageTitle: () => props.pageTitle ?? "",
onError: (e) => emit("error", e),
mountNote,
});
});
watch(
() => props.editable,
(on) => edgeless.value?.setEditable(on),
);
watch(
() => props.pageTitle,
() => edgeless.value?.view.schedule(),
);
onBeforeUnmount(() => {
edgeless.value?.destroy();
edgeless.value = null;
});
defineExpose({
/** The canvas: export, present, fit. */
get view() {
return edgeless.value?.view ?? null;
},
});
</script>
<template>
<div ref="host" class="dw-edgeless h-full w-full" />
</template>
+5 -1
View File
@@ -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,
+165
View File
@@ -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<EdgelessOptions>).provider;
delete (noteOpts as Partial<EdgelessOptions>).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();
},
};
}
+1
View File
@@ -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 "./";
+9
View File
@@ -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";
+9
View File
@@ -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<CanvasLabels, "colors">;
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,
};
+46
View File
@@ -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;
+27 -1
View File
@@ -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<String, dynamic>,
journalDate: json['journalDate'] as String,
@@ -768,6 +770,8 @@ class Page {
final PageFont font;
final PageMode defaultMode;
/// Tag ids
final List<String> 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<String, dynamic>,
mode: PageMode.fromJson(json['mode'] as String),
root: PageRef.fromJson(json['root'] as Map<String, dynamic>),
pages: (json['pages'] as List)
.map((e) => PageNode.fromJson(e as Map<String, dynamic>))
@@ -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<String, dynamic>? 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(),
};
+5 -1
View File
@@ -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<void> 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<void> setMode(String mode) => _post({'type': 'setMode', 'mode': mode});
/// Closes the topmost panel or menu over the text.
Future<void> dismiss() => _post({'type': 'dismiss'});
+22 -1
View File
@@ -58,6 +58,9 @@ class _PageScreenState extends State<PageScreen> {
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<PageScreen> {
_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<PageScreen> {
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<PageScreen> {
setState(() => _editing = false);
}
Future<void> _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<PageScreen> {
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<PageScreen> {
),
if (_editing)
TextButton(onPressed: _done, child: const Text('Done'))
else if (_canEdit)
else if (_canEdit && !_canvas)
IconButton(
key: const Key('edit'),
tooltip: 'Edit',
+10 -1
View File
@@ -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 {
+11 -2
View File
@@ -273,12 +273,21 @@ void main() {
'favorite': false,
'pinnedAt': '',
'fullWidth': false,
'defaultMode': 'page',
'font': '',
'tags': [],
'properties': <String, dynamic>{},
'journalDate': '',
'createdBy': <String, dynamic>{'id': 'u1', 'name': 'Ann', 'email': 'ann@docwell.test'},
'lastEditedBy': <String, dynamic>{'id': 'u1', 'name': 'Ann', 'email': 'ann@docwell.test'},
'createdBy': <String, dynamic>{
'id': 'u1',
'name': 'Ann',
'email': 'ann@docwell.test',
},
'lastEditedBy': <String, dynamic>{
'id': 'u1',
'name': 'Ann',
'email': 'ann@docwell.test',
},
});
await tester.pumpWidget(
MaterialApp(
+31 -1
View File
@@ -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"`
+27 -2
View File
@@ -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"
}
+3 -1
View File
@@ -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 {
+14
View File
@@ -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",
+57
View File
@@ -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":[]}}`)
}
+145
View File
@@ -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<Vec<u8>> = 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<T: ReadTxn>(txn: &T) -> Option<Value> {
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<Value> = 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::<Vec<_>>().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<T: ReadTxn>(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<String, Value>) -> Result<(), String> {
let map = txn.get_or_insert_map(SURFACE);
let keys: Vec<String> = 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(())
}
@@ -39,6 +39,7 @@ export function useEditorLabels() {
find: group("find", "find"),
dates: group("dates", "dates"),
database: group("database", "database"),
edgeless: group("edgeless", "edgeless"),
}));
}
+122 -1
View File
@@ -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"
}
}
+122 -1
View File
@@ -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"
}
}
+122 -1
View File
@@ -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"
}
}
+122 -1
View File
@@ -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"
}
}
+122 -1
View File
@@ -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"
}
}
@@ -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<string, unknown> | 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 {
+6 -2
View File
@@ -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;
+56 -3
View File
@@ -1,11 +1,12 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { SharedPage } from "@docwell/api-client";
import { DocwellEditor, followLink, isTargetHash, type FileHost } from "@docwell/editor";
import { DocwellEdgeless, DocwellEditor, followLink, isTargetHash, type FileHost } from "@docwell/editor";
import { DwCallout, DwIcon, DwLogo } from "@docwell/ui";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useApi } from "../api";
import { useEditorLabels } from "../composables/useEditorHosts";
import { usePlatform, useRuntimeConfig } from "../platform";
// A page shared by public link: read-only, no account needed. With subpages,
@@ -18,6 +19,20 @@ const route = useRoute();
const router = useRouter();
const shared = ref<SharedPage | null>(null);
const labels = useEditorLabels();
// Pages made as canvases open as one; "?mode=" switches, for anyone with the link.
const mode = computed(() => {
const q = route.query.mode;
if (q === "page" || q === "edgeless") return q;
return shared.value?.mode === "edgeless" ? "edgeless" : "page";
});
function setMode(m: "page" | "edgeless") {
const query = { ...route.query };
if (m === (shared.value?.mode ?? "page")) delete query.mode;
else query.mode = m;
void router.replace({ query, hash: route.hash });
}
const failed = ref(false);
const files: FileHost = {
@@ -93,10 +108,48 @@ onBeforeUnmount(() => {
<div class="min-h-dvh bg-surface">
<header class="flex h-12 items-center gap-3 border-b border-line px-4">
<DwLogo class="h-6" />
<span class="truncate text-ui-sm text-ink-muted">{{ $t("share.readOnly") }}</span>
<span class="min-w-0 flex-1 truncate text-ui-sm text-ink-muted">{{ $t("share.readOnly") }}</span>
<div
v-if="shared"
class="flex shrink-0 items-center rounded-sm border border-line p-0.5"
role="group"
:aria-label="$t('edgeless.mode')"
>
<button
v-for="m in ['page', 'edgeless'] as const"
:key="m"
type="button"
class="grid size-6 cursor-pointer place-items-center rounded-xs"
:class="mode === m ? 'bg-surface-hover text-ink' : 'text-ink-muted hover:text-ink'"
:aria-pressed="mode === m"
:aria-label="$t(`edgeless.${m}Mode`)"
:title="$t(`edgeless.${m}Mode`)"
:data-testid="`share-mode-${m}`"
@click="setMode(m)"
>
<DwIcon :name="m === 'page' ? 'page' : 'edgeless'" :size="16" />
</button>
</div>
</header>
<div class="mx-auto flex max-w-doc-wide gap-8 px-4 sm:px-8">
<section
v-if="shared && mode === 'edgeless'"
class="h-[calc(100dvh-3rem)]"
:aria-label="$t('edgeless.canvas')"
data-testid="shared-edgeless"
>
<DocwellEdgeless
:key="shared.id"
:content="shared.content ?? null"
:editable="false"
:files="files"
:labels="labels"
:page-title="shared.title || $t('home.untitled')"
:view-key="`docwell.share.${shared.id}`"
/>
</section>
<div v-else class="mx-auto flex max-w-doc-wide gap-8 px-4 sm:px-8">
<nav v-if="tree.length" class="hidden w-56 shrink-0 pt-10 md:block" :aria-label="$t('page.subpages')">
<RouterLink
:to="link(shared!.root.id)"
+118 -4
View File
@@ -1,8 +1,9 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { Comment, Page, PageFont, PageItem, Template } from "@docwell/api-client";
import type { Comment, Page, PageFont, PageItem, PageMode, Template } from "@docwell/api-client";
import {
CollabProvider,
DocwellEdgeless,
DocwellEditor,
encodeAnchor,
insertFiles,
@@ -259,6 +260,40 @@ async function attachPicked() {
input.value = "";
await run(() => insertFiles(editor, files.host, picked));
}
// Edgeless mode (ADR-14): the page as a canvas with its text as a note. The
// page has a default for everyone; "?mode=" in the address (or the side
// pane's own switch) shows the other view without changing it.
const edgelessRef = ref<InstanceType<typeof DocwellEdgeless> | null>(null);
const paneMode = ref<PageMode | null>(null);
const mode = computed<PageMode>(() => {
const wanted = main.value ? route.query.mode : paneMode.value;
if (wanted === "page" || wanted === "edgeless") return wanted;
return page.value?.defaultMode === "edgeless" ? "edgeless" : "page";
});
function setMode(m: PageMode) {
if (!main.value) {
paneMode.value = m;
return;
}
const query = { ...route.query };
if (m === (page.value?.defaultMode ?? "page")) delete query.mode;
else query.mode = m;
void router.replace({ query, hash: route.hash });
}
const setDefaultMode = (m: PageMode) =>
run(async () => {
const p = await api.pages.update(page.value!.id, { defaultMode: m });
if (page.value?.id === p.id) page.value = { ...p, title: page.value.title };
setMode(m);
});
const exportImage = (kind: "png" | "svg") =>
run(async () => {
const view = edgelessRef.value?.view;
if (!view) return;
const blob = await view.exportImage(kind);
saveBlob(blob, `${title.value.trim() || t("home.untitled")}.${kind}`);
});
// Redraw comment highlights when the list, the active one or the editor changes.
watch([comments, activeComment, () => editorRef.value?.editor], drawComments);
watch(() => editorRef.value?.editor, trackEmpty);
@@ -407,6 +442,7 @@ watch(
backlinks.value = [];
draft.value = null;
activeComment.value = "";
paneMode.value = null;
}
await load(id);
},
@@ -444,7 +480,13 @@ const exportAs = (format: "markdown" | "html" | "pdf" | "docx") =>
});
const menu = computed<MenuItem[]>(() => [
{ label: t("page.find"), icon: "search", onSelect: () => editorRef.value?.openFind() },
...(mode.value === "page"
? [{ label: t("page.find"), icon: "search" as const, onSelect: () => editorRef.value?.openFind() }]
: [
{ label: t("edgeless.present"), icon: "present" as const, onSelect: () => edgelessRef.value?.view?.present() },
{ label: t("edgeless.exportPng"), icon: "download" as const, onSelect: () => exportImage("png") },
{ label: t("edgeless.exportSvg"), icon: "download" as const, onSelect: () => exportImage("svg") },
]),
...(platform.kind === "web"
? [
{
@@ -479,6 +521,13 @@ const menu = computed<MenuItem[]>(() => [
onSelect: togglePin,
},
{ label: t("page.archive"), icon: "archive" as const, onSelect: () => archive() },
page.value?.defaultMode === "edgeless"
? { label: t("edgeless.defaultPage"), icon: "page" as const, onSelect: () => setDefaultMode("page") }
: {
label: t("edgeless.defaultEdgeless"),
icon: "edgeless" as const,
onSelect: () => setDefaultMode("edgeless"),
},
{
label: t(page.value?.fullWidth ? "page.standardWidth" : "page.fullWidth"),
icon: "width" as const,
@@ -566,6 +615,27 @@ const purge = () =>
}}</span>
</template>
</p>
<div
class="flex shrink-0 items-center rounded-sm border border-line p-0.5"
role="group"
:aria-label="$t('edgeless.mode')"
data-testid="mode-switch"
>
<button
v-for="m in ['page', 'edgeless'] as const"
:key="m"
type="button"
class="grid size-6 cursor-pointer place-items-center rounded-xs"
:class="mode === m ? 'bg-surface-hover text-ink' : 'text-ink-muted hover:text-ink'"
:aria-pressed="mode === m"
:aria-label="$t(`edgeless.${m}Mode`)"
:title="$t(`edgeless.${m}Mode`)"
:data-testid="`mode-${m}`"
@click="setMode(m)"
>
<DwIcon :name="m === 'page' ? 'page' : 'edgeless'" :size="16" />
</button>
</div>
<button
class="grid size-control-sm shrink-0 cursor-pointer place-items-center rounded-sm hover:bg-surface-hover"
:class="page.favorite ? 'text-warning' : 'text-ink-muted hover:text-ink'"
@@ -578,7 +648,7 @@ const purge = () =>
>
<DwIcon name="star" :size="16" :filled="page.favorite" />
</button>
<template v-if="editable && main">
<template v-if="editable && main && mode === 'page'">
<input ref="filePicker" type="file" multiple class="hidden" data-testid="attach-input" @change="attachPicked" />
<DwButton
variant="ghost"
@@ -632,8 +702,52 @@ const purge = () =>
</Teleport>
<ShareDialog v-if="page" v-model="shareOpen" :page="page" @changed="accessChanged" />
<div class="flex min-h-full items-start">
<div
class="flex"
:class="mode === 'edgeless' && page ? 'h-[calc(100dvh-3rem)] items-stretch md:h-full' : 'min-h-full items-start'"
>
<section
v-if="page && mode === 'edgeless'"
class="relative min-w-0 flex-1"
:aria-label="$t('edgeless.canvas')"
data-testid="page-edgeless"
>
<DocwellEdgeless
v-if="provider && synced && filesReady"
ref="edgelessRef"
:key="page.id"
:provider="provider"
:user="me"
:editable="editable"
:files="files.host"
:mentions="mentions"
:pages="pageLinks"
:links="linkHost"
:block-link="blockLink"
:drawio-url="config.drawioUrl"
:labels="labels"
:journals="canOrganize"
:synced-pages="syncedPages"
:code-line-numbers="prefs.codeLineNumbers"
:placeholder="editable ? $t('page.placeholder') : ''"
:page-title="title.trim() || $t('home.untitled')"
:styles="(prefs.edgelessStyles as never) ?? undefined"
:view-key="`docwell.edgeless.${page.id}`"
@styles="prefs.edgelessStyles = $event as never"
@navigate="router.push($event)"
@block-link-copied="blockLinkCopied"
@error="emit('error', $event)"
/>
<p
v-if="page.inTrash || page.archived"
role="status"
class="absolute top-3 left-1/2 z-10 -translate-x-1/2 rounded-md border border-line bg-surface-raised px-3 py-1.5 text-ui-sm text-ink-muted shadow-menu"
>
{{ page.inTrash ? $t("page.inTrash") : $t("page.archived") }}
</p>
</section>
<article
v-else
class="mx-auto min-w-0 flex-1 px-4 pt-6 pb-16 sm:px-16 sm:pt-10"
:class="[
page?.fullWidth ? 'max-w-doc-wide' : 'max-w-doc',
@@ -153,10 +153,31 @@ const when = (s: string) =>
<option value="lg">{{ $t("account.editor.sizes.lg") }}</option>
</select>
</label>
<label class="flex flex-wrap items-center gap-3 text-ui-md">
<span class="min-w-0 flex-1">{{ $t("account.editor.newPageMode") }}</span>
<select v-model="prefs.newPageMode" class="dw-input" data-testid="new-page-mode">
<option value="page">{{ $t("account.editor.modes.page") }}</option>
<option value="edgeless">{{ $t("account.editor.modes.edgeless") }}</option>
</select>
</label>
<label v-for="k in prefSwitches" :key="k" class="flex items-center gap-3 text-ui-md">
<input v-model="prefs[k]" type="checkbox" class="accent-primary" :data-testid="`pref-${k}`" />
{{ $t(`account.editor.${k}`) }}
</label>
<div class="flex flex-wrap items-center gap-3 text-ui-md">
<span class="min-w-0 flex-1">
{{ $t("account.editor.edgelessStyles") }}
<span class="block text-ui-sm text-ink-muted">{{ $t("account.editor.edgelessStylesHint") }}</span>
</span>
<DwButton
size="sm"
:disabled="!prefs.edgelessStyles"
data-testid="reset-edgeless-styles"
@click="prefs.edgelessStyles = null"
>
{{ $t("account.editor.resetStyles") }}
</DwButton>
</div>
</section>
<section v-if="totp" class="space-y-4 dw-card" data-testid="totp-section">
+10 -3
View File
@@ -995,6 +995,7 @@ paths:
isTemplate: { type: boolean, description: Offer the page as a template for new pages }
fullWidth: { type: boolean, description: Use the whole window instead of the reading column }
font: { $ref: "#/components/schemas/PageFont" }
defaultMode: { $ref: "#/components/schemas/PageMode" }
tags: { type: array, items: { type: string }, maxItems: 100, description: "Replaces the page's tags (tag ids)" }
properties:
type: object
@@ -3198,7 +3199,7 @@ components:
Page:
type: object
required:
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, archivedAt, archived, ancestors, role, restricted, isTemplate, favorite, pinnedAt, fullWidth, font, tags, properties, journalDate, createdBy, lastEditedBy]
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, archivedAt, archived, ancestors, role, restricted, isTemplate, favorite, pinnedAt, fullWidth, font, defaultMode, tags, properties, journalDate, createdBy, lastEditedBy]
properties:
id: { type: string }
workspace: { type: string }
@@ -3220,6 +3221,7 @@ components:
pinnedAt: { type: string, description: When the page was pinned to its space's home; empty if not }
fullWidth: { type: boolean, description: Shown across the whole window instead of the reading column }
font: { $ref: "#/components/schemas/PageFont" }
defaultMode: { $ref: "#/components/schemas/PageMode" }
tags: { type: array, items: { type: string }, description: Tag ids }
properties:
type: object
@@ -3228,6 +3230,10 @@ components:
journalDate: { type: string, description: The day (YYYY-MM-DD) of a journal page; empty otherwise }
createdBy: { $ref: "#/components/schemas/PageUser" }
lastEditedBy: { $ref: "#/components/schemas/PageUser" }
PageMode:
type: string
enum: [page, edgeless]
description: The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it
PageFont:
type: string
enum: ["", serif, mono]
@@ -3721,7 +3727,7 @@ components:
created: { type: string }
SharedPage:
type: object
required: [id, title, icon, updated, content, root, pages]
required: [id, title, icon, updated, content, mode, root, pages]
properties:
id: { type: string }
title: { type: string }
@@ -3729,7 +3735,8 @@ components:
updated: { type: string }
content:
oneOf: [{ type: object, additionalProperties: true }, { type: "null" }]
description: Tiptap JSON; files load from /api/v1/share/{token}/files/{fileId}
description: Tiptap JSON (with "surface", the edgeless canvas, when it has one); files load from /api/v1/share/{token}/files/{fileId}
mode: { $ref: "#/components/schemas/PageMode" }
root: { $ref: "#/components/schemas/PageRef" }
pages: { type: array, items: { $ref: "#/components/schemas/PageNode" }, description: Pages under the shared page, in tree order (only when the link includes subpages) }
Comment:
+20
View File
@@ -707,6 +707,10 @@
"resolved": "Packages/api-client",
"link": true
},
"node_modules/@docwell/canvas": {
"resolved": "Packages/canvas",
"link": true
},
"node_modules/@docwell/desktop": {
"resolved": "Desktop-App/frontend",
"link": true
@@ -11515,11 +11519,27 @@
"vitest": "^5.0.5"
}
},
"Packages/canvas": {
"name": "@docwell/canvas",
"version": "0.0.1",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@docwell/ui": "*",
"perfect-freehand": "^1.2.0",
"roughjs": "^4.6.4",
"yjs": "^13.6.33"
},
"devDependencies": {
"jsdom": "^30.1.3",
"vitest": "^5.0.5"
}
},
"Packages/editor": {
"name": "@docwell/editor",
"version": "0.0.1",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@docwell/canvas": "*",
"@docwell/ui": "*",
"@excalidraw/excalidraw": "^0.18.1",
"@floating-ui/dom": "^1.8.0",