diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js
index 1e0be849d..40c6b6758 100644
--- a/packages/webui/src/public/bus.js
+++ b/packages/webui/src/public/bus.js
@@ -730,6 +730,19 @@
// by the page. A textarea reads CRLF as LF, so the draft and the save are LF.
let canEdit = false, docKey = null;
const docStates = new Map();
+ // Row 154 (#1648, Q168): the visual editor (editor.js, window.MosaicEditor) edits the same draft text.
+ // Its view is destroyed whenever the page is redrawn, since it holds a document-level listener.
+ // docMode is the view asked for; docShown is the view on screen. They differ when a file opens as Source because
+ // the visual editor cannot write it back byte for byte, and a click on a button compares with what is on screen.
+ let docMode = 'visual', docShown = 'visual', editor = null;
+ function unmountEditor() { if (editor) { try { editor.api.destroy(); } catch { /* the page is being replaced */ } editor = null; } }
+ function mountEditor(s, host) {
+ unmountEditor();
+ try {
+ const api = window.MosaicEditor.mount(host, { text: s.text, editable: canEdit && !out(), onChange() { s.text = api.text(); s.status = ''; paintDoc(); } });
+ editor = { host, api };
+ } catch { host.textContent = 'The visual editor did not start. Use Source to edit this file. The draft is unchanged.'; }
+ }
const dirty = s => s.text !== s.original || s.saving;
const lf = v => String(v).replace(/\r\n?/g, '\n');
const DOC_PATH = /^(spec\/north-star\.md|docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md)$/;
@@ -746,13 +759,14 @@
return `${head('Docs', `${readLine()} The spec and the files under docs/ of each project. ${canEdit ? 'Open one to edit it; a save makes one commit in the project with you as the author.' : 'Saving needs a Console started with --send behind the sign-in proxy; this one only reads.'}`)}
${blocks.join('') || empty('This business declares no projects.', 'A project shows here when the business file names it.')}`;
}
- async function docView(get, project, file) {
+ async function docView(get, project, file, { reuseDraft = false } = {}) {
if (!SAFE.test(project)) return notFound(`${txt(project)} is not a project name.`);
if (!DOC_PATH.test(file)) return notFound(`${txt(file)} is not a spec or docs file.`);
docKey = JSON.stringify([project, file]);
for (const [k, v] of docStates) if (k !== docKey && !dirty(v)) docStates.delete(k);
let s = docStates.get(docKey);
- if (!s || !dirty(s)) {
+ // A switch between Visual and Source passes reuseDraft: the draft, clean or not, is already the file as opened.
+ if (!s || (!dirty(s) && !reuseDraft)) {
const r = await get.api(`project-file?project=${enc(project)}&path=${enc(file)}`), now = docStates.get(docKey);
// Typing during the read wins over what was read.
s = now && dirty(now) ? now : { project, path: file, commit: r.commit, raw: r.content, original: lf(r.content), text: lf(r.content), status: '', saving: false, at: r.at };
@@ -762,22 +776,38 @@
const unsafe = s.raw.includes('\0'); // a textarea can't hold it, so a save would not write what was read
const stateNote = unsafe ? 'This file holds a NUL character, which the editor cannot keep. Edit it where it lives.'
: `${s.raw.includes('\r') ? 'This file uses CRLF line endings; a save writes LF. ' : ''}${canEdit ? '' : 'Saving needs a Console started with --send behind the sign-in proxy; this one only reads.'}`;
- return `${head(`Edit ${txt(s.path)}`, `Project ${txt(s.project)}, opened at commit ${esc(s.commit.slice(0, 12))}. ${readLine()}`)}
-
All documents
+ // Row 154 (#1648, Q168): the visual editor is the default view and Source is row 148's textarea. The visual
+ // editor opens a file only when it writes the text back byte for byte; otherwise this opens Source.
+ let visualOk = false;
+ if (docMode === 'visual' && !unsafe && window.MosaicEditor && window.MosaicMarkdown) { try { visualOk = window.MosaicEditor.roundTrip(s.text) === s.text; } catch { /* Source */ } }
+ docShown = visualOk ? 'visual' : 'source';
+ const modeNote = docMode === 'visual' && !visualOk && !unsafe ?'The visual editor is not available for this file, so it is open as source. ' : '';
+ const modes = `Visual Source
`;
+ const actions = `Save to the project Reload from the project and discard the draft
+ ${txt(s.status)}
`;
+ const top = `${head(`Edit ${txt(s.path)}`, `Project ${txt(s.project)}, opened at commit ${esc(s.commit.slice(0, 12))}. ${readLine()}`)}
+ All documents
${modes}`;
+ if (visualOk) return `${top}
+ Document
+ A save writes Markdown. A block you do not touch is saved exactly as it was; a block you edit is rewritten in a standard form. Source the editor does not draw (tables, HTML, front matter) shows as a tinted block you edit as text. A link shows its target when you select it; an image shows its address and is never loaded.
+
+ `;
+ return `${top}
+
${modeNote}${stateNote}
+ ${actions}
Preview Headings, lists, quotes, code and links are drawn. Raw HTML and anything else shows as text. A link shows where it goes; an image shows its address and is never loaded.
`;
}
// The parts of the editor that follow the draft, set in place so typing never redraws the page.
function paintDoc() {
- const s = docStates.get(docKey), box = $('doc-preview');
- if (!s || !box) return;
+ const s = docStates.get(docKey), box = $('doc-preview'), host = $('doc-visual');
+ if (!s || !(box || host)) return;
+ if (host && editor?.host !== host) mountEditor(s, host);
// A preview that throws must not skip the lines below, or leave a save stuck on "Saving…".
- try {
+ if (box) try {
if (window.MosaicMarkdown) box.replaceChildren(window.MosaicMarkdown.render(s.text));
else box.textContent = 'The preview did not load. The source is unchanged.';
} catch { box.textContent = 'The preview failed. The source is unchanged.'; }
@@ -788,6 +818,11 @@
}
const saveable = s => canEdit && !out() && !s.saving && s.text !== s.original && !s.raw.includes('\0');
document.addEventListener('input', e => { const s = docStates.get(docKey); if (e.target.id !== 'doc-text' || !s) return; s.text = e.target.value; s.status = ''; paintDoc(); });
+ document.addEventListener('click', e => {
+ const mode = { 'doc-mode-visual': 'visual', 'doc-mode-source': 'source' }[e.target.id], s = docStates.get(docKey);
+ if (!mode || !s || s.saving || mode === docShown) return;
+ docMode = mode; render(false, { reuseDraft: true });
+ });
document.addEventListener('click', e => { if (e.target.id !== 'doc-reload') return; const s = docStates.get(docKey); if (s?.saving) return; docStates.delete(docKey); render(true); });
document.addEventListener('submit', async e => {
if (e.target.id !== 'doc-form') return;
@@ -863,7 +898,7 @@
// ---------------------------------------------------------------- router
// #/ and anything that is not a #/ route is the control board; the rest is this file's.
const routeOf = () => location.hash.startsWith('#/') ? location.hash.slice(1) : '/';
- function view(get, path, q) {
+ function view(get, path, q, opts) {
const parts = path.split('/').filter(Boolean).map(p => { try { return decodeURIComponent(p); } catch { return null; } });
if (parts.includes(null)) return notFound();
const [a, b, c] = parts, n = parts.length;
@@ -878,7 +913,7 @@
if (a === 'business' && n === 1) return businessView(get);
if (a === 'settings' && n === 1) return settingsView(get);
if (a === 'docs' && n === 1) return docsView(get);
- if (a === 'docs' && n === 3) return docView(get, b, c);
+ if (a === 'docs' && n === 3) return docView(get, b, c, opts);
if (a === 'trail' && n === 3 && b === 'task') return TASK.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a task reference.`);
if (a === 'trail' && n === 3 && b === 'decision') return SAFE.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a decision id.`);
if (a === 'trail' && n === 3 && b === 'message') return SAFE.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a message id.`);
@@ -908,7 +943,7 @@
}
else if (k.h1) $('bus-view').querySelector('h1')?.focus({ preventScroll: true });
}
- async function render(navigated) {
+ async function render(navigated, opts = {}) {
// A refresh due while this render reads would replace it: a navigation would lose its heading focus.
clearTimeout(timer);
if (out()) return;
@@ -925,7 +960,7 @@
}
if (board) {
// The board page keeps its own title; the Inbox count still follows the bus.
- if (shown !== null) { shown = null; $('bus-view').innerHTML = ''; document.title = 'Mosaic Console'; if (navigated) $('main').focus(); }
+ if (shown !== null) { shown = null; unmountEditor(); $('bus-view').innerHTML = ''; document.title = 'Mosaic Console'; if (navigated) $('main').focus(); }
// The held roles (row 95) are read with it. A refusal of either forgets both, as on the bus pages.
const [inbox, agents, messages] = await Promise.allSettled([fetchRead('inbox'), fetchRead('agents'), fetchRead('messages')]);
const failed = [inbox, agents, messages].filter(s => s.status === 'rejected').map(s => s.reason);
@@ -942,7 +977,7 @@
sections(path); schedule();
return;
}
- if (navigated || shown !== route) { $('bus-view').innerHTML = loadingView(SOURCES[path.split('/')[1]]); }
+ if (navigated || shown !== route) { unmountEditor(); $('bus-view').innerHTML = loadingView(SOURCES[path.split('/')[1]]); }
let html, state = 'fresh';
const live = reader(true);
try {
@@ -950,17 +985,18 @@
try { await live('messages'); }
catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; }
}
- html = await view(live, path, new URLSearchParams(query)); readAt = live.oldest(); }
+ html = await view(live, path, new URLSearchParams(query), opts); readAt = live.oldest(); }
catch (err) {
if (err.code === 'signed-out') return;
const kept = reader(false);
- try { if (refusal(err)) throw err; html = await view(kept, path, new URLSearchParams(query)); readAt = kept.oldest(); html = staleBanner(err) + html; state = 'stale'; }
+ try { if (refusal(err)) throw err; html = await view(kept, path, new URLSearchParams(query), opts); readAt = kept.oldest(); html = staleBanner(err) + html; state = 'stale'; }
catch { html = failedView(err) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; }
if (refusal(err)) forget();
}
if (g !== gen) return;
freshBus(state, SOURCES[path.split('/')[1]]);
const k = !navigated && shown === route ? keep() : null;
+ unmountEditor();
$('bus-view').innerHTML = html; shown = route;
if (path.startsWith('/docs/')) paintDoc();
sections(path);
diff --git a/packages/webui/src/public/editor.css b/packages/webui/src/public/editor.css
new file mode 100644
index 000000000..70526aac3
--- /dev/null
+++ b/packages/webui/src/public/editor.css
@@ -0,0 +1,90 @@
+/* Built by editor/build.mjs: prosemirror-view/style/prosemirror.css, then editor/editor.css. Do not edit. */
+.ProseMirror {
+ position: relative;
+}
+
+.ProseMirror {
+ word-wrap: break-word;
+ white-space: pre-wrap;
+ white-space: break-spaces;
+ -webkit-font-variant-ligatures: none;
+ font-variant-ligatures: none;
+ font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
+}
+
+.ProseMirror pre {
+ white-space: pre-wrap;
+}
+
+.ProseMirror li {
+ position: relative;
+}
+
+.ProseMirror-hideselection *::selection { background: transparent; }
+.ProseMirror-hideselection *::-moz-selection { background: transparent; }
+.ProseMirror-hideselection { caret-color: transparent; }
+
+/* See https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1421#issuecomment-1759320191 */
+.ProseMirror [draggable][contenteditable=false] { user-select: text }
+
+.ProseMirror-selectednode {
+ outline: 2px solid #8cf;
+}
+
+/* Make sure li selections wrap around markers */
+
+li.ProseMirror-selectednode {
+ outline: none;
+}
+
+li.ProseMirror-selectednode:after {
+ content: "";
+ position: absolute;
+ left: -32px;
+ right: -2px; top: -2px; bottom: -2px;
+ border: 2px solid #8cf;
+ pointer-events: none;
+}
+
+/* Protect against generic img rules */
+
+img.ProseMirror-separator {
+ display: inline !important;
+ border: none !important;
+ margin: 0 !important;
+}
+
+/* Row 154 (#1648, Q168): the Console's visual editor. Colours come from the Console's own variables. */
+.ed-wrap { display: flex; flex-direction: column; min-width: 0; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); }
+.ed-toolbar { display: flex; flex-wrap: wrap; gap: 4px; padding: 6px; border-bottom: 1px solid var(--line); }
+.ed-btn { font: inherit; font-size: 12px; padding: 3px 8px; border-radius: 4px; border: 1px solid var(--line); background: transparent; color: inherit; cursor: pointer; }
+.ed-btn:hover:not(:disabled) { background: rgba(127, 127, 127, 0.18); }
+.ed-btn.on { background: rgba(127, 127, 127, 0.32); font-weight: 600; }
+.ed-btn:disabled { opacity: 0.4; cursor: default; }
+.ed-linkbar { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; padding: 6px; border-bottom: 1px solid var(--line); }
+.ed-linkbar[hidden] { display: none; }
+.ed-link-input { flex: 1 1 18em; min-width: 8em; font: inherit; padding: 3px 6px; }
+.ed-link-note { font-size: 12px; opacity: 0.85; }
+.ed-surface { min-width: 0; overflow: auto; }
+.ed-surface .ProseMirror { min-height: 16em; max-height: 70vh; overflow: auto; padding: 10px 14px; outline: none; line-height: 1.5; overflow-wrap: anywhere; white-space: pre-wrap; }
+.ed-surface .ProseMirror p { margin: 0 0 0.8em; }
+.ed-surface .ProseMirror h1, .ed-surface .ProseMirror h2, .ed-surface .ProseMirror h3,
+.ed-surface .ProseMirror h4, .ed-surface .ProseMirror h5, .ed-surface .ProseMirror h6 { margin: 0.9em 0 0.4em; line-height: 1.25; }
+.ed-surface .ProseMirror h1 { font-size: 1.6em; }
+.ed-surface .ProseMirror h2 { font-size: 1.35em; }
+.ed-surface .ProseMirror h3 { font-size: 1.15em; }
+.ed-surface .ProseMirror blockquote { margin: 0 0 0.8em; padding-left: 12px; border-left: 3px solid var(--line); opacity: 0.92; }
+.ed-surface .ProseMirror ul, .ed-surface .ProseMirror ol { margin: 0 0 0.8em; padding-left: 1.6em; }
+.ed-surface .ProseMirror li > p { margin-bottom: 0.3em; }
+.ed-surface .ProseMirror code { font-family: ui-monospace, monospace; font-size: 0.92em; padding: 0 3px; border-radius: 3px; background: rgba(127, 127, 127, 0.2); }
+.ed-surface .ProseMirror pre { margin: 0 0 0.8em; padding: 8px 10px; border-radius: 4px; background: rgba(127, 127, 127, 0.16); overflow: auto; white-space: pre; }
+.ed-surface .ProseMirror pre code { padding: 0; background: none; }
+.ed-surface .ProseMirror pre.md-raw { border-left: 3px solid #b8860b; }
+.ed-surface .ProseMirror hr { border: 0; border-top: 1px solid var(--line); margin: 1em 0; }
+.ed-surface .ProseMirror a { color: inherit; text-decoration: underline; }
+.ed-surface .ProseMirror .md-image { font-family: ui-monospace, monospace; font-size: 0.9em; padding: 0 3px; border: 1px dashed var(--line); border-radius: 3px; }
+.ed-surface .ProseMirror .md-bad-link { text-decoration: line-through; }
+.ed-surface .ProseMirror-selectednode { outline: 2px solid #5b9bd5; }
+.doc-mode { display: flex; gap: 6px; margin: 8px 0; }
+.doc-mode .btn[aria-pressed="true"] { background: var(--raised); font-weight: 600; }
+.doc-edit.one { grid-template-columns: minmax(0, 1fr); }
diff --git a/packages/webui/src/public/editor.js b/packages/webui/src/public/editor.js
new file mode 100644
index 000000000..942228c2b
--- /dev/null
+++ b/packages/webui/src/public/editor.js
@@ -0,0 +1,18704 @@
+(() => {
+ var __create = Object.create;
+ var __defProp = Object.defineProperty;
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __getProtoOf = Object.getPrototypeOf;
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
+ var __commonJS = (cb, mod) => function __require() {
+ try {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+ } catch (e) {
+ throw mod = 0, e;
+ }
+ };
+ var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+ };
+ var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+ };
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+ ));
+
+ // third_party/editor/punycode.js/punycode.js
+ var require_punycode = __commonJS({
+ "third_party/editor/punycode.js/punycode.js"(exports, module) {
+ "use strict";
+ var maxInt = 2147483647;
+ var base2 = 36;
+ var tMin = 1;
+ var tMax = 26;
+ var skew = 38;
+ var damp = 700;
+ var initialBias = 72;
+ var initialN = 128;
+ var delimiter = "-";
+ var regexPunycode = /^xn--/;
+ var regexNonASCII = /[^\0-\x7F]/;
+ var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
+ var errors = {
+ "overflow": "Overflow: input needs wider integers to process",
+ "not-basic": "Illegal input >= 0x80 (not a basic code point)",
+ "invalid-input": "Invalid input"
+ };
+ var baseMinusTMin = base2 - tMin;
+ var floor = Math.floor;
+ var stringFromCharCode = String.fromCharCode;
+ function error(type) {
+ throw new RangeError(errors[type]);
+ }
+ function map(array, callback) {
+ const result = [];
+ let length = array.length;
+ while (length--) {
+ result[length] = callback(array[length]);
+ }
+ return result;
+ }
+ function mapDomain(domain, callback) {
+ const parts = domain.split("@");
+ let result = "";
+ if (parts.length > 1) {
+ result = parts[0] + "@";
+ domain = parts[1];
+ }
+ domain = domain.replace(regexSeparators, ".");
+ const labels = domain.split(".");
+ const encoded = map(labels, callback).join(".");
+ return result + encoded;
+ }
+ function ucs2decode(string) {
+ const output = [];
+ let counter = 0;
+ const length = string.length;
+ while (counter < length) {
+ const value = string.charCodeAt(counter++);
+ if (value >= 55296 && value <= 56319 && counter < length) {
+ const extra = string.charCodeAt(counter++);
+ if ((extra & 64512) == 56320) {
+ output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
+ } else {
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
+ }
+ var ucs2encode = (codePoints) => String.fromCodePoint(...codePoints);
+ var basicToDigit = function(codePoint) {
+ if (codePoint >= 48 && codePoint < 58) {
+ return 26 + (codePoint - 48);
+ }
+ if (codePoint >= 65 && codePoint < 91) {
+ return codePoint - 65;
+ }
+ if (codePoint >= 97 && codePoint < 123) {
+ return codePoint - 97;
+ }
+ return base2;
+ };
+ var digitToBasic = function(digit, flag) {
+ return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
+ };
+ var adapt = function(delta, numPoints, firstTime) {
+ let k = 0;
+ delta = firstTime ? floor(delta / damp) : delta >> 1;
+ delta += floor(delta / numPoints);
+ for (; delta > baseMinusTMin * tMax >> 1; k += base2) {
+ delta = floor(delta / baseMinusTMin);
+ }
+ return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
+ };
+ var decode2 = function(input) {
+ const output = [];
+ const inputLength = input.length;
+ let i2 = 0;
+ let n = initialN;
+ let bias = initialBias;
+ let basic = input.lastIndexOf(delimiter);
+ if (basic < 0) {
+ basic = 0;
+ }
+ for (let j = 0; j < basic; ++j) {
+ if (input.charCodeAt(j) >= 128) {
+ error("not-basic");
+ }
+ output.push(input.charCodeAt(j));
+ }
+ for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
+ const oldi = i2;
+ for (let w = 1, k = base2; ; k += base2) {
+ if (index >= inputLength) {
+ error("invalid-input");
+ }
+ const digit = basicToDigit(input.charCodeAt(index++));
+ if (digit >= base2) {
+ error("invalid-input");
+ }
+ if (digit > floor((maxInt - i2) / w)) {
+ error("overflow");
+ }
+ i2 += digit * w;
+ const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
+ if (digit < t) {
+ break;
+ }
+ const baseMinusT = base2 - t;
+ if (w > floor(maxInt / baseMinusT)) {
+ error("overflow");
+ }
+ w *= baseMinusT;
+ }
+ const out = output.length + 1;
+ bias = adapt(i2 - oldi, out, oldi == 0);
+ if (floor(i2 / out) > maxInt - n) {
+ error("overflow");
+ }
+ n += floor(i2 / out);
+ i2 %= out;
+ output.splice(i2++, 0, n);
+ }
+ return String.fromCodePoint(...output);
+ };
+ var encode2 = function(input) {
+ const output = [];
+ input = ucs2decode(input);
+ const inputLength = input.length;
+ let n = initialN;
+ let delta = 0;
+ let bias = initialBias;
+ for (const currentValue of input) {
+ if (currentValue < 128) {
+ output.push(stringFromCharCode(currentValue));
+ }
+ }
+ const basicLength = output.length;
+ let handledCPCount = basicLength;
+ if (basicLength) {
+ output.push(delimiter);
+ }
+ while (handledCPCount < inputLength) {
+ let m = maxInt;
+ for (const currentValue of input) {
+ if (currentValue >= n && currentValue < m) {
+ m = currentValue;
+ }
+ }
+ const handledCPCountPlusOne = handledCPCount + 1;
+ if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
+ error("overflow");
+ }
+ delta += (m - n) * handledCPCountPlusOne;
+ n = m;
+ for (const currentValue of input) {
+ if (currentValue < n && ++delta > maxInt) {
+ error("overflow");
+ }
+ if (currentValue === n) {
+ let q = delta;
+ for (let k = base2; ; k += base2) {
+ const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
+ if (q < t) {
+ break;
+ }
+ const qMinusT = q - t;
+ const baseMinusT = base2 - t;
+ output.push(
+ stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
+ );
+ q = floor(qMinusT / baseMinusT);
+ }
+ output.push(stringFromCharCode(digitToBasic(q, 0)));
+ bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
+ delta = 0;
+ ++handledCPCount;
+ }
+ }
+ ++delta;
+ ++n;
+ }
+ return output.join("");
+ };
+ var toUnicode = function(input) {
+ return mapDomain(input, function(string) {
+ return regexPunycode.test(string) ? decode2(string.slice(4).toLowerCase()) : string;
+ });
+ };
+ var toASCII = function(input) {
+ return mapDomain(input, function(string) {
+ return regexNonASCII.test(string) ? "xn--" + encode2(string) : string;
+ });
+ };
+ var punycode2 = {
+ /**
+ * A string representing the current Punycode.js version number.
+ * @memberOf punycode
+ * @type String
+ */
+ "version": "2.3.1",
+ /**
+ * An object of methods to convert from JavaScript's internal character
+ * representation (UCS-2) to Unicode code points, and back.
+ * @see
+ * @memberOf punycode
+ * @type Object
+ */
+ "ucs2": {
+ "decode": ucs2decode,
+ "encode": ucs2encode
+ },
+ "decode": decode2,
+ "encode": encode2,
+ "toASCII": toASCII,
+ "toUnicode": toUnicode
+ };
+ module.exports = punycode2;
+ }
+ });
+
+ // third_party/editor/prosemirror-model/src/diff.ts
+ function findDiffStart(a, b, pos) {
+ for (let i2 = 0; ; i2++) {
+ if (i2 == a.childCount || i2 == b.childCount)
+ return a.childCount == b.childCount ? null : pos;
+ let childA = a.child(i2), childB = b.child(i2);
+ if (childA == childB) {
+ pos += childA.nodeSize;
+ continue;
+ }
+ if (!childA.sameMarkup(childB)) return pos;
+ if (childA.isText && childA.text != childB.text) {
+ let tA = childA.text, tB = childB.text, j = 0;
+ for (; tA[j] == tB[j]; j++) pos++;
+ if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j))) pos--;
+ return pos;
+ }
+ if (childA.content.size || childB.content.size) {
+ let inner = findDiffStart(childA.content, childB.content, pos + 1);
+ if (inner != null) return inner;
+ }
+ pos += childA.nodeSize;
+ }
+ }
+ function findDiffEnd(a, b, posA, posB) {
+ for (let iA = a.childCount, iB = b.childCount; ; ) {
+ if (iA == 0 || iB == 0)
+ return iA == iB ? null : { a: posA, b: posB };
+ let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;
+ if (childA == childB) {
+ posA -= size;
+ posB -= size;
+ continue;
+ }
+ if (!childA.sameMarkup(childB)) return { a: posA, b: posB };
+ if (childA.isText && childA.text != childB.text) {
+ let tA = childA.text, tB = childB.text, iA2 = tA.length, iB2 = tB.length;
+ while (iA2 > 0 && iB2 > 0 && tA[iA2 - 1] == tB[iB2 - 1]) {
+ iA2--;
+ iB2--;
+ posA--;
+ posB--;
+ }
+ if (iA2 && iB2 && iA2 < tA.length && surrogateHigh(tA.charCodeAt(iA2 - 1)) && surrogateLow(tA.charCodeAt(iA2))) {
+ posA++;
+ posB++;
+ }
+ return { a: posA, b: posB };
+ }
+ if (childA.content.size || childB.content.size) {
+ let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
+ if (inner) return inner;
+ }
+ posA -= size;
+ posB -= size;
+ }
+ }
+ function surrogateLow(ch) {
+ return ch >= 56320 && ch < 57344;
+ }
+ function surrogateHigh(ch) {
+ return ch >= 55296 && ch < 56320;
+ }
+
+ // third_party/editor/prosemirror-model/src/fragment.ts
+ var Fragment = class _Fragment {
+ /// @internal
+ constructor(content, size) {
+ this.content = content;
+ this.size = size || 0;
+ if (size == null) for (let i2 = 0; i2 < content.length; i2++)
+ this.size += content[i2].nodeSize;
+ }
+ content;
+ /// The size of the fragment, which is the total of the size of
+ /// its content nodes.
+ size;
+ /// Invoke a callback for all descendant nodes between the given two
+ /// positions (relative to start of this fragment). Doesn't descend
+ /// into a node when the callback returns `false`.
+ nodesBetween(from, to, f, nodeStart = 0, parent) {
+ for (let i2 = 0, pos = 0; pos < to; i2++) {
+ let child = this.content[i2], end = pos + child.nodeSize;
+ if (end > from && f(child, nodeStart + pos, parent || null, i2) !== false && child.content.size) {
+ let start = pos + 1;
+ child.nodesBetween(
+ Math.max(0, from - start),
+ Math.min(child.content.size, to - start),
+ f,
+ nodeStart + start
+ );
+ }
+ pos = end;
+ }
+ }
+ /// Call the given callback for every descendant node. `pos` will be
+ /// relative to the start of the fragment. The callback may return
+ /// `false` to prevent traversal of a given node's children.
+ descendants(f) {
+ this.nodesBetween(0, this.size, f);
+ }
+ /// Extract the text between `from` and `to`. See the same method on
+ /// [`Node`](#model.Node.textBetween).
+ textBetween(from, to, blockSeparator, leafText) {
+ let text2 = "", first = true;
+ this.nodesBetween(from, to, (node, pos) => {
+ let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : "";
+ if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
+ if (first) first = false;
+ else text2 += blockSeparator;
+ }
+ text2 += nodeText;
+ }, 0);
+ return text2;
+ }
+ /// Create a new fragment containing the combined content of this
+ /// fragment and the other.
+ append(other) {
+ if (!other.size) return this;
+ if (!this.size) return other;
+ let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i2 = 0;
+ if (last.isText && last.sameMarkup(first)) {
+ content[content.length - 1] = last.withText(last.text + first.text);
+ i2 = 1;
+ }
+ for (; i2 < other.content.length; i2++) content.push(other.content[i2]);
+ return new _Fragment(content, this.size + other.size);
+ }
+ /// Cut out the sub-fragment between the two given positions.
+ cut(from, to = this.size) {
+ if (from == 0 && to == this.size) return this;
+ let result = [], size = 0;
+ if (to > from) for (let i2 = 0, pos = 0; pos < to; i2++) {
+ let child = this.content[i2], end = pos + child.nodeSize;
+ if (end > from) {
+ if (pos < from || end > to) {
+ if (child.isText)
+ child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));
+ else
+ child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));
+ }
+ result.push(child);
+ size += child.nodeSize;
+ }
+ pos = end;
+ }
+ return new _Fragment(result, size);
+ }
+ /// @internal
+ cutByIndex(from, to) {
+ if (from == to) return _Fragment.empty;
+ if (from == 0 && to == this.content.length) return this;
+ return new _Fragment(this.content.slice(from, to));
+ }
+ /// Create a new fragment in which the node at the given index is
+ /// replaced by the given node.
+ replaceChild(index, node) {
+ let current = this.content[index];
+ if (current == node) return this;
+ let copy2 = this.content.slice();
+ let size = this.size + node.nodeSize - current.nodeSize;
+ copy2[index] = node;
+ return new _Fragment(copy2, size);
+ }
+ /// Create a new fragment by prepending the given node to this
+ /// fragment.
+ addToStart(node) {
+ return new _Fragment([node].concat(this.content), this.size + node.nodeSize);
+ }
+ /// Create a new fragment by appending the given node to this
+ /// fragment.
+ addToEnd(node) {
+ return new _Fragment(this.content.concat(node), this.size + node.nodeSize);
+ }
+ /// Compare this fragment to another one.
+ eq(other) {
+ if (this.content.length != other.content.length) return false;
+ for (let i2 = 0; i2 < this.content.length; i2++)
+ if (!this.content[i2].eq(other.content[i2])) return false;
+ return true;
+ }
+ /// The first child of the fragment, or `null` if it is empty.
+ get firstChild() {
+ return this.content.length ? this.content[0] : null;
+ }
+ /// The last child of the fragment, or `null` if it is empty.
+ get lastChild() {
+ return this.content.length ? this.content[this.content.length - 1] : null;
+ }
+ /// The number of child nodes in this fragment.
+ get childCount() {
+ return this.content.length;
+ }
+ /// Get the child node at the given index. Raise an error when the
+ /// index is out of range.
+ child(index) {
+ let found2 = this.content[index];
+ if (!found2) throw new RangeError("Index " + index + " out of range for " + this);
+ return found2;
+ }
+ /// Get the child node at the given index, if it exists.
+ maybeChild(index) {
+ return this.content[index] || null;
+ }
+ /// Call `f` for every child node, passing the node, its offset
+ /// into this parent node, and its index.
+ forEach(f) {
+ for (let i2 = 0, p = 0; i2 < this.content.length; i2++) {
+ let child = this.content[i2];
+ f(child, p, i2);
+ p += child.nodeSize;
+ }
+ }
+ /// Find the first position at which this fragment and another
+ /// fragment differ, or `null` if they are the same.
+ findDiffStart(other, pos = 0) {
+ return findDiffStart(this, other, pos);
+ }
+ /// Find the first position, searching from the end, at which this
+ /// fragment and the given fragment differ, or `null` if they are
+ /// the same. Since this position will not be the same in both
+ /// nodes, an object with two separate positions is returned.
+ findDiffEnd(other, pos = this.size, otherPos = other.size) {
+ return findDiffEnd(this, other, pos, otherPos);
+ }
+ /// Find the index and inner offset corresponding to a given relative
+ /// position in this fragment. The result object will be reused
+ /// (overwritten) the next time the function is called. @internal
+ findIndex(pos) {
+ if (pos == 0) return retIndex(0, pos);
+ if (pos == this.size) return retIndex(this.content.length, pos);
+ if (pos > this.size || pos < 0) throw new RangeError(`Position ${pos} outside of fragment (${this})`);
+ for (let i2 = 0, curPos = 0; ; i2++) {
+ let cur = this.child(i2), end = curPos + cur.nodeSize;
+ if (end >= pos) {
+ if (end == pos) return retIndex(i2 + 1, end);
+ return retIndex(i2, curPos);
+ }
+ curPos = end;
+ }
+ }
+ /// Return a debugging string that describes this fragment.
+ toString() {
+ return "<" + this.toStringInner() + ">";
+ }
+ /// @internal
+ toStringInner() {
+ return this.content.join(", ");
+ }
+ /// Create a JSON-serializeable representation of this fragment.
+ toJSON() {
+ return this.content.length ? this.content.map((n) => n.toJSON()) : null;
+ }
+ /// Deserialize a fragment from its JSON representation.
+ static fromJSON(schema3, value) {
+ if (!value) return _Fragment.empty;
+ if (!Array.isArray(value)) throw new RangeError("Invalid input for Fragment.fromJSON");
+ return _Fragment.fromArray(value.map(schema3.nodeFromJSON));
+ }
+ /// Build a fragment from an array of nodes. Ensures that adjacent
+ /// text nodes with the same marks are joined together.
+ static fromArray(array) {
+ if (!array.length) return _Fragment.empty;
+ let joined, size = 0;
+ for (let i2 = 0; i2 < array.length; i2++) {
+ let node = array[i2];
+ size += node.nodeSize;
+ if (i2 && node.isText && array[i2 - 1].sameMarkup(node)) {
+ if (!joined) joined = array.slice(0, i2);
+ joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);
+ } else if (joined) {
+ joined.push(node);
+ }
+ }
+ return new _Fragment(joined || array, size);
+ }
+ /// Create a fragment from something that can be interpreted as a
+ /// set of nodes. For `null`, it returns the empty fragment. For a
+ /// fragment, the fragment itself. For a node or array of nodes, a
+ /// fragment containing those nodes.
+ static from(nodes) {
+ if (!nodes) return _Fragment.empty;
+ if (nodes instanceof _Fragment) return nodes;
+ if (Array.isArray(nodes)) return this.fromArray(nodes);
+ if (nodes.attrs) return new _Fragment([nodes], nodes.nodeSize);
+ throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
+ }
+ /// An empty fragment. Intended to be reused whenever a node doesn't
+ /// contain anything (rather than allocating a new empty fragment for
+ /// each leaf node).
+ static empty = new _Fragment([], 0);
+ };
+ var found = { index: 0, offset: 0 };
+ function retIndex(index, offset) {
+ found.index = index;
+ found.offset = offset;
+ return found;
+ }
+
+ // third_party/editor/prosemirror-model/src/comparedeep.ts
+ function compareDeep(a, b) {
+ if (a === b) return true;
+ if (!(a && typeof a == "object") || !(b && typeof b == "object")) return false;
+ let array = Array.isArray(a);
+ if (Array.isArray(b) != array) return false;
+ if (array) {
+ if (a.length != b.length) return false;
+ for (let i2 = 0; i2 < a.length; i2++) if (!compareDeep(a[i2], b[i2])) return false;
+ } else {
+ for (let p in a) if (!(p in b) || !compareDeep(a[p], b[p])) return false;
+ for (let p in b) if (!(p in a)) return false;
+ }
+ return true;
+ }
+
+ // third_party/editor/prosemirror-model/src/mark.ts
+ var Mark = class _Mark {
+ /// @internal
+ constructor(type, attrs2) {
+ this.type = type;
+ this.attrs = attrs2;
+ }
+ type;
+ attrs;
+ /// Given a set of marks, create a new set which contains this one as
+ /// well, in the right position. If this mark is already in the set,
+ /// the set itself is returned. If any marks that are set to be
+ /// [exclusive](#model.MarkSpec.excludes) with this mark are present,
+ /// those are replaced by this one.
+ addToSet(set2) {
+ let copy2, placed = false;
+ for (let i2 = 0; i2 < set2.length; i2++) {
+ let other = set2[i2];
+ if (this.eq(other)) return set2;
+ if (this.type.excludes(other.type)) {
+ if (!copy2) copy2 = set2.slice(0, i2);
+ } else if (other.type.excludes(this.type)) {
+ return set2;
+ } else {
+ if (!placed && other.type.rank > this.type.rank) {
+ if (!copy2) copy2 = set2.slice(0, i2);
+ copy2.push(this);
+ placed = true;
+ }
+ if (copy2) copy2.push(other);
+ }
+ }
+ if (!copy2) copy2 = set2.slice();
+ if (!placed) copy2.push(this);
+ return copy2;
+ }
+ /// Remove this mark from the given set, returning a new set. If this
+ /// mark is not in the set, the set itself is returned.
+ removeFromSet(set2) {
+ for (let i2 = 0; i2 < set2.length; i2++)
+ if (this.eq(set2[i2]))
+ return set2.slice(0, i2).concat(set2.slice(i2 + 1));
+ return set2;
+ }
+ /// Test whether this mark is in the given set of marks.
+ isInSet(set2) {
+ for (let i2 = 0; i2 < set2.length; i2++)
+ if (this.eq(set2[i2])) return true;
+ return false;
+ }
+ /// Test whether this mark has the same type and attributes as
+ /// another mark.
+ eq(other) {
+ return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
+ }
+ /// Convert this mark to a JSON-serializeable representation.
+ toJSON() {
+ let obj = { type: this.type.name };
+ for (let _ in this.attrs) {
+ obj.attrs = this.attrs;
+ break;
+ }
+ return obj;
+ }
+ /// Deserialize a mark from JSON.
+ static fromJSON(schema3, json) {
+ if (!json) throw new RangeError("Invalid input for Mark.fromJSON");
+ let type = schema3.marks[json.type];
+ if (!type) throw new RangeError(`There is no mark type ${json.type} in this schema`);
+ let mark = type.create(json.attrs);
+ return mark;
+ }
+ /// Test whether two sets of marks are identical.
+ static sameSet(a, b) {
+ if (a == b) return true;
+ if (a.length != b.length) return false;
+ for (let i2 = 0; i2 < a.length; i2++)
+ if (!a[i2].eq(b[i2])) return false;
+ return true;
+ }
+ /// Create a properly sorted mark set from null, a single mark, or an
+ /// unsorted array of marks.
+ static setFrom(marks) {
+ if (!marks || Array.isArray(marks) && marks.length == 0) return _Mark.none;
+ if (marks instanceof _Mark) return [marks];
+ let copy2 = marks.slice();
+ copy2.sort((a, b) => a.type.rank - b.type.rank);
+ return copy2;
+ }
+ /// The empty set of marks.
+ static none = [];
+ };
+
+ // third_party/editor/prosemirror-model/src/replace.ts
+ var ReplaceError = class extends Error {
+ };
+ var Slice = class _Slice {
+ /// Create a slice. When specifying a non-zero open depth, you must
+ /// make sure that there are nodes of at least that depth at the
+ /// appropriate side of the fragment—i.e. if the fragment is an
+ /// empty paragraph node, `openStart` and `openEnd` can't be greater
+ /// than 1.
+ ///
+ /// It is not necessary for the content of open nodes to conform to
+ /// the schema's content constraints, though it should be a valid
+ /// start/end/middle for such a node, depending on which sides are
+ /// open.
+ constructor(content, openStart, openEnd) {
+ this.content = content;
+ this.openStart = openStart;
+ this.openEnd = openEnd;
+ }
+ content;
+ openStart;
+ openEnd;
+ /// The size this slice would add when inserted into a document.
+ get size() {
+ return this.content.size - this.openStart - this.openEnd;
+ }
+ /// @internal
+ insertAt(pos, fragment) {
+ let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1);
+ return content && new _Slice(content, this.openStart, this.openEnd);
+ }
+ /// @internal
+ removeBetween(from, to) {
+ return new _Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);
+ }
+ /// Tests whether this slice is equal to another slice.
+ eq(other) {
+ return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
+ }
+ /// @internal
+ toString() {
+ return this.content + "(" + this.openStart + "," + this.openEnd + ")";
+ }
+ /// Convert a slice to a JSON-serializable representation.
+ toJSON() {
+ if (!this.content.size) return null;
+ let json = { content: this.content.toJSON() };
+ if (this.openStart > 0) json.openStart = this.openStart;
+ if (this.openEnd > 0) json.openEnd = this.openEnd;
+ return json;
+ }
+ /// Deserialize a slice from its JSON representation.
+ static fromJSON(schema3, json) {
+ if (!json) return _Slice.empty;
+ let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
+ if (typeof openStart != "number" || typeof openEnd != "number")
+ throw new RangeError("Invalid input for Slice.fromJSON");
+ return new _Slice(Fragment.fromJSON(schema3, json.content), openStart, openEnd);
+ }
+ /// Create a slice from a fragment by taking the maximum possible
+ /// open value on both side of the fragment.
+ static maxOpen(fragment, openIsolating = true) {
+ let openStart = 0, openEnd = 0;
+ for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) openStart++;
+ for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) openEnd++;
+ return new _Slice(fragment, openStart, openEnd);
+ }
+ /// The empty slice.
+ static empty = new _Slice(Fragment.empty, 0, 0);
+ };
+ function removeRange(content, from, to) {
+ let { index, offset } = content.findIndex(from), child = content.maybeChild(index);
+ let { index: indexTo, offset: offsetTo } = content.findIndex(to);
+ if (offset == from || child.isText) {
+ if (offsetTo != to && !content.child(indexTo).isText) throw new RangeError("Removing non-flat range");
+ return content.cut(0, from).append(content.cut(to));
+ }
+ if (index != indexTo) throw new RangeError("Removing non-flat range");
+ return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));
+ }
+ function insertInto(content, dist, insert, openStart, openEnd, parent) {
+ let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);
+ if (offset == dist || child.isText) {
+ if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert)) return null;
+ return content.cut(0, dist).append(insert).append(content.cut(dist));
+ }
+ let inner = insertInto(
+ child.content,
+ dist - offset - 1,
+ insert,
+ index == 0 ? openStart - 1 : 0,
+ index == content.childCount - 1 ? openEnd - 1 : 0,
+ child
+ );
+ return inner && content.replaceChild(index, child.copy(inner));
+ }
+ function replace($from, $to, slice) {
+ if (slice.openStart > $from.depth)
+ throw new ReplaceError("Inserted content deeper than insertion position");
+ if ($from.depth - slice.openStart != $to.depth - slice.openEnd)
+ throw new ReplaceError("Inconsistent open depths");
+ return replaceOuter($from, $to, slice, 0);
+ }
+ function replaceOuter($from, $to, slice, depth) {
+ let index = $from.index(depth), node = $from.node(depth);
+ if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
+ let inner = replaceOuter($from, $to, slice, depth + 1);
+ return node.copy(node.content.replaceChild(index, inner));
+ } else if (!slice.content.size) {
+ return close(node, replaceTwoWay($from, $to, depth));
+ } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) {
+ let parent = $from.parent, content = parent.content;
+ return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));
+ } else {
+ let { start, end } = prepareSliceForReplace(slice, $from);
+ return close(node, replaceThreeWay($from, start, end, $to, depth));
+ }
+ }
+ function checkJoin(main, sub) {
+ if (!sub.type.compatibleContent(main.type))
+ throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
+ }
+ function joinable($before, $after, depth) {
+ let node = $before.node(depth);
+ checkJoin(node, $after.node(depth));
+ return node;
+ }
+ function addNode(child, target) {
+ let last = target.length - 1;
+ if (last >= 0 && child.isText && child.sameMarkup(target[last]))
+ target[last] = child.withText(target[last].text + child.text);
+ else
+ target.push(child);
+ }
+ function addRange($start, $end, depth, target) {
+ let node = ($end || $start).node(depth);
+ let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
+ if ($start) {
+ startIndex = $start.index(depth);
+ if ($start.depth > depth) {
+ startIndex++;
+ } else if ($start.textOffset) {
+ addNode($start.nodeAfter, target);
+ startIndex++;
+ }
+ }
+ for (let i2 = startIndex; i2 < endIndex; i2++) addNode(node.child(i2), target);
+ if ($end && $end.depth == depth && $end.textOffset)
+ addNode($end.nodeBefore, target);
+ }
+ function close(node, content) {
+ if (!node.type.validContent(content))
+ throw new ReplaceError("Invalid content for node " + node.type.name);
+ return node.copy(content);
+ }
+ function replaceThreeWay($from, $start, $end, $to, depth) {
+ let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
+ let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
+ let content = [];
+ addRange(null, $from, depth, content);
+ if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
+ checkJoin(openStart, openEnd);
+ addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
+ } else {
+ if (openStart)
+ addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
+ addRange($start, $end, depth, content);
+ if (openEnd)
+ addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
+ }
+ addRange($to, null, depth, content);
+ return new Fragment(content);
+ }
+ function replaceTwoWay($from, $to, depth) {
+ let content = [];
+ addRange(null, $from, depth, content);
+ if ($from.depth > depth) {
+ let type = joinable($from, $to, depth + 1);
+ addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
+ }
+ addRange($to, null, depth, content);
+ return new Fragment(content);
+ }
+ function prepareSliceForReplace(slice, $along) {
+ let extra = $along.depth - slice.openStart, parent = $along.node(extra);
+ let node = parent.copy(slice.content);
+ for (let i2 = extra - 1; i2 >= 0; i2--)
+ node = $along.node(i2).copy(Fragment.from(node));
+ return {
+ start: node.resolveNoCache(slice.openStart + extra),
+ end: node.resolveNoCache(node.content.size - slice.openEnd - extra)
+ };
+ }
+
+ // third_party/editor/prosemirror-model/src/resolvedpos.ts
+ var ResolvedPos = class _ResolvedPos {
+ /// @internal
+ constructor(pos, path, parentOffset) {
+ this.pos = pos;
+ this.path = path;
+ this.parentOffset = parentOffset;
+ this.depth = path.length / 3 - 1;
+ }
+ pos;
+ path;
+ parentOffset;
+ /// The number of levels the parent node is from the root. If this
+ /// position points directly into the root node, it is 0. If it
+ /// points into a top-level paragraph, 1, and so on.
+ depth;
+ /// @internal
+ resolveDepth(val) {
+ if (val == null) return this.depth;
+ if (val < 0) return this.depth + val;
+ return val;
+ }
+ /// The parent node that the position points into. Note that even if
+ /// a position points into a text node, that node is not considered
+ /// the parent—text nodes are ‘flat’ in this model, and have no content.
+ get parent() {
+ return this.node(this.depth);
+ }
+ /// The root node in which the position was resolved.
+ get doc() {
+ return this.node(0);
+ }
+ /// The ancestor node at the given level. `p.node(p.depth)` is the
+ /// same as `p.parent`.
+ node(depth) {
+ return this.path[this.resolveDepth(depth) * 3];
+ }
+ /// The index into the ancestor at the given level. If this points
+ /// at the 3rd node in the 2nd paragraph on the top level, for
+ /// example, `p.index(0)` is 1 and `p.index(1)` is 2.
+ index(depth) {
+ return this.path[this.resolveDepth(depth) * 3 + 1];
+ }
+ /// The index pointing after this position into the ancestor at the
+ /// given level.
+ indexAfter(depth) {
+ depth = this.resolveDepth(depth);
+ return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
+ }
+ /// The (absolute) position at the start of the node at the given
+ /// level.
+ start(depth) {
+ depth = this.resolveDepth(depth);
+ return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
+ }
+ /// The (absolute) position at the end of the node at the given
+ /// level.
+ end(depth) {
+ depth = this.resolveDepth(depth);
+ return this.start(depth) + this.node(depth).content.size;
+ }
+ /// The (absolute) position directly before the wrapping node at the
+ /// given level, or, when `depth` is `this.depth + 1`, the original
+ /// position.
+ before(depth) {
+ depth = this.resolveDepth(depth);
+ if (!depth) throw new RangeError("There is no position before the top-level node");
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
+ }
+ /// The (absolute) position directly after the wrapping node at the
+ /// given level, or the original position when `depth` is `this.depth + 1`.
+ after(depth) {
+ depth = this.resolveDepth(depth);
+ if (!depth) throw new RangeError("There is no position after the top-level node");
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
+ }
+ /// When this position points into a text node, this returns the
+ /// distance between the position and the start of the text node.
+ /// Will be zero for positions that point between nodes.
+ get textOffset() {
+ return this.pos - this.path[this.path.length - 1];
+ }
+ /// Get the node directly after the position, if any. If the position
+ /// points into a text node, only the part of that node after the
+ /// position is returned.
+ get nodeAfter() {
+ let parent = this.parent, index = this.index(this.depth);
+ if (index == parent.childCount) return null;
+ let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);
+ return dOff ? parent.child(index).cut(dOff) : child;
+ }
+ /// Get the node directly before the position, if any. If the
+ /// position points into a text node, only the part of that node
+ /// before the position is returned.
+ get nodeBefore() {
+ let index = this.index(this.depth);
+ let dOff = this.pos - this.path[this.path.length - 1];
+ if (dOff) return this.parent.child(index).cut(0, dOff);
+ return index == 0 ? null : this.parent.child(index - 1);
+ }
+ /// Get the position at the given index in the parent node at the
+ /// given depth (which defaults to `this.depth`).
+ posAtIndex(index, depth) {
+ depth = this.resolveDepth(depth);
+ let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
+ for (let i2 = 0; i2 < index; i2++) pos += node.child(i2).nodeSize;
+ return pos;
+ }
+ /// Get the marks at this position, factoring in the surrounding
+ /// marks' [`inclusive`](#model.MarkSpec.inclusive) property. If the
+ /// position is at the start of a non-empty node, the marks of the
+ /// node after it (if any) are returned.
+ marks() {
+ let parent = this.parent, index = this.index();
+ if (parent.content.size == 0) return Mark.none;
+ if (this.textOffset) return parent.child(index).marks;
+ let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);
+ if (!main) {
+ let tmp = main;
+ main = other;
+ other = tmp;
+ }
+ let marks = main.marks;
+ for (var i2 = 0; i2 < marks.length; i2++)
+ if (marks[i2].type.spec.inclusive === false && (!other || !marks[i2].isInSet(other.marks)))
+ marks = marks[i2--].removeFromSet(marks);
+ return marks;
+ }
+ /// Get the marks after the current position, if any, except those
+ /// that are non-inclusive and not present at position `$end`. This
+ /// is mostly useful for getting the set of marks to preserve after a
+ /// deletion. Will return `null` if this position is at the end of
+ /// its parent node or its parent node isn't a textblock (in which
+ /// case no marks should be preserved).
+ marksAcross($end) {
+ let after = this.parent.maybeChild(this.index());
+ if (!after || !after.isInline) return null;
+ let marks = after.marks, next = $end.parent.maybeChild($end.index());
+ for (var i2 = 0; i2 < marks.length; i2++)
+ if (marks[i2].type.spec.inclusive === false && (!next || !marks[i2].isInSet(next.marks)))
+ marks = marks[i2--].removeFromSet(marks);
+ return marks;
+ }
+ /// The depth up to which this position and the given (non-resolved)
+ /// position share the same parent nodes.
+ sharedDepth(pos) {
+ for (let depth = this.depth; depth > 0; depth--)
+ if (this.start(depth) <= pos && this.end(depth) >= pos) return depth;
+ return 0;
+ }
+ /// Returns a range based on the place where this position and the
+ /// given position diverge around block content. If both point into
+ /// the same textblock, for example, a range around that textblock
+ /// will be returned. If they point into different blocks, the range
+ /// around those blocks in their shared ancestor is returned. You can
+ /// pass in an optional predicate that will be called with a parent
+ /// node to see if a range into that parent is acceptable.
+ blockRange(other = this, pred) {
+ if (other.pos < this.pos) return other.blockRange(this);
+ for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)
+ if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))
+ return new NodeRange(this, other, d);
+ return null;
+ }
+ /// Query whether the given position shares the same parent node.
+ sameParent(other) {
+ return this.pos - this.parentOffset == other.pos - other.parentOffset;
+ }
+ /// Return the greater of this and the given position.
+ max(other) {
+ return other.pos > this.pos ? other : this;
+ }
+ /// Return the smaller of this and the given position.
+ min(other) {
+ return other.pos < this.pos ? other : this;
+ }
+ /// @internal
+ toString() {
+ let str = "";
+ for (let i2 = 1; i2 <= this.depth; i2++)
+ str += (str ? "/" : "") + this.node(i2).type.name + "_" + this.index(i2 - 1);
+ return str + ":" + this.parentOffset;
+ }
+ /// @internal
+ static resolve(doc3, pos) {
+ if (!(pos >= 0 && pos <= doc3.content.size)) throw new RangeError("Position " + pos + " out of range");
+ let path = [];
+ let start = 0, parentOffset = pos;
+ for (let node = doc3; ; ) {
+ let { index, offset } = node.content.findIndex(parentOffset);
+ let rem = parentOffset - offset;
+ path.push(node, index, start + offset);
+ if (!rem) break;
+ node = node.child(index);
+ if (node.isText) break;
+ parentOffset = rem - 1;
+ start += offset + 1;
+ }
+ return new _ResolvedPos(pos, path, parentOffset);
+ }
+ /// @internal
+ static resolveCached(doc3, pos) {
+ let cache = resolveCache.get(doc3);
+ if (cache) {
+ for (let i2 = 0; i2 < cache.elts.length; i2++) {
+ let elt = cache.elts[i2];
+ if (elt.pos == pos) return elt;
+ }
+ } else {
+ resolveCache.set(doc3, cache = new ResolveCache());
+ }
+ let result = cache.elts[cache.i] = _ResolvedPos.resolve(doc3, pos);
+ cache.i = (cache.i + 1) % resolveCacheSize;
+ return result;
+ }
+ };
+ var ResolveCache = class {
+ elts = [];
+ i = 0;
+ };
+ var resolveCacheSize = 12;
+ var resolveCache = /* @__PURE__ */ new WeakMap();
+ var NodeRange = class {
+ /// Construct a node range. `$from` and `$to` should point into the
+ /// same node until at least the given `depth`, since a node range
+ /// denotes an adjacent set of nodes in a single parent node.
+ constructor($from, $to, depth) {
+ this.$from = $from;
+ this.$to = $to;
+ this.depth = depth;
+ }
+ $from;
+ $to;
+ depth;
+ /// The position at the start of the range.
+ get start() {
+ return this.$from.before(this.depth + 1);
+ }
+ /// The position at the end of the range.
+ get end() {
+ return this.$to.after(this.depth + 1);
+ }
+ /// The parent node that the range points into.
+ get parent() {
+ return this.$from.node(this.depth);
+ }
+ /// The start index of the range in the parent node.
+ get startIndex() {
+ return this.$from.index(this.depth);
+ }
+ /// The end index of the range in the parent node.
+ get endIndex() {
+ return this.$to.indexAfter(this.depth);
+ }
+ };
+
+ // third_party/editor/prosemirror-model/src/node.ts
+ var emptyAttrs = /* @__PURE__ */ Object.create(null);
+ var Node = class _Node {
+ /// @internal
+ constructor(type, attrs2, content, marks = Mark.none) {
+ this.type = type;
+ this.attrs = attrs2;
+ this.marks = marks;
+ this.content = content || Fragment.empty;
+ }
+ type;
+ attrs;
+ marks;
+ /// A container holding the node's children.
+ content;
+ /// The array of this node's child nodes.
+ get children() {
+ return this.content.content;
+ }
+ /// For text nodes, this contains the node's text content.
+ text;
+ /// The size of this node, as defined by the integer-based [indexing
+ /// scheme](/docs/guide/#doc.indexing). For text nodes, this is the
+ /// amount of characters. For other leaf nodes, it is one. For
+ /// non-leaf nodes, it is the size of the content plus two (the
+ /// start and end token).
+ get nodeSize() {
+ return this.isLeaf ? 1 : 2 + this.content.size;
+ }
+ /// The number of children that the node has.
+ get childCount() {
+ return this.content.childCount;
+ }
+ /// Get the child node at the given index. Raises an error when the
+ /// index is out of range.
+ child(index) {
+ return this.content.child(index);
+ }
+ /// Get the child node at the given index, if it exists.
+ maybeChild(index) {
+ return this.content.maybeChild(index);
+ }
+ /// Call `f` for every child node, passing the node, its offset
+ /// into this parent node, and its index.
+ forEach(f) {
+ this.content.forEach(f);
+ }
+ /// Invoke a callback for all descendant nodes recursively overlapping
+ /// the given two positions that are relative to start of this
+ /// node's content. This includes all ancestors of the nodes
+ /// containing the two positions. The callback is invoked with the
+ /// node, its position relative to the original node (method receiver),
+ /// its parent node, and its child index. When the callback returns
+ /// false for a given node, that node's children will not be
+ /// recursed over. The last parameter can be used to specify a
+ /// starting position to count from.
+ nodesBetween(from, to, f, startPos = 0) {
+ this.content.nodesBetween(from, to, f, startPos, this);
+ }
+ /// Call the given callback for every descendant node. Doesn't
+ /// descend into a node when the callback returns `false`.
+ descendants(f) {
+ this.nodesBetween(0, this.content.size, f);
+ }
+ /// Concatenates all the text nodes found in this fragment and its
+ /// children.
+ get textContent() {
+ return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
+ }
+ /// Get all text between positions `from` and `to`. When
+ /// `blockSeparator` is given, it will be inserted to separate text
+ /// from different block nodes. If `leafText` is given, it'll be
+ /// inserted for every non-text leaf node encountered, otherwise
+ /// [`leafText`](#model.NodeSpec.leafText) will be used.
+ textBetween(from, to, blockSeparator, leafText) {
+ return this.content.textBetween(from, to, blockSeparator, leafText);
+ }
+ /// Returns this node's first child, or `null` if there are no
+ /// children.
+ get firstChild() {
+ return this.content.firstChild;
+ }
+ /// Returns this node's last child, or `null` if there are no
+ /// children.
+ get lastChild() {
+ return this.content.lastChild;
+ }
+ /// Test whether two nodes represent the same piece of document.
+ eq(other) {
+ return this == other || this.sameMarkup(other) && this.content.eq(other.content);
+ }
+ /// Compare the markup (type, attributes, and marks) of this node to
+ /// those of another. Returns `true` if both have the same markup.
+ sameMarkup(other) {
+ return this.hasMarkup(other.type, other.attrs, other.marks);
+ }
+ /// Check whether this node's markup correspond to the given type,
+ /// attributes, and marks.
+ hasMarkup(type, attrs2, marks) {
+ return this.type == type && compareDeep(this.attrs, attrs2 || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);
+ }
+ /// Create a new node with the same markup as this node, containing
+ /// the given content (or empty, if no content is given).
+ copy(content = null) {
+ if (content == this.content) return this;
+ return new _Node(this.type, this.attrs, content, this.marks);
+ }
+ /// Create a copy of this node, with the given set of marks instead
+ /// of the node's own marks.
+ mark(marks) {
+ return marks == this.marks ? this : new _Node(this.type, this.attrs, this.content, marks);
+ }
+ /// Create a copy of this node with only the content between the
+ /// given positions. If `to` is not given, it defaults to the end of
+ /// the node.
+ cut(from, to = this.content.size) {
+ if (from == 0 && to == this.content.size) return this;
+ return this.copy(this.content.cut(from, to));
+ }
+ /// Cut out the part of the document between the given positions, and
+ /// return it as a `Slice` object.
+ slice(from, to = this.content.size, includeParents = false) {
+ if (from == to) return Slice.empty;
+ let $from = this.resolve(from), $to = this.resolve(to);
+ let depth = includeParents ? 0 : $from.sharedDepth(to);
+ let start = $from.start(depth), node = $from.node(depth);
+ let content = node.content.cut($from.pos - start, $to.pos - start);
+ return new Slice(content, $from.depth - depth, $to.depth - depth);
+ }
+ /// Replace the part of the document between the given positions with
+ /// the given slice. The slice must 'fit', meaning its open sides
+ /// must be able to connect to the surrounding content, and its
+ /// content nodes must be valid children for the node they are placed
+ /// into. If any of this is violated, an error of type
+ /// [`ReplaceError`](#model.ReplaceError) is thrown.
+ replace(from, to, slice) {
+ return replace(this.resolve(from), this.resolve(to), slice);
+ }
+ /// Find the node directly after the given position.
+ nodeAt(pos) {
+ for (let node = this; ; ) {
+ let { index, offset } = node.content.findIndex(pos);
+ node = node.maybeChild(index);
+ if (!node) return null;
+ if (offset == pos || node.isText) return node;
+ pos -= offset + 1;
+ }
+ }
+ /// Find the (direct) child node after the given offset, if any,
+ /// and return it along with its index and offset relative to this
+ /// node.
+ childAfter(pos) {
+ let { index, offset } = this.content.findIndex(pos);
+ return { node: this.content.maybeChild(index), index, offset };
+ }
+ /// Find the (direct) child node before the given offset, if any,
+ /// and return it along with its index and offset relative to this
+ /// node.
+ childBefore(pos) {
+ if (pos == 0) return { node: null, index: 0, offset: 0 };
+ let { index, offset } = this.content.findIndex(pos);
+ if (offset < pos) return { node: this.content.child(index), index, offset };
+ let node = this.content.child(index - 1);
+ return { node, index: index - 1, offset: offset - node.nodeSize };
+ }
+ /// Resolve the given position in the document, returning an
+ /// [object](#model.ResolvedPos) with information about its context.
+ resolve(pos) {
+ return ResolvedPos.resolveCached(this, pos);
+ }
+ /// @internal
+ resolveNoCache(pos) {
+ return ResolvedPos.resolve(this, pos);
+ }
+ /// Test whether a given mark or mark type occurs in this document
+ /// between the two given positions.
+ rangeHasMark(from, to, type) {
+ let found2 = false;
+ if (to > from) this.nodesBetween(from, to, (node) => {
+ if (type.isInSet(node.marks)) found2 = true;
+ return !found2;
+ });
+ return found2;
+ }
+ /// True when this is a block (non-inline node)
+ get isBlock() {
+ return this.type.isBlock;
+ }
+ /// True when this is a textblock node, a block node with inline
+ /// content.
+ get isTextblock() {
+ return this.type.isTextblock;
+ }
+ /// True when this node allows inline content.
+ get inlineContent() {
+ return this.type.inlineContent;
+ }
+ /// True when this is an inline node (a text node or a node that can
+ /// appear among text).
+ get isInline() {
+ return this.type.isInline;
+ }
+ /// True when this is a text node.
+ get isText() {
+ return this.type.isText;
+ }
+ /// True when this is a leaf node.
+ get isLeaf() {
+ return this.type.isLeaf;
+ }
+ /// True when this is an atom, i.e. when it does not have directly
+ /// editable content. This is usually the same as `isLeaf`, but can
+ /// be configured with the [`atom` property](#model.NodeSpec.atom)
+ /// on a node's spec (typically used when the node is displayed as
+ /// an uneditable [node view](#view.NodeView)).
+ get isAtom() {
+ return this.type.isAtom;
+ }
+ /// Return a string representation of this node for debugging
+ /// purposes.
+ toString() {
+ if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this);
+ let name = this.type.name;
+ if (this.content.size)
+ name += "(" + this.content.toStringInner() + ")";
+ return wrapMarks(this.marks, name);
+ }
+ /// Get the content match in this node at the given index.
+ contentMatchAt(index) {
+ let match2 = this.type.contentMatch.matchFragment(this.content, 0, index);
+ if (!match2) throw new Error("Called contentMatchAt on a node with invalid content");
+ return match2;
+ }
+ /// Test whether replacing the range between `from` and `to` (by
+ /// child index) with the given replacement fragment (which defaults
+ /// to the empty fragment) would leave the node's content valid. You
+ /// can optionally pass `start` and `end` indices into the
+ /// replacement fragment.
+ canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
+ let one = this.contentMatchAt(from).matchFragment(replacement, start, end);
+ let two = one && one.matchFragment(this.content, to);
+ if (!two || !two.validEnd) return false;
+ for (let i2 = start; i2 < end; i2++) if (!this.type.allowsMarks(replacement.child(i2).marks)) return false;
+ return true;
+ }
+ /// Test whether replacing the range `from` to `to` (by index) with
+ /// a node of the given type would leave the node's content valid.
+ canReplaceWith(from, to, type, marks) {
+ if (marks && !this.type.allowsMarks(marks)) return false;
+ let start = this.contentMatchAt(from).matchType(type);
+ let end = start && start.matchFragment(this.content, to);
+ return end ? end.validEnd : false;
+ }
+ /// Test whether the given node's content could be appended to this
+ /// node. If that node is empty, this will only return true if there
+ /// is at least one node type that can appear in both nodes (to avoid
+ /// merging completely incompatible nodes).
+ canAppend(other) {
+ if (other.content.size) return this.canReplace(this.childCount, this.childCount, other.content);
+ else return this.type.compatibleContent(other.type);
+ }
+ /// Check whether this node and its descendants conform to the
+ /// schema, and raise an exception when they do not.
+ check() {
+ this.type.checkContent(this.content);
+ checkAttrs(this.type.attrs, this.attrs, "node", this.type.name);
+ let copy2 = Mark.none;
+ for (let i2 = 0; i2 < this.marks.length; i2++) {
+ let mark = this.marks[i2];
+ checkAttrs(mark.type.attrs, mark.attrs, "mark", mark.type.name);
+ copy2 = mark.addToSet(copy2);
+ }
+ if (!Mark.sameSet(copy2, this.marks))
+ throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`);
+ this.content.forEach((node) => node.check());
+ }
+ /// Return a JSON-serializeable representation of this node.
+ toJSON() {
+ let obj = { type: this.type.name };
+ for (let _ in this.attrs) {
+ obj.attrs = this.attrs;
+ break;
+ }
+ if (this.content.size)
+ obj.content = this.content.toJSON();
+ if (this.marks.length)
+ obj.marks = this.marks.map((n) => n.toJSON());
+ return obj;
+ }
+ /// Deserialize a node from its JSON representation.
+ static fromJSON(schema3, json) {
+ if (!json) throw new RangeError("Invalid input for Node.fromJSON");
+ let marks = void 0;
+ if (json.marks) {
+ if (!Array.isArray(json.marks)) throw new RangeError("Invalid mark data for Node.fromJSON");
+ marks = json.marks.map(schema3.markFromJSON);
+ }
+ if (json.type == "text") {
+ if (typeof json.text != "string") throw new RangeError("Invalid text node in JSON");
+ return schema3.text(json.text, marks);
+ }
+ let content = Fragment.fromJSON(schema3, json.content);
+ let node = schema3.nodeType(json.type).create(json.attrs, content, marks);
+ return node;
+ }
+ };
+ Node.prototype.text = void 0;
+ var TextNode = class _TextNode extends Node {
+ text;
+ /// @internal
+ constructor(type, attrs2, content, marks) {
+ super(type, attrs2, null, marks);
+ if (!content) throw new RangeError("Empty text nodes are not allowed");
+ this.text = content;
+ }
+ toString() {
+ if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this);
+ return wrapMarks(this.marks, JSON.stringify(this.text));
+ }
+ get textContent() {
+ return this.text;
+ }
+ textBetween(from, to) {
+ return this.text.slice(from, to);
+ }
+ get nodeSize() {
+ return this.text.length;
+ }
+ mark(marks) {
+ return marks == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks);
+ }
+ withText(text2) {
+ if (text2 == this.text) return this;
+ return new _TextNode(this.type, this.attrs, text2, this.marks);
+ }
+ cut(from = 0, to = this.text.length) {
+ if (from == 0 && to == this.text.length) return this;
+ return this.withText(this.text.slice(from, to));
+ }
+ eq(other) {
+ return this.sameMarkup(other) && this.text == other.text;
+ }
+ toJSON() {
+ let base2 = super.toJSON();
+ base2.text = this.text;
+ return base2;
+ }
+ };
+ function wrapMarks(marks, str) {
+ for (let i2 = marks.length - 1; i2 >= 0; i2--)
+ str = marks[i2].type.name + "(" + str + ")";
+ return str;
+ }
+ function checkAttrs(attrs2, values, type, name) {
+ for (let attr in values)
+ if (!(attr in attrs2)) throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`);
+ for (let attr in attrs2) {
+ if (attrs2[attr].validate) attrs2[attr].validate(values[attr]);
+ }
+ }
+
+ // third_party/editor/orderedmap/index.js
+ function OrderedMap(content) {
+ this.content = content;
+ }
+ OrderedMap.prototype = {
+ constructor: OrderedMap,
+ find: function(key) {
+ for (var i2 = 0; i2 < this.content.length; i2 += 2)
+ if (this.content[i2] === key) return i2;
+ return -1;
+ },
+ // :: (string) → ?any
+ // Retrieve the value stored under `key`, or return undefined when
+ // no such key exists.
+ get: function(key) {
+ var found2 = this.find(key);
+ return found2 == -1 ? void 0 : this.content[found2 + 1];
+ },
+ // :: (string, any, ?string) → OrderedMap
+ // Create a new map by replacing the value of `key` with a new
+ // value, or adding a binding to the end of the map. If `newKey` is
+ // given, the key of the binding will be replaced with that key.
+ update: function(key, value, newKey) {
+ var self = newKey && newKey != key ? this.remove(newKey) : this;
+ var found2 = self.find(key), content = self.content.slice();
+ if (found2 == -1) {
+ content.push(newKey || key, value);
+ } else {
+ content[found2 + 1] = value;
+ if (newKey) content[found2] = newKey;
+ }
+ return new OrderedMap(content);
+ },
+ // :: (string) → OrderedMap
+ // Return a map with the given key removed, if it existed.
+ remove: function(key) {
+ var found2 = this.find(key);
+ if (found2 == -1) return this;
+ var content = this.content.slice();
+ content.splice(found2, 2);
+ return new OrderedMap(content);
+ },
+ // :: (string, any) → OrderedMap
+ // Add a new key to the start of the map.
+ addToStart: function(key, value) {
+ return new OrderedMap([key, value].concat(this.remove(key).content));
+ },
+ // :: (string, any) → OrderedMap
+ // Add a new key to the end of the map.
+ addToEnd: function(key, value) {
+ var content = this.remove(key).content.slice();
+ content.push(key, value);
+ return new OrderedMap(content);
+ },
+ // :: (string, string, any) → OrderedMap
+ // Add a key after the given key. If `place` is not found, the new
+ // key is added to the end.
+ addBefore: function(place, key, value) {
+ var without = this.remove(key), content = without.content.slice();
+ var found2 = without.find(place);
+ content.splice(found2 == -1 ? content.length : found2, 0, key, value);
+ return new OrderedMap(content);
+ },
+ // :: ((key: string, value: any))
+ // Call the given function for each key/value pair in the map, in
+ // order.
+ forEach: function(f) {
+ for (var i2 = 0; i2 < this.content.length; i2 += 2)
+ f(this.content[i2], this.content[i2 + 1]);
+ },
+ // :: (union) → OrderedMap
+ // Create a new map by prepending the keys in this map that don't
+ // appear in `map` before the keys in `map`.
+ prepend: function(map) {
+ map = OrderedMap.from(map);
+ if (!map.size) return this;
+ return new OrderedMap(map.content.concat(this.subtract(map).content));
+ },
+ // :: (union) → OrderedMap
+ // Create a new map by appending the keys in this map that don't
+ // appear in `map` after the keys in `map`.
+ append: function(map) {
+ map = OrderedMap.from(map);
+ if (!map.size) return this;
+ return new OrderedMap(this.subtract(map).content.concat(map.content));
+ },
+ // :: (union) → OrderedMap
+ // Create a map containing all the keys in this map that don't
+ // appear in `map`.
+ subtract: function(map) {
+ var result = this;
+ map = OrderedMap.from(map);
+ for (var i2 = 0; i2 < map.content.length; i2 += 2)
+ result = result.remove(map.content[i2]);
+ return result;
+ },
+ // :: () → Object
+ // Turn ordered map into a plain object.
+ toObject: function() {
+ var result = {};
+ this.forEach(function(key, value) {
+ result[key] = value;
+ });
+ return result;
+ },
+ // :: number
+ // The amount of keys in this map.
+ get size() {
+ return this.content.length >> 1;
+ }
+ };
+ OrderedMap.from = function(value) {
+ if (value instanceof OrderedMap) return value;
+ var content = [];
+ if (value) for (var prop in value) content.push(prop, value[prop]);
+ return new OrderedMap(content);
+ };
+
+ // third_party/editor/prosemirror-model/src/content.ts
+ var ContentMatch = class _ContentMatch {
+ /// @internal
+ constructor(validEnd) {
+ this.validEnd = validEnd;
+ }
+ validEnd;
+ /// @internal
+ next = [];
+ /// @internal
+ wrapCache = [];
+ /// @internal
+ static parse(string, nodeTypes) {
+ let stream = new TokenStream(string, nodeTypes);
+ if (stream.next == null) return _ContentMatch.empty;
+ let expr = parseExpr(stream);
+ if (stream.next) stream.err("Unexpected trailing text");
+ let match2 = dfa(nfa(expr));
+ checkForDeadEnds(match2, stream);
+ return match2;
+ }
+ /// Match a node type, returning a match after that node if
+ /// successful.
+ matchType(type) {
+ for (let i2 = 0; i2 < this.next.length; i2++)
+ if (this.next[i2].type == type) return this.next[i2].next;
+ return null;
+ }
+ /// Try to match a fragment. Returns the resulting match when
+ /// successful.
+ matchFragment(frag, start = 0, end = frag.childCount) {
+ let cur = this;
+ for (let i2 = start; cur && i2 < end; i2++)
+ cur = cur.matchType(frag.child(i2).type);
+ return cur;
+ }
+ /// @internal
+ get inlineContent() {
+ return this.next.length != 0 && this.next[0].type.isInline;
+ }
+ /// Get the first matching node type at this match position that can
+ /// be generated.
+ get defaultType() {
+ for (let i2 = 0; i2 < this.next.length; i2++) {
+ let { type } = this.next[i2];
+ if (!(type.isText || type.hasRequiredAttrs())) return type;
+ }
+ return null;
+ }
+ /// @internal
+ compatible(other) {
+ for (let i2 = 0; i2 < this.next.length; i2++)
+ for (let j = 0; j < other.next.length; j++)
+ if (this.next[i2].type == other.next[j].type) return true;
+ return false;
+ }
+ /// Try to match the given fragment, and if that fails, see if it can
+ /// be made to match by inserting nodes in front of it. When
+ /// successful, return a fragment of inserted nodes (which may be
+ /// empty if nothing had to be inserted). When `toEnd` is true, only
+ /// return a fragment if the resulting match goes to the end of the
+ /// content expression.
+ fillBefore(after, toEnd = false, startIndex = 0) {
+ let seen = [this];
+ function search(match2, types) {
+ let finished = match2.matchFragment(after, startIndex);
+ if (finished && (!toEnd || finished.validEnd))
+ return Fragment.from(types.map((tp) => tp.createAndFill()));
+ for (let i2 = 0; i2 < match2.next.length; i2++) {
+ let { type, next } = match2.next[i2];
+ if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
+ seen.push(next);
+ let found2 = search(next, types.concat(type));
+ if (found2) return found2;
+ }
+ }
+ return null;
+ }
+ return search(this, []);
+ }
+ /// Find a set of wrapping node types that would allow a node of the
+ /// given type to appear at this position. The result may be empty
+ /// (when it fits directly) and will be null when no such wrapping
+ /// exists.
+ findWrapping(target) {
+ for (let i2 = 0; i2 < this.wrapCache.length; i2 += 2)
+ if (this.wrapCache[i2] == target) return this.wrapCache[i2 + 1];
+ let computed = this.computeWrapping(target);
+ this.wrapCache.push(target, computed);
+ return computed;
+ }
+ /// @internal
+ computeWrapping(target) {
+ let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
+ while (active.length) {
+ let current = active.shift(), match2 = current.match;
+ if (match2.matchType(target)) {
+ let result = [];
+ for (let obj = current; obj.type; obj = obj.via)
+ result.push(obj.type);
+ return result.reverse();
+ }
+ for (let i2 = 0; i2 < match2.next.length; i2++) {
+ let { type, next } = match2.next[i2];
+ if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
+ active.push({ match: type.contentMatch, type, via: current });
+ seen[type.name] = true;
+ }
+ }
+ }
+ return null;
+ }
+ /// The number of outgoing edges this node has in the finite
+ /// automaton that describes the content expression.
+ get edgeCount() {
+ return this.next.length;
+ }
+ /// Get the _n_th outgoing edge from this node in the finite
+ /// automaton that describes the content expression.
+ edge(n) {
+ if (n >= this.next.length) throw new RangeError(`There's no ${n}th edge in this content match`);
+ return this.next[n];
+ }
+ /// @internal
+ toString() {
+ let seen = [];
+ function scan(m) {
+ seen.push(m);
+ for (let i2 = 0; i2 < m.next.length; i2++)
+ if (seen.indexOf(m.next[i2].next) == -1) scan(m.next[i2].next);
+ }
+ scan(this);
+ return seen.map((m, i2) => {
+ let out = i2 + (m.validEnd ? "*" : " ") + " ";
+ for (let i3 = 0; i3 < m.next.length; i3++)
+ out += (i3 ? ", " : "") + m.next[i3].type.name + "->" + seen.indexOf(m.next[i3].next);
+ return out;
+ }).join("\n");
+ }
+ /// @internal
+ static empty = new _ContentMatch(true);
+ };
+ var TokenStream = class {
+ constructor(string, nodeTypes) {
+ this.string = string;
+ this.nodeTypes = nodeTypes;
+ this.tokens = string.split(/\s*(?=\b|\W|$)/);
+ if (this.tokens[this.tokens.length - 1] == "") this.tokens.pop();
+ if (this.tokens[0] == "") this.tokens.shift();
+ }
+ string;
+ nodeTypes;
+ inline = null;
+ pos = 0;
+ tokens;
+ get next() {
+ return this.tokens[this.pos];
+ }
+ eat(tok) {
+ return this.next == tok && (this.pos++ || true);
+ }
+ err(str) {
+ throw new SyntaxError(str + " (in content expression '" + this.string + "')");
+ }
+ };
+ function parseExpr(stream) {
+ let exprs = [];
+ do {
+ exprs.push(parseExprSeq(stream));
+ } while (stream.eat("|"));
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
+ }
+ function parseExprSeq(stream) {
+ let exprs = [];
+ do {
+ exprs.push(parseExprSubscript(stream));
+ } while (stream.next && stream.next != ")" && stream.next != "|");
+ return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
+ }
+ function parseExprSubscript(stream) {
+ let expr = parseExprAtom(stream);
+ for (; ; ) {
+ if (stream.eat("+"))
+ expr = { type: "plus", expr };
+ else if (stream.eat("*"))
+ expr = { type: "star", expr };
+ else if (stream.eat("?"))
+ expr = { type: "opt", expr };
+ else if (stream.eat("{"))
+ expr = parseExprRange(stream, expr);
+ else break;
+ }
+ return expr;
+ }
+ function parseNum(stream) {
+ if (/\D/.test(stream.next)) stream.err("Expected number, got '" + stream.next + "'");
+ let result = Number(stream.next);
+ stream.pos++;
+ return result;
+ }
+ function parseExprRange(stream, expr) {
+ let min = parseNum(stream), max = min;
+ if (stream.eat(",")) {
+ if (stream.next != "}") max = parseNum(stream);
+ else max = -1;
+ }
+ if (!stream.eat("}")) stream.err("Unclosed braced range");
+ return { type: "range", min, max, expr };
+ }
+ function resolveName(stream, name) {
+ let types = stream.nodeTypes, type = types[name];
+ if (type) return [type];
+ let result = [];
+ for (let typeName in types) {
+ let type2 = types[typeName];
+ if (type2.isInGroup(name)) result.push(type2);
+ }
+ if (result.length == 0) stream.err("No node type or group '" + name + "' found");
+ return result;
+ }
+ function parseExprAtom(stream) {
+ if (stream.eat("(")) {
+ let expr = parseExpr(stream);
+ if (!stream.eat(")")) stream.err("Missing closing paren");
+ return expr;
+ } else if (!/\W/.test(stream.next)) {
+ let exprs = resolveName(stream, stream.next).map((type) => {
+ if (stream.inline == null) stream.inline = type.isInline;
+ else if (stream.inline != type.isInline) stream.err("Mixing inline and block content");
+ return { type: "name", value: type };
+ });
+ stream.pos++;
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
+ } else {
+ stream.err("Unexpected token '" + stream.next + "'");
+ }
+ }
+ function nfa(expr) {
+ let nfa2 = [[]];
+ connect(compile2(expr, 0), node());
+ return nfa2;
+ function node() {
+ return nfa2.push([]) - 1;
+ }
+ function edge(from, to, term) {
+ let edge2 = { term, to };
+ nfa2[from].push(edge2);
+ return edge2;
+ }
+ function connect(edges, to) {
+ edges.forEach((edge2) => edge2.to = to);
+ }
+ function compile2(expr2, from) {
+ if (expr2.type == "choice") {
+ return expr2.exprs.reduce((out, expr3) => out.concat(compile2(expr3, from)), []);
+ } else if (expr2.type == "seq") {
+ for (let i2 = 0; ; i2++) {
+ let next = compile2(expr2.exprs[i2], from);
+ if (i2 == expr2.exprs.length - 1) return next;
+ connect(next, from = node());
+ }
+ } else if (expr2.type == "star") {
+ let loop = node();
+ edge(from, loop);
+ connect(compile2(expr2.expr, loop), loop);
+ return [edge(loop)];
+ } else if (expr2.type == "plus") {
+ let loop = node();
+ connect(compile2(expr2.expr, from), loop);
+ connect(compile2(expr2.expr, loop), loop);
+ return [edge(loop)];
+ } else if (expr2.type == "opt") {
+ return [edge(from)].concat(compile2(expr2.expr, from));
+ } else if (expr2.type == "range") {
+ let cur = from;
+ for (let i2 = 0; i2 < expr2.min; i2++) {
+ let next = node();
+ connect(compile2(expr2.expr, cur), next);
+ cur = next;
+ }
+ if (expr2.max == -1) {
+ connect(compile2(expr2.expr, cur), cur);
+ } else {
+ for (let i2 = expr2.min; i2 < expr2.max; i2++) {
+ let next = node();
+ edge(cur, next);
+ connect(compile2(expr2.expr, cur), next);
+ cur = next;
+ }
+ }
+ return [edge(cur)];
+ } else if (expr2.type == "name") {
+ return [edge(from, void 0, expr2.value)];
+ } else {
+ throw new Error("Unknown expr type");
+ }
+ }
+ }
+ function cmp(a, b) {
+ return b - a;
+ }
+ function nullFrom(nfa2, node) {
+ let result = [];
+ scan(node);
+ return result.sort(cmp);
+ function scan(node2) {
+ let edges = nfa2[node2];
+ if (edges.length == 1 && !edges[0].term) return scan(edges[0].to);
+ result.push(node2);
+ for (let i2 = 0; i2 < edges.length; i2++) {
+ let { term, to } = edges[i2];
+ if (!term && result.indexOf(to) == -1) scan(to);
+ }
+ }
+ }
+ function dfa(nfa2) {
+ let labeled = /* @__PURE__ */ Object.create(null);
+ return explore(nullFrom(nfa2, 0));
+ function explore(states) {
+ let out = [];
+ states.forEach((node) => {
+ nfa2[node].forEach(({ term, to }) => {
+ if (!term) return;
+ let set2;
+ for (let i2 = 0; i2 < out.length; i2++) if (out[i2][0] == term) set2 = out[i2][1];
+ nullFrom(nfa2, to).forEach((node2) => {
+ if (!set2) out.push([term, set2 = []]);
+ if (set2.indexOf(node2) == -1) set2.push(node2);
+ });
+ });
+ });
+ let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
+ for (let i2 = 0; i2 < out.length; i2++) {
+ let states2 = out[i2][1].sort(cmp);
+ state.next.push({ type: out[i2][0], next: labeled[states2.join(",")] || explore(states2) });
+ }
+ return state;
+ }
+ }
+ function checkForDeadEnds(match2, stream) {
+ for (let i2 = 0, work = [match2]; i2 < work.length; i2++) {
+ let state = work[i2], dead = !state.validEnd, nodes = [];
+ for (let j = 0; j < state.next.length; j++) {
+ let { type, next } = state.next[j];
+ nodes.push(type.name);
+ if (dead && !(type.isText || type.hasRequiredAttrs())) dead = false;
+ if (work.indexOf(next) == -1) work.push(next);
+ }
+ if (dead) stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
+ }
+ }
+
+ // third_party/editor/prosemirror-model/src/schema.ts
+ function defaultAttrs(attrs2) {
+ let defaults = /* @__PURE__ */ Object.create(null);
+ for (let attrName in attrs2) {
+ let attr = attrs2[attrName];
+ if (!attr.hasDefault) return null;
+ defaults[attrName] = attr.default;
+ }
+ return defaults;
+ }
+ function computeAttrs(attrs2, value) {
+ let built = /* @__PURE__ */ Object.create(null);
+ for (let name in attrs2) {
+ let attr = attrs2[name];
+ let given = value && value[name];
+ if (given === void 0) {
+ if (attr.hasDefault) given = attr.default;
+ else throw new RangeError("No value supplied for attribute " + name);
+ } else if (attr.validate) {
+ attr.validate(given);
+ }
+ built[name] = given;
+ }
+ return built;
+ }
+ function initAttrs(typeName, attrs2) {
+ let result = /* @__PURE__ */ Object.create(null);
+ if (attrs2) for (let name in attrs2) result[name] = new Attribute(typeName, name, attrs2[name]);
+ return result;
+ }
+ var NodeType = class _NodeType {
+ /// @internal
+ constructor(name, schema3, spec) {
+ this.name = name;
+ this.schema = schema3;
+ this.spec = spec;
+ this.groups = spec.group ? spec.group.split(" ") : [];
+ this.attrs = initAttrs(name, spec.attrs);
+ this.defaultAttrs = defaultAttrs(this.attrs);
+ this.contentMatch = null;
+ this.inlineContent = null;
+ this.isBlock = !(spec.inline || name == "text");
+ this.isText = name == "text";
+ }
+ name;
+ schema;
+ spec;
+ /// @internal
+ groups;
+ /// @internal
+ attrs;
+ /// @internal
+ defaultAttrs;
+ /// True if this is a block type
+ isBlock;
+ /// True if this is the text node type.
+ isText;
+ /// True if this is an inline type.
+ get isInline() {
+ return !this.isBlock;
+ }
+ /// True if this is a textblock type, a block that contains inline
+ /// content.
+ get isTextblock() {
+ return this.isBlock && this.inlineContent;
+ }
+ /// True for node types that allow no content.
+ get isLeaf() {
+ return this.contentMatch == ContentMatch.empty;
+ }
+ /// True when this node is an atom, i.e. when it does not have
+ /// directly editable content.
+ get isAtom() {
+ return this.isLeaf || !!this.spec.atom;
+ }
+ /// Return true when this node type is part of the given
+ /// [group](#model.NodeSpec.group).
+ isInGroup(group) {
+ return this.groups.indexOf(group) > -1;
+ }
+ /// The set of marks allowed in this node. `null` means all marks
+ /// are allowed.
+ markSet = null;
+ /// The node type's [whitespace](#model.NodeSpec.whitespace) option.
+ get whitespace() {
+ return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
+ }
+ /// Tells you whether this node type has any required attributes.
+ hasRequiredAttrs() {
+ for (let n in this.attrs) if (this.attrs[n].isRequired) return true;
+ return false;
+ }
+ /// Indicates whether this node allows some of the same content as
+ /// the given node type.
+ compatibleContent(other) {
+ return this == other || this.contentMatch.compatible(other.contentMatch);
+ }
+ /// @internal
+ computeAttrs(attrs2) {
+ if (!attrs2 && this.defaultAttrs) return this.defaultAttrs;
+ else return computeAttrs(this.attrs, attrs2);
+ }
+ /// Create a `Node` of this type. The given attributes are
+ /// checked and defaulted (you can pass `null` to use the type's
+ /// defaults entirely, if no required attributes exist). `content`
+ /// may be a `Fragment`, a node, an array of nodes, or
+ /// `null`. Similarly `marks` may be `null` to default to the empty
+ /// set of marks.
+ create(attrs2 = null, content, marks) {
+ if (this.isText) throw new Error("NodeType.create can't construct text nodes");
+ return new Node(this, this.computeAttrs(attrs2), Fragment.from(content), Mark.setFrom(marks));
+ }
+ /// Like [`create`](#model.NodeType.create), but check the given content
+ /// against the node type's content restrictions, and throw an error
+ /// if it doesn't match.
+ createChecked(attrs2 = null, content, marks) {
+ content = Fragment.from(content);
+ this.checkContent(content);
+ return new Node(this, this.computeAttrs(attrs2), content, Mark.setFrom(marks));
+ }
+ /// Like [`create`](#model.NodeType.create), but see if it is
+ /// necessary to add nodes to the start or end of the given fragment
+ /// to make it fit the node. If no fitting wrapping can be found,
+ /// return null. Note that, due to the fact that required nodes can
+ /// always be created, this will always succeed if you pass null or
+ /// `Fragment.empty` as content.
+ createAndFill(attrs2 = null, content, marks) {
+ attrs2 = this.computeAttrs(attrs2);
+ content = Fragment.from(content);
+ if (content.size) {
+ let before = this.contentMatch.fillBefore(content);
+ if (!before) return null;
+ content = before.append(content);
+ }
+ let matched = this.contentMatch.matchFragment(content);
+ let after = matched && matched.fillBefore(Fragment.empty, true);
+ if (!after) return null;
+ return new Node(this, attrs2, content.append(after), Mark.setFrom(marks));
+ }
+ /// Returns true if the given fragment is valid content for this node
+ /// type.
+ validContent(content) {
+ let result = this.contentMatch.matchFragment(content);
+ if (!result || !result.validEnd) return false;
+ for (let i2 = 0; i2 < content.childCount; i2++)
+ if (!this.allowsMarks(content.child(i2).marks)) return false;
+ return true;
+ }
+ /// Throws a RangeError if the given fragment is not valid content for this
+ /// node type.
+ /// @internal
+ checkContent(content) {
+ if (!this.validContent(content))
+ throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
+ }
+ /// @internal no longer useful, but called by old prosemirror-view versions
+ checkAttrs(attrs2) {
+ }
+ /// Check whether the given mark type is allowed in this node.
+ allowsMarkType(markType) {
+ return this.markSet == null || this.markSet.indexOf(markType) > -1;
+ }
+ /// Test whether the given set of marks are allowed in this node.
+ allowsMarks(marks) {
+ if (this.markSet == null) return true;
+ for (let i2 = 0; i2 < marks.length; i2++) if (!this.allowsMarkType(marks[i2].type)) return false;
+ return true;
+ }
+ /// Removes the marks that are not allowed in this node from the given set.
+ allowedMarks(marks) {
+ if (this.markSet == null) return marks;
+ let copy2;
+ for (let i2 = 0; i2 < marks.length; i2++) {
+ if (!this.allowsMarkType(marks[i2].type)) {
+ if (!copy2) copy2 = marks.slice(0, i2);
+ } else if (copy2) {
+ copy2.push(marks[i2]);
+ }
+ }
+ return !copy2 ? marks : copy2.length ? copy2 : Mark.none;
+ }
+ /// @internal
+ static compile(nodes, schema3) {
+ let result = /* @__PURE__ */ Object.create(null);
+ nodes.forEach((name, spec) => result[name] = new _NodeType(name, schema3, spec));
+ let topType = schema3.spec.topNode || "doc";
+ if (!result[topType]) throw new RangeError("Schema is missing its top node type ('" + topType + "')");
+ if (!result.text) throw new RangeError("Every schema needs a 'text' type");
+ for (let _ in result.text.attrs) throw new RangeError("The text node type should not have attributes");
+ return result;
+ }
+ };
+ function validateType(typeName, attrName, type) {
+ let types = type.split("|");
+ return (value) => {
+ let name = value === null ? "null" : typeof value;
+ if (types.indexOf(name) < 0) throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);
+ };
+ }
+ var Attribute = class {
+ hasDefault;
+ default;
+ validate;
+ constructor(typeName, attrName, options) {
+ this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
+ this.default = options.default;
+ this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate;
+ }
+ get isRequired() {
+ return !this.hasDefault;
+ }
+ };
+ var MarkType = class _MarkType {
+ /// @internal
+ constructor(name, rank, schema3, spec) {
+ this.name = name;
+ this.rank = rank;
+ this.schema = schema3;
+ this.spec = spec;
+ this.attrs = initAttrs(name, spec.attrs);
+ this.excluded = null;
+ let defaults = defaultAttrs(this.attrs);
+ this.instance = defaults ? new Mark(this, defaults) : null;
+ }
+ name;
+ rank;
+ schema;
+ spec;
+ /// @internal
+ attrs;
+ /// @internal
+ instance;
+ /// Create a mark of this type. `attrs` may be `null` or an object
+ /// containing only some of the mark's attributes. The others, if
+ /// they have defaults, will be added.
+ create(attrs2 = null) {
+ if (!attrs2 && this.instance) return this.instance;
+ return new Mark(this, computeAttrs(this.attrs, attrs2));
+ }
+ /// @internal
+ static compile(marks, schema3) {
+ let result = /* @__PURE__ */ Object.create(null), rank = 0;
+ marks.forEach((name, spec) => result[name] = new _MarkType(name, rank++, schema3, spec));
+ return result;
+ }
+ /// When there is a mark of this type in the given set, a new set
+ /// without it is returned. Otherwise, the input set is returned.
+ removeFromSet(set2) {
+ for (var i2 = 0; i2 < set2.length; i2++) if (set2[i2].type == this) {
+ set2 = set2.slice(0, i2).concat(set2.slice(i2 + 1));
+ i2--;
+ }
+ return set2;
+ }
+ /// Tests whether there is a mark of this type in the given set.
+ isInSet(set2) {
+ for (let i2 = 0; i2 < set2.length; i2++)
+ if (set2[i2].type == this) return set2[i2];
+ }
+ /// Queries whether a given mark type is
+ /// [excluded](#model.MarkSpec.excludes) by this one.
+ excludes(other) {
+ return this.excluded.indexOf(other) > -1;
+ }
+ };
+ var Schema = class {
+ /// The [spec](#model.SchemaSpec) on which the schema is based,
+ /// with the added guarantee that its `nodes` and `marks`
+ /// properties are
+ /// [`OrderedMap`](https://code.haverbeke.berlin/marijn/orderedmap) instances
+ /// (not raw objects).
+ spec;
+ /// An object mapping the schema's node names to node type objects.
+ nodes;
+ /// A map from mark names to mark type objects.
+ marks;
+ /// The [linebreak
+ /// replacement](#model.NodeSpec.linebreakReplacement) node defined
+ /// in this schema, if any.
+ linebreakReplacement = null;
+ /// Construct a schema from a schema [specification](#model.SchemaSpec).
+ constructor(spec) {
+ let instanceSpec = this.spec = {};
+ for (let prop in spec) instanceSpec[prop] = spec[prop];
+ instanceSpec.nodes = OrderedMap.from(spec.nodes), instanceSpec.marks = OrderedMap.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this);
+ this.marks = MarkType.compile(this.spec.marks, this);
+ let contentExprCache = /* @__PURE__ */ Object.create(null);
+ for (let prop in this.nodes) {
+ if (prop in this.marks)
+ throw new RangeError(prop + " can not be both a node and a mark");
+ let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
+ type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
+ type.inlineContent = type.contentMatch.inlineContent;
+ if (type.spec.linebreakReplacement) {
+ if (this.linebreakReplacement) throw new RangeError("Multiple linebreak nodes defined");
+ if (!type.isInline || !type.isLeaf) throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
+ this.linebreakReplacement = type;
+ }
+ type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
+ }
+ for (let prop in this.marks) {
+ let type = this.marks[prop], excl = type.spec.excludes;
+ type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
+ }
+ this.nodeFromJSON = (json) => Node.fromJSON(this, json);
+ this.markFromJSON = (json) => Mark.fromJSON(this, json);
+ this.topNodeType = this.nodes[this.spec.topNode || "doc"];
+ this.cached.wrappings = /* @__PURE__ */ Object.create(null);
+ }
+ /// The type of the [default top node](#model.SchemaSpec.topNode)
+ /// for this schema.
+ topNodeType;
+ /// An object for storing whatever values modules may want to
+ /// compute and cache per schema. (If you want to store something
+ /// in it, try to use property names unlikely to clash.)
+ cached = /* @__PURE__ */ Object.create(null);
+ /// Create a node in this schema. The `type` may be a string or a
+ /// `NodeType` instance. Attributes will be extended with defaults,
+ /// `content` may be a `Fragment`, `null`, a `Node`, or an array of
+ /// nodes.
+ node(type, attrs2 = null, content, marks) {
+ if (typeof type == "string")
+ type = this.nodeType(type);
+ else if (!(type instanceof NodeType))
+ throw new RangeError("Invalid node type: " + type);
+ else if (type.schema != this)
+ throw new RangeError("Node type from different schema used (" + type.name + ")");
+ return type.createChecked(attrs2, content, marks);
+ }
+ /// Create a text node in the schema. Empty text nodes are not
+ /// allowed.
+ text(text2, marks) {
+ let type = this.nodes.text;
+ return new TextNode(type, type.defaultAttrs, text2, Mark.setFrom(marks));
+ }
+ /// Create a mark with the given type and attributes.
+ mark(type, attrs2) {
+ if (typeof type == "string") type = this.marks[type];
+ return type.create(attrs2);
+ }
+ /// Deserialize a node from its JSON representation. This method is
+ /// bound.
+ nodeFromJSON;
+ /// Deserialize a mark from its JSON representation. This method is
+ /// bound.
+ markFromJSON;
+ /// @internal
+ nodeType(name) {
+ let found2 = this.nodes[name];
+ if (!found2) throw new RangeError("Unknown node type: " + name);
+ return found2;
+ }
+ };
+ function gatherMarks(schema3, marks) {
+ let found2 = [];
+ for (let i2 = 0; i2 < marks.length; i2++) {
+ let name = marks[i2], mark = schema3.marks[name], ok = mark;
+ if (mark) {
+ found2.push(mark);
+ } else {
+ for (let prop in schema3.marks) {
+ let mark2 = schema3.marks[prop];
+ if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1)
+ found2.push(ok = mark2);
+ }
+ }
+ if (!ok) throw new SyntaxError("Unknown mark type: '" + marks[i2] + "'");
+ }
+ return found2;
+ }
+
+ // third_party/editor/prosemirror-model/src/from_dom.ts
+ function isTagRule(rule) {
+ return rule.tag != null;
+ }
+ function isStyleRule(rule) {
+ return rule.style != null;
+ }
+ var DOMParser = class _DOMParser {
+ /// Create a parser that targets the given schema, using the given
+ /// parsing rules.
+ constructor(schema3, rules2) {
+ this.schema = schema3;
+ this.rules = rules2;
+ let matchedStyles = this.matchedStyles = [];
+ rules2.forEach((rule) => {
+ if (isTagRule(rule)) {
+ this.tags.push(rule);
+ } else if (isStyleRule(rule)) {
+ let prop = /[^=]*/.exec(rule.style)[0];
+ if (matchedStyles.indexOf(prop) < 0) matchedStyles.push(prop);
+ this.styles.push(rule);
+ }
+ });
+ this.normalizeLists = !this.tags.some((r) => {
+ if (!/^(ul|ol)\b/.test(r.tag) || !r.node) return false;
+ let node = schema3.nodes[r.node];
+ return node.contentMatch.matchType(node);
+ });
+ }
+ schema;
+ rules;
+ /// @internal
+ tags = [];
+ /// @internal
+ styles = [];
+ /// @internal
+ matchedStyles;
+ /// @internal
+ normalizeLists;
+ /// Parse a document from the content of a DOM node.
+ parse(dom, options = {}) {
+ let context = new ParseContext(this, options, false);
+ context.addAll(dom, Mark.none, options.from, options.to);
+ return context.finish();
+ }
+ /// Parses the content of the given DOM node, like
+ /// [`parse`](#model.DOMParser.parse), and takes the same set of
+ /// options. But unlike that method, which produces a whole node,
+ /// this one returns a slice that is open at the sides, meaning that
+ /// the schema constraints aren't applied to the start of nodes to
+ /// the left of the input and the end of nodes at the end.
+ parseSlice(dom, options = {}) {
+ let context = new ParseContext(this, options, true);
+ context.addAll(dom, Mark.none, options.from, options.to);
+ return Slice.maxOpen(context.finish());
+ }
+ /// @internal
+ matchTag(dom, context, after) {
+ for (let i2 = after ? this.tags.indexOf(after) + 1 : 0; i2 < this.tags.length; i2++) {
+ let rule = this.tags[i2];
+ if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {
+ if (rule.getAttrs) {
+ let result = rule.getAttrs(dom);
+ if (result === false) continue;
+ rule.attrs = result || void 0;
+ }
+ return rule;
+ }
+ }
+ }
+ /// @internal
+ matchStyle(prop, value, context, after) {
+ for (let i2 = after ? this.styles.indexOf(after) + 1 : 0; i2 < this.styles.length; i2++) {
+ let rule = this.styles[i2], style = rule.style;
+ if (style.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop,
+ // or has an '=' sign after the prop, followed by the given
+ // value.
+ style.length > prop.length && (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))
+ continue;
+ if (rule.getAttrs) {
+ let result = rule.getAttrs(value);
+ if (result === false) continue;
+ rule.attrs = result || void 0;
+ }
+ return rule;
+ }
+ }
+ /// @internal
+ static schemaRules(schema3) {
+ let result = [];
+ function insert(rule) {
+ let priority = rule.priority == null ? 50 : rule.priority, i2 = 0;
+ for (; i2 < result.length; i2++) {
+ let next = result[i2], nextPriority = next.priority == null ? 50 : next.priority;
+ if (nextPriority < priority) break;
+ }
+ result.splice(i2, 0, rule);
+ }
+ for (let name in schema3.marks) {
+ let rules2 = schema3.marks[name].spec.parseDOM;
+ if (rules2) rules2.forEach((rule) => {
+ insert(rule = copy(rule));
+ if (!(rule.mark || rule.ignore || rule.clearMark))
+ rule.mark = name;
+ });
+ }
+ for (let name in schema3.nodes) {
+ let rules2 = schema3.nodes[name].spec.parseDOM;
+ if (rules2) rules2.forEach((rule) => {
+ insert(rule = copy(rule));
+ if (!(rule.node || rule.ignore || rule.mark))
+ rule.node = name;
+ });
+ }
+ return result;
+ }
+ /// Construct a DOM parser using the parsing rules listed in a
+ /// schema's [node specs](#model.NodeSpec.parseDOM), reordered by
+ /// [priority](#model.GenericParseRule.priority).
+ static fromSchema(schema3) {
+ return schema3.cached.domParser || (schema3.cached.domParser = new _DOMParser(schema3, _DOMParser.schemaRules(schema3)));
+ }
+ };
+ var blockTags = {
+ address: true,
+ article: true,
+ aside: true,
+ blockquote: true,
+ body: true,
+ canvas: true,
+ dd: true,
+ div: true,
+ dl: true,
+ fieldset: true,
+ figcaption: true,
+ figure: true,
+ footer: true,
+ form: true,
+ h1: true,
+ h2: true,
+ h3: true,
+ h4: true,
+ h5: true,
+ h6: true,
+ header: true,
+ hgroup: true,
+ hr: true,
+ li: true,
+ noscript: true,
+ ol: true,
+ output: true,
+ p: true,
+ pre: true,
+ section: true,
+ table: true,
+ tfoot: true,
+ ul: true
+ };
+ var ignoreTags = {
+ head: true,
+ noscript: true,
+ object: true,
+ script: true,
+ style: true,
+ title: true
+ };
+ var listTags = { ol: true, ul: true };
+ var OPT_PRESERVE_WS = 1;
+ var OPT_PRESERVE_WS_FULL = 2;
+ var OPT_OPEN_LEFT = 4;
+ function wsOptionsFor(type, preserveWhitespace, base2) {
+ if (preserveWhitespace != null) return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
+ return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT;
+ }
+ var NodeContext = class {
+ constructor(type, attrs2, marks, solid, match2, options) {
+ this.type = type;
+ this.attrs = attrs2;
+ this.marks = marks;
+ this.solid = solid;
+ this.options = options;
+ this.match = match2 || (options & OPT_OPEN_LEFT ? null : type.contentMatch);
+ }
+ type;
+ attrs;
+ marks;
+ solid;
+ options;
+ match;
+ content = [];
+ // Marks applied to the node's children
+ activeMarks = Mark.none;
+ findWrapping(node) {
+ if (!this.match) {
+ if (!this.type) return [];
+ let fill = this.type.contentMatch.fillBefore(Fragment.from(node));
+ if (fill) {
+ this.match = this.type.contentMatch.matchFragment(fill);
+ } else {
+ let start = this.type.contentMatch, wrap2;
+ if (wrap2 = start.findWrapping(node.type)) {
+ this.match = start;
+ return wrap2;
+ } else {
+ return null;
+ }
+ }
+ }
+ return this.match.findWrapping(node.type);
+ }
+ finish(openEnd) {
+ if (!(this.options & OPT_PRESERVE_WS)) {
+ let last = this.content[this.content.length - 1], m;
+ if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) {
+ let text2 = last;
+ if (last.text.length == m[0].length) this.content.pop();
+ else this.content[this.content.length - 1] = text2.withText(text2.text.slice(0, text2.text.length - m[0].length));
+ }
+ }
+ let content = Fragment.from(this.content);
+ if (!openEnd && this.match)
+ content = content.append(this.match.fillBefore(Fragment.empty, true));
+ return this.type ? this.type.create(this.attrs, content, this.marks) : content;
+ }
+ inlineContext(node) {
+ if (this.type) return this.type.inlineContent;
+ if (this.content.length) return this.content[0].isInline;
+ return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());
+ }
+ };
+ var ParseContext = class {
+ constructor(parser2, options, isOpen) {
+ this.parser = parser2;
+ this.options = options;
+ this.isOpen = isOpen;
+ let topNode = options.topNode, topContext;
+ let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
+ if (topNode)
+ topContext = new NodeContext(
+ topNode.type,
+ topNode.attrs,
+ Mark.none,
+ true,
+ options.topMatch || topNode.type.contentMatch,
+ topOptions
+ );
+ else if (isOpen)
+ topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);
+ else
+ topContext = new NodeContext(parser2.schema.topNodeType, null, Mark.none, true, null, topOptions);
+ this.nodes = [topContext];
+ this.find = options.findPositions;
+ this.needsBlock = false;
+ }
+ parser;
+ options;
+ isOpen;
+ open = 0;
+ find;
+ needsBlock;
+ nodes;
+ localPreserveWS = false;
+ get top() {
+ return this.nodes[this.open];
+ }
+ // Add a DOM node to the content. Text is inserted as text node,
+ // otherwise, the node is passed to `addElement` or, if it has a
+ // `style` attribute, `addElementWithStyles`.
+ addDOM(dom, marks) {
+ if (dom.nodeType == 3) this.addTextNode(dom, marks);
+ else if (dom.nodeType == 1) this.addElement(dom, marks);
+ }
+ addTextNode(dom, marks) {
+ let value = dom.nodeValue;
+ let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;
+ let { schema: schema3 } = this.parser;
+ if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) {
+ if (!preserveWS) {
+ value = value.replace(/[ \t\r\n\u000c]+/g, " ");
+ if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
+ let nodeBefore = top.content[top.content.length - 1];
+ let domNodeBefore = dom.previousSibling;
+ if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))
+ value = value.slice(1);
+ }
+ } else if (preserveWS === "full") {
+ value = value.replace(/\r\n?/g, "\n");
+ } else if (schema3.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema3.linebreakReplacement.create())) {
+ let lines = value.split(/\r?\n|\r/);
+ for (let i2 = 0; i2 < lines.length; i2++) {
+ if (i2) this.insertNode(schema3.linebreakReplacement.create(), marks, true);
+ if (lines[i2]) this.insertNode(schema3.text(lines[i2]), marks, !/\S/.test(lines[i2]));
+ }
+ value = "";
+ } else {
+ value = value.replace(/\r?\n|\r/g, " ");
+ }
+ if (value) this.insertNode(schema3.text(value), marks, !/\S/.test(value));
+ this.findInText(dom);
+ } else {
+ this.findInside(dom);
+ }
+ }
+ // Try to find a handler for the given tag and use that to parse. If
+ // none is found, the element's content nodes are added directly.
+ addElement(dom, marks, matchAfter) {
+ let outerWS = this.localPreserveWS, top = this.top;
+ if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace))
+ this.localPreserveWS = true;
+ let name = dom.nodeName.toLowerCase(), ruleID;
+ if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) normalizeList(dom);
+ let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter));
+ out:
+ if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {
+ this.findInside(dom);
+ this.ignoreFallback(dom, marks);
+ } else if (!rule || rule.skip || rule.closeParent) {
+ if (rule && rule.closeParent) this.open = Math.max(0, this.open - 1);
+ else if (rule && rule.skip.nodeType) dom = rule.skip;
+ let sync, oldNeedsBlock = this.needsBlock;
+ if (blockTags.hasOwnProperty(name)) {
+ if (top.content.length && top.content[0].isInline && this.open) {
+ this.open--;
+ top = this.top;
+ }
+ sync = true;
+ if (!top.type) this.needsBlock = true;
+ } else if (!dom.firstChild) {
+ this.leafFallback(dom, marks);
+ break out;
+ }
+ let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);
+ if (innerMarks) this.addAll(dom, innerMarks);
+ if (sync) this.sync(top);
+ this.needsBlock = oldNeedsBlock;
+ } else {
+ let innerMarks = this.readStyles(dom, marks);
+ if (innerMarks)
+ this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0);
+ }
+ this.localPreserveWS = outerWS;
+ }
+ // Called for leaf DOM nodes that would otherwise be ignored
+ leafFallback(dom, marks) {
+ if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
+ this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks);
+ }
+ // Called for ignored nodes
+ ignoreFallback(dom, marks) {
+ if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
+ this.findPlace(this.parser.schema.text("-"), marks, true);
+ }
+ // Run any style parser associated with the node's styles. Either
+ // return an updated array of marks, or null to indicate some of the
+ // styles had a rule with `ignore` set.
+ readStyles(dom, marks) {
+ let styles = dom.style;
+ if (styles && styles.length) for (let i2 = 0; i2 < this.parser.matchedStyles.length; i2++) {
+ let name = this.parser.matchedStyles[i2], value = styles.getPropertyValue(name);
+ if (value) for (let after = void 0; ; ) {
+ let rule = this.parser.matchStyle(name, value, this, after);
+ if (!rule) break;
+ if (rule.ignore) return null;
+ if (rule.clearMark)
+ marks = marks.filter((m) => !rule.clearMark(m));
+ else
+ marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));
+ if (rule.consuming === false) after = rule;
+ else break;
+ }
+ }
+ return marks;
+ }
+ // Look up a handler for the given node. If none are found, return
+ // false. Otherwise, apply it, use its return value to drive the way
+ // the node's content is wrapped, and return true.
+ addElementByRule(dom, rule, marks, continueAfter) {
+ let sync, nodeType;
+ if (rule.node) {
+ nodeType = this.parser.schema.nodes[rule.node];
+ if (!nodeType.isLeaf) {
+ let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);
+ if (inner) {
+ sync = true;
+ marks = inner;
+ }
+ } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) {
+ this.leafFallback(dom, marks);
+ }
+ } else {
+ let markType = this.parser.schema.marks[rule.mark];
+ marks = marks.concat(markType.create(rule.attrs));
+ }
+ let startIn = this.top;
+ if (nodeType && nodeType.isLeaf) {
+ this.findInside(dom);
+ } else if (continueAfter) {
+ this.addElement(dom, marks, continueAfter);
+ } else if (rule.getContent) {
+ this.findInside(dom);
+ rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false));
+ } else {
+ let contentDOM = dom;
+ if (typeof rule.contentElement == "string") contentDOM = dom.querySelector(rule.contentElement);
+ else if (typeof rule.contentElement == "function") contentDOM = rule.contentElement(dom);
+ else if (rule.contentElement) contentDOM = rule.contentElement;
+ this.findAround(dom, contentDOM, true);
+ this.addAll(contentDOM, marks);
+ this.findAround(dom, contentDOM, false);
+ }
+ if (sync && this.sync(startIn)) this.open--;
+ }
+ // Add all child nodes between `startIndex` and `endIndex` (or the
+ // whole node, if not given). If `sync` is passed, use it to
+ // synchronize after every block element.
+ addAll(parent, marks, startIndex, endIndex) {
+ let index = startIndex || 0;
+ for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {
+ this.findAtPoint(parent, index);
+ this.addDOM(dom, marks);
+ }
+ this.findAtPoint(parent, index);
+ }
+ // Try to find a way to fit the given node type into the current
+ // context. May add intermediate wrappers and/or leave non-solid
+ // nodes that we're in.
+ findPlace(node, marks, cautious) {
+ let route, sync;
+ for (let depth = this.open, penalty = 0; depth >= 0; depth--) {
+ let cx = this.nodes[depth];
+ let found2 = cx.findWrapping(node);
+ if (found2 && (!route || route.length > found2.length + penalty)) {
+ route = found2;
+ sync = cx;
+ if (!found2.length) break;
+ }
+ if (cx.solid) {
+ if (cautious) break;
+ penalty += 2;
+ }
+ }
+ if (!route) return null;
+ this.sync(sync);
+ for (let i2 = 0; i2 < route.length; i2++)
+ marks = this.enterInner(route[i2], null, marks, false);
+ return marks;
+ }
+ // Try to insert the given node, adjusting the context when needed.
+ insertNode(node, marks, cautious) {
+ if (node.isInline && this.needsBlock && !this.top.type) {
+ let block3 = this.textblockFromContext();
+ if (block3) marks = this.enterInner(block3, null, marks);
+ }
+ let innerMarks = this.findPlace(node, marks, cautious);
+ if (innerMarks) {
+ this.closeExtra();
+ let top = this.top;
+ if (top.match) top.match = top.match.matchType(node.type);
+ let nodeMarks = Mark.none;
+ for (let m of innerMarks.concat(node.marks))
+ if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))
+ nodeMarks = m.addToSet(nodeMarks);
+ top.content.push(node.mark(nodeMarks));
+ return true;
+ }
+ return false;
+ }
+ // Try to start a node of the given type, adjusting the context when
+ // necessary.
+ enter(type, attrs2, marks, preserveWS) {
+ let innerMarks = this.findPlace(type.create(attrs2), marks, false);
+ if (innerMarks) innerMarks = this.enterInner(type, attrs2, marks, true, preserveWS);
+ return innerMarks;
+ }
+ // Open a node of the given type
+ enterInner(type, attrs2, marks, solid = false, preserveWS) {
+ this.closeExtra();
+ let top = this.top;
+ top.match = top.match && top.match.matchType(type);
+ let options = wsOptionsFor(type, preserveWS, top.options);
+ if (top.options & OPT_OPEN_LEFT && top.content.length == 0) options |= OPT_OPEN_LEFT;
+ let applyMarks = Mark.none;
+ marks = marks.filter((m) => {
+ if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {
+ applyMarks = m.addToSet(applyMarks);
+ return false;
+ }
+ return true;
+ });
+ this.nodes.push(new NodeContext(type, attrs2, applyMarks, solid, null, options));
+ this.open++;
+ return marks;
+ }
+ // Make sure all nodes above this.open are finished and added to
+ // their parents
+ closeExtra(openEnd = false) {
+ let i2 = this.nodes.length - 1;
+ if (i2 > this.open) {
+ for (; i2 > this.open; i2--) this.nodes[i2 - 1].content.push(this.nodes[i2].finish(openEnd));
+ this.nodes.length = this.open + 1;
+ }
+ }
+ finish() {
+ this.open = 0;
+ this.closeExtra(this.isOpen);
+ return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
+ }
+ sync(to) {
+ for (let i2 = this.open; i2 >= 0; i2--) {
+ if (this.nodes[i2] == to) {
+ this.open = i2;
+ return true;
+ } else if (this.localPreserveWS) {
+ this.nodes[i2].options |= OPT_PRESERVE_WS;
+ }
+ }
+ return false;
+ }
+ get currentPos() {
+ this.closeExtra();
+ let pos = 0;
+ for (let i2 = this.open; i2 >= 0; i2--) {
+ let content = this.nodes[i2].content;
+ for (let j = content.length - 1; j >= 0; j--)
+ pos += content[j].nodeSize;
+ if (i2) pos++;
+ }
+ return pos;
+ }
+ findAtPoint(parent, offset) {
+ if (this.find) for (let i2 = 0; i2 < this.find.length; i2++) {
+ if (this.find[i2].node == parent && this.find[i2].offset == offset)
+ this.find[i2].pos = this.currentPos;
+ }
+ }
+ findInside(parent) {
+ if (this.find) for (let i2 = 0; i2 < this.find.length; i2++) {
+ if (this.find[i2].pos == null && parent.nodeType == 1 && parent.contains(this.find[i2].node))
+ this.find[i2].pos = this.currentPos;
+ }
+ }
+ findAround(parent, content, before) {
+ if (parent != content && this.find) for (let i2 = 0; i2 < this.find.length; i2++) {
+ if (this.find[i2].pos == null && parent.nodeType == 1 && parent.contains(this.find[i2].node)) {
+ let pos = content.compareDocumentPosition(this.find[i2].node);
+ if (pos & (before ? 2 : 4))
+ this.find[i2].pos = this.currentPos;
+ }
+ }
+ }
+ findInText(textNode) {
+ if (this.find) for (let i2 = 0; i2 < this.find.length; i2++) {
+ if (this.find[i2].node == textNode)
+ this.find[i2].pos = this.currentPos - (textNode.nodeValue.length - this.find[i2].offset);
+ }
+ }
+ // Determines whether the given context string matches this context.
+ matchesContext(context) {
+ if (context.indexOf("|") > -1)
+ return context.split(/\s*\|\s*/).some(this.matchesContext, this);
+ let parts = context.split("/");
+ let option = this.options.context;
+ let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
+ let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);
+ let match2 = (i2, depth) => {
+ for (; i2 >= 0; i2--) {
+ let part = parts[i2];
+ if (part == "") {
+ if (i2 == parts.length - 1 || i2 == 0) continue;
+ for (; depth >= minDepth; depth--)
+ if (match2(i2 - 1, depth)) return true;
+ return false;
+ } else {
+ let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;
+ if (!next || next.name != part && !next.isInGroup(part))
+ return false;
+ depth--;
+ }
+ }
+ return true;
+ };
+ return match2(parts.length - 1, this.open);
+ }
+ textblockFromContext() {
+ let $context = this.options.context;
+ if ($context) for (let d = $context.depth; d >= 0; d--) {
+ let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;
+ if (deflt && deflt.isTextblock && deflt.defaultAttrs) return deflt;
+ }
+ for (let name in this.parser.schema.nodes) {
+ let type = this.parser.schema.nodes[name];
+ if (type.isTextblock && type.defaultAttrs) return type;
+ }
+ }
+ };
+ function normalizeList(dom) {
+ for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
+ let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;
+ if (name && listTags.hasOwnProperty(name) && prevItem) {
+ prevItem.appendChild(child);
+ child = prevItem;
+ } else if (name == "li") {
+ prevItem = child;
+ } else if (name) {
+ prevItem = null;
+ }
+ }
+ }
+ function matches(dom, selector) {
+ return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
+ }
+ function copy(obj) {
+ let copy2 = {};
+ for (let prop in obj) copy2[prop] = obj[prop];
+ return copy2;
+ }
+ function markMayApply(markType, nodeType) {
+ let nodes = nodeType.schema.nodes;
+ for (let name in nodes) {
+ let parent = nodes[name];
+ if (!parent.allowsMarkType(markType)) continue;
+ let seen = [], scan = (match2) => {
+ seen.push(match2);
+ for (let i2 = 0; i2 < match2.edgeCount; i2++) {
+ let { type, next } = match2.edge(i2);
+ if (type == nodeType) return true;
+ if (seen.indexOf(next) < 0 && scan(next)) return true;
+ }
+ };
+ if (scan(parent.contentMatch)) return true;
+ }
+ }
+
+ // third_party/editor/prosemirror-model/src/to_dom.ts
+ var DOMSerializer = class _DOMSerializer {
+ /// Create a serializer. `nodes` should map node names to functions
+ /// that take a node and return a description of the corresponding
+ /// DOM. `marks` does the same for mark names, but also gets an
+ /// argument that tells it whether the mark's content is block or
+ /// inline content (for typical use, it'll always be inline). A mark
+ /// serializer may be `null` to indicate that marks of that type
+ /// should not be serialized.
+ constructor(nodes, marks) {
+ this.nodes = nodes;
+ this.marks = marks;
+ }
+ nodes;
+ marks;
+ /// Serialize the content of this fragment to a DOM fragment. When
+ /// not in the browser, the `document` option, containing a DOM
+ /// document, should be passed so that the serializer can create
+ /// nodes.
+ serializeFragment(fragment, options = {}, target) {
+ if (!target) target = doc(options).createDocumentFragment();
+ let top = target, active = [];
+ fragment.forEach((node) => {
+ if (active.length || node.marks.length) {
+ let keep = 0, rendered = 0;
+ while (keep < active.length && rendered < node.marks.length) {
+ let next = node.marks[rendered];
+ if (!this.marks[next.type.name]) {
+ rendered++;
+ continue;
+ }
+ if (!next.eq(active[keep][0]) || next.type.spec.spanning === false) break;
+ keep++;
+ rendered++;
+ }
+ while (keep < active.length) top = active.pop()[1];
+ while (rendered < node.marks.length) {
+ let add2 = node.marks[rendered++];
+ let markDOM = this.serializeMark(add2, node.isInline, options);
+ if (markDOM) {
+ active.push([add2, top]);
+ top.appendChild(markDOM.dom);
+ top = markDOM.contentDOM || markDOM.dom;
+ }
+ }
+ }
+ top.appendChild(this.serializeNodeInner(node, options));
+ });
+ return target;
+ }
+ /// @internal
+ serializeNodeInner(node, options) {
+ if (node.isText) return doc(options).createTextNode(node.text);
+ let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);
+ if (contentDOM) {
+ if (node.isLeaf)
+ throw new RangeError("Content hole not allowed in a leaf node spec");
+ this.serializeFragment(node.content, options, contentDOM);
+ }
+ return dom;
+ }
+ /// Serialize this node to a DOM node. This can be useful when you
+ /// need to serialize a part of a document, as opposed to the whole
+ /// document. To serialize a whole document, use
+ /// [`serializeFragment`](#model.DOMSerializer.serializeFragment) on
+ /// its [content](#model.Node.content).
+ serializeNode(node, options = {}) {
+ let dom = this.serializeNodeInner(node, options);
+ for (let i2 = node.marks.length - 1; i2 >= 0; i2--) {
+ let wrap2 = this.serializeMark(node.marks[i2], node.isInline, options);
+ if (wrap2) {
+ ;
+ (wrap2.contentDOM || wrap2.dom).appendChild(dom);
+ dom = wrap2.dom;
+ }
+ }
+ return dom;
+ }
+ /// @internal
+ serializeMark(mark, inline2, options = {}) {
+ let toDOM = this.marks[mark.type.name];
+ return toDOM && renderSpec(doc(options), toDOM(mark, inline2), null, mark.attrs);
+ }
+ static renderSpec(doc3, structure, xmlNS = null, blockArraysIn) {
+ if (typeof structure == "string") return { dom: doc3.createTextNode(structure) };
+ return renderSpec(doc3, structure, xmlNS, blockArraysIn);
+ }
+ /// Build a serializer using the [`toDOM`](#model.NodeSpec.toDOM)
+ /// properties in a schema's node and mark specs.
+ static fromSchema(schema3) {
+ return schema3.cached.domSerializer || (schema3.cached.domSerializer = new _DOMSerializer(this.nodesFromSchema(schema3), this.marksFromSchema(schema3)));
+ }
+ /// Gather the serializers in a schema's node specs into an object.
+ /// This can be useful as a base to build a custom serializer from.
+ static nodesFromSchema(schema3) {
+ let result = gatherToDOM(schema3.nodes);
+ if (!result.text) result.text = (node) => node.text;
+ return result;
+ }
+ /// Gather the serializers in a schema's mark specs into an object.
+ static marksFromSchema(schema3) {
+ return gatherToDOM(schema3.marks);
+ }
+ };
+ function gatherToDOM(obj) {
+ let result = {};
+ for (let name in obj) {
+ let toDOM = obj[name].spec.toDOM;
+ if (toDOM) result[name] = toDOM;
+ }
+ return result;
+ }
+ function doc(options) {
+ return options.document || window.document;
+ }
+ var suspiciousAttributeCache = /* @__PURE__ */ new WeakMap();
+ function suspiciousAttributes(attrs2) {
+ let value = suspiciousAttributeCache.get(attrs2);
+ if (value === void 0)
+ suspiciousAttributeCache.set(attrs2, value = suspiciousAttributesInner(attrs2));
+ return value;
+ }
+ function suspiciousAttributesInner(attrs2) {
+ let result = null;
+ function scan(value) {
+ if (value && typeof value == "object") {
+ if (Array.isArray(value)) {
+ if (typeof value[0] == "string") {
+ if (!result) result = [];
+ result.push(value);
+ } else {
+ for (let i2 = 0; i2 < value.length; i2++) scan(value[i2]);
+ }
+ } else {
+ for (let prop in value) scan(value[prop]);
+ }
+ }
+ }
+ scan(attrs2);
+ return result;
+ }
+ function renderSpec(doc3, structure, xmlNS, blockArraysIn) {
+ if (structure.nodeType == 1)
+ return { dom: structure };
+ if (structure.dom && structure.dom.nodeType == 1)
+ return structure;
+ let tagName = structure[0], suspicious;
+ if (typeof tagName != "string") throw new RangeError("Invalid array passed to renderSpec");
+ if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1)
+ throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
+ let space = tagName.indexOf(" ");
+ if (space > 0) {
+ xmlNS = tagName.slice(0, space);
+ tagName = tagName.slice(space + 1);
+ }
+ let contentDOM;
+ let dom = xmlNS ? doc3.createElementNS(xmlNS, tagName) : doc3.createElement(tagName);
+ let attrs2 = structure[1], start = 1;
+ if (attrs2 && typeof attrs2 == "object" && attrs2.nodeType == null && !Array.isArray(attrs2)) {
+ start = 2;
+ for (let name in attrs2) if (attrs2[name] != null) {
+ let space2 = name.indexOf(" ");
+ if (space2 > 0) dom.setAttributeNS(name.slice(0, space2), name.slice(space2 + 1), attrs2[name]);
+ else if (name == "style" && dom.style) dom.style.cssText = attrs2[name];
+ else dom.setAttribute(name, attrs2[name]);
+ }
+ }
+ for (let i2 = start; i2 < structure.length; i2++) {
+ let child = structure[i2];
+ if (child === 0) {
+ if (i2 < structure.length - 1 || i2 > start)
+ throw new RangeError("Content hole must be the only child of its parent node");
+ return { dom, contentDOM: dom };
+ } else if (typeof child == "string") {
+ dom.appendChild(doc3.createTextNode(child));
+ } else {
+ let { dom: inner, contentDOM: innerContent } = renderSpec(doc3, child, xmlNS, blockArraysIn);
+ dom.appendChild(inner);
+ if (innerContent) {
+ if (contentDOM) throw new RangeError("Multiple content holes");
+ contentDOM = innerContent;
+ }
+ }
+ }
+ return { dom, contentDOM };
+ }
+
+ // third_party/editor/prosemirror-transform/src/map.ts
+ var lower16 = 65535;
+ var factor16 = Math.pow(2, 16);
+ function makeRecover(index, offset) {
+ return index + offset * factor16;
+ }
+ function recoverIndex(value) {
+ return value & lower16;
+ }
+ function recoverOffset(value) {
+ return (value - (value & lower16)) / factor16;
+ }
+ var DEL_BEFORE = 1;
+ var DEL_AFTER = 2;
+ var DEL_ACROSS = 4;
+ var DEL_SIDE = 8;
+ var MapResult = class {
+ /// @internal
+ constructor(pos, delInfo, recover) {
+ this.pos = pos;
+ this.delInfo = delInfo;
+ this.recover = recover;
+ }
+ pos;
+ delInfo;
+ recover;
+ /// Tells you whether the position was deleted, that is, whether the
+ /// step removed the token on the side queried (via the `assoc`)
+ /// argument from the document.
+ get deleted() {
+ return (this.delInfo & DEL_SIDE) > 0;
+ }
+ /// Tells you whether the token before the mapped position was deleted.
+ get deletedBefore() {
+ return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0;
+ }
+ /// True when the token after the mapped position was deleted.
+ get deletedAfter() {
+ return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0;
+ }
+ /// Tells whether any of the steps mapped through deletes across the
+ /// position (including both the token before and after the
+ /// position).
+ get deletedAcross() {
+ return (this.delInfo & DEL_ACROSS) > 0;
+ }
+ };
+ var StepMap = class _StepMap {
+ /// Create a position map. The modifications to the document are
+ /// represented as an array of numbers, in which each group of three
+ /// represents a modified chunk as `[start, oldSize, newSize]`.
+ constructor(ranges, inverted = false) {
+ this.ranges = ranges;
+ this.inverted = inverted;
+ if (!ranges.length && _StepMap.empty) return _StepMap.empty;
+ }
+ ranges;
+ inverted;
+ /// @internal
+ recover(value) {
+ let diff = 0, index = recoverIndex(value);
+ if (!this.inverted) for (let i2 = 0; i2 < index; i2++)
+ diff += this.ranges[i2 * 3 + 2] - this.ranges[i2 * 3 + 1];
+ return this.ranges[index * 3] + diff + recoverOffset(value);
+ }
+ mapResult(pos, assoc = 1) {
+ return this._map(pos, assoc, false);
+ }
+ map(pos, assoc = 1) {
+ return this._map(pos, assoc, true);
+ }
+ /// @internal
+ _map(pos, assoc, simple) {
+ let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
+ for (let i2 = 0; i2 < this.ranges.length; i2 += 3) {
+ let start = this.ranges[i2] - (this.inverted ? diff : 0);
+ if (start > pos) break;
+ let oldSize = this.ranges[i2 + oldIndex], newSize = this.ranges[i2 + newIndex], end = start + oldSize;
+ if (pos <= end) {
+ let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;
+ let result = start + diff + (side < 0 ? 0 : newSize);
+ if (simple) return result;
+ let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i2 / 3, pos - start);
+ let del2 = 0;
+ if (oldSize) {
+ del2 |= pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
+ if (assoc < 0 ? pos != start : pos != end) del2 |= DEL_SIDE;
+ }
+ return new MapResult(result, del2, recover);
+ }
+ diff += newSize - oldSize;
+ }
+ return simple ? pos + diff : new MapResult(pos + diff, 0, null);
+ }
+ /// @internal
+ touches(pos, recover) {
+ let diff = 0, index = recoverIndex(recover);
+ let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
+ for (let i2 = 0; i2 < this.ranges.length; i2 += 3) {
+ let start = this.ranges[i2] - (this.inverted ? diff : 0);
+ if (start > pos) break;
+ let oldSize = this.ranges[i2 + oldIndex], end = start + oldSize;
+ if (pos <= end && i2 == index * 3) return true;
+ diff += this.ranges[i2 + newIndex] - oldSize;
+ }
+ return false;
+ }
+ /// Calls the given function on each of the changed ranges included in
+ /// this map.
+ forEach(f) {
+ let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
+ for (let i2 = 0, diff = 0; i2 < this.ranges.length; i2 += 3) {
+ let start = this.ranges[i2], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);
+ let oldSize = this.ranges[i2 + oldIndex], newSize = this.ranges[i2 + newIndex];
+ f(oldStart, oldStart + oldSize, newStart, newStart + newSize);
+ diff += newSize - oldSize;
+ }
+ }
+ /// Create an inverted version of this map. The result can be used to
+ /// map positions in the post-step document to the pre-step document.
+ invert() {
+ return new _StepMap(this.ranges, !this.inverted);
+ }
+ /// @internal
+ toString() {
+ return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
+ }
+ /// Create a map that moves all positions by offset `n` (which may be
+ /// negative). This can be useful when applying steps meant for a
+ /// sub-document to a larger document, or vice-versa.
+ static offset(n) {
+ return n == 0 ? _StepMap.empty : new _StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
+ }
+ /// A StepMap that contains no changed ranges.
+ static empty = new _StepMap([]);
+ };
+ var Mapping = class _Mapping {
+ /// Create a new mapping with the given position maps.
+ constructor(maps, mirror, from = 0, to = maps ? maps.length : 0) {
+ this.mirror = mirror;
+ this.from = from;
+ this.to = to;
+ this._maps = maps || [];
+ this.ownData = !(maps || mirror);
+ }
+ mirror;
+ from;
+ to;
+ /// The step maps in this mapping.
+ get maps() {
+ return this._maps;
+ }
+ _maps;
+ // False if maps/mirror are shared arrays that we shouldn't mutate
+ ownData;
+ /// Create a mapping that maps only through a part of this one.
+ slice(from = 0, to = this.maps.length) {
+ return new _Mapping(this._maps, this.mirror, from, to);
+ }
+ /// Add a step map to the end of this mapping. If `mirrors` is
+ /// given, it should be the index of the step map that is the mirror
+ /// image of this one.
+ appendMap(map, mirrors) {
+ if (!this.ownData) {
+ this._maps = this._maps.slice();
+ this.mirror = this.mirror && this.mirror.slice();
+ this.ownData = true;
+ }
+ this.to = this._maps.push(map);
+ if (mirrors != null) this.setMirror(this._maps.length - 1, mirrors);
+ }
+ /// Add all the step maps in a given mapping to this one (preserving
+ /// mirroring information).
+ appendMapping(mapping) {
+ for (let i2 = 0, startSize = this._maps.length; i2 < mapping._maps.length; i2++) {
+ let mirr = mapping.getMirror(i2);
+ this.appendMap(mapping._maps[i2], mirr != null && mirr < i2 ? startSize + mirr : void 0);
+ }
+ }
+ /// Finds the offset of the step map that mirrors the map at the
+ /// given offset, in this mapping (as per the second argument to
+ /// `appendMap`).
+ getMirror(n) {
+ if (this.mirror) {
+ for (let i2 = 0; i2 < this.mirror.length; i2++)
+ if (this.mirror[i2] == n) return this.mirror[i2 + (i2 % 2 ? -1 : 1)];
+ }
+ }
+ /// @internal
+ setMirror(n, m) {
+ if (!this.mirror) this.mirror = [];
+ this.mirror.push(n, m);
+ }
+ /// Append the inverse of the given mapping to this one.
+ appendMappingInverted(mapping) {
+ for (let i2 = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i2 >= 0; i2--) {
+ let mirr = mapping.getMirror(i2);
+ this.appendMap(mapping._maps[i2].invert(), mirr != null && mirr > i2 ? totalSize - mirr - 1 : void 0);
+ }
+ }
+ /// Create an inverted version of this mapping.
+ invert() {
+ let inverse = new _Mapping();
+ inverse.appendMappingInverted(this);
+ return inverse;
+ }
+ /// Map a position through this mapping.
+ map(pos, assoc = 1) {
+ if (this.mirror) return this._map(pos, assoc, true);
+ for (let i2 = this.from; i2 < this.to; i2++)
+ pos = this._maps[i2].map(pos, assoc);
+ return pos;
+ }
+ /// Map a position through this mapping, returning a mapping
+ /// result.
+ mapResult(pos, assoc = 1) {
+ return this._map(pos, assoc, false);
+ }
+ /// @internal
+ _map(pos, assoc, simple) {
+ let delInfo = 0;
+ for (let i2 = this.from; i2 < this.to; i2++) {
+ let map = this._maps[i2], result = map.mapResult(pos, assoc);
+ if (result.recover != null) {
+ let corr = this.getMirror(i2);
+ if (corr != null && corr > i2 && corr < this.to) {
+ i2 = corr;
+ pos = this._maps[corr].recover(result.recover);
+ continue;
+ }
+ }
+ delInfo |= result.delInfo;
+ pos = result.pos;
+ }
+ return simple ? pos : new MapResult(pos, delInfo, null);
+ }
+ };
+
+ // third_party/editor/prosemirror-transform/src/step.ts
+ var stepsByID = /* @__PURE__ */ Object.create(null);
+ var Step = class {
+ /// Get the step map that represents the changes made by this step,
+ /// and which can be used to transform between positions in the old
+ /// and the new document.
+ getMap() {
+ return StepMap.empty;
+ }
+ /// Try to merge this step with another one, to be applied directly
+ /// after it. Returns the merged step when possible, null if the
+ /// steps can't be merged.
+ merge(other) {
+ return null;
+ }
+ /// Deserialize a step from its JSON representation. Will call
+ /// through to the step class' own implementation of this method.
+ static fromJSON(schema3, json) {
+ if (!json || !json.stepType) throw new RangeError("Invalid input for Step.fromJSON");
+ let type = stepsByID[json.stepType];
+ if (!type) throw new RangeError(`No step type ${json.stepType} defined`);
+ return type.fromJSON(schema3, json);
+ }
+ /// To be able to serialize steps to JSON, each step needs a string
+ /// ID to attach to its JSON representation. Use this method to
+ /// register an ID for your step classes. Try to pick something
+ /// that's unlikely to clash with steps from other modules.
+ static jsonID(id, stepClass) {
+ if (id in stepsByID) throw new RangeError("Duplicate use of step JSON ID " + id);
+ stepsByID[id] = stepClass;
+ stepClass.prototype.jsonID = id;
+ return stepClass;
+ }
+ };
+ var StepResult = class _StepResult {
+ /// @internal
+ constructor(doc3, failed) {
+ this.doc = doc3;
+ this.failed = failed;
+ }
+ doc;
+ failed;
+ /// Create a successful step result.
+ static ok(doc3) {
+ return new _StepResult(doc3, null);
+ }
+ /// Create a failed step result.
+ static fail(message) {
+ return new _StepResult(null, message);
+ }
+ /// Call [`Node.replace`](#model.Node.replace) with the given
+ /// arguments. Create a successful result if it succeeds, and a
+ /// failed one if it throws a `ReplaceError`.
+ static fromReplace(doc3, from, to, slice) {
+ try {
+ return _StepResult.ok(doc3.replace(from, to, slice));
+ } catch (e) {
+ if (e instanceof ReplaceError) return _StepResult.fail(e.message);
+ throw e;
+ }
+ }
+ };
+
+ // third_party/editor/prosemirror-transform/src/mark_step.ts
+ function mapFragment(fragment, f, parent) {
+ let mapped = [];
+ for (let i2 = 0; i2 < fragment.childCount; i2++) {
+ let child = fragment.child(i2);
+ if (child.content.size) child = child.copy(mapFragment(child.content, f, child));
+ if (child.isInline) child = f(child, parent, i2);
+ mapped.push(child);
+ }
+ return Fragment.fromArray(mapped);
+ }
+ var AddMarkStep = class _AddMarkStep extends Step {
+ /// Create a mark step.
+ constructor(from, to, mark) {
+ super();
+ this.from = from;
+ this.to = to;
+ this.mark = mark;
+ }
+ from;
+ to;
+ mark;
+ apply(doc3) {
+ let oldSlice = doc3.slice(this.from, this.to), $from = doc3.resolve(this.from);
+ let parent = $from.node($from.sharedDepth(this.to));
+ let slice = new Slice(mapFragment(oldSlice.content, (node, parent2) => {
+ if (!node.isAtom || !parent2.type.allowsMarkType(this.mark.type)) return node;
+ return node.mark(this.mark.addToSet(node.marks));
+ }, parent), oldSlice.openStart, oldSlice.openEnd);
+ return StepResult.fromReplace(doc3, this.from, this.to, slice);
+ }
+ invert() {
+ return new RemoveMarkStep(this.from, this.to, this.mark);
+ }
+ map(mapping) {
+ let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
+ if (from.deleted && to.deleted || from.pos >= to.pos) return null;
+ return new _AddMarkStep(from.pos, to.pos, this.mark);
+ }
+ merge(other) {
+ if (other instanceof _AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
+ return new _AddMarkStep(
+ Math.min(this.from, other.from),
+ Math.max(this.to, other.to),
+ this.mark
+ );
+ return null;
+ }
+ toJSON() {
+ return {
+ stepType: "addMark",
+ mark: this.mark.toJSON(),
+ from: this.from,
+ to: this.to
+ };
+ }
+ /// @internal
+ static fromJSON(schema3, json) {
+ if (typeof json.from != "number" || typeof json.to != "number")
+ throw new RangeError("Invalid input for AddMarkStep.fromJSON");
+ return new _AddMarkStep(json.from, json.to, schema3.markFromJSON(json.mark));
+ }
+ };
+ Step.jsonID("addMark", AddMarkStep);
+ var RemoveMarkStep = class _RemoveMarkStep extends Step {
+ /// Create a mark-removing step.
+ constructor(from, to, mark) {
+ super();
+ this.from = from;
+ this.to = to;
+ this.mark = mark;
+ }
+ from;
+ to;
+ mark;
+ apply(doc3) {
+ let oldSlice = doc3.slice(this.from, this.to);
+ let slice = new Slice(mapFragment(oldSlice.content, (node) => {
+ return node.mark(this.mark.removeFromSet(node.marks));
+ }, doc3), oldSlice.openStart, oldSlice.openEnd);
+ return StepResult.fromReplace(doc3, this.from, this.to, slice);
+ }
+ invert() {
+ return new AddMarkStep(this.from, this.to, this.mark);
+ }
+ map(mapping) {
+ let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
+ if (from.deleted && to.deleted || from.pos >= to.pos) return null;
+ return new _RemoveMarkStep(from.pos, to.pos, this.mark);
+ }
+ merge(other) {
+ if (other instanceof _RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
+ return new _RemoveMarkStep(
+ Math.min(this.from, other.from),
+ Math.max(this.to, other.to),
+ this.mark
+ );
+ return null;
+ }
+ toJSON() {
+ return {
+ stepType: "removeMark",
+ mark: this.mark.toJSON(),
+ from: this.from,
+ to: this.to
+ };
+ }
+ /// @internal
+ static fromJSON(schema3, json) {
+ if (typeof json.from != "number" || typeof json.to != "number")
+ throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
+ return new _RemoveMarkStep(json.from, json.to, schema3.markFromJSON(json.mark));
+ }
+ };
+ Step.jsonID("removeMark", RemoveMarkStep);
+ var AddNodeMarkStep = class _AddNodeMarkStep extends Step {
+ /// Create a node mark step.
+ constructor(pos, mark) {
+ super();
+ this.pos = pos;
+ this.mark = mark;
+ }
+ pos;
+ mark;
+ apply(doc3) {
+ let node = doc3.nodeAt(this.pos);
+ if (!node) return StepResult.fail("No node at mark step's position");
+ let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));
+ return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
+ }
+ invert(doc3) {
+ let node = doc3.nodeAt(this.pos);
+ if (node) {
+ let newSet = this.mark.addToSet(node.marks);
+ if (newSet.length == node.marks.length) {
+ for (let i2 = 0; i2 < node.marks.length; i2++)
+ if (!node.marks[i2].isInSet(newSet))
+ return new _AddNodeMarkStep(this.pos, node.marks[i2]);
+ return new _AddNodeMarkStep(this.pos, this.mark);
+ }
+ }
+ return new RemoveNodeMarkStep(this.pos, this.mark);
+ }
+ map(mapping) {
+ let pos = mapping.mapResult(this.pos, 1);
+ return pos.deletedAfter ? null : new _AddNodeMarkStep(pos.pos, this.mark);
+ }
+ toJSON() {
+ return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
+ }
+ /// @internal
+ static fromJSON(schema3, json) {
+ if (typeof json.pos != "number")
+ throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
+ return new _AddNodeMarkStep(json.pos, schema3.markFromJSON(json.mark));
+ }
+ };
+ Step.jsonID("addNodeMark", AddNodeMarkStep);
+ var RemoveNodeMarkStep = class _RemoveNodeMarkStep extends Step {
+ /// Create a mark-removing step.
+ constructor(pos, mark) {
+ super();
+ this.pos = pos;
+ this.mark = mark;
+ }
+ pos;
+ mark;
+ apply(doc3) {
+ let node = doc3.nodeAt(this.pos);
+ if (!node) return StepResult.fail("No node at mark step's position");
+ let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));
+ return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
+ }
+ invert(doc3) {
+ let node = doc3.nodeAt(this.pos);
+ if (!node || !this.mark.isInSet(node.marks)) return this;
+ return new AddNodeMarkStep(this.pos, this.mark);
+ }
+ map(mapping) {
+ let pos = mapping.mapResult(this.pos, 1);
+ return pos.deletedAfter ? null : new _RemoveNodeMarkStep(pos.pos, this.mark);
+ }
+ toJSON() {
+ return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
+ }
+ /// @internal
+ static fromJSON(schema3, json) {
+ if (typeof json.pos != "number")
+ throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
+ return new _RemoveNodeMarkStep(json.pos, schema3.markFromJSON(json.mark));
+ }
+ };
+ Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
+
+ // third_party/editor/prosemirror-transform/src/replace_step.ts
+ var ReplaceStep = class _ReplaceStep extends Step {
+ /// The given `slice` should fit the 'gap' between `from` and
+ /// `to`—the depths must line up, and the surrounding nodes must be
+ /// able to be joined with the open sides of the slice. When
+ /// `structure` is true, the step will fail if the content between
+ /// from and to is not just a sequence of closing and then opening
+ /// tokens (this is to guard against rebased replace steps
+ /// overwriting something they weren't supposed to).
+ constructor(from, to, slice, structure = false) {
+ super();
+ this.from = from;
+ this.to = to;
+ this.slice = slice;
+ this.structure = structure;
+ }
+ from;
+ to;
+ slice;
+ structure;
+ apply(doc3) {
+ if (this.structure && contentBetween(doc3, this.from, this.to))
+ return StepResult.fail("Structure replace would overwrite content");
+ return StepResult.fromReplace(doc3, this.from, this.to, this.slice);
+ }
+ getMap() {
+ return new StepMap([this.from, this.to - this.from, this.slice.size]);
+ }
+ invert(doc3) {
+ return new _ReplaceStep(this.from, this.from + this.slice.size, doc3.slice(this.from, this.to));
+ }
+ map(mapping) {
+ let to = mapping.mapResult(this.to, -1);
+ let from = this.from == this.to && _ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1);
+ if (from.deletedAcross && to.deletedAcross) return null;
+ return new _ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);
+ }
+ merge(other) {
+ if (!(other instanceof _ReplaceStep) || other.structure || this.structure) return null;
+ if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
+ let slice = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
+ return new _ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);
+ } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
+ let slice = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
+ return new _ReplaceStep(other.from, this.to, slice, this.structure);
+ } else {
+ return null;
+ }
+ }
+ toJSON() {
+ let json = { stepType: "replace", from: this.from, to: this.to };
+ if (this.slice.size) json.slice = this.slice.toJSON();
+ if (this.structure) json.structure = true;
+ return json;
+ }
+ /// @internal
+ static fromJSON(schema3, json) {
+ if (typeof json.from != "number" || typeof json.to != "number")
+ throw new RangeError("Invalid input for ReplaceStep.fromJSON");
+ return new _ReplaceStep(json.from, json.to, Slice.fromJSON(schema3, json.slice), !!json.structure);
+ }
+ /// By default, for backwards compatibility, an inserting step
+ /// mapped over an insertion at that same position fill move after
+ /// the inserted content. In a collaborative editing situation, that
+ /// can make redone insertions appear in unexpected places. You can
+ /// set this to -1 to make such mapping keep the step before the
+ /// insertion instead.
+ static MAP_BIAS = 1;
+ };
+ Step.jsonID("replace", ReplaceStep);
+ var ReplaceAroundStep = class _ReplaceAroundStep extends Step {
+ /// Create a replace-around step with the given range and gap.
+ /// `insert` should be the point in the slice into which the content
+ /// of the gap should be moved. `structure` has the same meaning as
+ /// it has in the [`ReplaceStep`](#transform.ReplaceStep) class.
+ constructor(from, to, gapFrom, gapTo, slice, insert, structure = false) {
+ super();
+ this.from = from;
+ this.to = to;
+ this.gapFrom = gapFrom;
+ this.gapTo = gapTo;
+ this.slice = slice;
+ this.insert = insert;
+ this.structure = structure;
+ }
+ from;
+ to;
+ gapFrom;
+ gapTo;
+ slice;
+ insert;
+ structure;
+ apply(doc3) {
+ if (this.structure && (contentBetween(doc3, this.from, this.gapFrom) || contentBetween(doc3, this.gapTo, this.to)))
+ return StepResult.fail("Structure gap-replace would overwrite content");
+ let gap = doc3.slice(this.gapFrom, this.gapTo);
+ if (gap.openStart || gap.openEnd)
+ return StepResult.fail("Gap is not a flat range");
+ let inserted = this.slice.insertAt(this.insert, gap.content);
+ if (!inserted) return StepResult.fail("Content does not fit in gap");
+ return StepResult.fromReplace(doc3, this.from, this.to, inserted);
+ }
+ getMap() {
+ return new StepMap([
+ this.from,
+ this.gapFrom - this.from,
+ this.insert,
+ this.gapTo,
+ this.to - this.gapTo,
+ this.slice.size - this.insert
+ ]);
+ }
+ invert(doc3) {
+ let gap = this.gapTo - this.gapFrom;
+ return new _ReplaceAroundStep(
+ this.from,
+ this.from + this.slice.size + gap,
+ this.from + this.insert,
+ this.from + this.insert + gap,
+ doc3.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from),
+ this.gapFrom - this.from,
+ this.structure
+ );
+ }
+ map(mapping) {
+ let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
+ let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);
+ let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);
+ if (from.deletedAcross && to.deletedAcross || gapFrom < from.pos || gapTo > to.pos) return null;
+ return new _ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
+ }
+ toJSON() {
+ let json = {
+ stepType: "replaceAround",
+ from: this.from,
+ to: this.to,
+ gapFrom: this.gapFrom,
+ gapTo: this.gapTo,
+ insert: this.insert
+ };
+ if (this.slice.size) json.slice = this.slice.toJSON();
+ if (this.structure) json.structure = true;
+ return json;
+ }
+ /// @internal
+ static fromJSON(schema3, json) {
+ if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
+ throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
+ return new _ReplaceAroundStep(
+ json.from,
+ json.to,
+ json.gapFrom,
+ json.gapTo,
+ Slice.fromJSON(schema3, json.slice),
+ json.insert,
+ !!json.structure
+ );
+ }
+ };
+ Step.jsonID("replaceAround", ReplaceAroundStep);
+ function contentBetween(doc3, from, to) {
+ let $from = doc3.resolve(from), dist = to - from, depth = $from.depth;
+ while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
+ depth--;
+ dist--;
+ }
+ if (dist > 0) {
+ let next = $from.node(depth).maybeChild($from.indexAfter(depth));
+ while (dist > 0) {
+ if (!next || next.isLeaf) return true;
+ next = next.firstChild;
+ dist--;
+ }
+ }
+ return false;
+ }
+
+ // third_party/editor/prosemirror-transform/src/mark.ts
+ function addMark(tr, from, to, mark) {
+ let removed = [], added = [];
+ let removing, adding;
+ tr.doc.nodesBetween(from, to, (node, pos, parent) => {
+ if (!node.isInline) return;
+ let marks = node.marks;
+ if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {
+ let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);
+ let newSet = mark.addToSet(marks);
+ for (let i2 = 0; i2 < marks.length; i2++) {
+ if (!marks[i2].isInSet(newSet)) {
+ if (removing && removing.to == start && removing.mark.eq(marks[i2]))
+ removing.to = end;
+ else
+ removed.push(removing = new RemoveMarkStep(start, end, marks[i2]));
+ }
+ }
+ if (adding && adding.to == start)
+ adding.to = end;
+ else
+ added.push(adding = new AddMarkStep(start, end, mark));
+ }
+ });
+ removed.forEach((s) => tr.step(s));
+ added.forEach((s) => tr.step(s));
+ }
+ function removeMark(tr, from, to, mark) {
+ let matched = [], step = 0;
+ tr.doc.nodesBetween(from, to, (node, pos) => {
+ if (!node.isInline) return;
+ step++;
+ let toRemove = null;
+ if (mark instanceof MarkType) {
+ let set2 = node.marks, found2;
+ while (found2 = mark.isInSet(set2)) {
+ ;
+ (toRemove || (toRemove = [])).push(found2);
+ set2 = found2.removeFromSet(set2);
+ }
+ } else if (mark) {
+ if (mark.isInSet(node.marks)) toRemove = [mark];
+ } else {
+ toRemove = node.marks;
+ }
+ if (toRemove && toRemove.length) {
+ let end = Math.min(pos + node.nodeSize, to);
+ for (let i2 = 0; i2 < toRemove.length; i2++) {
+ let style = toRemove[i2], found2;
+ for (let j = 0; j < matched.length; j++) {
+ let m = matched[j];
+ if (m.step == step - 1 && style.eq(matched[j].style)) found2 = m;
+ }
+ if (found2) {
+ found2.to = end;
+ found2.step = step;
+ } else {
+ matched.push({ style, from: Math.max(pos, from), to: end, step });
+ }
+ }
+ }
+ });
+ matched.forEach((m) => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));
+ }
+ function clearIncompatible(tr, pos, parentType, match2 = parentType.contentMatch, clearNewlines = true) {
+ let node = tr.doc.nodeAt(pos);
+ let replSteps = [], cur = pos + 1;
+ for (let i2 = 0; i2 < node.childCount; i2++) {
+ let child = node.child(i2), end = cur + child.nodeSize;
+ let allowed = match2.matchType(child.type);
+ if (!allowed) {
+ replSteps.push(new ReplaceStep(cur, end, Slice.empty));
+ } else {
+ match2 = allowed;
+ for (let j = 0; j < child.marks.length; j++) if (!parentType.allowsMarkType(child.marks[j].type))
+ tr.step(new RemoveMarkStep(cur, end, child.marks[j]));
+ if (clearNewlines && child.isText && parentType.whitespace != "pre") {
+ let m, newline2 = /\r?\n|\r/g, slice;
+ while (m = newline2.exec(child.text)) {
+ if (!slice) slice = new Slice(
+ Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))),
+ 0,
+ 0
+ );
+ replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));
+ }
+ }
+ }
+ cur = end;
+ }
+ if (!match2.validEnd) {
+ let fill = match2.fillBefore(Fragment.empty, true);
+ tr.replace(cur, cur, new Slice(fill, 0, 0));
+ }
+ for (let i2 = replSteps.length - 1; i2 >= 0; i2--) tr.step(replSteps[i2]);
+ }
+
+ // third_party/editor/prosemirror-transform/src/structure.ts
+ function canCut(node, start, end) {
+ return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end));
+ }
+ function liftTarget(range) {
+ let parent = range.parent;
+ let content = parent.content.cutByIndex(range.startIndex, range.endIndex);
+ for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) {
+ let node = range.$from.node(depth);
+ let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;
+ if (depth < range.depth && node.canReplace(index, endIndex, content))
+ return depth;
+ if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) break;
+ if (index) contentBefore = 1;
+ if (endIndex < node.childCount) contentAfter = 1;
+ }
+ return null;
+ }
+ function lift(tr, range, target) {
+ let { $from, $to, depth } = range;
+ let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
+ let start = gapStart, end = gapEnd;
+ let before = Fragment.empty, openStart = 0;
+ for (let d = depth, splitting = false; d > target; d--)
+ if (splitting || $from.index(d) > 0) {
+ splitting = true;
+ before = Fragment.from($from.node(d).copy(before));
+ openStart++;
+ } else {
+ start--;
+ }
+ let after = Fragment.empty, openEnd = 0;
+ for (let d = depth, splitting = false; d > target; d--)
+ if (splitting || $to.after(d + 1) < $to.end(d)) {
+ splitting = true;
+ after = Fragment.from($to.node(d).copy(after));
+ openEnd++;
+ } else {
+ end++;
+ }
+ tr.step(new ReplaceAroundStep(
+ start,
+ end,
+ gapStart,
+ gapEnd,
+ new Slice(before.append(after), openStart, openEnd),
+ before.size - openStart,
+ true
+ ));
+ }
+ function findWrapping(range, nodeType, attrs2 = null, innerRange = range) {
+ let around = findWrappingOutside(range, nodeType);
+ let inner = around && findWrappingInside(innerRange, nodeType);
+ if (!inner) return null;
+ return around.map(withAttrs).concat({ type: nodeType, attrs: attrs2 }).concat(inner.map(withAttrs));
+ }
+ function withAttrs(type) {
+ return { type, attrs: null };
+ }
+ function findWrappingOutside(range, type) {
+ let { parent, startIndex, endIndex } = range;
+ let around = parent.contentMatchAt(startIndex).findWrapping(type);
+ if (!around) return null;
+ let outer = around.length ? around[0] : type;
+ return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
+ }
+ function findWrappingInside(range, type) {
+ let { parent, startIndex, endIndex } = range;
+ let inner = parent.child(startIndex);
+ let inside = type.contentMatch.findWrapping(inner.type);
+ if (!inside) return null;
+ let lastType = inside.length ? inside[inside.length - 1] : type;
+ let innerMatch = lastType.contentMatch;
+ for (let i2 = startIndex; innerMatch && i2 < endIndex; i2++)
+ innerMatch = innerMatch.matchType(parent.child(i2).type);
+ if (!innerMatch || !innerMatch.validEnd) return null;
+ return inside;
+ }
+ function wrap(tr, range, wrappers) {
+ let content = Fragment.empty;
+ for (let i2 = wrappers.length - 1; i2 >= 0; i2--) {
+ if (content.size) {
+ let match2 = wrappers[i2].type.contentMatch.matchFragment(content);
+ if (!match2 || !match2.validEnd)
+ throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
+ }
+ content = Fragment.from(wrappers[i2].type.create(wrappers[i2].attrs, content));
+ }
+ let start = range.start, end = range.end;
+ tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));
+ }
+ function setBlockType(tr, from, to, type, attrs2) {
+ if (!type.isTextblock) throw new RangeError("Type given to setBlockType should be a textblock");
+ let mapFrom = tr.steps.length;
+ tr.doc.nodesBetween(from, to, (node, pos) => {
+ let attrsHere = typeof attrs2 == "function" ? attrs2(node) : attrs2;
+ if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {
+ let convertNewlines = null;
+ if (type.schema.linebreakReplacement) {
+ let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);
+ if (pre && !supportLinebreak) convertNewlines = false;
+ else if (!pre && supportLinebreak) convertNewlines = true;
+ }
+ if (convertNewlines === false) replaceLinebreaks(tr, node, pos, mapFrom);
+ clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null);
+ let mapping = tr.mapping.slice(mapFrom);
+ let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);
+ tr.step(new ReplaceAroundStep(
+ startM,
+ endM,
+ startM + 1,
+ endM - 1,
+ new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0),
+ 1,
+ true
+ ));
+ if (convertNewlines === true) replaceNewlines(tr, node, pos, mapFrom);
+ return false;
+ }
+ });
+ }
+ function replaceNewlines(tr, node, pos, mapFrom) {
+ node.forEach((child, offset) => {
+ if (child.isText) {
+ let m, newline2 = /\r?\n|\r/g;
+ while (m = newline2.exec(child.text)) {
+ let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);
+ tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());
+ }
+ }
+ });
+ }
+ function replaceLinebreaks(tr, node, pos, mapFrom) {
+ node.forEach((child, offset) => {
+ if (child.type == child.type.schema.linebreakReplacement) {
+ let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);
+ tr.replaceWith(start, start + 1, node.type.schema.text("\n"));
+ }
+ });
+ }
+ function canChangeType(doc3, pos, type) {
+ let $pos = doc3.resolve(pos), index = $pos.index();
+ return $pos.parent.canReplaceWith(index, index + 1, type);
+ }
+ function setNodeMarkup(tr, pos, type, attrs2, marks) {
+ let node = tr.doc.nodeAt(pos);
+ if (!node) throw new RangeError("No node at given position");
+ if (!type) type = node.type;
+ let newNode = type.create(attrs2, null, marks || node.marks);
+ if (node.isLeaf)
+ return tr.replaceWith(pos, pos + node.nodeSize, newNode);
+ if (!type.validContent(node.content))
+ throw new RangeError("Invalid content for node type " + type.name);
+ tr.step(new ReplaceAroundStep(
+ pos,
+ pos + node.nodeSize,
+ pos + 1,
+ pos + node.nodeSize - 1,
+ new Slice(Fragment.from(newNode), 0, 0),
+ 1,
+ true
+ ));
+ }
+ function canSplit(doc3, pos, depth = 1, typesAfter) {
+ let $pos = doc3.resolve(pos), base2 = $pos.depth - depth;
+ let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;
+ if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))
+ return false;
+ for (let d = $pos.depth - 1, i2 = depth - 2; d > base2; d--, i2--) {
+ let node = $pos.node(d), index2 = $pos.index(d);
+ if (node.type.spec.isolating) return false;
+ let rest = node.content.cutByIndex(index2, node.childCount);
+ let overrideChild = typesAfter && typesAfter[i2 + 1];
+ if (overrideChild)
+ rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));
+ let after = typesAfter && typesAfter[i2] || node;
+ if (!node.canReplace(index2 + 1, node.childCount) || !after.type.validContent(rest))
+ return false;
+ }
+ let index = $pos.indexAfter(base2);
+ let baseType = typesAfter && typesAfter[0];
+ return $pos.node(base2).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base2 + 1).type);
+ }
+ function split(tr, pos, depth = 1, typesAfter) {
+ let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;
+ for (let d = $pos.depth, e = $pos.depth - depth, i2 = depth - 1; d > e; d--, i2--) {
+ before = Fragment.from($pos.node(d).copy(before));
+ let typeAfter = typesAfter && typesAfter[i2];
+ after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));
+ }
+ tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));
+ }
+ function canJoin(doc3, pos) {
+ let $pos = doc3.resolve(pos), index = $pos.index();
+ return joinable2($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1);
+ }
+ function canAppendWithSubstitutedLinebreaks(a, b) {
+ if (!b.content.size) a.type.compatibleContent(b.type);
+ let match2 = a.contentMatchAt(a.childCount);
+ let { linebreakReplacement } = a.type.schema;
+ for (let i2 = 0; i2 < b.childCount; i2++) {
+ let child = b.child(i2);
+ let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;
+ match2 = match2.matchType(type);
+ if (!match2) return false;
+ if (!a.type.allowsMarks(child.marks)) return false;
+ }
+ return match2.validEnd;
+ }
+ function joinable2(a, b) {
+ return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));
+ }
+ function join(tr, pos, depth) {
+ let convertNewlines = null;
+ let { linebreakReplacement } = tr.doc.type.schema;
+ let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;
+ if (linebreakReplacement && beforeType.inlineContent) {
+ let pre = beforeType.whitespace == "pre";
+ let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);
+ if (pre && !supportLinebreak) convertNewlines = false;
+ else if (!pre && supportLinebreak) convertNewlines = true;
+ }
+ let mapFrom = tr.steps.length;
+ if (convertNewlines === false) {
+ let $after = tr.doc.resolve(pos + depth);
+ replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);
+ }
+ if (beforeType.inlineContent)
+ clearIncompatible(
+ tr,
+ pos + depth - 1,
+ beforeType,
+ $before.node().contentMatchAt($before.index()),
+ convertNewlines == null
+ );
+ let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);
+ tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));
+ if (convertNewlines === true) {
+ let $full = tr.doc.resolve(start);
+ replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);
+ }
+ return tr;
+ }
+ function insertPoint(doc3, pos, nodeType) {
+ let $pos = doc3.resolve(pos);
+ if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) return pos;
+ if ($pos.parentOffset == 0)
+ for (let d = $pos.depth - 1; d >= 0; d--) {
+ let index = $pos.index(d);
+ if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.before(d + 1);
+ if (index > 0) return null;
+ }
+ if ($pos.parentOffset == $pos.parent.content.size)
+ for (let d = $pos.depth - 1; d >= 0; d--) {
+ let index = $pos.indexAfter(d);
+ if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.after(d + 1);
+ if (index < $pos.node(d).childCount) return null;
+ }
+ return null;
+ }
+ function dropPoint(doc3, pos, slice) {
+ let $pos = doc3.resolve(pos);
+ if (!slice.content.size) return pos;
+ let content = slice.content;
+ for (let i2 = 0; i2 < slice.openStart; i2++) content = content.firstChild.content;
+ for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {
+ for (let d = $pos.depth; d >= 0; d--) {
+ let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;
+ let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);
+ let parent = $pos.node(d), fits = false;
+ if (pass == 1) {
+ fits = parent.canReplace(insertPos, insertPos, content);
+ } else {
+ let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);
+ fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);
+ }
+ if (fits)
+ return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);
+ }
+ }
+ return null;
+ }
+
+ // third_party/editor/prosemirror-transform/src/replace.ts
+ function replaceStep(doc3, from, to = from, slice = Slice.empty) {
+ if (from == to && !slice.size) return null;
+ let $from = doc3.resolve(from), $to = doc3.resolve(to);
+ if (fitsTrivially($from, $to, slice)) return new ReplaceStep(from, to, slice);
+ return new Fitter($from, $to, slice).fit();
+ }
+ function fitsTrivially($from, $to, slice) {
+ return !slice.openStart && !slice.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice.content);
+ }
+ var Fitter = class {
+ constructor($from, $to, unplaced) {
+ this.$from = $from;
+ this.$to = $to;
+ this.unplaced = unplaced;
+ for (let i2 = 0; i2 <= $from.depth; i2++) {
+ let node = $from.node(i2);
+ this.frontier.push({
+ type: node.type,
+ match: node.contentMatchAt($from.indexAfter(i2))
+ });
+ }
+ for (let i2 = $from.depth; i2 > 0; i2--)
+ this.placed = Fragment.from($from.node(i2).copy(this.placed));
+ }
+ $from;
+ $to;
+ unplaced;
+ frontier = [];
+ placed = Fragment.empty;
+ get depth() {
+ return this.frontier.length - 1;
+ }
+ fit() {
+ while (this.unplaced.size) {
+ let fit = this.findFittable();
+ if (fit) this.placeNodes(fit);
+ else this.openMore() || this.dropNode();
+ }
+ let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
+ let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
+ if (!$to) return null;
+ let content = this.placed, openStart = $from.depth, openEnd = $to.depth;
+ while (openStart && openEnd && content.childCount == 1) {
+ content = content.firstChild.content;
+ openStart--;
+ openEnd--;
+ }
+ let slice = new Slice(content, openStart, openEnd);
+ if (moveInline > -1)
+ return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);
+ if (slice.size || $from.pos != this.$to.pos)
+ return new ReplaceStep($from.pos, $to.pos, slice);
+ return null;
+ }
+ // Find a position on the start spine of `this.unplaced` that has
+ // content that can be moved somewhere on the frontier. Returns two
+ // depths, one for the slice and one for the frontier.
+ findFittable() {
+ let startDepth = this.unplaced.openStart;
+ for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {
+ let node = cur.firstChild;
+ if (cur.childCount > 1) openEnd = 0;
+ if (node.type.spec.isolating && openEnd <= d) {
+ startDepth = d;
+ break;
+ }
+ cur = node.content;
+ }
+ for (let pass = 1; pass <= 2; pass++) {
+ for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
+ let fragment, parent = null;
+ if (sliceDepth) {
+ parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
+ fragment = parent.content;
+ } else {
+ fragment = this.unplaced.content;
+ }
+ let first = fragment.firstChild;
+ for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
+ let { type, match: match2 } = this.frontier[frontierDepth], wrap2, inject = null;
+ if (pass == 1 && (first ? match2.matchType(first.type) || (inject = match2.fillBefore(Fragment.from(first), false)) : parent && type.compatibleContent(parent.type)))
+ return { sliceDepth, frontierDepth, parent, inject };
+ else if (pass == 2 && first && (wrap2 = match2.findWrapping(first.type)))
+ return { sliceDepth, frontierDepth, parent, wrap: wrap2 };
+ if (parent && match2.matchType(parent.type)) break;
+ }
+ }
+ }
+ }
+ openMore() {
+ let { content, openStart, openEnd } = this.unplaced;
+ if (maxOpen(content, -1) <= openStart) return false;
+ if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd) openEnd++;
+ this.unplaced = new Slice(content, openStart + 1, openEnd);
+ return true;
+ }
+ dropNode() {
+ let { content, openStart, openEnd } = this.unplaced;
+ let inner = contentAt(content, openStart);
+ if (inner.childCount <= 1 && openStart > 0) {
+ let openAtEnd = content.size - openStart <= openStart + inner.size;
+ this.unplaced = new Slice(
+ dropFromFragment(content, openStart - 1, 1),
+ openStart - 1,
+ openAtEnd ? openStart - 1 : openEnd
+ );
+ } else {
+ this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
+ }
+ }
+ // Move content from the unplaced slice at `sliceDepth` to the
+ // frontier node at `frontierDepth`. Close that frontier node when
+ // applicable.
+ placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap2 }) {
+ while (this.depth > frontierDepth) this.closeFrontierNode();
+ if (wrap2) for (let i2 = 0; i2 < wrap2.length; i2++) this.openFrontierNode(wrap2[i2]);
+ let slice = this.unplaced, fragment = parent ? parent.content : slice.content;
+ let openStart = slice.openStart - sliceDepth;
+ let taken = 0, add2 = [];
+ let { match: match2, type } = this.frontier[frontierDepth];
+ if (inject) {
+ for (let i2 = 0; i2 < inject.childCount; i2++) add2.push(inject.child(i2));
+ match2 = match2.matchFragment(inject);
+ }
+ let openEndCount = fragment.size + sliceDepth - (slice.content.size - slice.openEnd);
+ while (taken < fragment.childCount) {
+ let next = fragment.child(taken), matches2 = match2.matchType(next.type);
+ if (!matches2) break;
+ taken++;
+ if (taken > 1 || openStart == 0 || next.content.size) {
+ match2 = matches2;
+ add2.push(closeNodeStart(
+ next.mark(type.allowedMarks(next.marks)),
+ taken == 1 ? openStart : 0,
+ taken == fragment.childCount ? openEndCount : -1
+ ));
+ }
+ }
+ let toEnd = taken == fragment.childCount;
+ if (!toEnd) openEndCount = -1;
+ this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add2));
+ this.frontier[frontierDepth].match = match2;
+ if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)
+ this.closeFrontierNode();
+ for (let i2 = 0, cur = fragment; i2 < openEndCount; i2++) {
+ let node = cur.lastChild;
+ this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });
+ cur = node.content;
+ }
+ this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(
+ dropFromFragment(slice.content, sliceDepth - 1, 1),
+ sliceDepth - 1,
+ openEndCount < 0 ? slice.openEnd : sliceDepth - 1
+ );
+ }
+ mustMoveInline() {
+ if (!this.$to.parent.isTextblock) return -1;
+ let top = this.frontier[this.depth], level;
+ if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth) return -1;
+ let { depth } = this.$to, after = this.$to.after(depth);
+ while (depth > 1 && after == this.$to.end(--depth)) ++after;
+ return after;
+ }
+ findCloseLevel($to) {
+ scan: for (let i2 = Math.min(this.depth, $to.depth); i2 >= 0; i2--) {
+ let { match: match2, type } = this.frontier[i2];
+ let dropInner = i2 < $to.depth && $to.end(i2 + 1) == $to.pos + ($to.depth - (i2 + 1));
+ let fit = contentAfterFits($to, i2, type, match2, dropInner);
+ if (!fit) continue;
+ for (let d = i2 - 1; d >= 0; d--) {
+ let { match: match3, type: type2 } = this.frontier[d];
+ let matches2 = contentAfterFits($to, d, type2, match3, true);
+ if (!matches2 || matches2.childCount) continue scan;
+ }
+ return { depth: i2, fit, move: dropInner ? $to.doc.resolve($to.after(i2 + 1)) : $to };
+ }
+ }
+ close($to) {
+ let close2 = this.findCloseLevel($to);
+ if (!close2) return null;
+ while (this.depth > close2.depth) this.closeFrontierNode();
+ if (close2.fit.childCount) this.placed = addToFragment(this.placed, close2.depth, close2.fit);
+ $to = close2.move;
+ for (let d = close2.depth + 1; d <= $to.depth; d++) {
+ let node = $to.node(d), add2 = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));
+ this.openFrontierNode(node.type, node.attrs, add2);
+ }
+ return $to;
+ }
+ openFrontierNode(type, attrs2 = null, content) {
+ let top = this.frontier[this.depth];
+ top.match = top.match.matchType(type);
+ this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs2, content)));
+ this.frontier.push({ type, match: type.contentMatch });
+ }
+ closeFrontierNode() {
+ let open = this.frontier.pop();
+ let add2 = open.match.fillBefore(Fragment.empty, true);
+ if (add2.childCount) this.placed = addToFragment(this.placed, this.frontier.length, add2);
+ }
+ };
+ function dropFromFragment(fragment, depth, count) {
+ if (depth == 0) return fragment.cutByIndex(count, fragment.childCount);
+ return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));
+ }
+ function addToFragment(fragment, depth, content) {
+ if (depth == 0) return fragment.append(content);
+ return fragment.replaceChild(
+ fragment.childCount - 1,
+ fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))
+ );
+ }
+ function contentAt(fragment, depth) {
+ for (let i2 = 0; i2 < depth; i2++) fragment = fragment.firstChild.content;
+ return fragment;
+ }
+ function closeNodeStart(node, openStart, openEnd) {
+ if (openStart <= 0) return node;
+ let frag = node.content;
+ if (openStart > 1)
+ frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
+ if (openStart > 0) {
+ frag = node.type.contentMatch.fillBefore(frag).append(frag);
+ if (openEnd <= 0) frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
+ }
+ return node.copy(frag);
+ }
+ function contentAfterFits($to, depth, type, match2, open) {
+ let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);
+ if (index == node.childCount && !type.compatibleContent(node.type)) return null;
+ let fit = match2.fillBefore(node.content, true, index);
+ return fit && !invalidMarks(type, node.content, index) ? fit : null;
+ }
+ function invalidMarks(type, fragment, start) {
+ for (let i2 = start; i2 < fragment.childCount; i2++)
+ if (!type.allowsMarks(fragment.child(i2).marks)) return true;
+ return false;
+ }
+ function definesContent(type) {
+ return type.spec.defining || type.spec.definingForContent;
+ }
+ function maxOpen(frag, side) {
+ for (let count = 0; ; count++) {
+ let ch = side < 0 ? frag.firstChild : frag.lastChild;
+ if (!ch || ch.isAtom) return count;
+ frag = ch.content;
+ }
+ }
+ function replaceRange(tr, from, to, slice) {
+ if (!slice.size) return tr.deleteRange(from, to);
+ let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);
+ if (fitsTrivially($from, $to, slice))
+ return tr.step(new ReplaceStep(from, to, slice));
+ let targetDepths = coveredDepths($from, $to);
+ if (targetDepths[targetDepths.length - 1] == 0) targetDepths.pop();
+ let preferredTarget = -($from.depth + 1);
+ targetDepths.unshift(preferredTarget);
+ for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {
+ let spec = $from.node(d).type.spec;
+ if (spec.defining || spec.definingAsContext || spec.isolating) break;
+ if (targetDepths.indexOf(d) > -1) preferredTarget = d;
+ else if ($from.before(d) == pos) targetDepths.splice(1, 0, -d);
+ }
+ let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
+ let leftNodes = [], preferredDepth = slice.openStart;
+ for (let content = slice.content, i2 = 0; ; i2++) {
+ let node = content.firstChild;
+ leftNodes.push(node);
+ if (i2 == slice.openStart) break;
+ content = node.content;
+ }
+ for (let d = preferredDepth - 1; d >= 0; d--) {
+ let leftNode = leftNodes[d], def = definesContent(leftNode.type);
+ if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1))) preferredDepth = d;
+ else if (def || !leftNode.type.isTextblock) break;
+ }
+ for (let j = slice.openStart; j >= 0; j--) {
+ let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);
+ let insert = leftNodes[openDepth];
+ if (!insert) continue;
+ for (let i2 = 0; i2 < targetDepths.length; i2++) {
+ let targetDepth = targetDepths[(i2 + preferredTargetIndex) % targetDepths.length], expand = true;
+ if (targetDepth < 0) {
+ expand = false;
+ targetDepth = -targetDepth;
+ }
+ let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);
+ if (parent.canReplaceWith(index, index, insert.type, insert.marks))
+ return tr.replace(
+ $from.before(targetDepth),
+ expand ? $to.after(targetDepth) : to,
+ new Slice(
+ closeFragment(slice.content, 0, slice.openStart, openDepth),
+ openDepth,
+ slice.openEnd
+ )
+ );
+ }
+ }
+ let startSteps = tr.steps.length;
+ for (let i2 = targetDepths.length - 1; i2 >= 0; i2--) {
+ tr.replace(from, to, slice);
+ if (tr.steps.length > startSteps) break;
+ let depth = targetDepths[i2];
+ if (depth < 0) continue;
+ from = $from.before(depth);
+ to = $to.after(depth);
+ }
+ }
+ function closeFragment(fragment, depth, oldOpen, newOpen, parent) {
+ if (depth < oldOpen) {
+ let first = fragment.firstChild;
+ fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));
+ }
+ if (depth > newOpen) {
+ let match2 = parent.contentMatchAt(0);
+ let start = match2.fillBefore(fragment).append(fragment);
+ fragment = start.append(match2.matchFragment(start).fillBefore(Fragment.empty, true));
+ }
+ return fragment;
+ }
+ function replaceRangeWith(tr, from, to, node) {
+ if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {
+ let point = insertPoint(tr.doc, from, node.type);
+ if (point != null) from = to = point;
+ }
+ tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));
+ }
+ function deleteRange(tr, from, to) {
+ let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);
+ if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() && $from.parentOffset == 0 && $to.parentOffset == 0) {
+ let shared = $from.sharedDepth(to), isolated = false;
+ for (let d = $from.depth; d > shared; d--) if ($from.node(d).type.spec.isolating) isolated = true;
+ for (let d = $to.depth; d > shared; d--) if ($to.node(d).type.spec.isolating) isolated = true;
+ if (!isolated) {
+ for (let d = $from.depth; d > 0 && from == $from.start(d); d--) from = $from.before(d);
+ for (let d = $to.depth; d > 0 && to == $to.start(d); d--) to = $to.before(d);
+ $from = tr.doc.resolve(from);
+ $to = tr.doc.resolve(to);
+ }
+ }
+ let covered = coveredDepths($from, $to);
+ for (let i2 = 0; i2 < covered.length; i2++) {
+ let depth = covered[i2], last = i2 == covered.length - 1;
+ if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd)
+ return tr.delete($from.start(depth), $to.end(depth));
+ if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
+ return tr.delete($from.before(depth), $to.after(depth));
+ }
+ for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {
+ if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))
+ return tr.delete($from.before(d), to);
+ }
+ tr.delete(from, to);
+ }
+ function coveredDepths($from, $to) {
+ let result = [], minDepth = Math.min($from.depth, $to.depth);
+ for (let d = minDepth; d >= 0; d--) {
+ let start = $from.start(d);
+ if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating) break;
+ if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1)
+ result.push(d);
+ }
+ return result;
+ }
+
+ // third_party/editor/prosemirror-transform/src/attr_step.ts
+ var AttrStep = class _AttrStep extends Step {
+ /// Construct an attribute step.
+ constructor(pos, attr, value) {
+ super();
+ this.pos = pos;
+ this.attr = attr;
+ this.value = value;
+ }
+ pos;
+ attr;
+ value;
+ apply(doc3) {
+ let node = doc3.nodeAt(this.pos);
+ if (!node) return StepResult.fail("No node at attribute step's position");
+ let attrs2 = /* @__PURE__ */ Object.create(null);
+ for (let name in node.attrs) attrs2[name] = node.attrs[name];
+ attrs2[this.attr] = this.value;
+ let updated = node.type.create(attrs2, null, node.marks);
+ return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
+ }
+ getMap() {
+ return StepMap.empty;
+ }
+ invert(doc3) {
+ return new _AttrStep(this.pos, this.attr, doc3.nodeAt(this.pos).attrs[this.attr]);
+ }
+ map(mapping) {
+ let pos = mapping.mapResult(this.pos, 1);
+ return pos.deletedAfter ? null : new _AttrStep(pos.pos, this.attr, this.value);
+ }
+ toJSON() {
+ return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
+ }
+ static fromJSON(schema3, json) {
+ if (typeof json.pos != "number" || typeof json.attr != "string")
+ throw new RangeError("Invalid input for AttrStep.fromJSON");
+ return new _AttrStep(json.pos, json.attr, json.value);
+ }
+ };
+ Step.jsonID("attr", AttrStep);
+ var DocAttrStep = class _DocAttrStep extends Step {
+ /// Construct an attribute step.
+ constructor(attr, value) {
+ super();
+ this.attr = attr;
+ this.value = value;
+ }
+ attr;
+ value;
+ apply(doc3) {
+ let attrs2 = /* @__PURE__ */ Object.create(null);
+ for (let name in doc3.attrs) attrs2[name] = doc3.attrs[name];
+ attrs2[this.attr] = this.value;
+ let updated = doc3.type.create(attrs2, doc3.content, doc3.marks);
+ return StepResult.ok(updated);
+ }
+ getMap() {
+ return StepMap.empty;
+ }
+ invert(doc3) {
+ return new _DocAttrStep(this.attr, doc3.attrs[this.attr]);
+ }
+ map(mapping) {
+ return this;
+ }
+ toJSON() {
+ return { stepType: "docAttr", attr: this.attr, value: this.value };
+ }
+ static fromJSON(schema3, json) {
+ if (typeof json.attr != "string")
+ throw new RangeError("Invalid input for DocAttrStep.fromJSON");
+ return new _DocAttrStep(json.attr, json.value);
+ }
+ };
+ Step.jsonID("docAttr", DocAttrStep);
+
+ // third_party/editor/prosemirror-transform/src/transform.ts
+ var TransformError = class extends Error {
+ };
+ TransformError = function TransformError2(message) {
+ let err = Error.call(this, message);
+ err.__proto__ = TransformError2.prototype;
+ return err;
+ };
+ TransformError.prototype = Object.create(Error.prototype);
+ TransformError.prototype.constructor = TransformError;
+ TransformError.prototype.name = "TransformError";
+ var Transform = class {
+ /// Create a transform that starts with the given document.
+ constructor(doc3) {
+ this.doc = doc3;
+ }
+ doc;
+ /// The steps in this transform.
+ steps = [];
+ /// The documents before each of the steps.
+ docs = [];
+ /// A mapping with the maps for each of the steps in this transform.
+ mapping = new Mapping();
+ /// The starting document.
+ get before() {
+ return this.docs.length ? this.docs[0] : this.doc;
+ }
+ /// Apply a new step in this transform, saving the result. Throws an
+ /// error when the step fails.
+ step(step) {
+ let result = this.maybeStep(step);
+ if (result.failed) throw new TransformError(result.failed);
+ return this;
+ }
+ /// Try to apply a step in this transformation, ignoring it if it
+ /// fails. Returns the step result.
+ maybeStep(step) {
+ let result = step.apply(this.doc);
+ if (!result.failed) this.addStep(step, result.doc);
+ return result;
+ }
+ /// True when the document has been changed (when there are any
+ /// steps).
+ get docChanged() {
+ return this.steps.length > 0;
+ }
+ /// Return a single range, in post-transform document positions,
+ /// that covers all content changed by this transform. Returns null
+ /// if no replacements are made. Note that this will ignore changes
+ /// that add/remove marks without replacing the underlying content.
+ changedRange() {
+ let from = 1e9, to = -1e9;
+ for (let i2 = 0; i2 < this.mapping.maps.length; i2++) {
+ let map = this.mapping.maps[i2];
+ if (i2) {
+ from = map.map(from, 1);
+ to = map.map(to, -1);
+ }
+ map.forEach((_f, _t, fromB, toB) => {
+ from = Math.min(from, fromB);
+ to = Math.max(to, toB);
+ });
+ }
+ return from == 1e9 ? null : { from, to };
+ }
+ /// @internal
+ addStep(step, doc3) {
+ this.docs.push(this.doc);
+ this.steps.push(step);
+ this.mapping.appendMap(step.getMap());
+ this.doc = doc3;
+ }
+ /// Replace the part of the document between `from` and `to` with the
+ /// given `slice`.
+ replace(from, to = from, slice = Slice.empty) {
+ let step = replaceStep(this.doc, from, to, slice);
+ if (step) this.step(step);
+ return this;
+ }
+ /// Replace the given range with the given content, which may be a
+ /// fragment, node, or array of nodes.
+ replaceWith(from, to, content) {
+ return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));
+ }
+ /// Delete the content between the given positions.
+ delete(from, to) {
+ return this.replace(from, to, Slice.empty);
+ }
+ /// Insert the given content at the given position.
+ insert(pos, content) {
+ return this.replaceWith(pos, pos, content);
+ }
+ /// Replace a range of the document with a given slice, using
+ /// `from`, `to`, and the slice's
+ /// [`openStart`](#model.Slice.openStart) property as hints, rather
+ /// than fixed start and end points. This method may grow the
+ /// replaced area or close open nodes in the slice in order to get a
+ /// fit that is more in line with WYSIWYG expectations, by dropping
+ /// fully covered parent nodes of the replaced region when they are
+ /// marked [non-defining as
+ /// context](#model.NodeSpec.definingAsContext), or including an
+ /// open parent node from the slice that _is_ marked as [defining
+ /// its content](#model.NodeSpec.definingForContent).
+ ///
+ /// This is the method, for example, to handle paste. The similar
+ /// [`replace`](#transform.Transform.replace) method is a more
+ /// primitive tool which will _not_ move the start and end of its given
+ /// range, and is useful in situations where you need more precise
+ /// control over what happens.
+ replaceRange(from, to, slice) {
+ replaceRange(this, from, to, slice);
+ return this;
+ }
+ /// Replace the given range with a node, but use `from` and `to` as
+ /// hints, rather than precise positions. When from and to are the same
+ /// and are at the start or end of a parent node in which the given
+ /// node doesn't fit, this method may _move_ them out towards a parent
+ /// that does allow the given node to be placed. When the given range
+ /// completely covers a parent node, this method may completely replace
+ /// that parent node.
+ replaceRangeWith(from, to, node) {
+ replaceRangeWith(this, from, to, node);
+ return this;
+ }
+ /// Delete the given range, expanding it to cover fully covered
+ /// parent nodes until a valid replace is found.
+ deleteRange(from, to) {
+ deleteRange(this, from, to);
+ return this;
+ }
+ /// Split the content in the given range off from its parent, if there
+ /// is sibling content before or after it, and move it up the tree to
+ /// the depth specified by `target`. You'll probably want to use
+ /// [`liftTarget`](#transform.liftTarget) to compute `target`, to make
+ /// sure the lift is valid.
+ lift(range, target) {
+ lift(this, range, target);
+ return this;
+ }
+ /// Join the blocks around the given position. If depth is 2, their
+ /// last and first siblings are also joined, and so on.
+ join(pos, depth = 1) {
+ join(this, pos, depth);
+ return this;
+ }
+ /// Wrap the given [range](#model.NodeRange) in the given set of wrappers.
+ /// The wrappers are assumed to be valid in this position, and should
+ /// probably be computed with [`findWrapping`](#transform.findWrapping).
+ wrap(range, wrappers) {
+ wrap(this, range, wrappers);
+ return this;
+ }
+ /// Set the type of all textblocks (partly) between `from` and `to` to
+ /// the given node type with the given attributes.
+ setBlockType(from, to = from, type, attrs2 = null) {
+ setBlockType(this, from, to, type, attrs2);
+ return this;
+ }
+ /// Change the type, attributes, and/or marks of the node at `pos`.
+ /// When `type` isn't given, the existing node type is preserved,
+ setNodeMarkup(pos, type, attrs2 = null, marks) {
+ setNodeMarkup(this, pos, type, attrs2, marks);
+ return this;
+ }
+ /// Set a single attribute on a given node to a new value.
+ /// The `pos` addresses the document content. Use `setDocAttribute`
+ /// to set attributes on the document itself.
+ setNodeAttribute(pos, attr, value) {
+ this.step(new AttrStep(pos, attr, value));
+ return this;
+ }
+ /// Set a single attribute on the document to a new value.
+ setDocAttribute(attr, value) {
+ this.step(new DocAttrStep(attr, value));
+ return this;
+ }
+ /// Add a mark to the node at position `pos`.
+ addNodeMark(pos, mark) {
+ this.step(new AddNodeMarkStep(pos, mark));
+ return this;
+ }
+ /// Remove a mark (or all marks of the given type) from the node at
+ /// position `pos`.
+ removeNodeMark(pos, mark) {
+ let node = this.doc.nodeAt(pos);
+ if (!node) throw new RangeError("No node at position " + pos);
+ if (mark instanceof Mark) {
+ if (mark.isInSet(node.marks)) this.step(new RemoveNodeMarkStep(pos, mark));
+ } else {
+ let set2 = node.marks, found2, steps = [];
+ while (found2 = mark.isInSet(set2)) {
+ steps.push(new RemoveNodeMarkStep(pos, found2));
+ set2 = found2.removeFromSet(set2);
+ }
+ for (let i2 = steps.length - 1; i2 >= 0; i2--) this.step(steps[i2]);
+ }
+ return this;
+ }
+ /// Split the node at the given position, and optionally, if `depth` is
+ /// greater than one, any number of nodes above that. By default, the
+ /// parts split off will inherit the node type of the original node.
+ /// This can be changed by passing an array of types and attributes to
+ /// use after the split (with the outermost nodes coming first).
+ split(pos, depth = 1, typesAfter) {
+ split(this, pos, depth, typesAfter);
+ return this;
+ }
+ /// Add the given mark to the inline content between `from` and `to`.
+ addMark(from, to, mark) {
+ addMark(this, from, to, mark);
+ return this;
+ }
+ /// Remove marks from inline nodes between `from` and `to`. When
+ /// `mark` is a single mark, remove precisely that mark. When it is
+ /// a mark type, remove all marks of that type. When it is null,
+ /// remove all marks of any type.
+ removeMark(from, to, mark) {
+ removeMark(this, from, to, mark);
+ return this;
+ }
+ /// Removes all marks and nodes from the content of the node at
+ /// `pos` that don't match the given new parent node type. Accepts
+ /// an optional starting [content match](#model.ContentMatch) as
+ /// third argument.
+ clearIncompatible(pos, parentType, match2) {
+ clearIncompatible(this, pos, parentType, match2);
+ return this;
+ }
+ };
+
+ // third_party/editor/prosemirror-state/src/selection.ts
+ var classesById = /* @__PURE__ */ Object.create(null);
+ var Selection = class {
+ /// Initialize a selection with the head and anchor and ranges. If no
+ /// ranges are given, constructs a single range across `$anchor` and
+ /// `$head`.
+ constructor($anchor, $head, ranges) {
+ this.$anchor = $anchor;
+ this.$head = $head;
+ this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
+ }
+ $anchor;
+ $head;
+ /// The ranges covered by the selection.
+ ranges;
+ /// The selection's anchor, as an unresolved position.
+ get anchor() {
+ return this.$anchor.pos;
+ }
+ /// The selection's head.
+ get head() {
+ return this.$head.pos;
+ }
+ /// The lower bound of the selection's main range.
+ get from() {
+ return this.$from.pos;
+ }
+ /// The upper bound of the selection's main range.
+ get to() {
+ return this.$to.pos;
+ }
+ /// The resolved lower bound of the selection's main range.
+ get $from() {
+ return this.ranges[0].$from;
+ }
+ /// The resolved upper bound of the selection's main range.
+ get $to() {
+ return this.ranges[0].$to;
+ }
+ /// Indicates whether the selection contains any content.
+ get empty() {
+ let ranges = this.ranges;
+ for (let i2 = 0; i2 < ranges.length; i2++)
+ if (ranges[i2].$from.pos != ranges[i2].$to.pos) return false;
+ return true;
+ }
+ /// Get the content of this selection as a slice.
+ content() {
+ return this.$from.doc.slice(this.from, this.to, true);
+ }
+ /// Replace the selection with a slice or, if no slice is given,
+ /// delete the selection. Will append to the given transaction.
+ replace(tr, content = Slice.empty) {
+ let lastNode = content.content.lastChild, lastParent = null;
+ for (let i2 = 0; i2 < content.openEnd; i2++) {
+ lastParent = lastNode;
+ lastNode = lastNode.lastChild;
+ }
+ let mapFrom = tr.steps.length, ranges = this.ranges;
+ for (let i2 = 0; i2 < ranges.length; i2++) {
+ let { $from, $to } = ranges[i2], mapping = tr.mapping.slice(mapFrom);
+ tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i2 ? Slice.empty : content);
+ if (i2 == 0)
+ selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
+ }
+ }
+ /// Replace the selection with the given node, appending the changes
+ /// to the given transaction.
+ replaceWith(tr, node) {
+ let mapFrom = tr.steps.length, ranges = this.ranges;
+ for (let i2 = 0; i2 < ranges.length; i2++) {
+ let { $from, $to } = ranges[i2], mapping = tr.mapping.slice(mapFrom);
+ let from = mapping.map($from.pos), to = mapping.map($to.pos);
+ if (i2) {
+ tr.deleteRange(from, to);
+ } else {
+ tr.replaceRangeWith(from, to, node);
+ selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);
+ }
+ }
+ }
+ /// Find a valid cursor or leaf node selection starting at the given
+ /// position and searching back if `dir` is negative, and forward if
+ /// positive. When `textOnly` is true, only consider cursor
+ /// selections. Will return null when no valid selection position is
+ /// found.
+ static findFrom($pos, dir, textOnly = false) {
+ let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
+ if (inner) return inner;
+ for (let depth = $pos.depth - 1; depth >= 0; depth--) {
+ let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
+ if (found2) return found2;
+ }
+ return null;
+ }
+ /// Find a valid cursor or leaf node selection near the given
+ /// position. Searches forward first by default, but if `bias` is
+ /// negative, it will search backwards first.
+ static near($pos, bias = 1) {
+ return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
+ }
+ /// Find the cursor or leaf node selection closest to the start of
+ /// the given document. Will return an
+ /// [`AllSelection`](#state.AllSelection) if no valid position
+ /// exists.
+ static atStart(doc3) {
+ return findSelectionIn(doc3, doc3, 0, 0, 1) || new AllSelection(doc3);
+ }
+ /// Find the cursor or leaf node selection closest to the end of the
+ /// given document.
+ static atEnd(doc3) {
+ return findSelectionIn(doc3, doc3, doc3.content.size, doc3.childCount, -1) || new AllSelection(doc3);
+ }
+ /// Deserialize the JSON representation of a selection. Must be
+ /// implemented for custom classes (as a static class method).
+ static fromJSON(doc3, json) {
+ if (!json || !json.type) throw new RangeError("Invalid input for Selection.fromJSON");
+ let cls = classesById[json.type];
+ if (!cls) throw new RangeError(`No selection type ${json.type} defined`);
+ return cls.fromJSON(doc3, json);
+ }
+ /// To be able to deserialize selections from JSON, custom selection
+ /// classes must register themselves with an ID string, so that they
+ /// can be disambiguated. Try to pick something that's unlikely to
+ /// clash with classes from other modules.
+ static jsonID(id, selectionClass) {
+ if (id in classesById) throw new RangeError("Duplicate use of selection JSON ID " + id);
+ classesById[id] = selectionClass;
+ selectionClass.prototype.jsonID = id;
+ return selectionClass;
+ }
+ /// Get a [bookmark](#state.SelectionBookmark) for this selection,
+ /// which is a value that can be mapped without having access to a
+ /// current document, and later resolved to a real selection for a
+ /// given document again. (This is used mostly by the history to
+ /// track and restore old selections.) The default implementation of
+ /// this method just converts the selection to a text selection and
+ /// returns the bookmark for that.
+ getBookmark() {
+ return TextSelection.between(this.$anchor, this.$head).getBookmark();
+ }
+ };
+ Selection.prototype.visible = true;
+ var SelectionRange = class {
+ /// Create a range.
+ constructor($from, $to) {
+ this.$from = $from;
+ this.$to = $to;
+ }
+ $from;
+ $to;
+ };
+ var warnedAboutTextSelection = false;
+ function checkTextSelection($pos) {
+ if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
+ warnedAboutTextSelection = true;
+ console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
+ }
+ }
+ var TextSelection = class _TextSelection extends Selection {
+ /// Construct a text selection between the given points.
+ constructor($anchor, $head = $anchor) {
+ checkTextSelection($anchor);
+ checkTextSelection($head);
+ super($anchor, $head);
+ }
+ /// Returns a resolved position if this is a cursor selection (an
+ /// empty text selection), and null otherwise.
+ get $cursor() {
+ return this.$anchor.pos == this.$head.pos ? this.$head : null;
+ }
+ map(doc3, mapping) {
+ let $head = doc3.resolve(mapping.map(this.head));
+ if (!$head.parent.inlineContent) return Selection.near($head);
+ let $anchor = doc3.resolve(mapping.map(this.anchor));
+ return new _TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
+ }
+ replace(tr, content = Slice.empty) {
+ super.replace(tr, content);
+ if (content == Slice.empty) {
+ let marks = this.$from.marksAcross(this.$to);
+ if (marks) tr.ensureMarks(marks);
+ }
+ }
+ eq(other) {
+ return other instanceof _TextSelection && other.anchor == this.anchor && other.head == this.head;
+ }
+ getBookmark() {
+ return new TextBookmark(this.anchor, this.head);
+ }
+ toJSON() {
+ return { type: "text", anchor: this.anchor, head: this.head };
+ }
+ /// @internal
+ static fromJSON(doc3, json) {
+ if (typeof json.anchor != "number" || typeof json.head != "number")
+ throw new RangeError("Invalid input for TextSelection.fromJSON");
+ return new _TextSelection(doc3.resolve(json.anchor), doc3.resolve(json.head));
+ }
+ /// Create a text selection from non-resolved positions.
+ static create(doc3, anchor, head = anchor) {
+ let $anchor = doc3.resolve(anchor);
+ return new this($anchor, head == anchor ? $anchor : doc3.resolve(head));
+ }
+ /// Return a text selection that spans the given positions or, if
+ /// they aren't text positions, find a text selection near them.
+ /// `bias` determines whether the method searches forward (default)
+ /// or backwards (negative number) first. Will fall back to calling
+ /// [`Selection.near`](#state.Selection^near) when the document
+ /// doesn't contain a valid text position.
+ static between($anchor, $head, bias) {
+ let dPos = $anchor.pos - $head.pos;
+ if (!bias || dPos) bias = dPos >= 0 ? 1 : -1;
+ if (!$head.parent.inlineContent) {
+ let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
+ if (found2) $head = found2.$head;
+ else return Selection.near($head, bias);
+ }
+ if (!$anchor.parent.inlineContent) {
+ if (dPos == 0) {
+ $anchor = $head;
+ } else {
+ $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
+ if ($anchor.pos < $head.pos != dPos < 0) $anchor = $head;
+ }
+ }
+ return new _TextSelection($anchor, $head);
+ }
+ };
+ Selection.jsonID("text", TextSelection);
+ var TextBookmark = class _TextBookmark {
+ constructor(anchor, head) {
+ this.anchor = anchor;
+ this.head = head;
+ }
+ anchor;
+ head;
+ map(mapping) {
+ return new _TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
+ }
+ resolve(doc3) {
+ return TextSelection.between(doc3.resolve(this.anchor), doc3.resolve(this.head));
+ }
+ };
+ var NodeSelection = class _NodeSelection extends Selection {
+ /// Create a node selection. Does not verify the validity of its
+ /// argument.
+ constructor($pos) {
+ let node = $pos.nodeAfter;
+ let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);
+ super($pos, $end);
+ this.node = node;
+ }
+ /// The selected node.
+ node;
+ map(doc3, mapping) {
+ let { deleted, pos } = mapping.mapResult(this.anchor);
+ let $pos = doc3.resolve(pos);
+ if (deleted) return Selection.near($pos);
+ return new _NodeSelection($pos);
+ }
+ content() {
+ return new Slice(Fragment.from(this.node), 0, 0);
+ }
+ eq(other) {
+ return other instanceof _NodeSelection && other.anchor == this.anchor;
+ }
+ toJSON() {
+ return { type: "node", anchor: this.anchor };
+ }
+ getBookmark() {
+ return new NodeBookmark(this.anchor);
+ }
+ /// @internal
+ static fromJSON(doc3, json) {
+ if (typeof json.anchor != "number")
+ throw new RangeError("Invalid input for NodeSelection.fromJSON");
+ return new _NodeSelection(doc3.resolve(json.anchor));
+ }
+ /// Create a node selection from non-resolved positions.
+ static create(doc3, from) {
+ return new _NodeSelection(doc3.resolve(from));
+ }
+ /// Determines whether the given node may be selected as a node
+ /// selection.
+ static isSelectable(node) {
+ return !node.isText && node.type.spec.selectable !== false;
+ }
+ };
+ NodeSelection.prototype.visible = false;
+ Selection.jsonID("node", NodeSelection);
+ var NodeBookmark = class _NodeBookmark {
+ constructor(anchor) {
+ this.anchor = anchor;
+ }
+ anchor;
+ map(mapping) {
+ let { deleted, pos } = mapping.mapResult(this.anchor);
+ return deleted ? new TextBookmark(pos, pos) : new _NodeBookmark(pos);
+ }
+ resolve(doc3) {
+ let $pos = doc3.resolve(this.anchor), node = $pos.nodeAfter;
+ if (node && NodeSelection.isSelectable(node)) return new NodeSelection($pos);
+ return Selection.near($pos);
+ }
+ };
+ var AllSelection = class _AllSelection extends Selection {
+ /// Create an all-selection over the given document.
+ constructor(doc3) {
+ super(doc3.resolve(0), doc3.resolve(doc3.content.size));
+ }
+ replace(tr, content = Slice.empty) {
+ if (content == Slice.empty) {
+ tr.delete(0, tr.doc.content.size);
+ let sel = Selection.atStart(tr.doc);
+ if (!sel.eq(tr.selection)) tr.setSelection(sel);
+ } else {
+ super.replace(tr, content);
+ }
+ }
+ toJSON() {
+ return { type: "all" };
+ }
+ /// @internal
+ static fromJSON(doc3) {
+ return new _AllSelection(doc3);
+ }
+ map(doc3) {
+ return new _AllSelection(doc3);
+ }
+ eq(other) {
+ return other instanceof _AllSelection;
+ }
+ getBookmark() {
+ return AllBookmark;
+ }
+ };
+ Selection.jsonID("all", AllSelection);
+ var AllBookmark = {
+ map() {
+ return this;
+ },
+ resolve(doc3) {
+ return new AllSelection(doc3);
+ }
+ };
+ function findSelectionIn(doc3, node, pos, index, dir, text2 = false) {
+ if (node.inlineContent) return TextSelection.create(doc3, pos);
+ for (let i2 = index - (dir > 0 ? 0 : 1); dir > 0 ? i2 < node.childCount : i2 >= 0; i2 += dir) {
+ let child = node.child(i2);
+ if (!child.isAtom) {
+ let inner = findSelectionIn(doc3, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text2);
+ if (inner) return inner;
+ } else if (!text2 && NodeSelection.isSelectable(child)) {
+ return NodeSelection.create(doc3, pos - (dir < 0 ? child.nodeSize : 0));
+ }
+ pos += child.nodeSize * dir;
+ }
+ return null;
+ }
+ function selectionToInsertionEnd(tr, startLen, bias) {
+ let last = tr.steps.length - 1;
+ if (last < startLen) return;
+ let step = tr.steps[last];
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return;
+ let map = tr.mapping.maps[last], end;
+ map.forEach((_from, _to, _newFrom, newTo) => {
+ if (end == null) end = newTo;
+ });
+ tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
+ }
+
+ // third_party/editor/prosemirror-state/src/transaction.ts
+ var UPDATED_SEL = 1;
+ var UPDATED_MARKS = 2;
+ var UPDATED_SCROLL = 4;
+ var Transaction = class extends Transform {
+ /// The timestamp associated with this transaction, in the same
+ /// format as `Date.now()`.
+ time;
+ curSelection;
+ // The step count for which the current selection is valid.
+ curSelectionFor = 0;
+ // Bitfield to track which aspects of the state were updated by
+ // this transaction.
+ updated = 0;
+ // Object used to store metadata properties for the transaction.
+ meta = /* @__PURE__ */ Object.create(null);
+ /// The stored marks set by this transaction, if any.
+ storedMarks;
+ /// @internal
+ constructor(state) {
+ super(state.doc);
+ this.time = Date.now();
+ this.curSelection = state.selection;
+ this.storedMarks = state.storedMarks;
+ }
+ /// The transaction's current selection. This defaults to the editor
+ /// selection [mapped](#state.Selection.map) through the steps in the
+ /// transaction, but can be overwritten with
+ /// [`setSelection`](#state.Transaction.setSelection).
+ get selection() {
+ if (this.curSelectionFor < this.steps.length) {
+ this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
+ this.curSelectionFor = this.steps.length;
+ }
+ return this.curSelection;
+ }
+ /// Update the transaction's current selection. Will determine the
+ /// selection that the editor gets when the transaction is applied.
+ setSelection(selection) {
+ if (selection.$from.doc != this.doc)
+ throw new RangeError("Selection passed to setSelection must point at the current document");
+ this.curSelection = selection;
+ this.curSelectionFor = this.steps.length;
+ this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
+ this.storedMarks = null;
+ return this;
+ }
+ /// Whether the selection was explicitly updated by this transaction.
+ get selectionSet() {
+ return (this.updated & UPDATED_SEL) > 0;
+ }
+ /// Set the current stored marks.
+ setStoredMarks(marks) {
+ this.storedMarks = marks;
+ this.updated |= UPDATED_MARKS;
+ return this;
+ }
+ /// Make sure the current stored marks or, if that is null, the marks
+ /// at the selection, match the given set of marks. Does nothing if
+ /// this is already the case.
+ ensureMarks(marks) {
+ if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
+ this.setStoredMarks(marks);
+ return this;
+ }
+ /// Add a mark to the set of stored marks.
+ addStoredMark(mark) {
+ return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
+ }
+ /// Remove a mark or mark type from the set of stored marks.
+ removeStoredMark(mark) {
+ return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
+ }
+ /// Whether the stored marks were explicitly set for this transaction.
+ get storedMarksSet() {
+ return (this.updated & UPDATED_MARKS) > 0;
+ }
+ /// @internal
+ addStep(step, doc3) {
+ super.addStep(step, doc3);
+ this.updated = this.updated & ~UPDATED_MARKS;
+ this.storedMarks = null;
+ }
+ /// Update the timestamp for the transaction.
+ setTime(time) {
+ this.time = time;
+ return this;
+ }
+ /// Replace the current selection with the given slice.
+ replaceSelection(slice) {
+ this.selection.replace(this, slice);
+ return this;
+ }
+ /// Replace the selection with the given node. When `inheritMarks` is
+ /// true and the content is inline, it inherits the marks from the
+ /// place where it is inserted.
+ replaceSelectionWith(node, inheritMarks = true) {
+ let selection = this.selection;
+ if (inheritMarks)
+ node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none));
+ selection.replaceWith(this, node);
+ return this;
+ }
+ /// Delete the selection.
+ deleteSelection() {
+ this.selection.replace(this);
+ return this;
+ }
+ /// Replace the given range, or the selection if no range is given,
+ /// with a text node containing the given string.
+ insertText(text2, from, to) {
+ let schema3 = this.doc.type.schema;
+ if (from == null) {
+ if (!text2) return this.deleteSelection();
+ return this.replaceSelectionWith(schema3.text(text2), true);
+ } else {
+ if (to == null) to = from;
+ if (!text2) return this.deleteRange(from, to);
+ let marks = this.storedMarks;
+ if (!marks) {
+ let $from = this.doc.resolve(from);
+ marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));
+ }
+ this.replaceRangeWith(from, to, schema3.text(text2, marks));
+ if (!this.selection.empty && this.selection.to == from + text2.length)
+ this.setSelection(Selection.near(this.selection.$to));
+ return this;
+ }
+ }
+ /// Store a metadata property in this transaction, keyed either by
+ /// name or by plugin.
+ setMeta(key, value) {
+ this.meta[typeof key == "string" ? key : key.key] = value;
+ return this;
+ }
+ /// Retrieve a metadata property for a given name or plugin.
+ getMeta(key) {
+ return this.meta[typeof key == "string" ? key : key.key];
+ }
+ /// Returns true if this transaction doesn't contain any metadata,
+ /// and can thus safely be extended.
+ get isGeneric() {
+ for (let _ in this.meta) return false;
+ return true;
+ }
+ /// Indicate that the editor should scroll the selection into view
+ /// when updated to the state produced by this transaction.
+ scrollIntoView() {
+ this.updated |= UPDATED_SCROLL;
+ return this;
+ }
+ /// True when this transaction has had `scrollIntoView` called on it.
+ get scrolledIntoView() {
+ return (this.updated & UPDATED_SCROLL) > 0;
+ }
+ };
+
+ // third_party/editor/prosemirror-state/src/state.ts
+ function bind(f, self) {
+ return !self || !f ? f : f.bind(self);
+ }
+ var FieldDesc = class {
+ constructor(name, desc, self) {
+ this.name = name;
+ this.init = bind(desc.init, self);
+ this.apply = bind(desc.apply, self);
+ }
+ name;
+ init;
+ apply;
+ };
+ var baseFields = [
+ new FieldDesc("doc", {
+ init(config2) {
+ return config2.doc || config2.schema.topNodeType.createAndFill();
+ },
+ apply(tr) {
+ return tr.doc;
+ }
+ }),
+ new FieldDesc("selection", {
+ init(config2, instance) {
+ return config2.selection || Selection.atStart(instance.doc);
+ },
+ apply(tr) {
+ return tr.selection;
+ }
+ }),
+ new FieldDesc("storedMarks", {
+ init(config2) {
+ return config2.storedMarks || null;
+ },
+ apply(tr, _marks, _old, state) {
+ return state.selection.$cursor ? tr.storedMarks : null;
+ }
+ }),
+ new FieldDesc("scrollToSelection", {
+ init() {
+ return 0;
+ },
+ apply(tr, prev) {
+ return tr.scrolledIntoView ? prev + 1 : prev;
+ }
+ })
+ ];
+ var Configuration = class {
+ constructor(schema3, plugins) {
+ this.schema = schema3;
+ this.fields = baseFields.slice();
+ if (plugins) plugins.forEach((plugin) => {
+ if (this.pluginsByKey[plugin.key])
+ throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
+ this.plugins.push(plugin);
+ this.pluginsByKey[plugin.key] = plugin;
+ if (plugin.spec.state)
+ this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
+ });
+ }
+ schema;
+ fields;
+ plugins = [];
+ pluginsByKey = /* @__PURE__ */ Object.create(null);
+ };
+ var EditorState = class _EditorState {
+ /// @internal
+ constructor(config2) {
+ this.config = config2;
+ }
+ config;
+ /// The schema of the state's document.
+ get schema() {
+ return this.config.schema;
+ }
+ /// The plugins that are active in this state.
+ get plugins() {
+ return this.config.plugins;
+ }
+ /// Apply the given transaction to produce a new state.
+ apply(tr) {
+ return this.applyTransaction(tr).state;
+ }
+ /// @internal
+ filterTransaction(tr, ignore = -1) {
+ for (let i2 = 0; i2 < this.config.plugins.length; i2++) if (i2 != ignore) {
+ let plugin = this.config.plugins[i2];
+ if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))
+ return false;
+ }
+ return true;
+ }
+ /// Verbose variant of [`apply`](#state.EditorState.apply) that
+ /// returns the precise transactions that were applied (which might
+ /// be influenced by the [transaction
+ /// hooks](#state.PluginSpec.filterTransaction) of
+ /// plugins) along with the new state.
+ applyTransaction(rootTr) {
+ if (!this.filterTransaction(rootTr)) return { state: this, transactions: [] };
+ let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;
+ for (; ; ) {
+ let haveNew = false;
+ for (let i2 = 0; i2 < this.config.plugins.length; i2++) {
+ let plugin = this.config.plugins[i2];
+ if (plugin.spec.appendTransaction) {
+ let n = seen ? seen[i2].n : 0, oldState = seen ? seen[i2].state : this;
+ let tr = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);
+ if (tr && newState.filterTransaction(tr, i2)) {
+ tr.setMeta("appendedTransaction", rootTr);
+ if (!seen) {
+ seen = [];
+ for (let j = 0; j < this.config.plugins.length; j++)
+ seen.push(j < i2 ? { state: newState, n: trs.length } : { state: this, n: 0 });
+ }
+ trs.push(tr);
+ newState = newState.applyInner(tr);
+ haveNew = true;
+ }
+ if (seen) seen[i2] = { state: newState, n: trs.length };
+ }
+ }
+ if (!haveNew) return { state: newState, transactions: trs };
+ }
+ }
+ /// @internal
+ applyInner(tr) {
+ if (!tr.before.eq(this.doc)) throw new RangeError("Applying a mismatched transaction");
+ let newInstance = new _EditorState(this.config), fields = this.config.fields;
+ for (let i2 = 0; i2 < fields.length; i2++) {
+ let field = fields[i2];
+ newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);
+ }
+ return newInstance;
+ }
+ /// Accessor that constructs and returns a new [transaction](#state.Transaction) from this state.
+ get tr() {
+ return new Transaction(this);
+ }
+ /// Create a new state.
+ static create(config2) {
+ let $config = new Configuration(config2.doc ? config2.doc.type.schema : config2.schema, config2.plugins);
+ let instance = new _EditorState($config);
+ for (let i2 = 0; i2 < $config.fields.length; i2++)
+ instance[$config.fields[i2].name] = $config.fields[i2].init(config2, instance);
+ return instance;
+ }
+ /// Create a new state based on this one, but with an adjusted set
+ /// of active plugins. State fields that exist in both sets of
+ /// plugins are kept unchanged. Those that no longer exist are
+ /// dropped, and those that are new are initialized using their
+ /// [`init`](#state.StateField.init) method, passing in the new
+ /// configuration object..
+ reconfigure(config2) {
+ let $config = new Configuration(this.schema, config2.plugins);
+ let fields = $config.fields, instance = new _EditorState($config);
+ for (let i2 = 0; i2 < fields.length; i2++) {
+ let name = fields[i2].name;
+ instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i2].init(config2, instance);
+ }
+ return instance;
+ }
+ /// Serialize this state to JSON. If you want to serialize the state
+ /// of plugins, pass an object mapping property names to use in the
+ /// resulting JSON object to plugin objects. The argument may also be
+ /// a string or number, in which case it is ignored, to support the
+ /// way `JSON.stringify` calls `toString` methods.
+ toJSON(pluginFields) {
+ let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
+ if (this.storedMarks) result.storedMarks = this.storedMarks.map((m) => m.toJSON());
+ if (pluginFields && typeof pluginFields == "object") for (let prop in pluginFields) {
+ if (prop == "doc" || prop == "selection")
+ throw new RangeError("The JSON fields `doc` and `selection` are reserved");
+ let plugin = pluginFields[prop], state = plugin.spec.state;
+ if (state && state.toJSON) result[prop] = state.toJSON.call(plugin, this[plugin.key]);
+ }
+ return result;
+ }
+ /// Deserialize a JSON representation of a state. `config` should
+ /// have at least a `schema` field, and should contain array of
+ /// plugins to initialize the state with. `pluginFields` can be used
+ /// to deserialize the state of plugins, by associating plugin
+ /// instances with the property names they use in the JSON object.
+ static fromJSON(config2, json, pluginFields) {
+ if (!json) throw new RangeError("Invalid input for EditorState.fromJSON");
+ if (!config2.schema) throw new RangeError("Required config field 'schema' missing");
+ let $config = new Configuration(config2.schema, config2.plugins);
+ let instance = new _EditorState($config);
+ $config.fields.forEach((field) => {
+ if (field.name == "doc") {
+ instance.doc = Node.fromJSON(config2.schema, json.doc);
+ } else if (field.name == "selection") {
+ instance.selection = Selection.fromJSON(instance.doc, json.selection);
+ } else if (field.name == "storedMarks") {
+ if (json.storedMarks) instance.storedMarks = json.storedMarks.map(config2.schema.markFromJSON);
+ } else {
+ if (pluginFields) for (let prop in pluginFields) {
+ let plugin = pluginFields[prop], state = plugin.spec.state;
+ if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) {
+ ;
+ instance[field.name] = state.fromJSON.call(plugin, config2, json[prop], instance);
+ return;
+ }
+ }
+ ;
+ instance[field.name] = field.init(config2, instance);
+ }
+ });
+ return instance;
+ }
+ };
+
+ // third_party/editor/prosemirror-state/src/plugin.ts
+ function bindProps(obj, self, target) {
+ for (let prop in obj) {
+ let val = obj[prop];
+ if (val instanceof Function) val = val.bind(self);
+ else if (prop == "handleDOMEvents") val = bindProps(val, self, {});
+ target[prop] = val;
+ }
+ return target;
+ }
+ var Plugin = class {
+ /// Create a plugin.
+ constructor(spec) {
+ this.spec = spec;
+ if (spec.props) bindProps(spec.props, this, this.props);
+ this.key = spec.key ? spec.key.key : createKey("plugin");
+ }
+ spec;
+ /// The [props](#view.EditorProps) exported by this plugin.
+ props = {};
+ /// @internal
+ key;
+ /// Extract the plugin's state field from an editor state.
+ getState(state) {
+ return state[this.key];
+ }
+ };
+ var keys = /* @__PURE__ */ Object.create(null);
+ function createKey(name) {
+ if (name in keys) return name + "$" + ++keys[name];
+ keys[name] = 0;
+ return name + "$";
+ }
+ var PluginKey = class {
+ /// @internal
+ key;
+ /// Create a plugin key.
+ constructor(name = "key") {
+ this.key = createKey(name);
+ }
+ /// Get the active plugin with this key, if any, from an editor
+ /// state.
+ get(state) {
+ return state.config.pluginsByKey[this.key];
+ }
+ /// Get the plugin's state from an editor state.
+ getState(state) {
+ return state[this.key];
+ }
+ };
+
+ // third_party/editor/prosemirror-view/src/dom.ts
+ var domIndex = function(node) {
+ for (var index = 0; ; index++) {
+ node = node.previousSibling;
+ if (!node) return index;
+ }
+ };
+ var parentNode = function(node) {
+ let parent = node.assignedSlot || node.parentNode;
+ return parent && parent.nodeType == 11 ? parent.host : parent;
+ };
+ var reusedRange = null;
+ var textRange = function(node, from, to) {
+ let range = reusedRange || (reusedRange = document.createRange());
+ range.setEnd(node, to == null ? node.nodeValue.length : to);
+ range.setStart(node, from || 0);
+ return range;
+ };
+ var clearReusedRange = function() {
+ reusedRange = null;
+ };
+ var isEquivalentPosition = function(node, off, targetNode, targetOff) {
+ return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1));
+ };
+ var atomElements = /^(img|br|input|textarea|hr)$/i;
+ function scanFor(node, off, targetNode, targetOff, dir) {
+ for (; ; ) {
+ if (node == targetNode && off == targetOff) return true;
+ if (off == (dir < 0 ? 0 : nodeSize(node))) {
+ let parent = node.parentNode;
+ if (!parent || !isElt(parent) || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false")
+ return false;
+ off = domIndex(node) + (dir < 0 ? 0 : 1);
+ node = parent;
+ } else if (isElt(node)) {
+ let child = node.childNodes[off + (dir < 0 ? -1 : 0)];
+ if (isElt(child) && child.contentEditable == "false") {
+ if (child.pmViewDesc?.ignoreForSelection) off += dir;
+ else return false;
+ } else {
+ node = child;
+ off = dir < 0 ? nodeSize(node) : 0;
+ }
+ } else {
+ return false;
+ }
+ }
+ }
+ function nodeSize(node) {
+ return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
+ }
+ function isElt(node) {
+ return node.nodeType == 1;
+ }
+ function isText(node) {
+ return node.nodeType == 3;
+ }
+ function contains(parent, child) {
+ return child ? parent.contains(isElt(child) ? child : child.parentNode) : false;
+ }
+ function textNodeBefore(node, offset) {
+ for (; ; ) {
+ if (isText(node) && offset) return node;
+ if (isElt(node) && offset > 0) {
+ if (node.contentEditable == "false") return null;
+ node = node.childNodes[offset - 1];
+ offset = nodeSize(node);
+ } else if (node.parentNode && !hasBlockDesc(node)) {
+ offset = domIndex(node);
+ node = node.parentNode;
+ } else {
+ return null;
+ }
+ }
+ }
+ function textNodeAfter(node, offset) {
+ for (; ; ) {
+ if (isText(node) && offset < node.nodeValue.length) return node;
+ if (isElt(node) && offset < node.childNodes.length) {
+ if (node.contentEditable == "false") return null;
+ node = node.childNodes[offset];
+ offset = 0;
+ } else if (node.parentNode && !hasBlockDesc(node)) {
+ offset = domIndex(node) + 1;
+ node = node.parentNode;
+ } else {
+ return null;
+ }
+ }
+ }
+ function isOnEdge(node, offset, parent) {
+ for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) {
+ if (node == parent) return true;
+ let index = domIndex(node);
+ node = node.parentNode;
+ if (!node) return false;
+ atStart = atStart && index == 0;
+ atEnd = atEnd && index == nodeSize(node);
+ }
+ }
+ function hasBlockDesc(dom) {
+ let desc;
+ for (let cur = dom; cur; cur = cur.parentNode) if (desc = cur.pmViewDesc) break;
+ return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);
+ }
+ var selectionCollapsed = function(domSel) {
+ return domSel.focusNode && isEquivalentPosition(
+ domSel.focusNode,
+ domSel.focusOffset,
+ domSel.anchorNode,
+ domSel.anchorOffset
+ );
+ };
+ function keyEvent(keyCode, key) {
+ let event = document.createEvent("Event");
+ event.initEvent("keydown", true, true);
+ event.keyCode = keyCode;
+ event.key = event.code = key;
+ return event;
+ }
+ function deepActiveElement(doc3) {
+ let elt = doc3.activeElement;
+ while (elt && elt.shadowRoot) elt = elt.shadowRoot.activeElement;
+ return elt;
+ }
+ function caretFromPoint(doc3, x, y) {
+ if (doc3.caretPositionFromPoint) {
+ try {
+ let pos = doc3.caretPositionFromPoint(x, y);
+ if (pos) return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };
+ } catch (_) {
+ }
+ }
+ if (doc3.caretRangeFromPoint) {
+ let range = doc3.caretRangeFromPoint(x, y);
+ if (range) return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };
+ }
+ }
+
+ // third_party/editor/prosemirror-view/src/browser.ts
+ var nav = typeof navigator != "undefined" ? navigator : null;
+ var doc2 = typeof document != "undefined" ? document : null;
+ var agent = nav && nav.userAgent || "";
+ var ie_edge = /Edge\/(\d+)/.exec(agent);
+ var ie_upto10 = /MSIE \d/.exec(agent);
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent);
+ var ie = !!(ie_upto10 || ie_11up || ie_edge);
+ var ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;
+ var gecko = !ie && /gecko\/(\d+)/i.test(agent);
+ var gecko_version = gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1];
+ var _chrome = !ie && /Chrome\/(\d+)/.exec(agent);
+ var chrome = !!_chrome;
+ var chrome_version = _chrome ? +_chrome[1] : 0;
+ var safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);
+ var ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);
+ var mac = ios || (nav ? /Mac/.test(nav.platform) : false);
+ var windows = nav ? /Win/.test(nav.platform) : false;
+ var android = /Android \d/.test(agent);
+ var webkit = !!doc2 && "webkitFontSmoothing" in doc2.documentElement.style;
+ var webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;
+
+ // third_party/editor/prosemirror-view/src/domcoords.ts
+ function windowRect(doc3) {
+ let vp = doc3.defaultView && doc3.defaultView.visualViewport;
+ if (vp) return {
+ left: 0,
+ right: vp.width,
+ top: 0,
+ bottom: vp.height
+ };
+ return {
+ left: 0,
+ right: doc3.documentElement.clientWidth,
+ top: 0,
+ bottom: doc3.documentElement.clientHeight
+ };
+ }
+ function getSide(value, side) {
+ return typeof value == "number" ? value : value[side];
+ }
+ function clientRect(node) {
+ let rect = node.getBoundingClientRect();
+ let scaleX = rect.width / node.offsetWidth || 1;
+ let scaleY = rect.height / node.offsetHeight || 1;
+ return {
+ left: rect.left,
+ right: rect.left + node.clientWidth * scaleX,
+ top: rect.top,
+ bottom: rect.top + node.clientHeight * scaleY
+ };
+ }
+ function scrollRectIntoView(view, rect, startDOM) {
+ if (!nonZero(rect) && rect.left == 0) return;
+ let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5;
+ let doc3 = view.dom.ownerDocument;
+ for (let parent = startDOM || view.dom; ; ) {
+ if (!parent) break;
+ if (!isElt(parent)) {
+ parent = parentNode(parent);
+ continue;
+ }
+ let atTop = parent == doc3.body;
+ let bounding = atTop ? windowRect(doc3) : clientRect(parent);
+ let moveX = 0, moveY = 0;
+ if (rect.top < bounding.top + getSide(scrollThreshold, "top"))
+ moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top"));
+ else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom"))
+ moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom");
+ if (rect.left < bounding.left + getSide(scrollThreshold, "left"))
+ moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left"));
+ else if (rect.right > bounding.right - getSide(scrollThreshold, "right"))
+ moveX = rect.right - bounding.right + getSide(scrollMargin, "right");
+ if (moveX || moveY) {
+ if (atTop) {
+ doc3.defaultView.scrollBy(moveX, moveY);
+ } else {
+ let startX = parent.scrollLeft, startY = parent.scrollTop;
+ if (moveY) parent.scrollTop += moveY;
+ if (moveX) parent.scrollLeft += moveX;
+ let dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY;
+ rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };
+ }
+ }
+ let pos = atTop ? "fixed" : getComputedStyle(parent).position;
+ if (/^(fixed|sticky)$/.test(pos)) break;
+ parent = pos == "absolute" ? parent.offsetParent : parentNode(parent);
+ }
+ }
+ function storeScrollPos(view) {
+ let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);
+ let refDOM, refTop;
+ for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {
+ let dom = view.root.elementFromPoint(x, y);
+ if (!dom || dom == view.dom || !view.dom.contains(dom)) continue;
+ let localRect = dom.getBoundingClientRect();
+ if (localRect.top >= startY - 20) {
+ refDOM = dom;
+ refTop = localRect.top;
+ break;
+ }
+ }
+ return { refDOM, refTop, stack: scrollStack(view.dom) };
+ }
+ function scrollStack(dom) {
+ let stack = [], doc3 = dom.ownerDocument;
+ for (let cur = dom; cur; cur = parentNode(cur)) {
+ stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });
+ if (dom == doc3) break;
+ }
+ return stack;
+ }
+ function resetScrollPos({ refDOM, refTop, stack }) {
+ let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;
+ restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);
+ }
+ function restoreScrollStack(stack, dTop) {
+ for (let i2 = 0; i2 < stack.length; i2++) {
+ let { dom, top, left } = stack[i2];
+ if (dom.scrollTop != top + dTop) dom.scrollTop = top + dTop;
+ if (dom.scrollLeft != left) dom.scrollLeft = left;
+ }
+ }
+ var preventScrollSupported = null;
+ function focusPreventScroll(dom) {
+ if (dom.setActive) return dom.setActive();
+ if (preventScrollSupported) return dom.focus(preventScrollSupported);
+ let stored = scrollStack(dom);
+ dom.focus(preventScrollSupported == null ? {
+ get preventScroll() {
+ preventScrollSupported = { preventScroll: true };
+ return true;
+ }
+ } : void 0);
+ if (!preventScrollSupported) {
+ preventScrollSupported = false;
+ restoreScrollStack(stored, 0);
+ }
+ }
+ function findOffsetInNode(node, coords) {
+ let closest;
+ let dxClosest = 2e8, coordsClosest, offset = 0;
+ let rowBot = coords.top, rowTop = coords.top;
+ let firstBelow, coordsBelow;
+ for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {
+ let rects;
+ if (isElt(child)) rects = child.getClientRects();
+ else if (isText(child)) rects = textRange(child).getClientRects();
+ else continue;
+ for (let i2 = 0; i2 < rects.length; i2++) {
+ let rect = rects[i2];
+ if (rect.top <= rowBot && rect.bottom >= rowTop) {
+ rowBot = Math.max(rect.bottom, rowBot);
+ rowTop = Math.min(rect.top, rowTop);
+ let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0;
+ if (dx < dxClosest) {
+ closest = child;
+ dxClosest = dx;
+ coordsClosest = dx && isText(closest) ? {
+ left: rect.right < coords.left ? rect.right : rect.left,
+ top: coords.top
+ } : coords;
+ if (isElt(child) && dx)
+ offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);
+ continue;
+ }
+ } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {
+ firstBelow = child;
+ coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };
+ }
+ if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom))
+ offset = childIndex + 1;
+ }
+ }
+ if (!closest && firstBelow) {
+ closest = firstBelow;
+ coordsClosest = coordsBelow;
+ dxClosest = 0;
+ }
+ if (closest && isText(closest)) return findOffsetInText(closest, coordsClosest);
+ if (!closest || dxClosest) return { node, offset };
+ return findOffsetInNode(closest, coordsClosest);
+ }
+ function findOffsetInText(node, coords) {
+ let len = node.nodeValue.length;
+ let range = document.createRange(), result;
+ for (let i2 = 0; i2 < len; i2++) {
+ range.setEnd(node, i2 + 1);
+ range.setStart(node, i2);
+ let rect = singleRect(range, 1);
+ if (rect.top == rect.bottom) continue;
+ if (inRect(coords, rect)) {
+ result = { node, offset: i2 + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };
+ break;
+ }
+ }
+ range.detach();
+ return result || { node, offset: 0 };
+ }
+ function inRect(coords, rect) {
+ return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;
+ }
+ function targetKludge(dom, coords) {
+ let parent = dom.parentNode;
+ if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)
+ return parent;
+ return dom;
+ }
+ function posFromElement(view, elt, coords) {
+ let { node, offset } = findOffsetInNode(elt, coords), bias = -1;
+ if (isElt(node) && !node.firstChild) {
+ let rect = node.getBoundingClientRect();
+ bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;
+ }
+ return view.docView.posFromDOM(node, offset, bias);
+ }
+ function posFromCaret(view, node, offset, coords) {
+ let outsideBlock = -1;
+ for (let cur = node, sawBlock = false; ; ) {
+ if (cur == view.dom) break;
+ let desc = view.docView.nearestDesc(cur, true), rect;
+ if (!desc) return null;
+ if (isElt(desc.dom) && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles
+ ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {
+ if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {
+ if (!sawBlock && rect.left > coords.left || rect.top > coords.top) outsideBlock = desc.posBefore;
+ else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top) outsideBlock = desc.posAfter;
+ sawBlock = true;
+ }
+ if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {
+ let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2;
+ return before ? desc.posBefore : desc.posAfter;
+ }
+ }
+ cur = desc.dom.parentNode;
+ }
+ return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);
+ }
+ function elementFromPoint(element, coords, box) {
+ let len = element.childNodes.length;
+ if (len && box.top < box.bottom) {
+ for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i2 = startI; ; ) {
+ let child = element.childNodes[i2];
+ if (isElt(child)) {
+ let rects = child.getClientRects();
+ for (let j = 0; j < rects.length; j++) {
+ let rect = rects[j];
+ if (inRect(coords, rect)) return elementFromPoint(child, coords, rect);
+ }
+ }
+ if ((i2 = (i2 + 1) % len) == startI) break;
+ }
+ }
+ return element;
+ }
+ function posAtCoords(view, coords) {
+ let doc3 = view.dom.ownerDocument, node, offset = 0;
+ let caret = caretFromPoint(doc3, coords.left, coords.top);
+ if (caret) ({ node, offset } = caret);
+ let elt = (view.root.elementFromPoint ? view.root : doc3).elementFromPoint(coords.left, coords.top);
+ let pos;
+ if (!elt || !view.dom.contains(elt)) {
+ let box = view.dom.getBoundingClientRect();
+ if (!inRect(coords, box)) return null;
+ elt = elementFromPoint(view.dom, coords, box);
+ if (!elt) return null;
+ }
+ if (safari) {
+ for (let p = elt; node && p; p = parentNode(p))
+ if (p.draggable) node = void 0;
+ }
+ elt = targetKludge(elt, coords);
+ if (node) {
+ if (gecko && isElt(node)) {
+ offset = Math.min(offset, node.childNodes.length);
+ if (offset < node.childNodes.length) {
+ let next = node.childNodes[offset], box;
+ if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top)
+ offset++;
+ }
+ }
+ let prev;
+ if (webkit && offset && isElt(node) && isElt(prev = node.childNodes[offset - 1]) && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top)
+ offset--;
+ if (node == view.dom && offset == node.childNodes.length - 1 && isElt(node.lastChild) && coords.top > node.lastChild.getBoundingClientRect().bottom)
+ pos = view.state.doc.content.size;
+ else if (offset == 0 || !isElt(node) || node.childNodes[offset - 1].nodeName != "BR")
+ pos = posFromCaret(view, node, offset, coords);
+ }
+ if (pos == null) pos = posFromElement(view, elt, coords);
+ let desc = view.docView.nearestDesc(elt, true);
+ return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };
+ }
+ function nonZero(rect) {
+ return rect.top < rect.bottom || rect.left < rect.right;
+ }
+ function singleRect(target, bias) {
+ let rects = target.getClientRects();
+ if (rects.length) {
+ let first = rects[bias < 0 ? 0 : rects.length - 1];
+ if (nonZero(first)) return first;
+ }
+ return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();
+ }
+ var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+ function coordsAtPos(view, pos, side) {
+ let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);
+ let supportEmptyRange = webkit || gecko;
+ if (isText(node)) {
+ if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {
+ let rect = singleRect(textRange(node, offset, offset), side);
+ if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {
+ let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);
+ if (rectBefore.top == rect.top) {
+ let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);
+ if (rectAfter.top != rect.top)
+ return flattenV(rectAfter, rectAfter.left < rectBefore.left);
+ }
+ }
+ return rect;
+ } else {
+ let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;
+ if (side < 0 && !offset) {
+ to++;
+ takeSide = -1;
+ } else if (side >= 0 && offset == node.nodeValue.length) {
+ from--;
+ takeSide = 1;
+ } else if (side < 0) {
+ from--;
+ } else {
+ to++;
+ }
+ return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);
+ }
+ }
+ let $dom = view.state.doc.resolve(pos - (atom || 0));
+ if (!$dom.parent.inlineContent) {
+ if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
+ let before = node.childNodes[offset - 1];
+ if (isElt(before)) return flattenH(before.getBoundingClientRect(), false);
+ }
+ if (atom == null && offset < nodeSize(node)) {
+ let after = node.childNodes[offset];
+ if (isElt(after)) return flattenH(after.getBoundingClientRect(), true);
+ }
+ return flattenH(node.getBoundingClientRect(), side >= 0);
+ }
+ if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
+ let before = node.childNodes[offset - 1];
+ let target = isText(before) ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : isElt(before) && (before.nodeName != "BR" || !before.nextSibling) ? before : null;
+ if (target) return flattenV(singleRect(target, 1), false);
+ }
+ if (atom == null && offset < nodeSize(node)) {
+ let after = node.childNodes[offset];
+ while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords) after = after.nextSibling;
+ let target = !after ? null : isText(after) ? textRange(after, 0, supportEmptyRange ? 0 : 1) : isElt(after) ? after : null;
+ if (target) return flattenV(singleRect(target, -1), true);
+ }
+ return flattenV(singleRect(isText(node) ? textRange(node) : node, -side), side >= 0);
+ }
+ function flattenV(rect, left) {
+ if (rect.width == 0) return rect;
+ let x = left ? rect.left : rect.right;
+ return { top: rect.top, bottom: rect.bottom, left: x, right: x };
+ }
+ function flattenH(rect, top) {
+ if (rect.height == 0) return rect;
+ let y = top ? rect.top : rect.bottom;
+ return { top: y, bottom: y, left: rect.left, right: rect.right };
+ }
+ function withFlushedState(view, state, f) {
+ let viewState = view.state, active = view.root.activeElement;
+ if (viewState != state) view.updateState(state);
+ if (active != view.dom) view.focus();
+ try {
+ return f();
+ } finally {
+ if (viewState != state) view.updateState(viewState);
+ if (active != view.dom && active) active.focus();
+ }
+ }
+ function endOfTextblockVertical(view, state, dir) {
+ let sel = state.selection;
+ let $pos = dir == "up" ? sel.$from : sel.$to;
+ return withFlushedState(view, state, () => {
+ let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1);
+ for (; ; ) {
+ let nearest = view.docView.nearestDesc(dom, true);
+ if (!nearest) break;
+ if (nearest.node.isBlock) {
+ dom = nearest.contentDOM || nearest.dom;
+ break;
+ }
+ dom = nearest.dom.parentNode;
+ }
+ let coords = coordsAtPos(view, $pos.pos, 1);
+ for (let child = dom.firstChild; child; child = child.nextSibling) {
+ let boxes;
+ if (isElt(child)) boxes = child.getClientRects();
+ else if (isText(child)) boxes = textRange(child, 0, child.nodeValue.length).getClientRects();
+ else continue;
+ for (let i2 = 0; i2 < boxes.length; i2++) {
+ let box = boxes[i2];
+ if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))
+ return false;
+ }
+ }
+ return true;
+ });
+ }
+ var maybeRTL = /[\u0590-\u08ac]/;
+ function endOfTextblockHorizontal(view, state, dir) {
+ let { $head } = state.selection;
+ if (!$head.parent.isTextblock) return false;
+ let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;
+ let sel = view.domSelection();
+ if (!sel) return $head.pos == $head.start() || $head.pos == $head.end();
+ if (!maybeRTL.test($head.parent.textContent) || !sel.modify)
+ return dir == "left" || dir == "backward" ? atStart : atEnd;
+ return withFlushedState(view, state, () => {
+ let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();
+ let oldBidiLevel = sel.caretBidiLevel;
+ sel.modify("move", dir, "character");
+ let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;
+ let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();
+ let result = newNode && !contains(parentDOM, newNode) || oldNode == newNode && oldOff == newOff;
+ try {
+ sel.collapse(anchorNode, anchorOffset);
+ if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend) sel.extend(oldNode, oldOff);
+ } catch (_) {
+ }
+ if (oldBidiLevel != null) sel.caretBidiLevel = oldBidiLevel;
+ return result;
+ });
+ }
+ var cachedState = null;
+ var cachedDir = null;
+ var cachedResult = false;
+ function endOfTextblock(view, state, dir) {
+ if (cachedState == state && cachedDir == dir) return cachedResult;
+ cachedState = state;
+ cachedDir = dir;
+ return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir);
+ }
+
+ // third_party/editor/prosemirror-view/src/viewdesc.ts
+ var NOT_DIRTY = 0;
+ var CHILD_DIRTY = 1;
+ var CONTENT_DIRTY = 2;
+ var NODE_DIRTY = 3;
+ var ViewDesc = class {
+ constructor(parent, children, dom, contentDOM) {
+ this.parent = parent;
+ this.children = children;
+ this.dom = dom;
+ this.contentDOM = contentDOM;
+ dom.pmViewDesc = this;
+ }
+ parent;
+ children;
+ dom;
+ contentDOM;
+ dirty = NOT_DIRTY;
+ // Used to check whether a given description corresponds to a
+ // widget/mark/node.
+ matchesWidget(widget) {
+ return false;
+ }
+ matchesMark(mark) {
+ return false;
+ }
+ matchesNode(node, outerDeco, innerDeco) {
+ return false;
+ }
+ matchesHack(nodeName) {
+ return false;
+ }
+ // When parsing in-editor content (in domchange.js), we allow
+ // descriptions to determine the parse rules that should be used to
+ // parse them.
+ parseRule(addedNodes) {
+ return null;
+ }
+ // Used by the editor's event handler to ignore events that come
+ // from certain descs.
+ stopEvent(event) {
+ return false;
+ }
+ // The size of the content represented by this desc.
+ get size() {
+ let size = 0;
+ for (let i2 = 0; i2 < this.children.length; i2++) size += this.children[i2].size;
+ return size;
+ }
+ // For block nodes, this represents the space taken up by their
+ // start/end tokens.
+ get border() {
+ return 0;
+ }
+ destroy() {
+ this.parent = void 0;
+ if (this.dom.pmViewDesc == this) this.dom.pmViewDesc = void 0;
+ for (let i2 = 0; i2 < this.children.length; i2++)
+ this.children[i2].destroy();
+ }
+ posBeforeChild(child) {
+ for (let i2 = 0, pos = this.posAtStart; ; i2++) {
+ let cur = this.children[i2];
+ if (cur == child) return pos;
+ pos += cur.size;
+ }
+ }
+ get posBefore() {
+ return this.parent.posBeforeChild(this);
+ }
+ get posAtStart() {
+ return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;
+ }
+ get posAfter() {
+ return this.posBefore + this.size;
+ }
+ get posAtEnd() {
+ return this.posAtStart + this.size - 2 * this.border;
+ }
+ localPosFromDOM(dom, offset, bias) {
+ if (this.contentDOM && contains(this.contentDOM, dom)) {
+ if (bias < 0) {
+ let domBefore, desc;
+ if (dom == this.contentDOM) {
+ domBefore = dom.childNodes[offset - 1];
+ } else {
+ while (dom.parentNode != this.contentDOM) dom = dom.parentNode;
+ domBefore = dom.previousSibling;
+ }
+ while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) domBefore = domBefore.previousSibling;
+ return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;
+ } else {
+ let domAfter, desc;
+ if (dom == this.contentDOM) {
+ domAfter = dom.childNodes[offset];
+ } else {
+ while (dom.parentNode != this.contentDOM) dom = dom.parentNode;
+ domAfter = dom.nextSibling;
+ }
+ while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) domAfter = domAfter.nextSibling;
+ return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;
+ }
+ }
+ let atEnd;
+ if (dom == this.dom && this.contentDOM) {
+ atEnd = offset > domIndex(this.contentDOM);
+ } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
+ atEnd = !!(dom.compareDocumentPosition(this.contentDOM) & 4);
+ } else if (this.dom.firstChild) {
+ if (offset == 0) for (let search = dom; ; search = search.parentNode) {
+ if (search == this.dom) {
+ atEnd = false;
+ break;
+ }
+ if (search.previousSibling) break;
+ }
+ if (atEnd == null && offset == dom.childNodes.length) for (let search = dom; ; search = search.parentNode) {
+ if (search == this.dom) {
+ atEnd = true;
+ break;
+ }
+ if (search.nextSibling) break;
+ }
+ }
+ return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;
+ }
+ nearestDesc(dom, onlyNodes = false) {
+ for (let first = true, cur = dom; cur; cur = cur.parentNode) {
+ let desc = this.getDesc(cur), nodeDOM;
+ if (desc && (!onlyNodes || desc.node)) {
+ if (first && (nodeDOM = desc.nodeDOM) && !(isElt(nodeDOM) ? contains(nodeDOM, dom) : nodeDOM == dom))
+ first = false;
+ else
+ return desc;
+ }
+ }
+ }
+ getDesc(dom) {
+ let desc = dom.pmViewDesc;
+ for (let cur = desc; cur; cur = cur.parent) if (cur == this) return desc;
+ }
+ posFromDOM(dom, offset, bias) {
+ for (let scan = dom; scan; scan = scan.parentNode) {
+ let desc = this.getDesc(scan);
+ if (desc) return desc.localPosFromDOM(dom, offset, bias);
+ }
+ return -1;
+ }
+ // Find the desc for the node after the given pos, if any. (When a
+ // parent node overrode rendering, there might not be one.)
+ descAt(pos) {
+ for (let i2 = 0, offset = 0; i2 < this.children.length; i2++) {
+ let child = this.children[i2], end = offset + child.size;
+ if (offset == pos && end != offset) {
+ while (!child.border && child.children.length) {
+ for (let i3 = 0; i3 < child.children.length; i3++) {
+ let inner = child.children[i3];
+ if (inner.size) {
+ child = inner;
+ break;
+ }
+ }
+ }
+ return child;
+ }
+ if (pos < end) return child.descAt(pos - offset - child.border);
+ offset = end;
+ }
+ }
+ domFromPos(pos, side) {
+ if (!this.contentDOM) return { node: this.dom, offset: 0, atom: pos + 1 };
+ let i2 = 0, offset = 0;
+ for (let curPos = 0; i2 < this.children.length; i2++) {
+ let child = this.children[i2], end = curPos + child.size;
+ if (end > pos) {
+ offset = pos - curPos;
+ break;
+ }
+ curPos = end;
+ }
+ if (offset) return this.children[i2].domFromPos(offset - this.children[i2].border, side);
+ for (; i2 > 0; i2--) {
+ let prev = this.children[i2 - 1];
+ if (prev.size || !(prev instanceof BufferHackViewDesc || prev instanceof WidgetViewDesc && prev.side >= 0))
+ break;
+ }
+ if (side <= 0) {
+ let prev, enter = true;
+ for (; ; i2--, enter = false) {
+ prev = i2 ? this.children[i2 - 1] : null;
+ if (!prev || prev.dom.parentNode == this.contentDOM) break;
+ }
+ if (prev && side && enter && !prev.border && !prev.domAtom) return prev.domFromPos(prev.size, side);
+ return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };
+ } else {
+ let next, enter = true;
+ for (; ; i2++, enter = false) {
+ next = i2 < this.children.length ? this.children[i2] : null;
+ if (!next || next.dom.parentNode == this.contentDOM) break;
+ }
+ if (next && enter && !next.border && !next.domAtom) return next.domFromPos(0, side);
+ return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };
+ }
+ }
+ // Used to find a DOM range in a single parent for a given changed
+ // range.
+ parseRange(from, to, base2 = 0) {
+ if (this.children.length == 0)
+ return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };
+ let fromOffset = -1, toOffset = -1;
+ for (let offset = base2, i2 = 0; ; i2++) {
+ let child = this.children[i2], end = offset + child.size;
+ if (fromOffset == -1 && from <= end) {
+ let childBase = offset + child.border;
+ if (from >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM))
+ return child.parseRange(from, to, childBase);
+ from = offset;
+ for (let j = i2; j > 0; j--) {
+ let prev = this.children[j - 1];
+ if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
+ fromOffset = domIndex(prev.dom) + 1;
+ break;
+ }
+ from -= prev.size;
+ }
+ if (fromOffset == -1) fromOffset = 0;
+ }
+ if (fromOffset > -1 && (end > to || i2 == this.children.length - 1)) {
+ to = end;
+ for (let j = i2 + 1; j < this.children.length; j++) {
+ let next = this.children[j];
+ if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
+ toOffset = domIndex(next.dom);
+ break;
+ }
+ to += next.size;
+ }
+ if (toOffset == -1) toOffset = this.contentDOM.childNodes.length;
+ break;
+ }
+ offset = end;
+ }
+ return { node: this.contentDOM, from, to, fromOffset, toOffset };
+ }
+ emptyChildAt(side) {
+ if (this.border || !this.contentDOM || !this.children.length) return false;
+ let child = this.children[side < 0 ? 0 : this.children.length - 1];
+ return child.size == 0 || child.emptyChildAt(side);
+ }
+ domAfterPos(pos) {
+ let { node, offset } = this.domFromPos(pos, 0);
+ if (!isElt(node) || offset == node.childNodes.length)
+ throw new RangeError("No node after pos " + pos);
+ return node.childNodes[offset];
+ }
+ // View descs are responsible for setting any selection that falls
+ // entirely inside of them, so that custom implementations can do
+ // custom things with the selection. Note that this falls apart when
+ // a selection starts in such a node and ends in another, in which
+ // case we just use whatever domFromPos produces as a best effort.
+ setSelection(anchor, head, view, force = false) {
+ let from = Math.min(anchor, head), to = Math.max(anchor, head);
+ for (let i2 = 0, offset = 0; i2 < this.children.length; i2++) {
+ let child = this.children[i2], end = offset + child.size;
+ if (from > offset && to < end)
+ return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);
+ offset = end;
+ }
+ let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);
+ let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);
+ let domSel = view.root.getSelection();
+ let selRange = view.domSelectionRange();
+ let brKludge = false;
+ if ((gecko || safari) && anchor == head) {
+ let { node, offset } = anchorDOM;
+ if (isText(node)) {
+ brKludge = !!(offset && node.nodeValue[offset - 1] == "\n");
+ if (brKludge && offset == node.nodeValue.length) {
+ for (let scan = node, after; scan; scan = scan.parentNode) {
+ if (after = scan.nextSibling) {
+ if (after.nodeName == "BR")
+ anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };
+ break;
+ }
+ let desc = scan.pmViewDesc;
+ if (desc && desc.node && desc.node.isBlock) break;
+ }
+ }
+ } else {
+ let prev = node.childNodes[offset - 1];
+ brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false");
+ }
+ }
+ if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && isElt(selRange.focusNode)) {
+ let after = selRange.focusNode.childNodes[selRange.focusOffset];
+ if (after && after.contentEditable == "false") force = true;
+ }
+ if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))
+ return;
+ let domSelExtended = false;
+ if ((domSel.extend || anchor == head) && !(brKludge && gecko)) {
+ domSel.collapse(anchorDOM.node, anchorDOM.offset);
+ try {
+ if (anchor != head)
+ domSel.extend(headDOM.node, headDOM.offset);
+ domSelExtended = true;
+ } catch (_) {
+ }
+ }
+ if (!domSelExtended) {
+ if (anchor > head) {
+ let tmp = anchorDOM;
+ anchorDOM = headDOM;
+ headDOM = tmp;
+ }
+ let range = document.createRange();
+ range.setEnd(headDOM.node, headDOM.offset);
+ range.setStart(anchorDOM.node, anchorDOM.offset);
+ domSel.removeAllRanges();
+ domSel.addRange(range);
+ }
+ }
+ ignoreMutation(mutation) {
+ return !this.contentDOM && mutation.type != "selection";
+ }
+ get contentLost() {
+ return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);
+ }
+ // Remove a subtree of the element tree that has been touched
+ // by a DOM change, so that the next update will redraw it.
+ markDirty(from, to) {
+ for (let offset = 0, i2 = 0; i2 < this.children.length; i2++) {
+ let child = this.children[i2], end = offset + child.size;
+ if (offset == end ? from <= end && to >= offset : from < end && to > offset) {
+ let startInside = offset + child.border, endInside = end - child.border;
+ if (from >= startInside && to <= endInside) {
+ this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;
+ if (from == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM)) child.dirty = NODE_DIRTY;
+ else child.markDirty(from - startInside, to - startInside);
+ return;
+ } else {
+ child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY;
+ }
+ }
+ offset = end;
+ }
+ this.dirty = CONTENT_DIRTY;
+ }
+ markParentsDirty() {
+ let level = 1;
+ for (let node = this.parent; node; node = node.parent, level++) {
+ let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;
+ if (node.dirty < dirty) node.dirty = dirty;
+ }
+ }
+ get domAtom() {
+ return false;
+ }
+ get ignoreForCoords() {
+ return false;
+ }
+ get ignoreForSelection() {
+ return false;
+ }
+ isText(text2) {
+ return false;
+ }
+ };
+ var WidgetViewDesc = class extends ViewDesc {
+ constructor(parent, widget, view, pos) {
+ let self, dom = widget.type.toDOM;
+ if (typeof dom == "function") dom = dom(view, () => {
+ if (!self) return pos;
+ if (self.parent) return self.parent.posBeforeChild(self);
+ });
+ if (!widget.type.spec.raw) {
+ let elt = isElt(dom) ? dom : document.createElement("span");
+ if (elt != dom) elt.appendChild(dom);
+ if (!elt.hasAttribute("contenteditable"))
+ elt.contentEditable = "false";
+ elt.classList.add("ProseMirror-widget");
+ }
+ super(parent, [], dom, null);
+ this.widget = widget;
+ this.widget = widget;
+ self = this;
+ }
+ widget;
+ matchesWidget(widget) {
+ return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);
+ }
+ parseRule() {
+ return { ignore: true };
+ }
+ stopEvent(event) {
+ let stop = this.widget.spec.stopEvent;
+ return stop ? stop(event) : false;
+ }
+ ignoreMutation(mutation) {
+ return mutation.type != "selection" || this.widget.spec.ignoreSelection;
+ }
+ destroy() {
+ this.widget.type.destroy(this.dom);
+ super.destroy();
+ }
+ get domAtom() {
+ return true;
+ }
+ get ignoreForSelection() {
+ return !!this.widget.type.spec.relaxedSide;
+ }
+ get side() {
+ return this.widget.type.side;
+ }
+ };
+ var CompositionViewDesc = class extends ViewDesc {
+ constructor(parent, dom, textDOM, text2) {
+ super(parent, [], dom, null);
+ this.textDOM = textDOM;
+ this.text = text2;
+ }
+ textDOM;
+ text;
+ get size() {
+ return this.text.length;
+ }
+ localPosFromDOM(dom, offset) {
+ if (dom != this.textDOM) return this.posAtStart + (offset ? this.size : 0);
+ return this.posAtStart + offset;
+ }
+ domFromPos(pos) {
+ return { node: this.textDOM, offset: pos };
+ }
+ ignoreMutation(mut) {
+ return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue;
+ }
+ };
+ var MarkViewDesc = class _MarkViewDesc extends ViewDesc {
+ constructor(parent, mark, dom, contentDOM, spec) {
+ super(parent, [], dom, contentDOM);
+ this.mark = mark;
+ this.spec = spec;
+ }
+ mark;
+ spec;
+ static create(parent, mark, inline2, view) {
+ let custom = view.nodeViews[mark.type.name];
+ let spec = custom && custom(mark, view, inline2);
+ if (!spec || !spec.dom)
+ spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline2), null, mark.attrs);
+ return new _MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);
+ }
+ parseRule() {
+ if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView) return null;
+ return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };
+ }
+ matchesMark(mark) {
+ return this.dirty != NODE_DIRTY && this.mark.eq(mark);
+ }
+ markDirty(from, to) {
+ super.markDirty(from, to);
+ if (this.dirty != NOT_DIRTY) {
+ let parent = this.parent;
+ while (!parent.node) parent = parent.parent;
+ if (parent.dirty < this.dirty) parent.dirty = this.dirty;
+ this.dirty = NOT_DIRTY;
+ }
+ }
+ slice(from, to, view) {
+ let copy2 = _MarkViewDesc.create(this.parent, this.mark, true, view);
+ let nodes = this.children, size = this.size;
+ if (to < size) nodes = replaceNodes(nodes, to, size, view);
+ if (from > 0) nodes = replaceNodes(nodes, 0, from, view);
+ for (let i2 = 0; i2 < nodes.length; i2++) nodes[i2].parent = copy2;
+ copy2.children = nodes;
+ return copy2;
+ }
+ ignoreMutation(mutation) {
+ return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
+ }
+ destroy() {
+ if (this.spec.destroy) this.spec.destroy();
+ super.destroy();
+ }
+ };
+ var NodeViewDesc = class _NodeViewDesc extends ViewDesc {
+ constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM) {
+ super(parent, [], dom, contentDOM);
+ this.node = node;
+ this.outerDeco = outerDeco;
+ this.innerDeco = innerDeco;
+ this.nodeDOM = nodeDOM;
+ }
+ node;
+ outerDeco;
+ innerDeco;
+ nodeDOM;
+ // By default, a node is rendered using the `toDOM` method from the
+ // node type spec. But client code can use the `nodeViews` spec to
+ // supply a custom node view, which can influence various aspects of
+ // the way the node works.
+ //
+ // (Using subclassing for this was intentionally decided against,
+ // since it'd require exposing a whole slew of finicky
+ // implementation details to the user code that they probably will
+ // never need.)
+ static create(parent, node, outerDeco, innerDeco, view, pos) {
+ let custom = view.nodeViews[node.type.name], descObj;
+ let spec = custom && custom(node, view, () => {
+ if (!descObj) return pos;
+ if (descObj.parent) return descObj.parent.posBeforeChild(descObj);
+ }, outerDeco, innerDeco);
+ let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;
+ if (node.isText) {
+ if (!dom) dom = document.createTextNode(node.text);
+ else if (!isText(dom)) throw new RangeError("Text must be rendered as a DOM text node");
+ } else if (!dom) {
+ let spec2 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);
+ ({ dom, contentDOM } = spec2);
+ }
+ if (!contentDOM && !node.isText && dom.nodeName != "BR") {
+ if (!dom.hasAttribute("contenteditable")) dom.contentEditable = "false";
+ if (node.type.spec.draggable) dom.draggable = true;
+ }
+ let nodeDOM = dom;
+ dom = applyOuterDeco(dom, outerDeco, node);
+ if (spec)
+ return descObj = new CustomNodeViewDesc(
+ parent,
+ node,
+ outerDeco,
+ innerDeco,
+ dom,
+ contentDOM || null,
+ nodeDOM,
+ spec
+ );
+ else if (node.isText)
+ return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM);
+ else
+ return new _NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM);
+ }
+ parseRule(addedNodes) {
+ if (this.node.type.spec.reparseInView) return null;
+ let rule = { node: this.node.type.name, attrs: this.node.attrs };
+ if (this.node.type.whitespace == "pre") rule.preserveWhitespace = "full";
+ if (!this.contentDOM) {
+ rule.getContent = () => this.node.content;
+ } else if (!this.contentLost) {
+ rule.contentElement = this.contentDOM;
+ } else {
+ for (let i2 = this.children.length - 1; i2 >= 0; i2--) {
+ let child = this.children[i2];
+ if (this.dom.contains(child.dom.parentNode)) {
+ rule.contentElement = child.dom.parentNode;
+ break;
+ }
+ }
+ if (!rule.contentElement) {
+ let found2 = addedNodes && addedNodes.find((n) => isElt(n) && addedNodes.indexOf(n.parentNode) < 0 && this.dom.contains(n));
+ if (found2)
+ rule.contentElement = found2;
+ else
+ rule.getContent = () => Fragment.empty;
+ }
+ }
+ return rule;
+ }
+ matchesNode(node, outerDeco, innerDeco) {
+ return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);
+ }
+ get size() {
+ return this.node.nodeSize;
+ }
+ get border() {
+ return this.node.isLeaf ? 0 : 1;
+ }
+ // Syncs `this.children` to match `this.node.content` and the local
+ // decorations, possibly introducing nesting for marks. Then, in a
+ // separate step, syncs the DOM inside `this.contentDOM` to
+ // `this.children`.
+ updateChildren(view, pos) {
+ let inline2 = this.node.inlineContent, off = pos;
+ let composition = view.composing ? this.localCompositionInfo(view, pos) : null;
+ let localComposition = composition && composition.pos > -1 ? composition : null;
+ let compositionInChild = composition && composition.pos < 0;
+ let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);
+ let addBuffers = this.node.inlineContent, atBufferPos = addBuffers && this.node.isBlock;
+ iterDeco(this.node, this.innerDeco, (widget, i2, insideNode) => {
+ if (widget.spec.marks)
+ updater.syncToMarks(widget.spec.marks, inline2, view, i2);
+ else if (widget.type.side >= 0 && !insideNode)
+ updater.syncToMarks(i2 == this.node.childCount ? Mark.none : this.node.child(i2).marks, inline2, view, i2);
+ updater.placeWidget(widget, view, off);
+ }, (child, outerDeco, innerDeco, i2) => {
+ updater.syncToMarks(child.marks, inline2, view, i2);
+ if (atBufferPos && child.isAtom && !child.isText) updater.addHackNode("IMG", updater.top);
+ let compIndex;
+ if (updater.findNodeMatch(child, outerDeco, innerDeco, i2)) {
+ } else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) {
+ } else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i2, off)) {
+ } else {
+ updater.addNode(child, outerDeco, innerDeco, view, off);
+ }
+ off += child.nodeSize;
+ if (addBuffers) atBufferPos = child.isAtom && !child.isText;
+ });
+ updater.syncToMarks([], inline2, view, 0);
+ if (this.node.isTextblock) updater.addTextblockHacks();
+ updater.destroyRest();
+ if (updater.changed || this.dirty == CONTENT_DIRTY) {
+ if (localComposition) this.protectLocalComposition(view, localComposition);
+ renderDescs(this.contentDOM, this.children, view);
+ if (ios) iosHacks(this.dom);
+ }
+ }
+ localCompositionInfo(view, pos) {
+ let { from, to } = view.state.selection;
+ if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) return null;
+ let textNode = view.input.compositionNode;
+ if (!textNode || !this.dom.contains(textNode.parentNode)) return null;
+ if (this.node.inlineContent) {
+ let text2 = textNode.nodeValue;
+ let textPos = findTextInFragment(this.node.content, text2, from - pos, to - pos);
+ return textPos < 0 ? null : { node: textNode, pos: textPos, text: text2 };
+ } else {
+ return { node: textNode, pos: -1, text: "" };
+ }
+ }
+ protectLocalComposition(view, { node, pos, text: text2 }) {
+ if (this.getDesc(node)) return;
+ let topNode = node;
+ for (; ; topNode = topNode.parentNode) {
+ if (topNode.parentNode == this.contentDOM) break;
+ while (topNode.previousSibling) topNode.parentNode.removeChild(topNode.previousSibling);
+ while (topNode.nextSibling) topNode.parentNode.removeChild(topNode.nextSibling);
+ if (topNode.pmViewDesc) topNode.pmViewDesc = void 0;
+ }
+ let desc = new CompositionViewDesc(this, topNode, node, text2);
+ view.input.compositionNodes.push(desc);
+ this.children = replaceNodes(this.children, pos, pos + text2.length, view, desc);
+ }
+ // If this desc must be updated to match the given node decoration,
+ // do so and return true.
+ update(node, outerDeco, innerDeco, view) {
+ if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node)) return false;
+ this.updateInner(node, outerDeco, innerDeco, view);
+ return true;
+ }
+ updateInner(node, outerDeco, innerDeco, view) {
+ this.updateOuterDeco(outerDeco);
+ this.node = node;
+ this.innerDeco = innerDeco;
+ if (this.contentDOM) this.updateChildren(view, this.posAtStart);
+ this.dirty = NOT_DIRTY;
+ }
+ updateOuterDeco(outerDeco) {
+ if (sameOuterDeco(outerDeco, this.outerDeco)) return;
+ let needsWrap = !isElt(this.nodeDOM);
+ let oldDOM = this.dom;
+ this.dom = patchOuterDeco(
+ this.dom,
+ this.nodeDOM,
+ computeOuterDeco(this.outerDeco, this.node, needsWrap),
+ computeOuterDeco(outerDeco, this.node, needsWrap)
+ );
+ if (this.dom != oldDOM) {
+ oldDOM.pmViewDesc = void 0;
+ this.dom.pmViewDesc = this;
+ }
+ this.outerDeco = outerDeco;
+ }
+ // Mark this node as being the selected node.
+ selectNode() {
+ if (isElt(this.nodeDOM)) {
+ this.nodeDOM.classList.add("ProseMirror-selectednode");
+ if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.draggable = true;
+ }
+ }
+ // Remove selected node marking from this node.
+ deselectNode() {
+ if (isElt(this.nodeDOM)) {
+ this.nodeDOM.classList.remove("ProseMirror-selectednode");
+ if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.removeAttribute("draggable");
+ }
+ }
+ get domAtom() {
+ return this.node.isAtom;
+ }
+ };
+ function docViewDesc(doc3, outerDeco, innerDeco, dom, view) {
+ applyOuterDeco(dom, outerDeco, doc3);
+ let docView = new NodeViewDesc(void 0, doc3, outerDeco, innerDeco, dom, dom, dom);
+ if (docView.contentDOM) docView.updateChildren(view, 0);
+ return docView;
+ }
+ var TextViewDesc = class _TextViewDesc extends NodeViewDesc {
+ constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM) {
+ super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM);
+ }
+ parseRule() {
+ let skip = this.nodeDOM.parentNode;
+ while (skip && skip != this.dom && !skip.pmIsDeco) skip = skip.parentNode;
+ return { skip: skip || true };
+ }
+ update(node, outerDeco, innerDeco, view) {
+ if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node)) return false;
+ this.updateOuterDeco(outerDeco);
+ if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {
+ this.nodeDOM.nodeValue = node.text;
+ if (view.trackWrites == this.nodeDOM) view.trackWrites = null;
+ }
+ this.node = node;
+ this.dirty = NOT_DIRTY;
+ return true;
+ }
+ inParent() {
+ let parentDOM = this.parent.contentDOM;
+ for (let n = this.nodeDOM; n; n = n.parentNode) if (n == parentDOM) return true;
+ return false;
+ }
+ domFromPos(pos) {
+ return { node: this.nodeDOM, offset: pos };
+ }
+ localPosFromDOM(dom, offset, bias) {
+ if (dom == this.nodeDOM) return this.posAtStart + Math.min(offset, this.node.text.length);
+ return super.localPosFromDOM(dom, offset, bias);
+ }
+ ignoreMutation(mutation) {
+ return mutation.type != "characterData" && mutation.type != "selection";
+ }
+ slice(from, to, _view) {
+ let node = this.node.cut(from, to), dom = document.createTextNode(node.text);
+ return new _TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom);
+ }
+ markDirty(from, to) {
+ super.markDirty(from, to);
+ if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))
+ this.dirty = NODE_DIRTY;
+ }
+ get domAtom() {
+ return false;
+ }
+ isText(text2) {
+ return this.node.text == text2;
+ }
+ };
+ var BufferHackViewDesc = class extends ViewDesc {
+ parseRule() {
+ return { ignore: true };
+ }
+ matchesHack(nodeName) {
+ return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName;
+ }
+ get domAtom() {
+ return true;
+ }
+ get ignoreForCoords() {
+ return this.dom.nodeName == "IMG";
+ }
+ };
+ var CustomNodeViewDesc = class extends NodeViewDesc {
+ constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec) {
+ super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM);
+ this.spec = spec;
+ }
+ spec;
+ // A custom `update` method gets to decide whether the update goes
+ // through. If it does, and there's a `contentDOM` node, our logic
+ // updates the children.
+ update(node, outerDeco, innerDeco, view) {
+ if (this.dirty == NODE_DIRTY) return false;
+ if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {
+ let result = this.spec.update(node, outerDeco, innerDeco);
+ if (result) this.updateInner(node, outerDeco, innerDeco, view);
+ return result;
+ } else if (!this.contentDOM && !node.isLeaf) {
+ return false;
+ } else {
+ return super.update(node, outerDeco, innerDeco, view);
+ }
+ }
+ selectNode() {
+ this.spec.selectNode ? this.spec.selectNode() : super.selectNode();
+ }
+ deselectNode() {
+ this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();
+ }
+ setSelection(anchor, head, view, force) {
+ this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force);
+ }
+ destroy() {
+ if (this.spec.destroy) this.spec.destroy();
+ super.destroy();
+ }
+ stopEvent(event) {
+ return this.spec.stopEvent ? this.spec.stopEvent(event) : false;
+ }
+ ignoreMutation(mutation) {
+ return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
+ }
+ };
+ function renderDescs(parentDOM, descs, view) {
+ let dom = parentDOM.firstChild, written2 = false;
+ for (let i2 = 0; i2 < descs.length; i2++) {
+ let desc = descs[i2], childDOM = desc.dom;
+ if (childDOM.parentNode == parentDOM) {
+ while (childDOM != dom) {
+ dom = rm(dom);
+ written2 = true;
+ }
+ dom = dom.nextSibling;
+ } else {
+ written2 = true;
+ parentDOM.insertBefore(childDOM, dom);
+ }
+ if (desc instanceof MarkViewDesc) {
+ let pos = dom ? dom.previousSibling : parentDOM.lastChild;
+ renderDescs(desc.contentDOM, desc.children, view);
+ dom = pos ? pos.nextSibling : parentDOM.firstChild;
+ }
+ }
+ while (dom) {
+ dom = rm(dom);
+ written2 = true;
+ }
+ if (written2 && view.trackWrites == parentDOM) view.trackWrites = null;
+ }
+ var OuterDecoLevel = function(nodeName) {
+ if (nodeName) this.nodeName = nodeName;
+ };
+ OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null);
+ var noDeco = [new OuterDecoLevel()];
+ function computeOuterDeco(outerDeco, node, needsWrap) {
+ if (outerDeco.length == 0) return noDeco;
+ let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top];
+ for (let i2 = 0; i2 < outerDeco.length; i2++) {
+ let attrs2 = outerDeco[i2].type.attrs;
+ if (!attrs2) continue;
+ if (attrs2.nodeName)
+ result.push(top = new OuterDecoLevel(attrs2.nodeName));
+ for (let name in attrs2) {
+ let val = attrs2[name];
+ if (val == null) continue;
+ if (needsWrap && result.length == 1)
+ result.push(top = new OuterDecoLevel(node.isInline ? "span" : "div"));
+ if (name == "class") top.class = (top.class ? top.class + " " : "") + val;
+ else if (name == "style") top.style = (top.style ? top.style + ";" : "") + val;
+ else if (name != "nodeName") top[name] = val;
+ }
+ }
+ return result;
+ }
+ function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {
+ if (prevComputed == noDeco && curComputed == noDeco) return nodeDOM;
+ let curDOM = nodeDOM;
+ for (let i2 = 0; i2 < curComputed.length; i2++) {
+ let deco = curComputed[i2], prev = prevComputed[i2];
+ if (i2) {
+ let parent;
+ if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {
+ curDOM = parent;
+ } else {
+ parent = document.createElement(deco.nodeName);
+ parent.pmIsDeco = true;
+ parent.appendChild(curDOM);
+ prev = noDeco[0];
+ curDOM = parent;
+ }
+ }
+ patchAttributes(curDOM, prev || noDeco[0], deco);
+ }
+ return curDOM;
+ }
+ function patchAttributes(dom, prev, cur) {
+ for (let name in prev)
+ if (name != "class" && name != "style" && name != "nodeName" && !(name in cur))
+ dom.removeAttribute(name);
+ for (let name in cur)
+ if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name])
+ dom.setAttribute(name, cur[name]);
+ if (prev.class != cur.class) {
+ let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : [];
+ let curList = cur.class ? cur.class.split(" ").filter(Boolean) : [];
+ for (let i2 = 0; i2 < prevList.length; i2++) if (curList.indexOf(prevList[i2]) == -1)
+ dom.classList.remove(prevList[i2]);
+ for (let i2 = 0; i2 < curList.length; i2++) if (prevList.indexOf(curList[i2]) == -1)
+ dom.classList.add(curList[i2]);
+ if (dom.classList.length == 0)
+ dom.removeAttribute("class");
+ }
+ if (prev.style != cur.style) {
+ if (prev.style) {
+ let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m;
+ while (m = prop.exec(prev.style))
+ dom.style.removeProperty(m[1]);
+ }
+ if (cur.style)
+ dom.style.cssText += cur.style;
+ }
+ }
+ function applyOuterDeco(dom, deco, node) {
+ return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, !isElt(dom)));
+ }
+ function sameOuterDeco(a, b) {
+ if (a.length != b.length) return false;
+ for (let i2 = 0; i2 < a.length; i2++) if (!a[i2].type.eq(b[i2].type)) return false;
+ return true;
+ }
+ function rm(dom) {
+ let next = dom.nextSibling;
+ dom.parentNode.removeChild(dom);
+ return next;
+ }
+ var ViewTreeUpdater = class {
+ constructor(top, lock, view) {
+ this.lock = lock;
+ this.view = view;
+ this.top = top;
+ this.preMatch = preMatch(top.node.content, top);
+ }
+ lock;
+ view;
+ // Index into `this.top`'s child array, represents the current
+ // update position.
+ index = 0;
+ // When entering a mark, the current top and index are pushed
+ // onto this.
+ stack = [];
+ // Tracks whether anything was changed
+ changed = false;
+ preMatch;
+ top;
+ // Destroy and remove the children between the given indices in
+ // `this.top`.
+ destroyBetween(start, end) {
+ if (start == end) return;
+ for (let i2 = start; i2 < end; i2++) this.top.children[i2].destroy();
+ this.top.children.splice(start, end - start);
+ this.changed = true;
+ }
+ // Destroy all remaining children in `this.top`.
+ destroyRest() {
+ this.destroyBetween(this.index, this.top.children.length);
+ }
+ // Sync the current stack of mark descs with the given array of
+ // marks, reusing existing mark descs when possible.
+ syncToMarks(marks, inline2, view, parentIndex) {
+ let keep = 0, depth = this.stack.length >> 1;
+ let maxKeep = Math.min(depth, marks.length);
+ while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)
+ keep++;
+ while (keep < depth) {
+ this.destroyRest();
+ this.top.dirty = NOT_DIRTY;
+ this.index = this.stack.pop();
+ this.top = this.stack.pop();
+ depth--;
+ }
+ while (depth < marks.length) {
+ this.stack.push(this.top, this.index + 1);
+ let found2 = -1, scanTo = this.top.children.length;
+ if (parentIndex < this.preMatch.index) scanTo = Math.min(this.index + 3, scanTo);
+ for (let i2 = this.index; i2 < scanTo; i2++) {
+ let next = this.top.children[i2];
+ if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {
+ found2 = i2;
+ break;
+ }
+ }
+ if (found2 < 0 && this.index < this.top.children.length) {
+ let cur = this.top.children[this.index];
+ if (cur instanceof MarkViewDesc && cur.dirty != NODE_DIRTY && cur.mark.type == marks[depth].type && cur.spec.update && !this.isLocked(cur.dom) && cur.spec.update(marks[depth])) {
+ cur.mark = marks[depth];
+ found2 = this.index;
+ this.changed = true;
+ }
+ }
+ if (found2 > -1) {
+ if (found2 > this.index) {
+ this.changed = true;
+ this.destroyBetween(this.index, found2);
+ }
+ this.top = this.top.children[this.index];
+ } else {
+ let markDesc = MarkViewDesc.create(this.top, marks[depth], inline2, view);
+ this.top.children.splice(this.index, 0, markDesc);
+ this.top = markDesc;
+ this.changed = true;
+ }
+ this.index = 0;
+ depth++;
+ }
+ }
+ // Try to find a node desc matching the given data. Skip over it and
+ // return true when successful.
+ findNodeMatch(node, outerDeco, innerDeco, index) {
+ let found2 = -1, targetDesc;
+ if (index >= this.preMatch.index && (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) {
+ found2 = this.top.children.indexOf(targetDesc, this.index);
+ } else {
+ for (let i2 = this.index, e = Math.min(this.top.children.length, i2 + 5); i2 < e; i2++) {
+ let child = this.top.children[i2];
+ if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {
+ found2 = i2;
+ break;
+ }
+ }
+ }
+ if (found2 < 0) return false;
+ this.destroyBetween(this.index, found2);
+ this.index++;
+ return true;
+ }
+ updateNodeAt(node, outerDeco, innerDeco, index, view) {
+ let child = this.top.children[index];
+ if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM) child.dirty = CONTENT_DIRTY;
+ if (!child.update(node, outerDeco, innerDeco, view)) return false;
+ this.destroyBetween(this.index, index);
+ this.index++;
+ return true;
+ }
+ findIndexWithChild(domNode) {
+ for (; ; ) {
+ let parent = domNode.parentNode;
+ if (!parent) return -1;
+ if (parent == this.top.contentDOM) {
+ let desc = domNode.pmViewDesc;
+ if (desc) for (let i2 = this.index; i2 < this.top.children.length; i2++) {
+ if (this.top.children[i2] == desc) return i2;
+ }
+ return -1;
+ }
+ domNode = parent;
+ }
+ }
+ // Try to update the next node, if any, to the given data. Checks
+ // pre-matches to avoid overwriting nodes that could still be used.
+ updateNextNode(node, outerDeco, innerDeco, view, index, pos) {
+ for (let i2 = this.index; i2 < this.top.children.length; i2++) {
+ let next = this.top.children[i2];
+ if (next instanceof NodeViewDesc) {
+ let preMatch2 = this.preMatch.matched.get(next);
+ if (preMatch2 != null && preMatch2 != index) return false;
+ let nextDOM = next.dom, updated;
+ let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));
+ if (!locked && next.update(node, outerDeco, innerDeco, view)) {
+ this.destroyBetween(this.index, i2);
+ if (next.dom != nextDOM) this.changed = true;
+ this.index++;
+ return true;
+ } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {
+ this.destroyBetween(this.index, i2);
+ this.top.children[this.index] = updated;
+ if (updated.contentDOM) {
+ updated.dirty = CONTENT_DIRTY;
+ updated.updateChildren(view, pos + 1);
+ updated.dirty = NOT_DIRTY;
+ }
+ this.changed = true;
+ this.index++;
+ return true;
+ }
+ break;
+ }
+ }
+ return false;
+ }
+ // When a node with content is replaced by a different node with
+ // identical content, move over its children.
+ recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {
+ if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco)) return null;
+ let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
+ if (wrapper.contentDOM) {
+ wrapper.children = next.children;
+ next.children = [];
+ for (let ch of wrapper.children) ch.parent = wrapper;
+ }
+ next.destroy();
+ return wrapper;
+ }
+ // Insert the node as a newly created node desc.
+ addNode(node, outerDeco, innerDeco, view, pos) {
+ let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
+ if (desc.contentDOM) desc.updateChildren(view, pos + 1);
+ this.top.children.splice(this.index++, 0, desc);
+ this.changed = true;
+ }
+ placeWidget(widget, view, pos) {
+ let next = this.index < this.top.children.length ? this.top.children[this.index] : null;
+ if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) {
+ this.index++;
+ } else {
+ let desc = new WidgetViewDesc(this.top, widget, view, pos);
+ this.top.children.splice(this.index++, 0, desc);
+ this.changed = true;
+ }
+ }
+ // Make sure a textblock looks and behaves correctly in
+ // contentEditable.
+ addTextblockHacks() {
+ let lastChild = this.top.children[this.index - 1], parent = this.top;
+ while (lastChild instanceof MarkViewDesc) {
+ parent = lastChild;
+ lastChild = parent.children[parent.children.length - 1];
+ }
+ if (!lastChild || // Empty textblock
+ !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) {
+ if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false")
+ this.addHackNode("IMG", parent);
+ this.addHackNode("BR", this.top);
+ }
+ }
+ addHackNode(nodeName, parent) {
+ if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {
+ this.index++;
+ } else {
+ let dom = document.createElement(nodeName);
+ if (nodeName == "IMG") {
+ dom.className = "ProseMirror-separator";
+ dom.alt = "";
+ }
+ if (nodeName == "BR") dom.className = "ProseMirror-trailingBreak";
+ let hack = new BufferHackViewDesc(this.top, [], dom, null);
+ if (parent != this.top) parent.children.push(hack);
+ else parent.children.splice(this.index++, 0, hack);
+ this.changed = true;
+ }
+ }
+ isLocked(node) {
+ return this.lock && (node == this.lock || isElt(node) && node.contains(this.lock.parentNode));
+ }
+ };
+ function preMatch(frag, parentDesc) {
+ let curDesc = parentDesc, descI = curDesc.children.length;
+ let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches2 = [];
+ outer: while (fI > 0) {
+ let desc;
+ for (; ; ) {
+ if (descI) {
+ let next = curDesc.children[descI - 1];
+ if (next instanceof MarkViewDesc) {
+ curDesc = next;
+ descI = next.children.length;
+ } else {
+ desc = next;
+ descI--;
+ break;
+ }
+ } else if (curDesc == parentDesc) {
+ break outer;
+ } else {
+ descI = curDesc.parent.children.indexOf(curDesc);
+ curDesc = curDesc.parent;
+ }
+ }
+ let node = desc.node;
+ if (!node) continue;
+ if (node != frag.child(fI - 1)) break;
+ --fI;
+ matched.set(desc, fI);
+ matches2.push(desc);
+ }
+ return { index: fI, matched, matches: matches2.reverse() };
+ }
+ function compareSide(a, b) {
+ return a.type.side - b.type.side;
+ }
+ function iterDeco(parent, deco, onWidget, onNode) {
+ let locals = deco.locals(parent), offset = 0;
+ if (locals.length == 0) {
+ for (let i2 = 0; i2 < parent.childCount; i2++) {
+ let child = parent.child(i2);
+ onNode(child, locals, deco.forChild(offset, child), i2);
+ offset += child.nodeSize;
+ }
+ return;
+ }
+ let decoIndex = 0, active = [], restNode = null;
+ for (let parentIndex = 0; ; ) {
+ let widget, widgets;
+ while (decoIndex < locals.length && locals[decoIndex].to == offset) {
+ let next = locals[decoIndex++];
+ if (next.widget) {
+ if (!widget) widget = next;
+ else (widgets || (widgets = [widget])).push(next);
+ }
+ }
+ if (widget) {
+ if (widgets) {
+ widgets.sort(compareSide);
+ for (let i2 = 0; i2 < widgets.length; i2++) onWidget(widgets[i2], parentIndex, !!restNode);
+ } else {
+ onWidget(widget, parentIndex, !!restNode);
+ }
+ }
+ let child, index;
+ if (restNode) {
+ index = -1;
+ child = restNode;
+ restNode = null;
+ } else if (parentIndex < parent.childCount) {
+ index = parentIndex;
+ child = parent.child(parentIndex++);
+ } else {
+ break;
+ }
+ for (let i2 = 0; i2 < active.length; i2++) if (active[i2].to <= offset) active.splice(i2--, 1);
+ while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)
+ active.push(locals[decoIndex++]);
+ let end = offset + child.nodeSize;
+ if (child.isText) {
+ let cutAt = end;
+ if (decoIndex < locals.length && locals[decoIndex].from < cutAt) cutAt = locals[decoIndex].from;
+ for (let i2 = 0; i2 < active.length; i2++) if (active[i2].to < cutAt) cutAt = active[i2].to;
+ if (cutAt < end) {
+ restNode = child.cut(cutAt - offset);
+ child = child.cut(0, cutAt - offset);
+ end = cutAt;
+ index = -1;
+ }
+ } else {
+ while (decoIndex < locals.length && locals[decoIndex].to < end) decoIndex++;
+ }
+ let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice();
+ onNode(child, outerDeco, deco.forChild(offset, child), index);
+ offset = end;
+ }
+ }
+ function iosHacks(dom) {
+ if (dom.nodeName == "UL" || dom.nodeName == "OL") {
+ let oldCSS = dom.style.cssText;
+ dom.style.cssText = oldCSS + "; list-style: square !important";
+ window.getComputedStyle(dom).listStyle;
+ dom.style.cssText = oldCSS;
+ }
+ }
+ function findTextInFragment(frag, text2, from, to) {
+ for (let i2 = 0, pos = 0; i2 < frag.childCount && pos <= to; ) {
+ let child = frag.child(i2++), childStart = pos;
+ pos += child.nodeSize;
+ if (!child.isText) continue;
+ let str = child.text;
+ while (i2 < frag.childCount) {
+ let next = frag.child(i2++);
+ pos += next.nodeSize;
+ if (!next.isText) break;
+ str += next.text;
+ }
+ if (pos >= from) {
+ if (pos >= to && str.slice(to - text2.length - childStart, to - childStart) == text2)
+ return to - text2.length;
+ let found2 = childStart < to ? str.lastIndexOf(text2, to - childStart - 1) : -1;
+ if (found2 >= 0 && found2 + text2.length + childStart >= from)
+ return childStart + found2;
+ if (from == to && str.length >= to + text2.length - childStart && str.slice(to - childStart, to - childStart + text2.length) == text2)
+ return to;
+ }
+ }
+ return -1;
+ }
+ function replaceNodes(nodes, from, to, view, replacement) {
+ let result = [];
+ for (let i2 = 0, off = 0; i2 < nodes.length; i2++) {
+ let child = nodes[i2], start = off, end = off += child.size;
+ if (start >= to || end <= from) {
+ result.push(child);
+ } else {
+ if (start < from) result.push(child.slice(0, from - start, view));
+ if (replacement) {
+ result.push(replacement);
+ replacement = void 0;
+ }
+ if (end > to) result.push(child.slice(to - start, child.size, view));
+ }
+ }
+ return result;
+ }
+
+ // third_party/editor/prosemirror-view/src/selection.ts
+ function selectionFromDOM(view, origin = null) {
+ let domSel = view.domSelectionRange(), doc3 = view.state.doc;
+ if (!domSel.focusNode) return null;
+ let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;
+ let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);
+ if (head < 0) return null;
+ let $head = doc3.resolve(head), anchor, selection;
+ if (selectionCollapsed(domSel)) {
+ anchor = head;
+ while (nearestDesc && !nearestDesc.node) nearestDesc = nearestDesc.parent;
+ if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) && nearestDesc.parent && !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {
+ let pos = nearestDesc.posBefore;
+ selection = new NodeSelection(head == pos ? $head : doc3.resolve(pos));
+ } else if (gecko && origin == "key" && head > view.state.selection.to && isElt(domSel.focusNode) && domSel.focusOffset == domSel.focusNode.childNodes.length && nearestDesc && nearestDesc.posAtStart > view.state.selection.to) {
+ for (let scan = domSel.focusNode; ; scan = scan.parentNode) {
+ if (getComputedStyle(scan).overflow != "visible") {
+ selection = Selection.findFrom(doc3.resolve(nearestDesc.posAtStart), 1);
+ break;
+ }
+ if (scan == nearestDesc.dom || scan.nextSibling || !scan.parentNode || !isElt(scan.parentNode)) break;
+ }
+ }
+ } else {
+ if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {
+ let min = head, max = head;
+ for (let i2 = 0; i2 < domSel.rangeCount; i2++) {
+ let range = domSel.getRangeAt(i2);
+ min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));
+ max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));
+ }
+ if (min < 0) return null;
+ [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];
+ $head = doc3.resolve(head);
+ } else {
+ anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);
+ }
+ if (anchor < 0) return null;
+ }
+ let $anchor = doc3.resolve(anchor);
+ if (!selection) {
+ let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1;
+ selection = selectionBetween(view, $anchor, $head, bias);
+ }
+ return selection;
+ }
+ function editorOwnsSelection(view) {
+ return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);
+ }
+ function selectionToDOM(view, force = false) {
+ let sel = view.state.selection;
+ syncNodeSelection(view, sel);
+ if (!editorOwnsSelection(view)) return;
+ let mouseDown = view.input.mouseDown;
+ if (!force && chrome && mouseDown) {
+ let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;
+ if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(
+ domSel.anchorNode,
+ domSel.anchorOffset,
+ curSel.anchorNode,
+ curSel.anchorOffset
+ ) && mouseDown.delaySelUpdate()) {
+ view.domObserver.setCurSelection();
+ return;
+ }
+ }
+ view.domObserver.disconnectSelection();
+ if (view.cursorWrapper) {
+ selectCursorWrapper(view);
+ } else {
+ let { anchor, head } = sel, resetEditableFrom, resetEditableTo;
+ if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {
+ if (!sel.$from.parent.inlineContent)
+ resetEditableFrom = temporarilyEditableNear(view, sel.from);
+ if (!sel.empty && !sel.$from.parent.inlineContent)
+ resetEditableTo = temporarilyEditableNear(view, sel.to);
+ }
+ view.docView.setSelection(anchor, head, view, force);
+ if (brokenSelectBetweenUneditable) {
+ if (resetEditableFrom) resetEditable(resetEditableFrom);
+ if (resetEditableTo) resetEditable(resetEditableTo);
+ }
+ if (sel.visible) {
+ view.dom.classList.remove("ProseMirror-hideselection");
+ } else {
+ view.dom.classList.add("ProseMirror-hideselection");
+ if ("onselectionchange" in document) removeClassOnSelectionChange(view);
+ }
+ }
+ view.domObserver.setCurSelection();
+ view.domObserver.connectSelection();
+ }
+ var brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;
+ function temporarilyEditableNear(view, pos) {
+ let { node, offset } = view.docView.domFromPos(pos, 0);
+ let after = offset < node.childNodes.length ? node.childNodes[offset] : null;
+ let before = offset ? node.childNodes[offset - 1] : null;
+ if (safari && after && after.contentEditable == "false") return setEditable(after);
+ if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) {
+ if (after) return setEditable(after);
+ else if (before) return setEditable(before);
+ }
+ }
+ function setEditable(element) {
+ element.contentEditable = "true";
+ if (safari && element.draggable) {
+ element.draggable = false;
+ element.wasDraggable = true;
+ }
+ return element;
+ }
+ function resetEditable(element) {
+ element.contentEditable = "false";
+ if (element.wasDraggable) {
+ element.draggable = true;
+ element.wasDraggable = null;
+ }
+ }
+ function removeClassOnSelectionChange(view) {
+ let doc3 = view.dom.ownerDocument;
+ doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard);
+ let domSel = view.domSelectionRange();
+ let node = domSel.anchorNode, offset = domSel.anchorOffset;
+ doc3.addEventListener("selectionchange", view.input.hideSelectionGuard = () => {
+ if (domSel.anchorNode != node || domSel.anchorOffset != offset) {
+ doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard);
+ setTimeout(() => {
+ if (!editorOwnsSelection(view) || view.state.selection.visible)
+ view.dom.classList.remove("ProseMirror-hideselection");
+ }, 20);
+ }
+ });
+ }
+ function selectCursorWrapper(view) {
+ let domSel = view.domSelection();
+ if (!domSel) return;
+ let node = view.cursorWrapper.dom, img = node.nodeName == "IMG";
+ if (img) domSel.collapse(node.parentNode, domIndex(node) + 1);
+ else domSel.collapse(node, 0);
+ if (!img && !view.state.selection.visible && ie && ie_version <= 11) {
+ ;
+ node.disabled = true;
+ node.disabled = false;
+ }
+ }
+ function syncNodeSelection(view, sel) {
+ if (sel instanceof NodeSelection) {
+ let desc = view.docView.descAt(sel.from);
+ if (desc != view.lastSelectedViewDesc) {
+ clearNodeSelection(view);
+ if (desc) desc.selectNode();
+ view.lastSelectedViewDesc = desc;
+ }
+ } else {
+ clearNodeSelection(view);
+ }
+ }
+ function clearNodeSelection(view) {
+ if (view.lastSelectedViewDesc) {
+ if (view.lastSelectedViewDesc.parent)
+ view.lastSelectedViewDesc.deselectNode();
+ view.lastSelectedViewDesc = void 0;
+ }
+ }
+ function selectionBetween(view, $anchor, $head, bias) {
+ return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias);
+ }
+ function hasFocusAndSelection(view) {
+ if (view.editable && !view.hasFocus()) return false;
+ return hasSelection(view);
+ }
+ function hasSelection(view) {
+ let sel = view.domSelectionRange();
+ if (!sel.anchorNode) return false;
+ try {
+ return contains(view.dom, sel.anchorNode) && (view.editable || contains(view.dom, sel.focusNode));
+ } catch (_) {
+ return false;
+ }
+ }
+ function anchorInRightPlace(view) {
+ let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);
+ let domSel = view.domSelectionRange();
+ return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);
+ }
+
+ // third_party/editor/prosemirror-view/src/capturekeys.ts
+ function moveSelectionBlock(state, dir) {
+ let { $anchor, $head } = state.selection;
+ let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);
+ let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;
+ return $start && Selection.findFrom($start, dir);
+ }
+ function apply(view, sel) {
+ view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
+ return true;
+ }
+ function selectHorizontally(view, dir, mods) {
+ let sel = view.state.selection;
+ if (sel instanceof TextSelection) {
+ if (mods.indexOf("s") > -1) {
+ let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;
+ if (!node || node.isText || !node.isLeaf) return false;
+ let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));
+ return apply(view, new TextSelection(sel.$anchor, $newHead));
+ } else if (!sel.empty) {
+ return false;
+ } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) {
+ let next = moveSelectionBlock(view.state, dir);
+ if (next && next instanceof NodeSelection) return apply(view, next);
+ return false;
+ } else if (!(mac && mods.indexOf("m") > -1)) {
+ let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;
+ if (!node || node.isText) return false;
+ let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;
+ if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) return false;
+ if (NodeSelection.isSelectable(node)) {
+ return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));
+ } else {
+ return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));
+ }
+ }
+ } else if (sel instanceof NodeSelection && sel.node.isInline) {
+ return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));
+ } else {
+ let next = moveSelectionBlock(view.state, dir);
+ if (next) return apply(view, next);
+ return false;
+ }
+ }
+ function isIgnorable(dom, dir) {
+ let desc = dom.pmViewDesc;
+ return desc ? desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR") : isElt(dom) && dom.contentEditable == "false";
+ }
+ function skipIgnoredNodes(view, dir) {
+ return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);
+ }
+ function skipIgnoredNodesBefore(view) {
+ let sel = view.domSelectionRange();
+ let node = sel.focusNode, offset = sel.focusOffset;
+ if (!node) return;
+ let moveNode, moveOffset, force = false;
+ if (gecko && isElt(node) && offset < nodeSize(node) && isIgnorable(node.childNodes[offset], -1)) force = true;
+ for (; ; ) {
+ if (offset > 0) {
+ if (!isElt(node)) break;
+ let before = node.childNodes[offset - 1];
+ if (isIgnorable(before, -1)) {
+ moveNode = node;
+ moveOffset = --offset;
+ } else if (isText(before)) {
+ node = before;
+ offset = node.nodeValue.length;
+ } else {
+ break;
+ }
+ } else if (isBlockNode(node)) {
+ break;
+ } else {
+ let prev = node.previousSibling;
+ while (prev && isIgnorable(prev, -1)) {
+ moveNode = node.parentNode;
+ moveOffset = domIndex(prev);
+ prev = prev.previousSibling;
+ }
+ if (!prev) {
+ node = node.parentNode;
+ if (node == view.dom) break;
+ offset = 0;
+ } else {
+ node = prev;
+ offset = nodeSize(node);
+ }
+ }
+ }
+ if (force) setSelFocus(view, node, offset);
+ else if (moveNode) setSelFocus(view, moveNode, moveOffset);
+ }
+ function skipIgnoredNodesAfter(view) {
+ let sel = view.domSelectionRange();
+ let node = sel.focusNode, offset = sel.focusOffset;
+ if (!node) return;
+ let len = nodeSize(node);
+ let moveNode, moveOffset;
+ for (; ; ) {
+ if (offset < len) {
+ if (!isElt(node)) break;
+ let after = node.childNodes[offset];
+ if (isIgnorable(after, 1)) {
+ moveNode = node;
+ moveOffset = ++offset;
+ } else {
+ break;
+ }
+ } else if (isBlockNode(node)) {
+ break;
+ } else {
+ let next = node.nextSibling;
+ while (next && isIgnorable(next, 1)) {
+ moveNode = next.parentNode;
+ moveOffset = domIndex(next) + 1;
+ next = next.nextSibling;
+ }
+ if (!next) {
+ node = node.parentNode;
+ if (node == view.dom) break;
+ offset = len = 0;
+ } else {
+ node = next;
+ offset = 0;
+ len = nodeSize(node);
+ }
+ }
+ }
+ if (moveNode) setSelFocus(view, moveNode, moveOffset);
+ }
+ function isBlockNode(dom) {
+ let desc = dom.pmViewDesc;
+ return desc && desc.node && desc.node.isBlock;
+ }
+ function textNodeAfter2(node, offset) {
+ while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {
+ offset = domIndex(node) + 1;
+ node = node.parentNode;
+ }
+ while (node && offset < node.childNodes.length) {
+ let next = node.childNodes[offset];
+ if (isText(next)) return next;
+ if (isElt(next) && next.contentEditable == "false") break;
+ node = next;
+ offset = 0;
+ }
+ }
+ function textNodeBefore2(node, offset) {
+ while (node && !offset && !hasBlockDesc(node)) {
+ offset = domIndex(node);
+ node = node.parentNode;
+ }
+ while (node && offset) {
+ let next = node.childNodes[offset - 1];
+ if (isText(next)) return next;
+ if (isElt(next) && next.contentEditable == "false") break;
+ node = next;
+ offset = node.childNodes.length;
+ }
+ }
+ function setSelFocus(view, node, offset) {
+ if (!isText(node)) {
+ let before, after;
+ if (after = textNodeAfter2(node, offset)) {
+ node = after;
+ offset = 0;
+ } else if (before = textNodeBefore2(node, offset)) {
+ node = before;
+ offset = before.nodeValue.length;
+ }
+ }
+ let sel = view.domSelection();
+ if (!sel) return;
+ if (selectionCollapsed(sel)) {
+ let range = document.createRange();
+ range.setEnd(node, offset);
+ range.setStart(node, offset);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ } else if (sel.extend) {
+ sel.extend(node, offset);
+ }
+ view.domObserver.setCurSelection();
+ let { state } = view;
+ setTimeout(() => {
+ if (view.state == state) selectionToDOM(view);
+ }, 50);
+ }
+ function findDirection(view, pos) {
+ let $pos = view.state.doc.resolve(pos);
+ if (!(chrome || windows) && $pos.parent.inlineContent) {
+ let coords = view.coordsAtPos(pos);
+ if (pos > $pos.start()) {
+ let before = view.coordsAtPos(pos - 1);
+ let mid = (before.top + before.bottom) / 2;
+ if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)
+ return before.left < coords.left ? "ltr" : "rtl";
+ }
+ if (pos < $pos.end()) {
+ let after = view.coordsAtPos(pos + 1);
+ let mid = (after.top + after.bottom) / 2;
+ if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)
+ return after.left > coords.left ? "ltr" : "rtl";
+ }
+ }
+ let computed = getComputedStyle(view.dom).direction;
+ return computed == "rtl" ? "rtl" : "ltr";
+ }
+ function selectVertically(view, dir, mods) {
+ let sel = view.state.selection;
+ if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) return false;
+ if (mac && mods.indexOf("m") > -1) return false;
+ let { $from, $to } = sel;
+ if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) {
+ let next = moveSelectionBlock(view.state, dir);
+ if (next && next instanceof NodeSelection)
+ return apply(view, next);
+ }
+ if (!$from.parent.inlineContent) {
+ let side = dir < 0 ? $from : $to;
+ let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);
+ return beyond ? apply(view, beyond) : false;
+ }
+ return false;
+ }
+ function stopNativeHorizontalDelete(view, dir) {
+ if (!(view.state.selection instanceof TextSelection)) return true;
+ let { $head, $anchor, empty: empty2 } = view.state.selection;
+ if (!$head.sameParent($anchor)) return true;
+ if (!empty2) return false;
+ if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) return true;
+ let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);
+ if (nextNode && !nextNode.isText) {
+ let tr = view.state.tr;
+ if (dir < 0) tr.delete($head.pos - nextNode.nodeSize, $head.pos);
+ else tr.delete($head.pos, $head.pos + nextNode.nodeSize);
+ view.dispatch(tr);
+ return true;
+ }
+ return false;
+ }
+ function switchEditable(view, node, state) {
+ view.domObserver.stop();
+ node.contentEditable = state;
+ view.domObserver.start();
+ }
+ function safariDownArrowBug(view) {
+ if (!safari || view.state.selection.$head.parentOffset > 0) return false;
+ let { focusNode, focusOffset } = view.domSelectionRange();
+ if (focusNode && isElt(focusNode) && focusOffset == 0 && focusNode.firstChild && isElt(focusNode.firstChild) && focusNode.firstChild.contentEditable == "false") {
+ let child = focusNode.firstChild;
+ switchEditable(view, child, "true");
+ setTimeout(() => switchEditable(view, child, "false"), 20);
+ }
+ return false;
+ }
+ function getMods(event) {
+ let result = "";
+ if (event.ctrlKey) result += "c";
+ if (event.metaKey) result += "m";
+ if (event.altKey) result += "a";
+ if (event.shiftKey) result += "s";
+ return result;
+ }
+ function captureKeyDown(view, event) {
+ let code4 = event.keyCode, mods = getMods(event);
+ if (code4 == 8 || mac && code4 == 72 && mods == "c") {
+ return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);
+ } else if (code4 == 46 && !event.shiftKey || mac && code4 == 68 && mods == "c") {
+ return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);
+ } else if (code4 == 13 || code4 == 27) {
+ return true;
+ } else if (code4 == 37 || mac && code4 == 66 && mods == "c") {
+ let dir = code4 == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1;
+ return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
+ } else if (code4 == 39 || mac && code4 == 70 && mods == "c") {
+ let dir = code4 == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1;
+ return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
+ } else if (code4 == 38 || mac && code4 == 80 && mods == "c") {
+ return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);
+ } else if (code4 == 40 || mac && code4 == 78 && mods == "c") {
+ return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);
+ } else if (mods == (mac ? "m" : "c") && (code4 == 66 || code4 == 73 || code4 == 89 || code4 == 90)) {
+ return true;
+ }
+ return false;
+ }
+
+ // third_party/editor/prosemirror-view/src/clipboard.ts
+ function serializeForClipboard(view, slice) {
+ view.someProp("transformCopied", (f) => {
+ slice = f(slice, view);
+ });
+ let context = [], { content, openStart, openEnd } = slice;
+ while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {
+ openStart--;
+ openEnd--;
+ let node = content.firstChild;
+ context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);
+ content = node.content;
+ }
+ let serializer2 = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema);
+ let doc3 = detachedDoc(), wrap2 = doc3.createElement("div");
+ wrap2.appendChild(serializer2.serializeFragment(content, { document: doc3 }));
+ let firstChild = wrap2.firstChild, needsWrap, wrappers = 0;
+ while (firstChild && isElt(firstChild) && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
+ for (let i2 = needsWrap.length - 1; i2 >= 0; i2--) {
+ let wrapper = doc3.createElement(needsWrap[i2]);
+ while (wrap2.firstChild) wrapper.appendChild(wrap2.firstChild);
+ wrap2.appendChild(wrapper);
+ wrappers++;
+ }
+ firstChild = wrap2.firstChild;
+ }
+ if (firstChild && isElt(firstChild))
+ firstChild.setAttribute(
+ "data-pm-slice",
+ `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`
+ );
+ let text2 = view.someProp("clipboardTextSerializer", (f) => f(slice, view)) || slice.content.textBetween(0, slice.content.size, "\n\n");
+ return { dom: wrap2, text: text2, slice };
+ }
+ function parseFromClipboard(view, text2, html, plainText, $context) {
+ let inCode = $context.parent.type.spec.code;
+ let dom, slice;
+ if (!html && !text2) return null;
+ let asText = !!text2 && (plainText || inCode || !html);
+ if (asText) {
+ view.someProp("transformPastedText", (f) => {
+ text2 = f(text2, inCode || plainText, view);
+ });
+ if (inCode) {
+ slice = new Slice(Fragment.from(view.state.schema.text(text2.replace(/\r\n?/g, "\n"))), 0, 0);
+ view.someProp("transformPasted", (f) => {
+ slice = f(slice, view, true);
+ });
+ return slice;
+ }
+ let parsed = view.someProp("clipboardTextParser", (f) => f(text2, $context, plainText, view));
+ if (parsed) {
+ slice = parsed;
+ } else {
+ let marks = $context.marks();
+ let { schema: schema3 } = view.state, serializer2 = DOMSerializer.fromSchema(schema3);
+ dom = document.createElement("div");
+ text2.split(/(?:\r\n?|\n)+/).forEach((block3) => {
+ let p = dom.appendChild(document.createElement("p"));
+ if (block3) p.appendChild(serializer2.serializeNode(schema3.text(block3, marks)));
+ });
+ }
+ } else {
+ view.someProp("transformPastedHTML", (f) => {
+ html = f(html, view);
+ });
+ dom = readHTML(html);
+ if (webkit) restoreReplacedSpaces(dom);
+ }
+ let contextNode = dom && dom.querySelector("[data-pm-slice]");
+ let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || "");
+ if (sliceData && sliceData[3]) for (let i2 = +sliceData[3]; i2 > 0; i2--) {
+ let child = dom.firstChild;
+ while (child && !isElt(child)) child = child.nextSibling;
+ if (!child) break;
+ dom = child;
+ }
+ if (!slice) {
+ let parser2 = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema);
+ slice = parser2.parseSlice(dom, {
+ preserveWhitespace: !!(asText || sliceData),
+ context: $context,
+ ruleFromNode(dom2) {
+ if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName)) return { ignore: true };
+ return null;
+ }
+ });
+ }
+ if (sliceData) {
+ slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);
+ } else {
+ slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);
+ if (slice.openStart || slice.openEnd) {
+ let openStart = 0, openEnd = 0;
+ for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) {
+ }
+ for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) {
+ }
+ slice = closeSlice(slice, openStart, openEnd);
+ }
+ }
+ view.someProp("transformPasted", (f) => {
+ slice = f(slice, view, asText);
+ });
+ return slice;
+ }
+ var inlineParents = /^(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 normalizeSiblings(fragment, $context) {
+ if (fragment.childCount < 2) return fragment;
+ for (let d = $context.depth; d >= 0; d--) {
+ let parent = $context.node(d);
+ let match2 = parent.contentMatchAt($context.index(d));
+ let lastWrap, result = [];
+ fragment.forEach((node) => {
+ if (!result) return;
+ let wrap2 = match2.findWrapping(node.type), inLast;
+ if (!wrap2) return result = null;
+ if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result[result.length - 1], 0)) {
+ result[result.length - 1] = inLast;
+ } else {
+ if (result.length) result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);
+ let wrapped = withWrappers(node, wrap2);
+ result.push(wrapped);
+ match2 = match2.matchType(wrapped.type);
+ lastWrap = wrap2;
+ }
+ });
+ if (result) return Fragment.from(result);
+ }
+ return fragment;
+ }
+ function withWrappers(node, wrap2, from = 0) {
+ for (let i2 = wrap2.length - 1; i2 >= from; i2--)
+ node = wrap2[i2].create(null, Fragment.from(node));
+ return node;
+ }
+ function addToSibling(wrap2, lastWrap, node, sibling, depth) {
+ if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) {
+ let inner = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1);
+ if (inner) return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));
+ let match2 = sibling.contentMatchAt(sibling.childCount);
+ if (match2.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1]))
+ return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1))));
+ }
+ }
+ function closeRight(node, depth) {
+ if (depth == 0) return node;
+ let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));
+ let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);
+ return node.copy(fragment.append(fill));
+ }
+ function closeRange(fragment, side, from, to, depth, openEnd) {
+ let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;
+ if (fragment.childCount > 1) openEnd = 0;
+ if (depth < to - 1) inner = closeRange(inner, side, from, to, depth + 1, openEnd);
+ if (depth >= from)
+ inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));
+ return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));
+ }
+ function closeSlice(slice, openStart, openEnd) {
+ if (openStart < slice.openStart)
+ slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);
+ if (openEnd < slice.openEnd)
+ slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);
+ return slice;
+ }
+ var wrapMap = {
+ 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 detachedDoc() {
+ return document.implementation.createHTMLDocument("title");
+ }
+ var _policy = null;
+ function maybeWrapTrusted(html) {
+ let trustedTypes = window.trustedTypes;
+ if (!trustedTypes) return html;
+ if (!_policy) {
+ if (_policy = trustedTypes.defaultPolicy)
+ try {
+ return _policy.createHTML(html);
+ } catch {
+ }
+ _policy = trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s });
+ }
+ return _policy.createHTML(html);
+ }
+ function readHTML(html) {
+ let metas = /^(\s* ]*>)*/.exec(html);
+ if (metas) html = html.slice(metas[0].length);
+ let doc3 = detachedDoc(), elt = doc3.body;
+ let firstTag = /<([a-z][^>\s]+)/i.exec(html), wrap2;
+ if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()])
+ html = wrap2.map((n) => "<" + n + ">").join("") + html + wrap2.map((n) => "" + n + ">").reverse().join("");
+ elt.innerHTML = maybeWrapTrusted(html);
+ if (wrap2) for (let i2 = 0; i2 < wrap2.length; i2++) elt = elt.querySelector(wrap2[i2]) || elt;
+ for (let i2 = 0; i2 < doc3.styleSheets.length; i2++) {
+ let style = doc3.styleSheets[i2];
+ for (let j = 0; j < style.rules.length; j++) {
+ let rule = style.rules[j];
+ if (rule instanceof CSSStyleRule) {
+ let matches2 = elt.querySelectorAll(rule.selectorText);
+ for (let k = 0; k < matches2.length; k++)
+ matches2[k].style.cssText += rule.style.cssText;
+ }
+ }
+ }
+ return elt;
+ }
+ function restoreReplacedSpaces(dom) {
+ let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space");
+ for (let i2 = 0; i2 < nodes.length; i2++) {
+ let node = nodes[i2];
+ if (node.childNodes.length == 1 && node.textContent == "\xA0" && node.parentNode)
+ node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node);
+ }
+ }
+ function addContext(slice, context) {
+ if (!slice.size) return slice;
+ let schema3 = slice.content.firstChild.type.schema, array;
+ try {
+ array = JSON.parse(context);
+ } catch (e) {
+ return slice;
+ }
+ let { content, openStart, openEnd } = slice;
+ for (let i2 = array.length - 2; i2 >= 0; i2 -= 2) {
+ let type = schema3.nodes[array[i2]];
+ if (!type || type.hasRequiredAttrs()) break;
+ try {
+ content = Fragment.from(type.create(array[i2 + 1], content));
+ } catch (e) {
+ break;
+ }
+ openStart++;
+ openEnd++;
+ }
+ return new Slice(content, openStart, openEnd);
+ }
+
+ // third_party/editor/prosemirror-view/src/input.ts
+ var handlers = {};
+ var editHandlers = {};
+ var passiveHandlers = { touchstart: true, touchmove: true };
+ var InputState = class {
+ shiftKey = false;
+ mouseDown = null;
+ lastKeyCode = null;
+ lastKeyCodeTime = 0;
+ lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 };
+ lastSelectionOrigin = null;
+ lastSelectionTime = 0;
+ lastIOSEnter = 0;
+ lastIOSEnterFallbackTimeout = -1;
+ lastFocus = 0;
+ lastTouch = 0;
+ lastChromeDelete = 0;
+ composing = false;
+ compositionNode = null;
+ composingTimeout = -1;
+ compositionNodes = [];
+ compositionEndedAt = -2e8;
+ compositionID = 1;
+ badSafariComposition = false;
+ // Set to a composition ID when there are pending changes at compositionend
+ compositionPendingChanges = 0;
+ domChangeCount = 0;
+ eventHandlers = /* @__PURE__ */ Object.create(null);
+ hideSelectionGuard = null;
+ };
+ function initInput(view) {
+ for (let event in handlers) {
+ let handler = handlers[event];
+ view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => {
+ if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers)))
+ handler(view, event2);
+ }, passiveHandlers[event] ? { passive: true } : void 0);
+ }
+ if (safari) view.dom.addEventListener("input", () => null);
+ ensureListeners(view);
+ }
+ function setSelectionOrigin(view, origin) {
+ view.input.lastSelectionOrigin = origin;
+ view.input.lastSelectionTime = Date.now();
+ }
+ function destroyInput(view) {
+ if (view.input.mouseDown) view.input.mouseDown.done();
+ view.domObserver.stop();
+ for (let type in view.input.eventHandlers)
+ view.dom.removeEventListener(type, view.input.eventHandlers[type]);
+ clearTimeout(view.input.composingTimeout);
+ clearTimeout(view.input.lastIOSEnterFallbackTimeout);
+ }
+ function ensureListeners(view) {
+ view.someProp("handleDOMEvents", (currentHandlers) => {
+ for (let type in currentHandlers) if (!view.input.eventHandlers[type])
+ view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event));
+ });
+ }
+ function runCustomHandler(view, event) {
+ return view.someProp("handleDOMEvents", (handlers2) => {
+ let handler = handlers2[event.type];
+ return handler ? handler(view, event) || event.defaultPrevented : false;
+ });
+ }
+ function eventBelongsToView(view, event) {
+ if (!event.bubbles) return true;
+ if (event.defaultPrevented) return false;
+ for (let node = event.target; node != view.dom; node = node.parentNode)
+ if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event))
+ return false;
+ return true;
+ }
+ function dispatchEvent(view, event) {
+ if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers)))
+ handlers[event.type](view, event);
+ }
+ editHandlers.keydown = (view, _event) => {
+ let event = _event;
+ view.input.shiftKey = event.keyCode == 16 || event.shiftKey;
+ if (inOrNearComposition(view, event)) return;
+ view.input.lastKeyCode = event.keyCode;
+ view.input.lastKeyCodeTime = Date.now();
+ if (android && chrome && event.keyCode == 13) return;
+ if (event.keyCode != 229) view.domObserver.forceFlush();
+ if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {
+ let now = Date.now();
+ view.input.lastIOSEnter = now;
+ view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {
+ if (view.input.lastIOSEnter == now) {
+ view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")));
+ view.input.lastIOSEnter = 0;
+ }
+ }, 200);
+ } else if (view.someProp("handleKeyDown", (f) => f(view, event)) || captureKeyDown(view, event)) {
+ event.preventDefault();
+ } else {
+ setSelectionOrigin(view, "key");
+ }
+ };
+ editHandlers.keyup = (view, event) => {
+ if (event.keyCode == 16) view.input.shiftKey = false;
+ };
+ editHandlers.keypress = (view, _event) => {
+ let event = _event;
+ if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac && event.metaKey) return;
+ if (view.someProp("handleKeyPress", (f) => f(view, event))) {
+ event.preventDefault();
+ return;
+ }
+ let sel = view.state.selection;
+ if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {
+ let text2 = String.fromCharCode(event.charCode);
+ let deflt = () => view.state.tr.insertText(text2).scrollIntoView();
+ if (!/[\r\n]/.test(text2) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text2, deflt)))
+ view.dispatch(deflt());
+ event.preventDefault();
+ }
+ };
+ function eventCoords(event) {
+ return { left: event.clientX, top: event.clientY };
+ }
+ function isNear(event, click) {
+ let dx = click.x - event.clientX, dy = click.y - event.clientY;
+ return dx * dx + dy * dy < 100;
+ }
+ function runHandlerOnContext(view, propName, pos, inside, event) {
+ if (inside == -1) return false;
+ let $pos = view.state.doc.resolve(inside);
+ for (let i2 = $pos.depth + 1; i2 > 0; i2--) {
+ if (view.someProp(propName, (f) => i2 > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i2), event, true) : f(view, pos, $pos.node(i2), $pos.before(i2), event, false)))
+ return true;
+ }
+ return false;
+ }
+ function updateSelection(view, selection, origin) {
+ if (!view.focused) view.focus();
+ if (view.state.selection.eq(selection)) return;
+ let tr = view.state.tr.setSelection(selection);
+ if (origin == "pointer") tr.setMeta("pointer", true);
+ view.dispatch(tr);
+ }
+ function selectClickedLeaf(view, inside) {
+ if (inside == -1) return false;
+ let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;
+ if (node && node.isAtom && NodeSelection.isSelectable(node)) {
+ updateSelection(view, new NodeSelection($pos), "pointer");
+ return true;
+ }
+ return false;
+ }
+ function selectClickedNode(view, inside) {
+ if (inside == -1) return false;
+ let sel = view.state.selection, selectedNode, selectAt;
+ if (sel instanceof NodeSelection) selectedNode = sel.node;
+ let $pos = view.state.doc.resolve(inside);
+ for (let i2 = $pos.depth + 1; i2 > 0; i2--) {
+ let node = i2 > $pos.depth ? $pos.nodeAfter : $pos.node(i2);
+ if (NodeSelection.isSelectable(node)) {
+ if (selectedNode && sel.$from.depth > 0 && i2 >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)
+ selectAt = $pos.before(sel.$from.depth);
+ else
+ selectAt = $pos.before(i2);
+ break;
+ }
+ }
+ if (selectAt != null) {
+ updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer");
+ return true;
+ } else {
+ return false;
+ }
+ }
+ function handleSingleClick(view, pos, inside, event, selectNode) {
+ return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));
+ }
+ function handleDoubleClick(view, pos, inside, event) {
+ return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event));
+ }
+ function handleTripleClick(view, pos, inside, event) {
+ return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event);
+ }
+ function defaultTripleClick(view, inside, event) {
+ if (event.button != 0) return false;
+ let selection = selectionForTripleClick(view, inside, true), doc3 = view.state.doc;
+ if (!selection) return false;
+ updateSelection(view, selection, "pointer");
+ if (selection instanceof TextSelection && doc3.eq(view.state.doc))
+ view.input.mouseDown = new TripleClickDrag(view, selection);
+ return true;
+ }
+ function selectionForTripleClick(view, inside, selectNodes) {
+ let doc3 = view.state.doc;
+ if (inside == -1) return doc3.inlineContent ? TextSelection.create(doc3, 0, doc3.content.size) : null;
+ let $pos = doc3.resolve(inside);
+ for (let i2 = $pos.depth + 1; i2 > 0; i2--) {
+ let node = i2 > $pos.depth ? $pos.nodeAfter : $pos.node(i2);
+ let nodePos = $pos.before(i2);
+ if (node.inlineContent)
+ return TextSelection.create(doc3, nodePos + 1, nodePos + 1 + node.content.size);
+ else if (selectNodes && NodeSelection.isSelectable(node))
+ return NodeSelection.create(doc3, nodePos);
+ }
+ return null;
+ }
+ function forceDOMFlush(view) {
+ return endComposition(view);
+ }
+ var selectNodeModifier = mac ? "metaKey" : "ctrlKey";
+ handlers.mousedown = (view, _event) => {
+ let event = _event;
+ view.input.shiftKey = event.shiftKey;
+ let flushed = forceDOMFlush(view);
+ let now = Date.now(), type = "singleClick";
+ if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) {
+ if (view.input.lastClick.type == "singleClick") type = "doubleClick";
+ else if (view.input.lastClick.type == "doubleClick") type = "tripleClick";
+ }
+ view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };
+ if (view.input.mouseDown) view.input.mouseDown.done();
+ let pos = view.posAtCoords(eventCoords(event));
+ if (!pos) return;
+ if (type == "singleClick") {
+ view.input.mouseDown = new LeftMouseDown(view, pos, event, !!flushed);
+ } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {
+ event.preventDefault();
+ } else {
+ setSelectionOrigin(view, "pointer");
+ }
+ };
+ var MouseDown = class {
+ constructor(view) {
+ this.view = view;
+ view.root.addEventListener("mouseup", this.up = this.up.bind(this));
+ view.root.addEventListener("mousemove", this.move = this.move.bind(this));
+ }
+ view;
+ mightDrag = null;
+ up(event) {
+ this.done();
+ }
+ move(event) {
+ if (event.buttons == 0) this.done();
+ }
+ done() {
+ this.view.root.removeEventListener("mouseup", this.up);
+ this.view.root.removeEventListener("mousemove", this.move);
+ if (this.view.input.mouseDown == this) this.view.input.mouseDown = null;
+ }
+ delaySelUpdate() {
+ return false;
+ }
+ };
+ var LeftMouseDown = class extends MouseDown {
+ constructor(view, pos, event, flushed) {
+ super(view);
+ this.pos = pos;
+ this.event = event;
+ this.flushed = flushed;
+ this.startDoc = view.state.doc;
+ this.selectNode = !!event[selectNodeModifier];
+ this.allowDefault = event.shiftKey;
+ let targetNode, targetPos;
+ if (pos.inside > -1) {
+ targetNode = view.state.doc.nodeAt(pos.inside);
+ targetPos = pos.inside;
+ } else {
+ let $pos = view.state.doc.resolve(pos.pos);
+ targetNode = $pos.parent;
+ targetPos = $pos.depth ? $pos.before() : 0;
+ }
+ const target = flushed ? null : event.target;
+ const targetDesc = target ? view.docView.nearestDesc(target, true) : null;
+ this.target = targetDesc && isElt(targetDesc.nodeDOM) ? targetDesc.nodeDOM : null;
+ let { selection } = view.state;
+ if (event.button == 0 && (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos))
+ this.mightDrag = {
+ node: targetNode,
+ pos: targetPos,
+ addAttr: !!(this.target && !this.target.draggable),
+ setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable"))
+ };
+ if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {
+ this.view.domObserver.stop();
+ if (this.mightDrag.addAttr) this.target.draggable = true;
+ if (this.mightDrag.setUneditable)
+ setTimeout(() => {
+ if (this.view.input.mouseDown == this) this.target.setAttribute("contentEditable", "false");
+ }, 20);
+ this.view.domObserver.start();
+ }
+ setSelectionOrigin(view, "pointer");
+ }
+ pos;
+ event;
+ flushed;
+ startDoc;
+ selectNode;
+ allowDefault;
+ delayedSelectionSync = false;
+ target;
+ done() {
+ super.done();
+ if (this.mightDrag && this.target) {
+ this.view.domObserver.stop();
+ if (this.mightDrag.addAttr) this.target.removeAttribute("draggable");
+ if (this.mightDrag.setUneditable) this.target.removeAttribute("contentEditable");
+ this.view.domObserver.start();
+ }
+ if (this.delayedSelectionSync) setTimeout(() => {
+ if (!this.view.isDestroyed) selectionToDOM(this.view);
+ });
+ }
+ up(event) {
+ this.done();
+ if (!this.view.dom.contains(event.target))
+ return;
+ let pos = this.pos;
+ if (this.view.state.doc != this.startDoc) pos = this.view.posAtCoords(eventCoords(event));
+ this.updateAllowDefault(event);
+ if (this.allowDefault || !pos) {
+ setSelectionOrigin(this.view, "pointer");
+ } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {
+ event.preventDefault();
+ } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements
+ safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a
+ // cursor, but still report that the node is selected
+ // when asked through getSelection. You'll then get a
+ // situation where clicking at the point where that
+ // (hidden) cursor is doesn't change the selection, and
+ // thus doesn't get a reaction from ProseMirror. This
+ // works around that.
+ chrome && !this.view.state.selection.visible && Math.min(
+ Math.abs(pos.pos - this.view.state.selection.from),
+ Math.abs(pos.pos - this.view.state.selection.to)
+ ) <= 2)) {
+ updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer");
+ event.preventDefault();
+ } else {
+ setSelectionOrigin(this.view, "pointer");
+ }
+ }
+ move(event) {
+ this.updateAllowDefault(event);
+ setSelectionOrigin(this.view, "pointer");
+ super.move(event);
+ }
+ updateAllowDefault(event) {
+ if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4))
+ this.allowDefault = true;
+ }
+ delaySelUpdate() {
+ if (!this.allowDefault) return false;
+ this.delayedSelectionSync = true;
+ return true;
+ }
+ };
+ var TripleClickDrag = class extends MouseDown {
+ constructor(view, startSelection) {
+ super(view);
+ this.startSelection = startSelection;
+ this.startDoc = view.state.doc;
+ }
+ startSelection;
+ startDoc;
+ move(event) {
+ if (event.buttons == 0 || this.view.isDestroyed || !this.view.state.doc.eq(this.startDoc)) {
+ this.done();
+ return;
+ }
+ event.preventDefault();
+ setSelectionOrigin(this.view, "pointer");
+ let pos = this.view.posAtCoords(eventCoords(event));
+ let target = pos && selectionForTripleClick(this.view, pos.inside, false);
+ if (!target) return;
+ let { doc: doc3 } = this.view.state, start = this.startSelection;
+ let [anchor, head] = target.from < start.from ? [start.to, target.from] : [start.from, target.to];
+ updateSelection(this.view, TextSelection.create(doc3, anchor, head), "pointer");
+ }
+ };
+ handlers.touchstart = (view) => {
+ view.input.lastTouch = Date.now();
+ forceDOMFlush(view);
+ setSelectionOrigin(view, "pointer");
+ };
+ handlers.touchmove = (view) => {
+ view.input.lastTouch = Date.now();
+ setSelectionOrigin(view, "pointer");
+ };
+ handlers.contextmenu = (view) => forceDOMFlush(view);
+ function inOrNearComposition(view, event) {
+ if (view.composing) return true;
+ if (safari && Math.abs(Date.now() - view.input.compositionEndedAt) < 500) {
+ view.input.compositionEndedAt = -2e8;
+ return true;
+ }
+ return false;
+ }
+ var timeoutComposition = android ? 5e3 : -1;
+ editHandlers.compositionstart = editHandlers.compositionupdate = (view) => {
+ if (!view.composing) {
+ view.domObserver.flush();
+ let { state } = view, $pos = state.selection.$to;
+ if (state.selection instanceof TextSelection && state.selection.empty && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows && selectionBeforeUneditable(view))) {
+ view.markCursor = view.state.storedMarks || $pos.marks();
+ endComposition(view, true);
+ view.markCursor = null;
+ } else {
+ endComposition(view, !state.selection.empty);
+ if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {
+ let sel = view.domSelectionRange();
+ for (let node = sel.focusNode, offset = sel.focusOffset; node && isElt(node) && offset != 0; ) {
+ let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];
+ if (!before) break;
+ if (isText(before)) {
+ let sel2 = view.domSelection();
+ if (sel2) sel2.collapse(before, before.nodeValue.length);
+ break;
+ } else {
+ node = before;
+ offset = -1;
+ }
+ }
+ }
+ }
+ view.input.composing = true;
+ }
+ scheduleComposeEnd(view, timeoutComposition);
+ };
+ function selectionBeforeUneditable(view) {
+ let { focusNode, focusOffset } = view.domSelectionRange();
+ if (!focusNode || !isElt(focusNode) || focusOffset >= focusNode.childNodes.length) return false;
+ let next = focusNode.childNodes[focusOffset];
+ return isElt(next) && next.contentEditable == "false";
+ }
+ editHandlers.compositionend = (view, event) => {
+ if (view.composing) {
+ view.input.composing = false;
+ view.input.compositionEndedAt = Date.now();
+ view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;
+ view.input.compositionNode = null;
+ if (view.input.badSafariComposition) view.domObserver.forceFlush();
+ else if (view.input.compositionPendingChanges) Promise.resolve().then(() => view.domObserver.flush());
+ view.input.compositionID++;
+ scheduleComposeEnd(view, 20);
+ }
+ };
+ function scheduleComposeEnd(view, delay) {
+ clearTimeout(view.input.composingTimeout);
+ if (delay > -1) view.input.composingTimeout = setTimeout(() => endComposition(view), delay);
+ }
+ function clearComposition(view) {
+ if (view.composing) {
+ view.input.composing = false;
+ view.input.compositionEndedAt = Date.now();
+ }
+ while (view.input.compositionNodes.length > 0) view.input.compositionNodes.pop().markParentsDirty();
+ }
+ function findCompositionNode(view) {
+ let sel = view.domSelectionRange();
+ if (!sel.focusNode) return null;
+ let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);
+ let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);
+ if (textBefore && textAfter && textBefore != textAfter) {
+ let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;
+ if (textBefore == lastChanged || textAfter == lastChanged) return lastChanged;
+ if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {
+ return textAfter;
+ } else if (view.input.compositionNode == textAfter) {
+ let descBefore = textBefore.pmViewDesc;
+ if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))
+ return textAfter;
+ }
+ }
+ return textBefore || textAfter;
+ }
+ function endComposition(view, restarting = false) {
+ if (android && view.domObserver.flushingSoon >= 0) return;
+ view.domObserver.forceFlush();
+ clearComposition(view);
+ if (restarting || view.docView && view.docView.dirty) {
+ let sel = selectionFromDOM(view), cur = view.state.selection;
+ if (sel && !sel.eq(cur)) view.dispatch(view.state.tr.setSelection(sel));
+ else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent) view.dispatch(view.state.tr.deleteSelection());
+ else view.updateState(view.state);
+ return true;
+ }
+ return false;
+ }
+ function captureCopy(view, dom) {
+ if (!view.dom.parentNode) return;
+ let wrap2 = view.dom.parentNode.appendChild(document.createElement("div"));
+ wrap2.appendChild(dom);
+ wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px";
+ let sel = getSelection(), range = document.createRange();
+ range.selectNodeContents(dom);
+ view.dom.blur();
+ sel.removeAllRanges();
+ sel.addRange(range);
+ setTimeout(() => {
+ if (wrap2.parentNode) wrap2.parentNode.removeChild(wrap2);
+ view.focus();
+ }, 50);
+ }
+ var brokenClipboardAPI = ie && ie_version < 15 || ios && webkit_version < 604;
+ handlers.copy = editHandlers.cut = (view, _event) => {
+ let event = _event;
+ let sel = view.state.selection, cut = event.type == "cut";
+ if (sel.empty) return;
+ let data = brokenClipboardAPI ? null : event.clipboardData;
+ let slice = sel.content(), { dom, text: text2 } = serializeForClipboard(view, slice);
+ if (data) {
+ event.preventDefault();
+ data.clearData();
+ data.setData("text/html", dom.innerHTML);
+ data.setData("text/plain", text2);
+ } else {
+ captureCopy(view, dom);
+ }
+ if (cut) view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
+ };
+ function sliceSingleNode(slice) {
+ return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;
+ }
+ function capturePaste(view, event) {
+ if (!view.dom.parentNode) return;
+ let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;
+ let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div"));
+ if (!plainText) target.contentEditable = "true";
+ target.style.cssText = "position: fixed; left: -10000px; top: 10px";
+ target.focus();
+ let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
+ setTimeout(() => {
+ view.focus();
+ if (target.parentNode) target.parentNode.removeChild(target);
+ if (plainText) doPaste(view, target.value, null, plain, event);
+ else doPaste(view, target.textContent, target.innerHTML, plain, event);
+ }, 50);
+ }
+ function doPaste(view, text2, html, preferPlain, event) {
+ let slice = parseFromClipboard(view, text2, html, preferPlain, view.state.selection.$from);
+ if (view.someProp("handlePaste", (f) => f(view, event, slice || Slice.empty))) return true;
+ if (!slice) return false;
+ let singleNode = sliceSingleNode(slice);
+ let tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice);
+ view.dispatch(tr.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste"));
+ return true;
+ }
+ function getText(clipboardData) {
+ let text2 = clipboardData.getData("text/plain") || clipboardData.getData("Text");
+ if (text2) return text2;
+ let uris = clipboardData.getData("text/uri-list");
+ return uris ? uris.replace(/\r?\n/g, " ") : "";
+ }
+ editHandlers.paste = (view, _event) => {
+ let event = _event;
+ if (view.composing && !android) return;
+ let data = brokenClipboardAPI ? null : event.clipboardData;
+ let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
+ if (data && doPaste(view, getText(data), data.getData("text/html"), plain, event))
+ event.preventDefault();
+ else
+ capturePaste(view, event);
+ };
+ var Dragging = class {
+ constructor(slice, move, node) {
+ this.slice = slice;
+ this.move = move;
+ this.node = node;
+ }
+ slice;
+ move;
+ node;
+ };
+ var dragCopyModifier = mac ? "altKey" : "ctrlKey";
+ function dragMoves(view, event) {
+ let copy2;
+ view.someProp("dragCopies", (test2) => {
+ copy2 = copy2 || test2(event);
+ });
+ return copy2 != null ? !copy2 : !event[dragCopyModifier];
+ }
+ handlers.dragstart = (view, _event) => {
+ let event = _event;
+ let mouseDown = view.input.mouseDown;
+ if (mouseDown) mouseDown.done();
+ if (!event.dataTransfer) return;
+ let sel = view.state.selection;
+ let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));
+ let node;
+ if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) {
+ } else if (mouseDown && mouseDown.mightDrag) {
+ node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);
+ } else if (event.target && isElt(event.target)) {
+ let desc = view.docView.nearestDesc(event.target, true);
+ if (desc && desc.node.type.spec.draggable && desc != view.docView)
+ node = NodeSelection.create(view.state.doc, desc.posBefore);
+ }
+ let draggedSlice = (node || view.state.selection).content();
+ let { dom, text: text2, slice } = serializeForClipboard(view, draggedSlice);
+ if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)
+ event.dataTransfer.clearData();
+ event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML);
+ event.dataTransfer.effectAllowed = "copyMove";
+ if (!brokenClipboardAPI) event.dataTransfer.setData("text/plain", text2);
+ view.dragging = new Dragging(slice, dragMoves(view, event), node);
+ };
+ handlers.dragend = (view) => {
+ let dragging = view.dragging;
+ window.setTimeout(() => {
+ if (view.dragging == dragging) view.dragging = null;
+ }, 50);
+ };
+ editHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();
+ editHandlers.drop = (view, event) => {
+ try {
+ handleDrop(view, event, view.dragging);
+ } finally {
+ view.dragging = null;
+ }
+ };
+ function handleDrop(view, event, dragging) {
+ if (!event.dataTransfer) return;
+ let eventPos = view.posAtCoords(eventCoords(event));
+ if (!eventPos) return;
+ let $mouse = view.state.doc.resolve(eventPos.pos);
+ let slice = dragging && dragging.slice;
+ if (slice) {
+ view.someProp("transformPasted", (f) => {
+ slice = f(slice, view, false);
+ });
+ } else {
+ slice = parseFromClipboard(
+ view,
+ getText(event.dataTransfer),
+ brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"),
+ false,
+ $mouse
+ );
+ }
+ let move = !!(dragging && dragMoves(view, event));
+ if (view.someProp("handleDrop", (f) => f(view, event, slice || Slice.empty, move))) {
+ event.preventDefault();
+ return;
+ }
+ if (!slice) return;
+ event.preventDefault();
+ let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;
+ if (insertPos == null) insertPos = $mouse.pos;
+ let tr = view.state.tr;
+ if (move) {
+ let { node } = dragging;
+ if (node) node.replace(tr);
+ else tr.deleteSelection();
+ }
+ let pos = tr.mapping.map(insertPos);
+ let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;
+ let beforeInsert = tr.doc;
+ if (isNode)
+ tr.replaceRangeWith(pos, pos, slice.content.firstChild);
+ else
+ tr.replaceRange(pos, pos, slice);
+ if (tr.doc.eq(beforeInsert)) return;
+ let $pos = tr.doc.resolve(pos);
+ if (isNode && NodeSelection.isSelectable(slice.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {
+ tr.setSelection(new NodeSelection($pos));
+ } else {
+ let end = tr.mapping.map(insertPos);
+ tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);
+ tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));
+ }
+ view.focus();
+ view.dispatch(tr.setMeta("uiEvent", "drop"));
+ }
+ handlers.focus = (view) => {
+ view.input.lastFocus = Date.now();
+ if (!view.focused) {
+ view.domObserver.stop();
+ view.dom.classList.add("ProseMirror-focused");
+ view.domObserver.start();
+ view.focused = true;
+ setTimeout(() => {
+ if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))
+ selectionToDOM(view);
+ }, 20);
+ }
+ };
+ handlers.blur = (view, _event) => {
+ let event = _event;
+ if (view.focused) {
+ view.domObserver.stop();
+ view.dom.classList.remove("ProseMirror-focused");
+ view.domObserver.start();
+ if (event.relatedTarget && view.dom.contains(event.relatedTarget))
+ view.domObserver.currentSelection.clear();
+ view.focused = false;
+ }
+ };
+ handlers.beforeinput = (view, _event) => {
+ let event = _event;
+ if (android && event.inputType == "deleteContentBackward") {
+ view.domObserver.flushSoon();
+ let { domChangeCount } = view.input;
+ setTimeout(() => {
+ if (view.input.domChangeCount != domChangeCount) return;
+ view.dom.blur();
+ view.focus();
+ if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) return;
+ let { $cursor } = view.state.selection;
+ if ($cursor && $cursor.pos > 0) view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());
+ }, 50);
+ }
+ };
+ for (let prop in editHandlers) handlers[prop] = editHandlers[prop];
+
+ // third_party/editor/prosemirror-view/src/decoration.ts
+ function compareObjs(a, b) {
+ if (a == b) return true;
+ for (let p in a) if (a[p] !== b[p]) return false;
+ for (let p in b) if (!(p in a)) return false;
+ return true;
+ }
+ var WidgetType = class _WidgetType {
+ constructor(toDOM, spec) {
+ this.toDOM = toDOM;
+ this.spec = spec || noSpec;
+ this.side = this.spec.side || 0;
+ }
+ toDOM;
+ spec;
+ side;
+ map(mapping, span2, offset, oldOffset) {
+ let { pos, deleted } = mapping.mapResult(span2.from + oldOffset, this.side < 0 ? -1 : 1);
+ return deleted ? null : new Decoration(pos - offset, pos - offset, this);
+ }
+ valid() {
+ return true;
+ }
+ eq(other) {
+ return this == other || other instanceof _WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec));
+ }
+ destroy(node) {
+ if (this.spec.destroy) this.spec.destroy(node);
+ }
+ };
+ var InlineType = class _InlineType {
+ constructor(attrs2, spec) {
+ this.attrs = attrs2;
+ this.spec = spec || noSpec;
+ }
+ attrs;
+ spec;
+ map(mapping, span2, offset, oldOffset) {
+ let from = mapping.map(span2.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;
+ let to = mapping.map(span2.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;
+ return from >= to ? null : new Decoration(from, to, this);
+ }
+ valid(_, span2) {
+ return span2.from < span2.to;
+ }
+ eq(other) {
+ return this == other || other instanceof _InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
+ }
+ static is(span2) {
+ return span2.type instanceof _InlineType;
+ }
+ destroy() {
+ }
+ };
+ var NodeType7 = class _NodeType {
+ constructor(attrs2, spec) {
+ this.attrs = attrs2;
+ this.spec = spec || noSpec;
+ }
+ attrs;
+ spec;
+ map(mapping, span2, offset, oldOffset) {
+ let from = mapping.mapResult(span2.from + oldOffset, 1);
+ if (from.deleted) return null;
+ let to = mapping.mapResult(span2.to + oldOffset, -1);
+ if (to.deleted || to.pos <= from.pos) return null;
+ return new Decoration(from.pos - offset, to.pos - offset, this);
+ }
+ valid(node, span2) {
+ let { index, offset } = node.content.findIndex(span2.from), child;
+ return offset == span2.from && !(child = node.child(index)).isText && offset + child.nodeSize == span2.to;
+ }
+ eq(other) {
+ return this == other || other instanceof _NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
+ }
+ destroy() {
+ }
+ };
+ var Decoration = class _Decoration {
+ /// @internal
+ constructor(from, to, type) {
+ this.from = from;
+ this.to = to;
+ this.type = type;
+ }
+ from;
+ to;
+ type;
+ /// @internal
+ copy(from, to) {
+ return new _Decoration(from, to, this.type);
+ }
+ /// @internal
+ eq(other, offset = 0) {
+ return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;
+ }
+ /// @internal
+ map(mapping, offset, oldOffset) {
+ return this.type.map(mapping, this, offset, oldOffset);
+ }
+ /// Creates a widget decoration, which is a DOM node that's shown in
+ /// the document at the given position. It is recommended that you
+ /// delay rendering the widget by passing a function that will be
+ /// called when the widget is actually drawn in a view, but you can
+ /// also directly pass a DOM node. `getPos` can be used to find the
+ /// widget's current document position.
+ static widget(pos, toDOM, spec) {
+ return new _Decoration(pos, pos, new WidgetType(toDOM, spec));
+ }
+ /// Creates an inline decoration, which adds the given attributes to
+ /// each inline node between `from` and `to`.
+ static inline(from, to, attrs2, spec) {
+ return new _Decoration(from, to, new InlineType(attrs2, spec));
+ }
+ /// Creates a node decoration. `from` and `to` should point precisely
+ /// before and after a node in the document. That node, and only that
+ /// node, will receive the given attributes.
+ static node(from, to, attrs2, spec) {
+ return new _Decoration(from, to, new NodeType7(attrs2, spec));
+ }
+ /// The spec provided when creating this decoration. Can be useful
+ /// if you've stored extra information in that object.
+ get spec() {
+ return this.type.spec;
+ }
+ /// @internal
+ get inline() {
+ return this.type instanceof InlineType;
+ }
+ /// @internal
+ get widget() {
+ return this.type instanceof WidgetType;
+ }
+ };
+ var none = [];
+ var noSpec = {};
+ var DecorationSet = class _DecorationSet {
+ /// @internal
+ local;
+ /// @internal
+ children;
+ /// @internal
+ constructor(local, children) {
+ this.local = local.length ? local : none;
+ this.children = children.length ? children : none;
+ }
+ /// Create a set of decorations, using the structure of the given
+ /// document. This will consume (modify) the `decorations` array, so
+ /// you must make a copy if you want need to preserve that.
+ static create(doc3, decorations) {
+ return decorations.length ? buildTree(decorations, doc3, 0, noSpec) : empty;
+ }
+ /// Find all decorations in this set which touch the given range
+ /// (including decorations that start or end directly at the
+ /// boundaries) and match the given predicate on their spec. When
+ /// `start` and `end` are omitted, all decorations in the set are
+ /// considered. When `predicate` isn't given, all decorations are
+ /// assumed to match.
+ find(start, end, predicate) {
+ let result = [];
+ this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);
+ return result;
+ }
+ findInner(start, end, result, offset, predicate) {
+ for (let i2 = 0; i2 < this.local.length; i2++) {
+ let span2 = this.local[i2];
+ if (span2.from <= end && span2.to >= start && (!predicate || predicate(span2.spec)))
+ result.push(span2.copy(span2.from + offset, span2.to + offset));
+ }
+ for (let i2 = 0; i2 < this.children.length; i2 += 3) {
+ if (this.children[i2] < end && this.children[i2 + 1] > start) {
+ let childOff = this.children[i2] + 1;
+ this.children[i2 + 2].findInner(
+ start - childOff,
+ end - childOff,
+ result,
+ offset + childOff,
+ predicate
+ );
+ }
+ }
+ }
+ /// Map the set of decorations in response to a change in the
+ /// document.
+ map(mapping, doc3, options) {
+ if (this == empty || mapping.maps.length == 0) return this;
+ return this.mapInner(mapping, doc3, 0, 0, options || noSpec);
+ }
+ /// @internal
+ mapInner(mapping, node, offset, oldOffset, options) {
+ let newLocal;
+ for (let i2 = 0; i2 < this.local.length; i2++) {
+ let mapped = this.local[i2].map(mapping, offset, oldOffset);
+ if (mapped && mapped.type.valid(node, mapped)) (newLocal || (newLocal = [])).push(mapped);
+ else if (options.onRemove) options.onRemove(this.local[i2].spec);
+ }
+ if (this.children.length)
+ return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);
+ else
+ return newLocal ? new _DecorationSet(newLocal.sort(byPos), none) : empty;
+ }
+ /// Add the given array of decorations to the ones in the set,
+ /// producing a new set. Consumes the `decorations` array. Needs
+ /// access to the current document to create the appropriate tree
+ /// structure.
+ add(doc3, decorations) {
+ if (!decorations.length) return this;
+ if (this == empty) return _DecorationSet.create(doc3, decorations);
+ return this.addInner(doc3, decorations, 0);
+ }
+ addInner(doc3, decorations, offset) {
+ let children, childIndex = 0;
+ doc3.forEach((childNode, childOffset) => {
+ let baseOffset = childOffset + offset, found2;
+ if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset))) return;
+ if (!children) children = this.children.slice();
+ while (childIndex < children.length && children[childIndex] < childOffset) childIndex += 3;
+ if (children[childIndex] == childOffset)
+ children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1);
+ else
+ children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec));
+ childIndex += 3;
+ });
+ let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);
+ for (let i2 = 0; i2 < local.length; i2++) if (!local[i2].type.valid(doc3, local[i2])) local.splice(i2--, 1);
+ return new _DecorationSet(
+ local.length ? this.local.concat(local).sort(byPos) : this.local,
+ children || this.children
+ );
+ }
+ /// Create a new set that contains the decorations in this set, minus
+ /// the ones in the given array.
+ remove(decorations) {
+ if (decorations.length == 0 || this == empty) return this;
+ return this.removeInner(decorations, 0);
+ }
+ removeInner(decorations, offset) {
+ let children = this.children, local = this.local;
+ for (let i2 = 0; i2 < children.length; i2 += 3) {
+ let found2;
+ let from = children[i2] + offset, to = children[i2 + 1] + offset;
+ for (let j = 0, span2; j < decorations.length; j++) if (span2 = decorations[j]) {
+ if (span2.from > from && span2.to < to) {
+ decorations[j] = null;
+ (found2 || (found2 = [])).push(span2);
+ }
+ }
+ if (!found2) continue;
+ if (children == this.children) children = this.children.slice();
+ let removed = children[i2 + 2].removeInner(found2, from + 1);
+ if (removed != empty) {
+ children[i2 + 2] = removed;
+ } else {
+ children.splice(i2, 3);
+ i2 -= 3;
+ }
+ }
+ if (local.length) {
+ for (let i2 = 0, span2; i2 < decorations.length; i2++) if (span2 = decorations[i2]) {
+ for (let j = 0; j < local.length; j++) if (local[j].eq(span2, offset)) {
+ if (local == this.local) local = this.local.slice();
+ local.splice(j--, 1);
+ }
+ }
+ }
+ if (children == this.children && local == this.local) return this;
+ return local.length || children.length ? new _DecorationSet(local, children) : empty;
+ }
+ forChild(offset, node) {
+ if (this == empty) return this;
+ if (node.isLeaf) return _DecorationSet.empty;
+ let child, local;
+ for (let i2 = 0; i2 < this.children.length; i2 += 3) if (this.children[i2] >= offset) {
+ if (this.children[i2] == offset) child = this.children[i2 + 2];
+ break;
+ }
+ let start = offset + 1, end = start + node.content.size;
+ for (let i2 = 0; i2 < this.local.length; i2++) {
+ let dec = this.local[i2];
+ if (dec.from < end && dec.to > start && dec.type instanceof InlineType) {
+ let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;
+ if (from < to) (local || (local = [])).push(dec.copy(from, to));
+ }
+ }
+ if (local) {
+ let localSet = new _DecorationSet(local.sort(byPos), none);
+ return child ? new DecorationGroup([localSet, child]) : localSet;
+ }
+ return child || empty;
+ }
+ /// @internal
+ eq(other) {
+ if (this == other) return true;
+ if (!(other instanceof _DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length) return false;
+ for (let i2 = 0; i2 < this.local.length; i2++)
+ if (!this.local[i2].eq(other.local[i2])) return false;
+ for (let i2 = 0; i2 < this.children.length; i2 += 3)
+ if (this.children[i2] != other.children[i2] || this.children[i2 + 1] != other.children[i2 + 1] || !this.children[i2 + 2].eq(other.children[i2 + 2]))
+ return false;
+ return true;
+ }
+ /// @internal
+ locals(node) {
+ return removeOverlap(this.localsInner(node));
+ }
+ /// @internal
+ localsInner(node) {
+ if (this == empty) return none;
+ if (node.inlineContent || !this.local.some(InlineType.is)) return this.local;
+ let result = [];
+ for (let i2 = 0; i2 < this.local.length; i2++) {
+ if (!(this.local[i2].type instanceof InlineType))
+ result.push(this.local[i2]);
+ }
+ return result;
+ }
+ /// The empty set of decorations.
+ static empty = new _DecorationSet([], []);
+ /// @internal
+ static removeOverlap = removeOverlap;
+ forEachSet(f) {
+ f(this);
+ }
+ };
+ var empty = DecorationSet.empty;
+ var DecorationGroup = class _DecorationGroup {
+ constructor(members) {
+ this.members = members;
+ }
+ members;
+ map(mapping, doc3) {
+ const mappedDecos = this.members.map(
+ (member) => member.map(mapping, doc3, noSpec)
+ );
+ return _DecorationGroup.from(mappedDecos);
+ }
+ forChild(offset, child) {
+ if (child.isLeaf) return DecorationSet.empty;
+ let found2 = [];
+ for (let i2 = 0; i2 < this.members.length; i2++) {
+ let result = this.members[i2].forChild(offset, child);
+ if (result == empty) continue;
+ if (result instanceof _DecorationGroup) found2 = found2.concat(result.members);
+ else found2.push(result);
+ }
+ return _DecorationGroup.from(found2);
+ }
+ eq(other) {
+ if (!(other instanceof _DecorationGroup) || other.members.length != this.members.length) return false;
+ for (let i2 = 0; i2 < this.members.length; i2++)
+ if (!this.members[i2].eq(other.members[i2])) return false;
+ return true;
+ }
+ locals(node) {
+ let result, sorted = true;
+ for (let i2 = 0; i2 < this.members.length; i2++) {
+ let locals = this.members[i2].localsInner(node);
+ if (!locals.length) continue;
+ if (!result) {
+ result = locals;
+ } else {
+ if (sorted) {
+ result = result.slice();
+ sorted = false;
+ }
+ for (let j = 0; j < locals.length; j++) result.push(locals[j]);
+ }
+ }
+ return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;
+ }
+ // Create a group for the given array of decoration sets, or return
+ // a single set when possible.
+ static from(members) {
+ switch (members.length) {
+ case 0:
+ return empty;
+ case 1:
+ return members[0];
+ default:
+ return new _DecorationGroup(
+ members.every((m) => m instanceof DecorationSet) ? members : members.reduce(
+ (r, m) => r.concat(m instanceof DecorationSet ? m : m.members),
+ []
+ )
+ );
+ }
+ }
+ forEachSet(f) {
+ for (let i2 = 0; i2 < this.members.length; i2++) this.members[i2].forEachSet(f);
+ }
+ };
+ function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {
+ let children = oldChildren.slice();
+ for (let i2 = 0, baseOffset = oldOffset; i2 < mapping.maps.length; i2++) {
+ let moved = 0;
+ mapping.maps[i2].forEach((oldStart, oldEnd, newStart, newEnd) => {
+ let dSize = newEnd - newStart - (oldEnd - oldStart);
+ for (let i3 = 0; i3 < children.length; i3 += 3) {
+ let end = children[i3 + 1];
+ if (end < 0 || oldStart > end + baseOffset - moved) continue;
+ let start = children[i3] + baseOffset - moved;
+ if (oldEnd >= start) {
+ children[i3 + 1] = oldStart <= start ? -2 : -1;
+ } else if (oldStart >= baseOffset && dSize) {
+ ;
+ children[i3] += dSize;
+ children[i3 + 1] += dSize;
+ }
+ }
+ moved += dSize;
+ });
+ baseOffset = mapping.maps[i2].map(baseOffset, -1);
+ }
+ let mustRebuild = false;
+ for (let i2 = 0; i2 < children.length; i2 += 3) if (children[i2 + 1] < 0) {
+ if (children[i2 + 1] == -2) {
+ mustRebuild = true;
+ children[i2 + 1] = -1;
+ continue;
+ }
+ let from = mapping.map(oldChildren[i2] + oldOffset), fromLocal = from - offset;
+ if (fromLocal < 0 || fromLocal >= node.content.size) {
+ mustRebuild = true;
+ continue;
+ }
+ let to = mapping.map(oldChildren[i2 + 1] + oldOffset, -1), toLocal = to - offset;
+ let { index, offset: childOffset } = node.content.findIndex(fromLocal);
+ let childNode = node.maybeChild(index);
+ if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {
+ let mapped = children[i2 + 2].mapInner(mapping, childNode, from + 1, oldChildren[i2] + oldOffset + 1, options);
+ if (mapped != empty) {
+ children[i2] = fromLocal;
+ children[i2 + 1] = toLocal;
+ children[i2 + 2] = mapped;
+ } else {
+ children[i2 + 1] = -2;
+ mustRebuild = true;
+ }
+ } else {
+ mustRebuild = true;
+ }
+ }
+ if (mustRebuild) {
+ let decorations = mapAndGatherRemainingDecorations(
+ children,
+ oldChildren,
+ newLocal,
+ mapping,
+ offset,
+ oldOffset,
+ options
+ );
+ let built = buildTree(decorations, node, 0, options);
+ newLocal = built.local;
+ for (let i2 = 0; i2 < children.length; i2 += 3) if (children[i2 + 1] < 0) {
+ children.splice(i2, 3);
+ i2 -= 3;
+ }
+ for (let i2 = 0, j = 0; i2 < built.children.length; i2 += 3) {
+ let from = built.children[i2];
+ while (j < children.length && children[j] < from) j += 3;
+ children.splice(j, 0, built.children[i2], built.children[i2 + 1], built.children[i2 + 2]);
+ }
+ }
+ return new DecorationSet(newLocal.sort(byPos), children);
+ }
+ function moveSpans(spans, offset) {
+ if (!offset || !spans.length) return spans;
+ let result = [];
+ for (let i2 = 0; i2 < spans.length; i2++) {
+ let span2 = spans[i2];
+ result.push(new Decoration(span2.from + offset, span2.to + offset, span2.type));
+ }
+ return result;
+ }
+ function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {
+ function gather(set2, oldOffset2) {
+ for (let i2 = 0; i2 < set2.local.length; i2++) {
+ let mapped = set2.local[i2].map(mapping, offset, oldOffset2);
+ if (mapped) decorations.push(mapped);
+ else if (options.onRemove) options.onRemove(set2.local[i2].spec);
+ }
+ for (let i2 = 0; i2 < set2.children.length; i2 += 3)
+ gather(set2.children[i2 + 2], set2.children[i2] + oldOffset2 + 1);
+ }
+ for (let i2 = 0; i2 < children.length; i2 += 3) if (children[i2 + 1] == -1)
+ gather(children[i2 + 2], oldChildren[i2] + oldOffset + 1);
+ return decorations;
+ }
+ function takeSpansForNode(spans, node, offset) {
+ if (node.isLeaf) return null;
+ let end = offset + node.nodeSize, found2 = null;
+ for (let i2 = 0, span2; i2 < spans.length; i2++) {
+ if ((span2 = spans[i2]) && span2.from > offset && span2.to < end) {
+ ;
+ (found2 || (found2 = [])).push(span2);
+ spans[i2] = null;
+ }
+ }
+ return found2;
+ }
+ function withoutNulls(array) {
+ let result = [];
+ for (let i2 = 0; i2 < array.length; i2++)
+ if (array[i2] != null) result.push(array[i2]);
+ return result;
+ }
+ function buildTree(spans, node, offset, options) {
+ let children = [], hasNulls = false;
+ node.forEach((childNode, localStart) => {
+ let found2 = takeSpansForNode(spans, childNode, localStart + offset);
+ if (found2) {
+ hasNulls = true;
+ let subtree = buildTree(found2, childNode, offset + localStart + 1, options);
+ if (subtree != empty)
+ children.push(localStart, localStart + childNode.nodeSize, subtree);
+ }
+ });
+ let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);
+ for (let i2 = 0; i2 < locals.length; i2++) if (!locals[i2].type.valid(node, locals[i2])) {
+ if (options.onRemove) options.onRemove(locals[i2].spec);
+ locals.splice(i2--, 1);
+ }
+ return locals.length || children.length ? new DecorationSet(locals, children) : empty;
+ }
+ function byPos(a, b) {
+ return a.from - b.from || a.to - b.to;
+ }
+ function removeOverlap(spans) {
+ let working = spans;
+ for (let i2 = 0; i2 < working.length - 1; i2++) {
+ let span2 = working[i2];
+ if (span2.from != span2.to) for (let j = i2 + 1; j < working.length; j++) {
+ let next = working[j];
+ if (next.from == span2.from) {
+ if (next.to != span2.to) {
+ if (working == spans) working = spans.slice();
+ working[j] = next.copy(next.from, span2.to);
+ insertAhead(working, j + 1, next.copy(span2.to, next.to));
+ }
+ continue;
+ } else {
+ if (next.from < span2.to) {
+ if (working == spans) working = spans.slice();
+ working[i2] = span2.copy(span2.from, next.from);
+ insertAhead(working, j, span2.copy(next.from, span2.to));
+ }
+ break;
+ }
+ }
+ }
+ return working;
+ }
+ function insertAhead(array, i2, deco) {
+ while (i2 < array.length && byPos(deco, array[i2]) > 0) i2++;
+ array.splice(i2, 0, deco);
+ }
+ function viewDecorations(view) {
+ let found2 = [];
+ view.someProp("decorations", (f) => {
+ let result = f(view.state);
+ if (result && result != empty) found2.push(result);
+ });
+ if (view.cursorWrapper)
+ found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));
+ return DecorationGroup.from(found2);
+ }
+
+ // third_party/editor/prosemirror-view/src/domobserver.ts
+ var observeOptions = {
+ childList: true,
+ characterData: true,
+ characterDataOldValue: true,
+ attributes: true,
+ attributeOldValue: true,
+ subtree: true
+ };
+ var useCharData = ie && ie_version <= 11;
+ var SelectionState = class {
+ anchorNode = null;
+ anchorOffset = 0;
+ focusNode = null;
+ focusOffset = 0;
+ set(sel) {
+ this.anchorNode = sel.anchorNode;
+ this.anchorOffset = sel.anchorOffset;
+ this.focusNode = sel.focusNode;
+ this.focusOffset = sel.focusOffset;
+ }
+ clear() {
+ this.anchorNode = this.focusNode = null;
+ }
+ eq(sel) {
+ return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;
+ }
+ };
+ var DOMObserver = class {
+ constructor(view, handleDOMChange) {
+ this.view = view;
+ this.handleDOMChange = handleDOMChange;
+ this.observer = window.MutationObserver && new window.MutationObserver((mutations) => {
+ for (let i2 = 0; i2 < mutations.length; i2++) this.queue.push(mutations[i2]);
+ if (ie && ie_version <= 11 && mutations.some(
+ (m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length
+ )) {
+ this.flushSoon();
+ } else if (safari && view.composing && mutations.some(
+ (m) => m.type == "childList" && m.target.nodeName == "TR"
+ )) {
+ view.input.badSafariComposition = true;
+ this.flushSoon();
+ } else {
+ this.flush();
+ }
+ });
+ if (useCharData) {
+ this.onCharData = (e) => {
+ this.queue.push({ target: e.target, type: "characterData", oldValue: e.prevValue });
+ this.flushSoon();
+ };
+ }
+ this.onSelectionChange = this.onSelectionChange.bind(this);
+ }
+ view;
+ handleDOMChange;
+ queue = [];
+ flushingSoon = -1;
+ observer = null;
+ currentSelection = new SelectionState();
+ onCharData = null;
+ suppressingSelectionUpdates = false;
+ lastChangedTextNode = null;
+ flushSoon() {
+ if (this.flushingSoon < 0)
+ this.flushingSoon = window.setTimeout(() => {
+ this.flushingSoon = -1;
+ this.flush();
+ }, 20);
+ }
+ forceFlush() {
+ if (this.flushingSoon > -1) {
+ window.clearTimeout(this.flushingSoon);
+ this.flushingSoon = -1;
+ this.flush();
+ }
+ }
+ start() {
+ if (this.observer) {
+ this.observer.takeRecords();
+ this.observer.observe(this.view.dom, observeOptions);
+ }
+ if (this.onCharData)
+ this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
+ this.connectSelection();
+ }
+ stop() {
+ if (this.observer) {
+ let take = this.observer.takeRecords();
+ if (take.length) {
+ for (let i2 = 0; i2 < take.length; i2++) this.queue.push(take[i2]);
+ window.setTimeout(() => this.flush(), 20);
+ }
+ this.observer.disconnect();
+ }
+ if (this.onCharData) this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
+ this.disconnectSelection();
+ }
+ connectSelection() {
+ this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
+ }
+ disconnectSelection() {
+ this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
+ }
+ suppressSelectionUpdates() {
+ this.suppressingSelectionUpdates = true;
+ setTimeout(() => this.suppressingSelectionUpdates = false, 50);
+ }
+ onSelectionChange() {
+ if (!hasFocusAndSelection(this.view)) return;
+ if (this.suppressingSelectionUpdates) return selectionToDOM(this.view);
+ if (ie && ie_version <= 11 && !this.view.state.selection.empty) {
+ let sel = this.view.domSelectionRange();
+ if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
+ return this.flushSoon();
+ }
+ this.flush();
+ }
+ setCurSelection() {
+ this.currentSelection.set(this.view.domSelectionRange());
+ }
+ ignoreSelectionChange(sel) {
+ if (!sel.focusNode) return true;
+ let ancestors = /* @__PURE__ */ new Set(), container;
+ for (let scan = sel.focusNode; scan; scan = parentNode(scan)) ancestors.add(scan);
+ for (let scan = sel.anchorNode; scan; scan = parentNode(scan)) if (ancestors.has(scan)) {
+ container = scan;
+ break;
+ }
+ let desc = container && this.view.docView.nearestDesc(container);
+ if (desc && desc.ignoreMutation({
+ type: "selection",
+ target: isText(container) ? container.parentNode : container
+ })) {
+ this.setCurSelection();
+ return true;
+ }
+ }
+ pendingRecords() {
+ if (this.observer) for (let mut of this.observer.takeRecords()) this.queue.push(mut);
+ return this.queue;
+ }
+ flush() {
+ let { view } = this;
+ if (!view.docView || this.flushingSoon > -1) return;
+ let mutations = this.pendingRecords();
+ if (mutations.length) this.queue = [];
+ let sel = view.domSelectionRange();
+ let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);
+ let from = -1, to = -1, typeOver = false, added = [];
+ if (view.editable) {
+ for (let i2 = 0; i2 < mutations.length; i2++) {
+ let result = this.registerMutation(mutations[i2], added);
+ if (result) {
+ from = from < 0 ? result.from : Math.min(result.from, from);
+ to = to < 0 ? result.to : Math.max(result.to, to);
+ if (result.typeOver) typeOver = true;
+ }
+ }
+ }
+ if (added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46 || chrome && (view.composing || view.input.compositionEndedAt > Date.now() - 50) && mutations.some((m) => m.type == "childList" && m.removedNodes.length))) {
+ for (let node of added) if (node.nodeName == "BR" && node.parentNode) {
+ let after = node.nextSibling;
+ while (after && isElt(after)) {
+ if (after.contentEditable == "false") {
+ node.parentNode.removeChild(node);
+ break;
+ }
+ after = after.firstChild;
+ }
+ }
+ } else if (gecko && added.length) {
+ let brs = added.filter((n) => n.nodeName == "BR");
+ if (brs.length == 2) {
+ let [a, b] = brs;
+ if (a.parentNode && a.parentNode.parentNode == b.parentNode) b.remove();
+ else a.remove();
+ } else {
+ let { focusNode } = this.currentSelection;
+ for (let br of brs) {
+ let parent = br.parentNode;
+ if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent))
+ br.remove();
+ }
+ }
+ }
+ let readSel = null;
+ if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {
+ view.input.lastFocus = 0;
+ selectionToDOM(view);
+ this.currentSelection.set(sel);
+ view.scrollToSelection();
+ } else if (from > -1 || newSel) {
+ if (from > -1) {
+ view.docView.markDirty(from, to);
+ checkCSS(view);
+ }
+ if (view.input.badSafariComposition) {
+ view.input.badSafariComposition = false;
+ fixUpBadSafariComposition(view, added);
+ }
+ this.handleDOMChange(from, to, typeOver, added);
+ if (view.docView && view.docView.dirty) view.updateState(view.state);
+ else if (!this.currentSelection.eq(sel)) selectionToDOM(view);
+ this.currentSelection.set(sel);
+ }
+ }
+ registerMutation(mut, added) {
+ if (added.indexOf(mut.target) > -1) return null;
+ let desc = this.view.docView.nearestDesc(mut.target);
+ if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
+ mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))
+ return null;
+ if (!desc || desc.ignoreMutation(mut)) return null;
+ if (mut.type == "childList") {
+ for (let i2 = 0; i2 < mut.addedNodes.length; i2++) {
+ let node = mut.addedNodes[i2];
+ added.push(node);
+ if (isText(node)) this.lastChangedTextNode = node;
+ }
+ if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))
+ return { from: desc.posBefore, to: desc.posAfter };
+ let prev = mut.previousSibling, next = mut.nextSibling;
+ if (ie && ie_version <= 11 && mut.addedNodes.length) {
+ for (let i2 = 0; i2 < mut.addedNodes.length; i2++) {
+ let { previousSibling, nextSibling } = mut.addedNodes[i2];
+ if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) prev = previousSibling;
+ if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) next = nextSibling;
+ }
+ }
+ let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0;
+ let from = desc.localPosFromDOM(mut.target, fromOffset, -1);
+ let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length;
+ let to = desc.localPosFromDOM(mut.target, toOffset, 1);
+ return { from, to };
+ } else if (mut.type == "attributes") {
+ return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };
+ } else {
+ this.lastChangedTextNode = mut.target;
+ return {
+ from: desc.posAtStart,
+ to: desc.posAtEnd,
+ // An event was generated for a text change that didn't change
+ // any text. Mark the dom change to fall back to assuming the
+ // selection was typed over with an identical value if it can't
+ // find another change.
+ typeOver: mut.target.nodeValue == mut.oldValue
+ };
+ }
+ }
+ };
+ var cssChecked = /* @__PURE__ */ new WeakMap();
+ var cssCheckWarned = false;
+ function checkCSS(view) {
+ if (cssChecked.has(view)) return;
+ cssChecked.set(view, null);
+ if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {
+ view.requiresGeckoHackNode = gecko;
+ if (cssCheckWarned) return;
+ console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.");
+ cssCheckWarned = true;
+ }
+ }
+ function rangeToSelectionRange(view, range) {
+ let anchorNode = range.startContainer, anchorOffset = range.startOffset;
+ let focusNode = range.endContainer, focusOffset = range.endOffset;
+ let currentAnchor = view.domAtPos(view.state.selection.anchor);
+ if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))
+ [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
+ return { anchorNode, anchorOffset, focusNode, focusOffset };
+ }
+ function safariShadowSelectionRange(view, selection) {
+ if (selection.getComposedRanges) {
+ let range = selection.getComposedRanges(view.root)[0];
+ if (range) return rangeToSelectionRange(view, range);
+ }
+ let found2;
+ function read(event) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ found2 = event.getTargetRanges()[0];
+ }
+ view.dom.addEventListener("beforeinput", read, true);
+ document.execCommand("indent");
+ view.dom.removeEventListener("beforeinput", read, true);
+ return found2 ? rangeToSelectionRange(view, found2) : null;
+ }
+ function blockParent(view, node) {
+ for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {
+ let desc = view.docView.nearestDesc(p, true);
+ if (desc && desc.node.isBlock) return p;
+ }
+ return null;
+ }
+ function fixUpBadSafariComposition(view, addedNodes) {
+ let { focusNode, focusOffset } = view.domSelectionRange();
+ for (let node of addedNodes) {
+ if (node.parentNode?.nodeName == "TR") {
+ let nextCell = node.nextSibling;
+ while (nextCell && (nextCell.nodeName != "TD" && nextCell.nodeName != "TH")) nextCell = nextCell.nextSibling;
+ if (nextCell) {
+ let parent = nextCell;
+ for (; ; ) {
+ let first = parent.firstChild;
+ if (!first || !isElt(first) || first.contentEditable == "false" || /^(BR|IMG)$/.test(first.nodeName)) break;
+ parent = first;
+ }
+ parent.insertBefore(node, parent.firstChild);
+ if (focusNode == node) view.domSelection().collapse(node, focusOffset);
+ } else {
+ node.parentNode.removeChild(node);
+ }
+ }
+ }
+ }
+
+ // third_party/editor/prosemirror-view/src/domchange.ts
+ function parseBetween(view, from_, to_, addedNodes) {
+ let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);
+ let domSel = view.domSelectionRange();
+ let find;
+ let anchor = domSel.anchorNode;
+ if (anchor && contains(view.dom, anchor)) {
+ find = [{ node: anchor, offset: domSel.anchorOffset }];
+ if (!selectionCollapsed(domSel))
+ find.push({ node: domSel.focusNode, offset: domSel.focusOffset });
+ }
+ if (chrome && view.input.lastKeyCode === 8) {
+ for (let off = toOffset; off > fromOffset; off--) {
+ let node = parent.childNodes[off - 1], desc = node.pmViewDesc;
+ if (node.nodeName == "BR" && !desc) {
+ toOffset = off;
+ break;
+ }
+ if (!desc || desc.size) break;
+ }
+ }
+ let startDoc = view.state.doc;
+ let parser2 = view.someProp("domParser") || DOMParser.fromSchema(view.state.schema);
+ let $from = startDoc.resolve(from);
+ let sel = null, doc3 = parser2.parse(parent, {
+ topNode: $from.parent,
+ topMatch: $from.parent.contentMatchAt($from.index()),
+ topOpen: true,
+ from: fromOffset,
+ to: toOffset,
+ preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true,
+ findPositions: find,
+ ruleFromNode: ruleFromNode(addedNodes),
+ context: $from
+ });
+ if (find && find[0].pos != null) {
+ let anchor2 = find[0].pos, head = find[1] && find[1].pos;
+ if (head == null) head = anchor2;
+ sel = { anchor: anchor2 + from, head: head + from };
+ }
+ return { doc: doc3, sel, from, to };
+ }
+ var ruleFromNode = (added) => (dom) => {
+ let desc = dom.pmViewDesc;
+ if (desc) {
+ return desc.parseRule(added);
+ } else if (dom.nodeName == "BR" && dom.parentNode) {
+ if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {
+ let skip = document.createElement("div");
+ skip.appendChild(document.createElement("li"));
+ return { skip };
+ } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {
+ return { ignore: true };
+ }
+ } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) {
+ return { ignore: true };
+ }
+ return null;
+ };
+ var isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;
+ function readDOMChange(view, from, to, typeOver, addedNodes) {
+ let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);
+ view.input.compositionPendingChanges = 0;
+ if (from < 0) {
+ let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;
+ let newSel = selectionFromDOM(view, origin);
+ if (newSel && !view.state.selection.eq(newSel)) {
+ if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))))
+ return;
+ let tr = view.state.tr.setSelection(newSel);
+ if (origin == "pointer") tr.setMeta("pointer", true);
+ else if (origin == "key") tr.scrollIntoView();
+ if (compositionID) tr.setMeta("composition", compositionID);
+ view.dispatch(tr);
+ }
+ return;
+ }
+ let $before = view.state.doc.resolve(from);
+ let shared = $before.sharedDepth(to);
+ from = $before.before(shared + 1);
+ to = view.state.doc.resolve(to).after(shared + 1);
+ let sel = view.state.selection;
+ let parse2 = parseBetween(view, from, to, addedNodes);
+ let doc3 = view.state.doc, compare = doc3.slice(parse2.from, parse2.to);
+ let preferredPos, preferredSide;
+ if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {
+ preferredPos = view.state.selection.to;
+ preferredSide = "end";
+ } else {
+ preferredPos = view.state.selection.from;
+ preferredSide = "start";
+ }
+ view.input.lastKeyCode = null;
+ let change = findDiff(compare.content, parse2.doc.content, parse2.from, preferredPos, preferredSide);
+ if (change) view.input.domChangeCount++;
+ if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => isElt(n) && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) {
+ view.input.lastIOSEnter = 0;
+ return;
+ }
+ if (!change) {
+ if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse2.sel && parse2.sel.anchor != parse2.sel.head)) {
+ change = { start: sel.from, endA: sel.to, endB: sel.to };
+ } else {
+ if (parse2.sel) {
+ let sel2 = resolveSelection(view, view.state.doc, parse2.sel);
+ if (sel2 && !sel2.eq(view.state.selection)) {
+ let tr = view.state.tr.setSelection(sel2);
+ if (compositionID) tr.setMeta("composition", compositionID);
+ view.dispatch(tr);
+ }
+ }
+ return;
+ }
+ }
+ if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) {
+ if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse2.from) {
+ change.start = view.state.selection.from;
+ } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse2.to) {
+ change.endB += view.state.selection.to - change.endA;
+ change.endA = view.state.selection.to;
+ }
+ }
+ if (ie && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse2.from && parse2.doc.textBetween(change.start - parse2.from - 1, change.start - parse2.from + 1) == " \xA0") {
+ change.start--;
+ change.endA--;
+ change.endB--;
+ }
+ let $from = parse2.doc.resolveNoCache(change.start - parse2.from);
+ let $to = parse2.doc.resolveNoCache(change.endB - parse2.from);
+ let $fromA = doc3.resolve(change.start);
+ let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;
+ if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && looksLikeEnter(parse2.doc, $from.pos, $to.pos)) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) {
+ view.input.lastIOSEnter = 0;
+ return;
+ }
+ if (view.state.selection.anchor > change.start && looksLikeBackspace(doc3, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) {
+ if (android && chrome) view.domObserver.suppressSelectionUpdates();
+ return;
+ }
+ if (chrome && change.endB == change.start)
+ view.input.lastChromeDelete = Date.now();
+ if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse2.sel && parse2.sel.anchor == parse2.sel.head && parse2.sel.head == change.endA) {
+ change.endB -= 2;
+ $to = parse2.doc.resolveNoCache(change.endB - parse2.from);
+ setTimeout(() => {
+ view.someProp("handleKeyDown", function(f) {
+ return f(view, keyEvent(13, "Enter"));
+ });
+ }, 20);
+ }
+ let chFrom = change.start, chTo = change.endA;
+ let mkTr = (base2) => {
+ let tr = base2 || view.state.tr.replace(chFrom, chTo, parse2.doc.slice(
+ change.start - parse2.from,
+ change.endB - parse2.from
+ ));
+ if (parse2.sel) {
+ let sel2 = resolveSelection(view, tr.doc, parse2.sel);
+ if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr.mapping.map(chTo) - 1) || ie && sel2.empty && sel2.head == chFrom))
+ tr.setSelection(sel2);
+ }
+ if (compositionID) tr.setMeta("composition", compositionID);
+ return tr.scrollIntoView();
+ };
+ let markChange;
+ if (inlineChange) {
+ if ($from.pos == $to.pos) {
+ if (ie && ie_version <= 11 && $from.parentOffset == 0) {
+ view.domObserver.suppressSelectionUpdates();
+ setTimeout(() => selectionToDOM(view), 20);
+ }
+ let tr = mkTr(view.state.tr.delete(chFrom, chTo));
+ let marks = doc3.resolve(change.start).marksAcross(doc3.resolve(change.endA));
+ if (marks) tr.ensureMarks(marks);
+ view.dispatch(tr);
+ } else if (
+ // Adding or removing a mark
+ change.endA == change.endB && (markChange = isMarkChange(
+ $from.parent.content.cut($from.parentOffset, $to.parentOffset),
+ $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())
+ ))
+ ) {
+ let tr = mkTr(view.state.tr);
+ if (markChange.type == "add") tr.addMark(chFrom, chTo, markChange.mark);
+ else tr.removeMark(chFrom, chTo, markChange.mark);
+ view.dispatch(tr);
+ } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {
+ let text2 = $from.parent.textBetween($from.parentOffset, $to.parentOffset);
+ let deflt = () => mkTr(view.state.tr.insertText(text2, chFrom, chTo));
+ if (!view.someProp("handleTextInput", (f) => f(view, chFrom, chTo, text2, deflt)))
+ view.dispatch(deflt());
+ } else {
+ view.dispatch(mkTr());
+ }
+ } else {
+ view.dispatch(mkTr());
+ }
+ }
+ function resolveSelection(view, doc3, parsedSel) {
+ if (Math.max(parsedSel.anchor, parsedSel.head) > doc3.content.size) return null;
+ return selectionBetween(view, doc3.resolve(parsedSel.anchor), doc3.resolve(parsedSel.head));
+ }
+ function isMarkChange(cur, prev) {
+ let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;
+ let added = curMarks, removed = prevMarks, type, mark, update;
+ for (let i2 = 0; i2 < prevMarks.length; i2++) added = prevMarks[i2].removeFromSet(added);
+ for (let i2 = 0; i2 < curMarks.length; i2++) removed = curMarks[i2].removeFromSet(removed);
+ if (added.length == 1 && removed.length == 0) {
+ mark = added[0];
+ type = "add";
+ update = (node) => node.mark(mark.addToSet(node.marks));
+ } else if (added.length == 0 && removed.length == 1) {
+ mark = removed[0];
+ type = "remove";
+ update = (node) => node.mark(mark.removeFromSet(node.marks));
+ } else {
+ return null;
+ }
+ let updated = [];
+ for (let i2 = 0; i2 < prev.childCount; i2++) updated.push(update(prev.child(i2)));
+ if (Fragment.from(updated).eq(cur)) return { mark, type };
+ }
+ function looksLikeBackspace(old, start, end, $newStart, $newEnd) {
+ if (
+ // The content must have shrunk
+ end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into
+ skipClosingAndOpening($newStart, true, false) < $newEnd.pos
+ )
+ return false;
+ let $start = old.resolve(start);
+ if (!$newStart.parent.isTextblock) {
+ let after = $start.nodeAfter;
+ return after != null && end == start + after.nodeSize;
+ }
+ if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)
+ return false;
+ let $next = old.resolve(skipClosingAndOpening($start, true, true));
+ if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end)
+ return false;
+ return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);
+ }
+ function looksLikeEnter(content, from, to) {
+ let newTextlines = 0, newLeaves = 0;
+ content.nodesBetween(from, to, (node, pos) => {
+ if (node.isTextblock && pos >= from && pos < to)
+ newTextlines++;
+ else if (node.isText ? /\S/.test(node.text.slice(Math.max(0, from - pos), Math.min(node.nodeSize, to - pos))) : node.isLeaf)
+ newLeaves++;
+ });
+ return newLeaves == 0 && newTextlines == 1;
+ }
+ function skipClosingAndOpening($pos, fromEnd, mayOpen) {
+ let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;
+ while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {
+ depth--;
+ end++;
+ fromEnd = false;
+ }
+ if (mayOpen) {
+ let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));
+ while (next && !next.isLeaf) {
+ next = next.firstChild;
+ end++;
+ }
+ }
+ return end;
+ }
+ function findDiff(a, b, pos, preferredPos, preferredSide) {
+ let start = a.findDiffStart(b, pos), lenA = pos + a.size, lenB = pos + b.size;
+ if (start == null) return null;
+ let { a: endA, b: endB } = a.findDiffEnd(b, lenA, lenB);
+ if (preferredSide == "end") {
+ let adjust = Math.max(0, start - Math.min(endA, endB));
+ preferredPos -= endA + adjust - start;
+ }
+ if (endA < start && lenA < lenB) {
+ let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;
+ start -= move;
+ endB = start + (endB - endA);
+ endA = start;
+ } else if (endB < start) {
+ let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;
+ start -= move;
+ endA = start + (endA - endB);
+ endB = start;
+ }
+ return { start, endA, endB };
+ }
+
+ // third_party/editor/prosemirror-view/src/index.ts
+ var EditorView = class {
+ /// @internal
+ _props;
+ directPlugins;
+ _root = null;
+ /// @internal
+ focused = false;
+ /// Kludge used to work around a Chrome bug @internal
+ trackWrites = null;
+ mounted = false;
+ /// @internal
+ markCursor = null;
+ /// @internal
+ cursorWrapper = null;
+ /// @internal
+ nodeViews;
+ /// @internal
+ lastSelectedViewDesc = void 0;
+ /// @internal
+ docView;
+ /// @internal
+ input = new InputState();
+ prevDirectPlugins = [];
+ pluginViews = [];
+ /// Holds `true` when a hack node is needed in Firefox to prevent the
+ /// [space is eaten issue](https://code.haverbeke.berlin/prosemirror/prosemirror/issues/651)
+ /// @internal
+ requiresGeckoHackNode = false;
+ /// The view's current [state](#state.EditorState).
+ state;
+ /// Create a view. `place` may be a DOM node that the editor should
+ /// be appended to, a function that will place it into the document,
+ /// or an object whose `mount` property holds the node to use as the
+ /// document container. If it is `null`, the editor will not be
+ /// added to the document.
+ constructor(place, props) {
+ this._props = props;
+ this.state = props.state;
+ this.directPlugins = props.plugins || [];
+ this.directPlugins.forEach(checkStateComponent);
+ this.dispatch = this.dispatch.bind(this);
+ this.dom = place && place.mount || document.createElement("div");
+ if (place) {
+ if (place.appendChild) place.appendChild(this.dom);
+ else if (typeof place == "function") place(this.dom);
+ else if (place.mount) this.mounted = true;
+ }
+ this.editable = getEditable(this);
+ updateCursorWrapper(this);
+ this.nodeViews = buildNodeViews(this);
+ this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);
+ this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));
+ this.domObserver.start();
+ initInput(this);
+ this.updatePluginViews();
+ }
+ /// An editable DOM node containing the document. (You probably
+ /// should not directly interfere with its content.)
+ dom;
+ /// Indicates whether the editor is currently [editable](#view.EditorProps.editable).
+ editable;
+ /// When editor content is being dragged, this object contains
+ /// information about the dragged slice and whether it is being
+ /// copied or moved. At any other time, it is null.
+ dragging = null;
+ /// Holds `true` when a
+ /// [composition](https://w3c.github.io/uievents/#events-compositionevents)
+ /// is active.
+ get composing() {
+ return this.input.composing;
+ }
+ /// The view's current [props](#view.EditorProps).
+ get props() {
+ if (this._props.state != this.state) {
+ let prev = this._props;
+ this._props = {};
+ for (let name in prev) this._props[name] = prev[name];
+ this._props.state = this.state;
+ }
+ return this._props;
+ }
+ /// Update the view's props. Will immediately cause an update to
+ /// the DOM.
+ update(props) {
+ if (props.handleDOMEvents != this._props.handleDOMEvents) ensureListeners(this);
+ let prevProps = this._props;
+ this._props = props;
+ if (props.plugins) {
+ props.plugins.forEach(checkStateComponent);
+ this.directPlugins = props.plugins;
+ }
+ this.updateStateInner(props.state, prevProps);
+ }
+ /// Update the view by updating existing props object with the object
+ /// given as argument. Equivalent to `view.update(Object.assign({},
+ /// view.props, props))`.
+ setProps(props) {
+ let updated = {};
+ for (let name in this._props) updated[name] = this._props[name];
+ updated.state = this.state;
+ for (let name in props) updated[name] = props[name];
+ this.update(updated);
+ }
+ /// Update the editor's `state` prop, without touching any of the
+ /// other props.
+ updateState(state) {
+ this.updateStateInner(state, this._props);
+ }
+ updateStateInner(state, prevProps) {
+ let prev = this.state, redraw = false, updateSel = false;
+ if (state.storedMarks && this.composing) {
+ clearComposition(this);
+ updateSel = true;
+ }
+ this.state = state;
+ let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;
+ if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {
+ let nodeViews = buildNodeViews(this);
+ if (changedNodeViews(nodeViews, this.nodeViews)) {
+ this.nodeViews = nodeViews;
+ redraw = true;
+ }
+ }
+ if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {
+ ensureListeners(this);
+ }
+ this.editable = getEditable(this);
+ updateCursorWrapper(this);
+ let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);
+ let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve";
+ let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);
+ if (updateDoc || !state.selection.eq(prev.selection)) updateSel = true;
+ let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);
+ if (updateSel) {
+ this.domObserver.stop();
+ let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);
+ if (updateDoc) {
+ let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null;
+ if (this.composing) this.input.compositionNode = findCompositionNode(this);
+ if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {
+ this.docView.updateOuterDeco(outerDeco);
+ this.docView.destroy();
+ this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);
+ }
+ if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites))) forceSelUpdate = true;
+ }
+ let mouseDown = this.input.mouseDown;
+ if (forceSelUpdate || !(mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this) && mouseDown.delaySelUpdate())) {
+ selectionToDOM(this, forceSelUpdate);
+ } else {
+ syncNodeSelection(this, state.selection);
+ this.domObserver.setCurSelection();
+ }
+ this.domObserver.start();
+ }
+ this.updatePluginViews(prev);
+ if (this.dragging?.node && !prev.doc.eq(state.doc))
+ this.updateDraggedNode(this.dragging, prev);
+ if (scroll == "reset") {
+ this.dom.scrollTop = 0;
+ } else if (scroll == "to selection") {
+ this.scrollToSelection();
+ } else if (oldScrollPos) {
+ resetScrollPos(oldScrollPos);
+ }
+ }
+ /// @internal
+ scrollToSelection() {
+ let startDOM = this.domSelectionRange().focusNode;
+ if (!startDOM || !contains(this.dom, startDOM)) {
+ } else if (this.someProp("handleScrollToSelection", (f) => f(this))) {
+ } else if (this.state.selection instanceof NodeSelection) {
+ let target = this.docView.domAfterPos(this.state.selection.from);
+ if (isElt(target)) scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);
+ } else {
+ scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);
+ }
+ }
+ destroyPluginViews() {
+ let view;
+ while (view = this.pluginViews.pop()) if (view.destroy) view.destroy();
+ }
+ updatePluginViews(prevState) {
+ if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
+ this.prevDirectPlugins = this.directPlugins;
+ this.destroyPluginViews();
+ for (let i2 = 0; i2 < this.directPlugins.length; i2++) {
+ let plugin = this.directPlugins[i2];
+ if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this));
+ }
+ for (let i2 = 0; i2 < this.state.plugins.length; i2++) {
+ let plugin = this.state.plugins[i2];
+ if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this));
+ }
+ } else {
+ for (let i2 = 0; i2 < this.pluginViews.length; i2++) {
+ let pluginView = this.pluginViews[i2];
+ if (pluginView.update) pluginView.update(this, prevState);
+ }
+ }
+ }
+ updateDraggedNode(dragging, prev) {
+ let sel = dragging.node, found2 = -1;
+ if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) {
+ found2 = sel.from;
+ } else {
+ let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);
+ let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos);
+ if (moved == sel.node) found2 = movedPos;
+ }
+ this.dragging = new Dragging(
+ dragging.slice,
+ dragging.move,
+ found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2)
+ );
+ }
+ someProp(propName, f) {
+ let prop = this._props && this._props[propName], value;
+ if (prop != null && (value = f ? f(prop) : prop)) return value;
+ for (let i2 = 0; i2 < this.directPlugins.length; i2++) {
+ let prop2 = this.directPlugins[i2].props[propName];
+ if (prop2 != null && (value = f ? f(prop2) : prop2)) return value;
+ }
+ let plugins = this.state.plugins;
+ if (plugins) for (let i2 = 0; i2 < plugins.length; i2++) {
+ let prop2 = plugins[i2].props[propName];
+ if (prop2 != null && (value = f ? f(prop2) : prop2)) return value;
+ }
+ }
+ /// Query whether the view has focus.
+ hasFocus() {
+ if (ie) {
+ let node = this.root.activeElement;
+ if (node == this.dom) return true;
+ if (!node || !this.dom.contains(node)) return false;
+ while (node && this.dom != node && this.dom.contains(node)) {
+ if (node.contentEditable == "false") return false;
+ node = node.parentElement;
+ }
+ return true;
+ }
+ return this.root.activeElement == this.dom;
+ }
+ /// Focus the editor.
+ focus() {
+ this.domObserver.stop();
+ if (this.editable) focusPreventScroll(this.dom);
+ selectionToDOM(this);
+ this.domObserver.start();
+ }
+ /// Get the document root in which the editor exists. This will
+ /// usually be the top-level `document`, but might be a [shadow
+ /// DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
+ /// root if the editor is inside one.
+ get root() {
+ let cached = this._root;
+ if (cached == null) for (let search = this.dom.parentNode; search; search = search.parentNode) {
+ if (search.nodeType == 9 || search.nodeType == 11 && search.host) {
+ if (!search.getSelection)
+ Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();
+ return this._root = search;
+ }
+ }
+ return cached || document;
+ }
+ /// When an existing editor view is moved to a new document or
+ /// shadow tree, call this to make it recompute its root.
+ updateRoot() {
+ this._root = null;
+ }
+ /// Given a pair of viewport coordinates, return the document
+ /// position that corresponds to them. May return null if the given
+ /// coordinates aren't inside of the editor. When an object is
+ /// returned, its `pos` property is the position nearest to the
+ /// coordinates, and its `inside` property holds the position of the
+ /// inner node that the position falls inside of, or -1 if it is at
+ /// the top level, not in any node.
+ posAtCoords(coords) {
+ return posAtCoords(this, coords);
+ }
+ /// Returns the viewport rectangle at a given document position.
+ /// `left` and `right` will be the same number, as this returns a
+ /// flat cursor-ish rectangle. If the position is between two things
+ /// that aren't directly adjacent, `side` determines which element
+ /// is used. When < 0, the element before the position is used,
+ /// otherwise the element after.
+ coordsAtPos(pos, side = 1) {
+ return coordsAtPos(this, pos, side);
+ }
+ /// Find the DOM position that corresponds to the given document
+ /// position. When `side` is negative, find the position as close as
+ /// possible to the content before the position. When positive,
+ /// prefer positions close to the content after the position. When
+ /// zero, prefer as shallow a position as possible.
+ ///
+ /// Note that you should **not** mutate the editor's internal DOM,
+ /// only inspect it (and even that is usually not necessary).
+ domAtPos(pos, side = 0) {
+ return this.docView.domFromPos(pos, side);
+ }
+ /// Find the DOM node that represents the document node after the
+ /// given position. May return `null` when the position doesn't point
+ /// in front of a node or if the node is inside an opaque node view.
+ ///
+ /// This is intended to be able to call things like
+ /// `getBoundingClientRect` on that DOM node. Do **not** mutate the
+ /// editor DOM directly, or add styling this way, since that will be
+ /// immediately overriden by the editor as it redraws the node.
+ nodeDOM(pos) {
+ let desc = this.docView.descAt(pos);
+ return desc ? desc.nodeDOM : null;
+ }
+ /// Find the document position that corresponds to a given DOM
+ /// position. (Whenever possible, it is preferable to inspect the
+ /// document structure directly, rather than poking around in the
+ /// DOM, but sometimes—for example when interpreting an event
+ /// target—you don't have a choice.)
+ ///
+ /// The `bias` parameter can be used to influence which side of a DOM
+ /// node to use when the position is inside a leaf node.
+ posAtDOM(node, offset, bias = -1) {
+ let pos = this.docView.posFromDOM(node, offset, bias);
+ if (pos == null) throw new RangeError("DOM position not inside the editor");
+ return pos;
+ }
+ /// Find out whether the selection is at the end of a textblock when
+ /// moving in a given direction. When, for example, given `"left"`,
+ /// it will return true if moving left from the current cursor
+ /// position would leave that position's parent textblock. Will apply
+ /// to the view's current state by default, but it is possible to
+ /// pass a different state.
+ endOfTextblock(dir, state) {
+ return endOfTextblock(this, state || this.state, dir);
+ }
+ /// Run the editor's paste logic with the given HTML string. The
+ /// `event`, if given, will be passed to the
+ /// [`handlePaste`](#view.EditorProps.handlePaste) hook.
+ pasteHTML(html, event) {
+ return doPaste(this, "", html, false, event || new ClipboardEvent("paste"));
+ }
+ /// Run the editor's paste logic with the given plain-text input.
+ pasteText(text2, event) {
+ return doPaste(this, text2, null, true, event || new ClipboardEvent("paste"));
+ }
+ /// Serialize the given slice as it would be if it was copied from
+ /// this editor. Returns a DOM element that contains a
+ /// representation of the slice as its children, a textual
+ /// representation, and the transformed slice (which can be
+ /// different from the given input due to hooks like
+ /// [`transformCopied`](#view.EditorProps.transformCopied)).
+ serializeForClipboard(slice) {
+ return serializeForClipboard(this, slice);
+ }
+ /// Removes the editor from the DOM and destroys all [node
+ /// views](#view.NodeView).
+ destroy() {
+ if (!this.docView) return;
+ destroyInput(this);
+ this.destroyPluginViews();
+ if (this.mounted) {
+ this.docView.update(this.state.doc, [], viewDecorations(this), this);
+ this.dom.textContent = "";
+ } else if (this.dom.parentNode) {
+ this.dom.parentNode.removeChild(this.dom);
+ }
+ this.docView.destroy();
+ this.docView = null;
+ clearReusedRange();
+ }
+ /// This is true when the view has been
+ /// [destroyed](#view.EditorView.destroy) (and thus should not be
+ /// used anymore).
+ get isDestroyed() {
+ return this.docView == null;
+ }
+ /// Used for testing.
+ dispatchEvent(event) {
+ return dispatchEvent(this, event);
+ }
+ /// @internal
+ domSelectionRange() {
+ let sel = this.dom.isConnected !== false && this.domSelection();
+ if (!sel) return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };
+ return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;
+ }
+ /// @internal
+ domSelection() {
+ return this.root.getSelection();
+ }
+ };
+ EditorView.prototype.dispatch = function(tr) {
+ let dispatchTransaction = this._props.dispatchTransaction;
+ if (dispatchTransaction) dispatchTransaction.call(this, tr);
+ else this.updateState(this.state.apply(tr));
+ };
+ function computeDocDeco(view) {
+ let attrs2 = /* @__PURE__ */ Object.create(null);
+ attrs2.class = "ProseMirror";
+ attrs2.contenteditable = String(view.editable);
+ view.someProp("attributes", (value) => {
+ if (typeof value == "function") value = value(view.state);
+ if (value) for (let attr in value) {
+ if (attr == "class")
+ attrs2.class += " " + value[attr];
+ else if (attr == "style")
+ attrs2.style = (attrs2.style ? attrs2.style + ";" : "") + value[attr];
+ else if (!attrs2[attr] && attr != "contenteditable" && attr != "nodeName")
+ attrs2[attr] = String(value[attr]);
+ }
+ });
+ if (!attrs2.translate) attrs2.translate = "no";
+ return [Decoration.node(0, view.state.doc.content.size, attrs2)];
+ }
+ function updateCursorWrapper(view) {
+ if (view.markCursor) {
+ let dom = document.createElement("img");
+ dom.className = "ProseMirror-separator";
+ dom.setAttribute("mark-placeholder", "true");
+ dom.setAttribute("alt", "");
+ view.cursorWrapper = { dom, deco: Decoration.widget(
+ view.state.selection.from,
+ dom,
+ { raw: true, marks: view.markCursor }
+ ) };
+ } else {
+ view.cursorWrapper = null;
+ }
+ }
+ function getEditable(view) {
+ return !view.someProp("editable", (value) => value(view.state) === false);
+ }
+ function selectionContextChanged(sel1, sel2) {
+ let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));
+ return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);
+ }
+ function buildNodeViews(view) {
+ let result = /* @__PURE__ */ Object.create(null);
+ function add2(obj) {
+ for (let prop in obj) if (!Object.prototype.hasOwnProperty.call(result, prop))
+ result[prop] = obj[prop];
+ }
+ view.someProp("nodeViews", add2);
+ view.someProp("markViews", add2);
+ return result;
+ }
+ function changedNodeViews(a, b) {
+ let nA = 0, nB = 0;
+ for (let prop in a) {
+ if (a[prop] != b[prop]) return true;
+ nA++;
+ }
+ for (let _ in b) nB++;
+ return nA != nB;
+ }
+ function checkStateComponent(plugin) {
+ if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)
+ throw new RangeError("Plugins passed directly to the view must not have a state component");
+ }
+
+ // third_party/editor/rope-sequence/index.js
+ var GOOD_LEAF_SIZE = 200;
+ var RopeSequence = class _RopeSequence {
+ // length:: number
+ // The length of the rope.
+ // :: (union<[T], RopeSequence>) → RopeSequence
+ // Append an array or other rope to this one, returning a new rope.
+ append(other) {
+ if (!other.length) return this;
+ other = _RopeSequence.from(other);
+ return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
+ }
+ // :: (union<[T], RopeSequence>) → RopeSequence
+ // Prepend an array or other rope to this one, returning a new rope.
+ prepend(other) {
+ if (!other.length) return this;
+ return _RopeSequence.from(other).append(this);
+ }
+ appendInner(other) {
+ return new Append(this, other);
+ }
+ // :: (?number, ?number) → RopeSequence
+ // Create a rope repesenting a sub-sequence of this rope.
+ slice(from = 0, to = this.length) {
+ if (from >= to) return _RopeSequence.empty;
+ return this.sliceInner(Math.max(0, from), Math.min(this.length, to));
+ }
+ // :: (number) → T
+ // Retrieve the element at the given position from this rope.
+ get(i2) {
+ if (i2 < 0 || i2 >= this.length) return void 0;
+ return this.getInner(i2);
+ }
+ // :: ((element: T, index: number) → ?bool, ?number, ?number)
+ // Call the given function for each element between the given
+ // indices. This tends to be more efficient than looping over the
+ // indices and calling `get`, because it doesn't have to descend the
+ // tree for every element.
+ forEach(f, from = 0, to = this.length) {
+ if (from <= to)
+ this.forEachInner(f, from, to, 0);
+ else
+ this.forEachInvertedInner(f, from, to, 0);
+ }
+ // :: ((element: T, index: number) → U, ?number, ?number) → [U]
+ // Map the given functions over the elements of the rope, producing
+ // a flat array.
+ map(f, from = 0, to = this.length) {
+ let result = [];
+ this.forEach((elt, i2) => result.push(f(elt, i2)), from, to);
+ return result;
+ }
+ // :: (?union<[T], RopeSequence>) → RopeSequence
+ // Create a rope representing the given array, or return the rope
+ // itself if a rope was given.
+ static from(values) {
+ if (values instanceof _RopeSequence) return values;
+ return values && values.length ? new Leaf(values) : _RopeSequence.empty;
+ }
+ // flatten:: () → [T]
+ // Return the content of this rope as an array.
+ };
+ var Leaf = class _Leaf extends RopeSequence {
+ constructor(values) {
+ super();
+ this.values = values;
+ }
+ flatten() {
+ return this.values;
+ }
+ sliceInner(from, to) {
+ if (from == 0 && to == this.length) return this;
+ return new _Leaf(this.values.slice(from, to));
+ }
+ getInner(i2) {
+ return this.values[i2];
+ }
+ forEachInner(f, from, to, start) {
+ for (let i2 = from; i2 < to; i2++)
+ if (f(this.values[i2], start + i2) === false) return false;
+ }
+ forEachInvertedInner(f, from, to, start) {
+ for (let i2 = from - 1; i2 >= to; i2--)
+ if (f(this.values[i2], start + i2) === false) return false;
+ }
+ leafAppend(other) {
+ if (this.length + other.length <= GOOD_LEAF_SIZE)
+ return new _Leaf(this.values.concat(other.flatten()));
+ }
+ leafPrepend(other) {
+ if (this.length + other.length <= GOOD_LEAF_SIZE)
+ return new _Leaf(other.flatten().concat(this.values));
+ }
+ get length() {
+ return this.values.length;
+ }
+ get depth() {
+ return 0;
+ }
+ };
+ RopeSequence.empty = new Leaf([]);
+ var Append = class _Append extends RopeSequence {
+ constructor(left, right) {
+ super();
+ this.left = left;
+ this.right = right;
+ this.length = left.length + right.length;
+ this.depth = Math.max(left.depth, right.depth) + 1;
+ }
+ flatten() {
+ return this.left.flatten().concat(this.right.flatten());
+ }
+ getInner(i2) {
+ return i2 < this.left.length ? this.left.get(i2) : this.right.get(i2 - this.left.length);
+ }
+ forEachInner(f, from, to, start) {
+ let leftLen = this.left.length;
+ if (from < leftLen && this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)
+ return false;
+ if (to > leftLen && this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)
+ return false;
+ }
+ forEachInvertedInner(f, from, to, start) {
+ let leftLen = this.left.length;
+ if (from > leftLen && this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)
+ return false;
+ if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)
+ return false;
+ }
+ sliceInner(from, to) {
+ if (from == 0 && to == this.length) return this;
+ let leftLen = this.left.length;
+ if (to <= leftLen) return this.left.slice(from, to);
+ if (from >= leftLen) return this.right.slice(from - leftLen, to - leftLen);
+ return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen));
+ }
+ leafAppend(other) {
+ let inner = this.right.leafAppend(other);
+ if (inner) return new _Append(this.left, inner);
+ }
+ leafPrepend(other) {
+ let inner = this.left.leafPrepend(other);
+ if (inner) return new _Append(inner, this.right);
+ }
+ appendInner(other) {
+ if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)
+ return new _Append(this.left, new _Append(this.right, other));
+ return new _Append(this, other);
+ }
+ };
+ var rope_sequence_default = RopeSequence;
+
+ // third_party/editor/prosemirror-history/src/history.ts
+ var max_empty_items = 500;
+ var Branch = class _Branch {
+ constructor(items, eventCount) {
+ this.items = items;
+ this.eventCount = eventCount;
+ }
+ items;
+ eventCount;
+ // Pop the latest event off the branch's history and apply it
+ // to a document transform.
+ popEvent(state, preserveItems) {
+ if (this.eventCount == 0) return null;
+ let end = this.items.length;
+ for (; ; end--) {
+ let next = this.items.get(end - 1);
+ if (next.selection) {
+ --end;
+ break;
+ }
+ }
+ let remap, mapFrom;
+ if (preserveItems) {
+ remap = this.remapping(end, this.items.length);
+ mapFrom = remap.maps.length;
+ }
+ let transform = state.tr;
+ let selection, remaining;
+ let addAfter = [], addBefore = [];
+ this.items.forEach((item, i2) => {
+ if (!item.step) {
+ if (!remap) {
+ remap = this.remapping(end, i2 + 1);
+ mapFrom = remap.maps.length;
+ }
+ mapFrom--;
+ addBefore.push(item);
+ return;
+ }
+ if (remap) {
+ addBefore.push(new Item(item.map));
+ let step = item.step.map(remap.slice(mapFrom)), map;
+ if (step && transform.maybeStep(step).doc) {
+ map = transform.mapping.maps[transform.mapping.maps.length - 1];
+ addAfter.push(new Item(map, void 0, void 0, addAfter.length + addBefore.length));
+ }
+ mapFrom--;
+ if (map) remap.appendMap(map, mapFrom);
+ } else {
+ transform.maybeStep(item.step);
+ }
+ if (item.selection) {
+ selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;
+ remaining = new _Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);
+ return false;
+ }
+ }, this.items.length, 0);
+ return { remaining, transform, selection };
+ }
+ // Create a new branch with the given transform added.
+ addTransform(transform, selection, histOptions, preserveItems) {
+ let newItems = [], eventCount = this.eventCount;
+ let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;
+ for (let i2 = 0; i2 < transform.steps.length; i2++) {
+ let step = transform.steps[i2].invert(transform.docs[i2]);
+ let item = new Item(transform.mapping.maps[i2], step, selection), merged;
+ if (merged = lastItem && lastItem.merge(item)) {
+ item = merged;
+ if (i2) newItems.pop();
+ else oldItems = oldItems.slice(0, oldItems.length - 1);
+ }
+ newItems.push(item);
+ if (selection) {
+ eventCount++;
+ selection = void 0;
+ }
+ if (!preserveItems) lastItem = item;
+ }
+ let overflow = eventCount - histOptions.depth;
+ if (overflow > DEPTH_OVERFLOW) {
+ oldItems = cutOffEvents(oldItems, overflow);
+ eventCount -= overflow;
+ }
+ return new _Branch(oldItems.append(newItems), eventCount);
+ }
+ remapping(from, to) {
+ let maps = new Mapping();
+ this.items.forEach((item, i2) => {
+ let mirrorPos = item.mirrorOffset != null && i2 - item.mirrorOffset >= from ? maps.maps.length - item.mirrorOffset : void 0;
+ maps.appendMap(item.map, mirrorPos);
+ }, from, to);
+ return maps;
+ }
+ addMaps(array) {
+ if (this.eventCount == 0) return this;
+ return new _Branch(this.items.append(array.map((map) => new Item(map))), this.eventCount);
+ }
+ // When the collab module receives remote changes, the history has
+ // to know about those, so that it can adjust the steps that were
+ // rebased on top of the remote changes, and include the position
+ // maps for the remote changes in its array of items.
+ rebased(rebasedTransform, rebasedCount) {
+ if (!this.eventCount) return this;
+ rebasedCount = Math.min(this.items.length, rebasedCount);
+ let rebasedItems = [], start = this.items.length - rebasedCount;
+ let mapping = rebasedTransform.mapping;
+ let newUntil = rebasedTransform.steps.length;
+ let eventCount = this.eventCount;
+ this.items.forEach((item) => {
+ if (item.selection) eventCount--;
+ }, start);
+ let iRebased = rebasedCount;
+ this.items.forEach((item) => {
+ let pos = mapping.getMirror(--iRebased);
+ if (pos == null) return;
+ newUntil = Math.min(newUntil, pos);
+ let map = mapping.maps[pos];
+ if (item.step) {
+ let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
+ let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));
+ if (selection) eventCount++;
+ rebasedItems.push(new Item(map, step, selection));
+ } else {
+ rebasedItems.push(new Item(map));
+ }
+ }, start);
+ let newMaps = [];
+ for (let i2 = rebasedCount; i2 < newUntil; i2++)
+ newMaps.push(new Item(mapping.maps[i2]));
+ let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);
+ let branch = new _Branch(items, eventCount);
+ if (branch.emptyItemCount() > max_empty_items)
+ branch = branch.compress(this.items.length - rebasedItems.length);
+ return branch;
+ }
+ emptyItemCount() {
+ let count = 0;
+ this.items.forEach((item) => {
+ if (!item.step) count++;
+ });
+ return count;
+ }
+ // Compressing a branch means rewriting it to push the air (map-only
+ // items) out. During collaboration, these naturally accumulate
+ // because each remote change adds one. The `upto` argument is used
+ // to ensure that only the items below a given level are compressed,
+ // because `rebased` relies on a clean, untouched set of items in
+ // order to associate old items with rebased steps.
+ compress(upto = this.items.length) {
+ let remap = this.remapping(0, upto), mapFrom = remap.maps.length;
+ let items = [], events = 0;
+ this.items.forEach((item, i2) => {
+ if (i2 >= upto) {
+ items.push(item);
+ if (item.selection) events++;
+ } else if (item.step) {
+ let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();
+ mapFrom--;
+ if (map) remap.appendMap(map, mapFrom);
+ if (step) {
+ let selection = item.selection && item.selection.map(remap.slice(mapFrom));
+ if (selection) events++;
+ let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;
+ if (merged = items.length && items[last].merge(newItem))
+ items[last] = merged;
+ else
+ items.push(newItem);
+ }
+ } else if (item.map) {
+ mapFrom--;
+ }
+ }, this.items.length, 0);
+ return new _Branch(rope_sequence_default.from(items.reverse()), events);
+ }
+ static empty = new _Branch(rope_sequence_default.empty, 0);
+ };
+ function cutOffEvents(items, n) {
+ let cutPoint;
+ items.forEach((item, i2) => {
+ if (item.selection && n-- == 0) {
+ cutPoint = i2;
+ return false;
+ }
+ });
+ return items.slice(cutPoint);
+ }
+ var Item = class _Item {
+ constructor(map, step, selection, mirrorOffset) {
+ this.map = map;
+ this.step = step;
+ this.selection = selection;
+ this.mirrorOffset = mirrorOffset;
+ }
+ map;
+ step;
+ selection;
+ mirrorOffset;
+ merge(other) {
+ if (this.step && other.step && !other.selection) {
+ let step = other.step.merge(this.step);
+ if (step) return new _Item(step.getMap().invert(), step, this.selection);
+ }
+ }
+ };
+ var HistoryState = class {
+ constructor(done, undone, prevRanges, prevTime, prevComposition) {
+ this.done = done;
+ this.undone = undone;
+ this.prevRanges = prevRanges;
+ this.prevTime = prevTime;
+ this.prevComposition = prevComposition;
+ }
+ done;
+ undone;
+ prevRanges;
+ prevTime;
+ prevComposition;
+ };
+ var DEPTH_OVERFLOW = 20;
+ function applyTransaction(history2, state, tr, options) {
+ let historyTr = tr.getMeta(historyKey), rebased;
+ if (historyTr) return historyTr.historyState;
+ if (tr.getMeta(closeHistoryKey)) history2 = new HistoryState(history2.done, history2.undone, null, 0, -1);
+ let appended = tr.getMeta("appendedTransaction");
+ if (tr.steps.length == 0) {
+ return history2;
+ } else if (appended && appended.getMeta(historyKey)) {
+ if (appended.getMeta(historyKey).redo)
+ return new HistoryState(
+ history2.done.addTransform(tr, void 0, options, mustPreserveItems(state)),
+ history2.undone,
+ rangesFor(tr.mapping.maps),
+ history2.prevTime,
+ history2.prevComposition
+ );
+ else
+ return new HistoryState(
+ history2.done,
+ history2.undone.addTransform(tr, void 0, options, mustPreserveItems(state)),
+ null,
+ history2.prevTime,
+ history2.prevComposition
+ );
+ } else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
+ let composition = tr.getMeta("composition");
+ let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history2.prevRanges));
+ let prevRanges = appended ? mapRanges(history2.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);
+ return new HistoryState(
+ history2.done.addTransform(
+ tr,
+ newGroup ? state.selection.getBookmark() : void 0,
+ options,
+ mustPreserveItems(state)
+ ),
+ Branch.empty,
+ prevRanges,
+ tr.time,
+ composition == null ? history2.prevComposition : composition
+ );
+ } else if (rebased = tr.getMeta("rebased")) {
+ return new HistoryState(
+ history2.done.rebased(tr, rebased),
+ history2.undone.rebased(tr, rebased),
+ mapRanges(history2.prevRanges, tr.mapping),
+ history2.prevTime,
+ history2.prevComposition
+ );
+ } else {
+ return new HistoryState(
+ history2.done.addMaps(tr.mapping.maps),
+ history2.undone.addMaps(tr.mapping.maps),
+ mapRanges(history2.prevRanges, tr.mapping),
+ history2.prevTime,
+ history2.prevComposition
+ );
+ }
+ }
+ function isAdjacentTo(transform, prevRanges) {
+ if (!prevRanges) return false;
+ if (!transform.docChanged) return true;
+ let adjacent = false;
+ transform.mapping.maps[0].forEach((start, end) => {
+ for (let i2 = 0; i2 < prevRanges.length; i2 += 2)
+ if (start <= prevRanges[i2 + 1] && end >= prevRanges[i2])
+ adjacent = true;
+ });
+ return adjacent;
+ }
+ function rangesFor(maps) {
+ let result = [];
+ for (let i2 = maps.length - 1; i2 >= 0 && result.length == 0; i2--)
+ maps[i2].forEach((_from, _to, from, to) => result.push(from, to));
+ return result;
+ }
+ function mapRanges(ranges, mapping) {
+ if (!ranges) return null;
+ let result = [];
+ for (let i2 = 0; i2 < ranges.length; i2 += 2) {
+ let from = mapping.map(ranges[i2], 1), to = mapping.map(ranges[i2 + 1], -1);
+ if (from <= to) result.push(from, to);
+ }
+ return result;
+ }
+ function histTransaction(history2, state, redo2) {
+ let preserveItems = mustPreserveItems(state);
+ let histOptions = historyKey.get(state).spec.config;
+ let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems);
+ if (!pop) return null;
+ let selection = pop.selection.resolve(pop.transform.doc);
+ let added = (redo2 ? history2.done : history2.undone).addTransform(
+ pop.transform,
+ state.selection.getBookmark(),
+ histOptions,
+ preserveItems
+ );
+ let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1);
+ return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist });
+ }
+ var cachedPreserveItems = false;
+ var cachedPreserveItemsPlugins = null;
+ function mustPreserveItems(state) {
+ let plugins = state.plugins;
+ if (cachedPreserveItemsPlugins != plugins) {
+ cachedPreserveItems = false;
+ cachedPreserveItemsPlugins = plugins;
+ for (let i2 = 0; i2 < plugins.length; i2++) if (plugins[i2].spec.historyPreserveItems) {
+ cachedPreserveItems = true;
+ break;
+ }
+ }
+ return cachedPreserveItems;
+ }
+ var historyKey = new PluginKey("history");
+ var closeHistoryKey = new PluginKey("closeHistory");
+ function history(config2 = {}) {
+ config2 = {
+ depth: config2.depth || 100,
+ newGroupDelay: config2.newGroupDelay || 500
+ };
+ return new Plugin({
+ key: historyKey,
+ state: {
+ init() {
+ return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);
+ },
+ apply(tr, hist, state) {
+ return applyTransaction(hist, state, tr, config2);
+ }
+ },
+ config: config2,
+ props: {
+ handleDOMEvents: {
+ beforeinput(view, e) {
+ let inputType = e.inputType;
+ let command = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null;
+ if (!command || !view.editable) return false;
+ e.preventDefault();
+ return command(view.state, view.dispatch);
+ }
+ }
+ }
+ });
+ }
+ function buildCommand(redo2, scroll) {
+ return (state, dispatch) => {
+ let hist = historyKey.getState(state);
+ if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0) return false;
+ if (dispatch) {
+ let tr = histTransaction(hist, state, redo2);
+ if (tr) dispatch(scroll ? tr.scrollIntoView() : tr);
+ }
+ return true;
+ };
+ }
+ var undo = buildCommand(false, true);
+ var redo = buildCommand(true, true);
+ var undoNoScroll = buildCommand(false, false);
+ var redoNoScroll = buildCommand(true, false);
+
+ // third_party/editor/w3c-keyname/index.js
+ var base = {
+ 8: "Backspace",
+ 9: "Tab",
+ 10: "Enter",
+ 12: "NumLock",
+ 13: "Enter",
+ 16: "Shift",
+ 17: "Control",
+ 18: "Alt",
+ 20: "CapsLock",
+ 27: "Escape",
+ 32: " ",
+ 33: "PageUp",
+ 34: "PageDown",
+ 35: "End",
+ 36: "Home",
+ 37: "ArrowLeft",
+ 38: "ArrowUp",
+ 39: "ArrowRight",
+ 40: "ArrowDown",
+ 44: "PrintScreen",
+ 45: "Insert",
+ 46: "Delete",
+ 59: ";",
+ 61: "=",
+ 91: "Meta",
+ 92: "Meta",
+ 106: "*",
+ 107: "+",
+ 108: ",",
+ 109: "-",
+ 110: ".",
+ 111: "/",
+ 144: "NumLock",
+ 145: "ScrollLock",
+ 160: "Shift",
+ 161: "Shift",
+ 162: "Control",
+ 163: "Control",
+ 164: "Alt",
+ 165: "Alt",
+ 173: "-",
+ 186: ";",
+ 187: "=",
+ 188: ",",
+ 189: "-",
+ 190: ".",
+ 191: "/",
+ 192: "`",
+ 219: "[",
+ 220: "\\",
+ 221: "]",
+ 222: "'"
+ };
+ var shift = {
+ 48: ")",
+ 49: "!",
+ 50: "@",
+ 51: "#",
+ 52: "$",
+ 53: "%",
+ 54: "^",
+ 55: "&",
+ 56: "*",
+ 57: "(",
+ 59: ":",
+ 61: "+",
+ 173: "_",
+ 186: ":",
+ 187: "+",
+ 188: "<",
+ 189: "_",
+ 190: ">",
+ 191: "?",
+ 192: "~",
+ 219: "{",
+ 220: "|",
+ 221: "}",
+ 222: '"'
+ };
+ var mac2 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
+ var ie2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
+ for (i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
+ var i;
+ for (i = 1; i <= 24; i++) base[i + 111] = "F" + i;
+ var i;
+ for (i = 65; i <= 90; i++) {
+ base[i] = String.fromCharCode(i + 32);
+ shift[i] = String.fromCharCode(i);
+ }
+ var i;
+ for (code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
+ var code;
+ function keyName(event) {
+ var ignoreKey = mac2 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
+ var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
+ if (name == "Esc") name = "Escape";
+ if (name == "Del") name = "Delete";
+ if (name == "Left") name = "ArrowLeft";
+ if (name == "Up") name = "ArrowUp";
+ if (name == "Right") name = "ArrowRight";
+ if (name == "Down") name = "ArrowDown";
+ return name;
+ }
+
+ // third_party/editor/prosemirror-keymap/src/keymap.ts
+ var mac3 = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
+ var windows2 = typeof navigator != "undefined" && /Win/.test(navigator.platform);
+ function normalizeKeyName(name) {
+ let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];
+ if (result == "Space") result = " ";
+ let alt, ctrl, shift2, meta;
+ for (let i2 = 0; i2 < parts.length - 1; i2++) {
+ let mod = parts[i2];
+ if (/^(cmd|meta|m)$/i.test(mod)) meta = true;
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
+ else if (/^s(hift)?$/i.test(mod)) shift2 = true;
+ else if (/^mod$/i.test(mod)) {
+ if (mac3) meta = true;
+ else ctrl = true;
+ } else throw new Error("Unrecognized modifier name: " + mod);
+ }
+ if (alt) result = "Alt-" + result;
+ if (ctrl) result = "Ctrl-" + result;
+ if (meta) result = "Meta-" + result;
+ if (shift2) result = "Shift-" + result;
+ return result;
+ }
+ function normalize(map) {
+ let copy2 = /* @__PURE__ */ Object.create(null);
+ for (let prop in map) copy2[normalizeKeyName(prop)] = map[prop];
+ return copy2;
+ }
+ function modifiers(name, event, shift2 = true) {
+ if (event.altKey) name = "Alt-" + name;
+ if (event.ctrlKey) name = "Ctrl-" + name;
+ if (event.metaKey) name = "Meta-" + name;
+ if (shift2 && event.shiftKey) name = "Shift-" + name;
+ return name;
+ }
+ function keymap(bindings) {
+ return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
+ }
+ function keydownHandler(bindings) {
+ let map = normalize(bindings);
+ return function(view, event) {
+ let name = keyName(event), baseName, direct = map[modifiers(name, event)];
+ if (direct && direct(view.state, view.dispatch, view)) return true;
+ if (name.length == 1 && name != " ") {
+ if (event.shiftKey) {
+ let noShift = map[modifiers(name, event, false)];
+ if (noShift && noShift(view.state, view.dispatch, view)) return true;
+ }
+ if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
+ !(windows2 && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) {
+ let fromCode = map[modifiers(baseName, event)];
+ if (fromCode && fromCode(view.state, view.dispatch, view)) return true;
+ }
+ }
+ return false;
+ };
+ }
+
+ // third_party/editor/prosemirror-commands/src/commands.ts
+ var deleteSelection = (state, dispatch) => {
+ if (state.selection.empty) return false;
+ if (dispatch) dispatch(state.tr.deleteSelection().scrollIntoView());
+ return true;
+ };
+ function atBlockStart(state, view) {
+ let { $cursor } = state.selection;
+ if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0))
+ return null;
+ return $cursor;
+ }
+ var joinBackward = (state, dispatch, view) => {
+ let $cursor = atBlockStart(state, view);
+ if (!$cursor) return false;
+ let $cut = findCutBefore($cursor);
+ if (!$cut) {
+ let range = $cursor.blockRange(), target = range && liftTarget(range);
+ if (target == null) return false;
+ if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());
+ return true;
+ }
+ let before = $cut.nodeBefore;
+ if (deleteBarrier(state, $cut, dispatch, -1)) return true;
+ if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) {
+ for (let depth = $cursor.depth; ; depth--) {
+ let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);
+ if (delStep && delStep.slice.size < delStep.to - delStep.from) {
+ if (dispatch) {
+ let tr = state.tr.step(delStep);
+ tr.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));
+ dispatch(tr.scrollIntoView());
+ }
+ return true;
+ }
+ if (depth == 1 || $cursor.node(depth - 1).childCount > 1) break;
+ }
+ }
+ if (before.isAtom && $cut.depth == $cursor.depth - 1) {
+ if (dispatch) dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
+ return true;
+ }
+ return false;
+ };
+ function textblockAt(node, side, only = false) {
+ for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
+ if (scan.isTextblock) return true;
+ if (only && scan.childCount != 1) return false;
+ }
+ return false;
+ }
+ var selectNodeBackward = (state, dispatch, view) => {
+ let { $head, empty: empty2 } = state.selection, $cut = $head;
+ if (!empty2) return false;
+ if ($head.parent.isTextblock) {
+ if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) return false;
+ $cut = findCutBefore($head);
+ }
+ let node = $cut && $cut.nodeBefore;
+ if (!node || !NodeSelection.isSelectable(node)) return false;
+ if (dispatch)
+ dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
+ return true;
+ };
+ function findCutBefore($pos) {
+ if (!$pos.parent.type.spec.isolating) for (let i2 = $pos.depth - 1; i2 >= 0; i2--) {
+ if ($pos.index(i2) > 0) return $pos.doc.resolve($pos.before(i2 + 1));
+ if ($pos.node(i2).type.spec.isolating) break;
+ }
+ return null;
+ }
+ function atBlockEnd(state, view) {
+ let { $cursor } = state.selection;
+ if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size))
+ return null;
+ return $cursor;
+ }
+ var joinForward = (state, dispatch, view) => {
+ let $cursor = atBlockEnd(state, view);
+ if (!$cursor) return false;
+ let $cut = findCutAfter($cursor);
+ if (!$cut) return false;
+ let after = $cut.nodeAfter;
+ if (deleteBarrier(state, $cut, dispatch, 1)) return true;
+ if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) {
+ let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
+ if (delStep && delStep.slice.size < delStep.to - delStep.from) {
+ if (dispatch) {
+ let tr = state.tr.step(delStep);
+ tr.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1) : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));
+ dispatch(tr.scrollIntoView());
+ }
+ return true;
+ }
+ }
+ if (after.isAtom && $cut.depth == $cursor.depth - 1) {
+ if (dispatch) dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
+ return true;
+ }
+ return false;
+ };
+ var selectNodeForward = (state, dispatch, view) => {
+ let { $head, empty: empty2 } = state.selection, $cut = $head;
+ if (!empty2) return false;
+ if ($head.parent.isTextblock) {
+ if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
+ return false;
+ $cut = findCutAfter($head);
+ }
+ let node = $cut && $cut.nodeAfter;
+ if (!node || !NodeSelection.isSelectable(node)) return false;
+ if (dispatch)
+ dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
+ return true;
+ };
+ function findCutAfter($pos) {
+ if (!$pos.parent.type.spec.isolating) for (let i2 = $pos.depth - 1; i2 >= 0; i2--) {
+ let parent = $pos.node(i2);
+ if ($pos.index(i2) + 1 < parent.childCount) return $pos.doc.resolve($pos.after(i2 + 1));
+ if (parent.type.spec.isolating) break;
+ }
+ return null;
+ }
+ var newlineInCode = (state, dispatch) => {
+ let { $head, $anchor } = state.selection;
+ if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false;
+ if (dispatch) dispatch(state.tr.insertText("\n").scrollIntoView());
+ return true;
+ };
+ function defaultBlockAt(match2) {
+ for (let i2 = 0; i2 < match2.edgeCount; i2++) {
+ let { type } = match2.edge(i2);
+ if (type.isTextblock && !type.hasRequiredAttrs()) return type;
+ }
+ return null;
+ }
+ var exitCode = (state, dispatch) => {
+ let { $head, $anchor } = state.selection;
+ if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false;
+ let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));
+ if (!type || !above.canReplaceWith(after, after, type)) return false;
+ if (dispatch) {
+ let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());
+ tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));
+ dispatch(tr.scrollIntoView());
+ }
+ return true;
+ };
+ var createParagraphNear = (state, dispatch) => {
+ let sel = state.selection, { $from, $to } = sel;
+ if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) return false;
+ let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
+ if (!type || !type.isTextblock) return false;
+ if (dispatch) {
+ let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
+ let tr = state.tr.insert(side, type.createAndFill());
+ tr.setSelection(TextSelection.create(tr.doc, side + 1));
+ dispatch(tr.scrollIntoView());
+ }
+ return true;
+ };
+ var liftEmptyBlock = (state, dispatch) => {
+ let { $cursor } = state.selection;
+ if (!$cursor || $cursor.parent.content.size) return false;
+ if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
+ let before = $cursor.before();
+ if (canSplit(state.doc, before)) {
+ if (dispatch) dispatch(state.tr.split(before).scrollIntoView());
+ return true;
+ }
+ }
+ let range = $cursor.blockRange(), target = range && liftTarget(range);
+ if (target == null) return false;
+ if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());
+ return true;
+ };
+ function splitBlockAs(splitNode) {
+ return (state, dispatch) => {
+ if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
+ let { $from: $from2 } = state.selection;
+ if (!$from2.parentOffset || !canSplit(state.doc, $from2.pos)) return false;
+ if (dispatch) dispatch(state.tr.split($from2.pos).scrollIntoView());
+ return true;
+ }
+ if (!state.selection.$from.depth) return false;
+ let tr = state.tr;
+ if (!state.selection.empty && (state.selection instanceof TextSelection || state.selection instanceof AllSelection))
+ tr.deleteSelection();
+ let { $from } = tr.selection, mapFrom = tr.steps.length;
+ let types = [];
+ let splitDepth, deflt, atEnd = false, atStart = false;
+ for (let d = $from.depth; ; d--) {
+ let node = $from.node(d);
+ if (node.isBlock) {
+ atEnd = $from.end(d) == $from.pos + ($from.depth - d);
+ atStart = $from.start(d) == $from.pos - ($from.depth - d);
+ deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));
+ let splitType = splitNode && splitNode($from.parent, atEnd, $from);
+ types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));
+ splitDepth = d;
+ break;
+ } else {
+ if (d == 1) return false;
+ types.unshift(null);
+ }
+ }
+ let splitPos = $from.pos;
+ let can = canSplit(tr.doc, splitPos, types.length, types);
+ if (!can) {
+ types[0] = deflt ? { type: deflt } : null;
+ can = canSplit(tr.doc, splitPos, types.length, types);
+ }
+ if (!can) return false;
+ tr.split(splitPos, types.length, types);
+ if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {
+ let mapping = tr.mapping.slice(mapFrom);
+ let first = mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);
+ if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))
+ tr.setNodeMarkup(mapping.map($from.before(splitDepth)), deflt);
+ }
+ if (dispatch) dispatch(tr.scrollIntoView());
+ return true;
+ };
+ }
+ var splitBlock = splitBlockAs();
+ var selectAll = (state, dispatch) => {
+ if (dispatch) dispatch(state.tr.setSelection(new AllSelection(state.doc)));
+ return true;
+ };
+ function joinMaybeClear(state, $pos, dispatch) {
+ let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();
+ if (!before || !after || !before.type.compatibleContent(after.type)) return false;
+ if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {
+ if (dispatch) dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
+ return true;
+ }
+ if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))
+ return false;
+ if (dispatch)
+ dispatch(state.tr.join($pos.pos).scrollIntoView());
+ return true;
+ }
+ function deleteBarrier(state, $cut, dispatch, dir) {
+ let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match2;
+ let isolated = before.type.spec.isolating || after.type.spec.isolating;
+ if (!isolated && joinMaybeClear(state, $cut, dispatch)) return true;
+ let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);
+ if (canDelAfter && (conn = (match2 = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match2.matchType(conn[0] || after.type).validEnd) {
+ if (dispatch) {
+ let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty;
+ for (let i2 = conn.length - 1; i2 >= 0; i2--)
+ wrap2 = Fragment.from(conn[i2].create(null, wrap2));
+ wrap2 = Fragment.from(before.copy(wrap2));
+ let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true));
+ let $joinAt = tr.doc.resolve(end + 2 * conn.length);
+ if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr.doc, $joinAt.pos)) tr.join($joinAt.pos);
+ dispatch(tr.scrollIntoView());
+ }
+ return true;
+ }
+ let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1);
+ let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);
+ if (target != null && target >= $cut.depth) {
+ if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());
+ return true;
+ }
+ if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) {
+ let at = before, wrap2 = [];
+ for (; ; ) {
+ wrap2.push(at);
+ if (at.isTextblock) break;
+ at = at.lastChild;
+ }
+ let afterText = after, afterDepth = 1;
+ for (; !afterText.isTextblock; afterText = afterText.firstChild) afterDepth++;
+ if (at.canReplace(at.childCount, at.childCount, afterText.content)) {
+ if (dispatch) {
+ let end = Fragment.empty;
+ for (let i2 = wrap2.length - 1; i2 >= 0; i2--) end = Fragment.from(wrap2[i2].copy(end));
+ let tr = state.tr.step(new ReplaceAroundStep(
+ $cut.pos - wrap2.length,
+ $cut.pos + after.nodeSize,
+ $cut.pos + afterDepth,
+ $cut.pos + after.nodeSize - afterDepth,
+ new Slice(end, wrap2.length, 0),
+ 0,
+ true
+ ));
+ dispatch(tr.scrollIntoView());
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+ function selectTextblockSide(side) {
+ return function(state, dispatch) {
+ let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
+ let depth = $pos.depth;
+ while ($pos.node(depth).isInline) {
+ if (!depth) return false;
+ depth--;
+ }
+ if (!$pos.node(depth).isTextblock) return false;
+ if (dispatch)
+ dispatch(state.tr.setSelection(TextSelection.create(
+ state.doc,
+ side < 0 ? $pos.start(depth) : $pos.end(depth)
+ )));
+ return true;
+ };
+ }
+ var selectTextblockStart = selectTextblockSide(-1);
+ var selectTextblockEnd = selectTextblockSide(1);
+ function wrapIn(nodeType, attrs2 = null) {
+ return function(state, dispatch) {
+ let { $from, $to } = state.selection;
+ let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs2);
+ if (!wrapping) return false;
+ if (dispatch) dispatch(state.tr.wrap(range, wrapping).scrollIntoView());
+ return true;
+ };
+ }
+ function setBlockType2(nodeType, attrs2 = null) {
+ return function(state, dispatch) {
+ let applicable = false;
+ for (let i2 = 0; i2 < state.selection.ranges.length && !applicable; i2++) {
+ let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i2];
+ state.doc.nodesBetween(from, to, (node, pos) => {
+ if (applicable) return false;
+ if (!node.isTextblock || node.hasMarkup(nodeType, attrs2)) return;
+ if (node.type == nodeType) {
+ applicable = true;
+ } else {
+ let $pos = state.doc.resolve(pos), index = $pos.index();
+ applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);
+ }
+ });
+ }
+ if (!applicable) return false;
+ if (dispatch) {
+ let tr = state.tr;
+ for (let i2 = 0; i2 < state.selection.ranges.length; i2++) {
+ let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i2];
+ tr.setBlockType(from, to, nodeType, attrs2);
+ }
+ dispatch(tr.scrollIntoView());
+ }
+ return true;
+ };
+ }
+ function markApplies(doc3, ranges, type, enterAtoms) {
+ for (let i2 = 0; i2 < ranges.length; i2++) {
+ let { $from, $to } = ranges[i2];
+ let can = $from.depth == 0 ? doc3.inlineContent && doc3.type.allowsMarkType(type) : false;
+ doc3.nodesBetween($from.pos, $to.pos, (node, pos) => {
+ if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)
+ return false;
+ can = node.inlineContent && node.type.allowsMarkType(type);
+ });
+ if (can) return true;
+ }
+ return false;
+ }
+ function removeInlineAtoms(ranges) {
+ let result = [];
+ for (let i2 = 0; i2 < ranges.length; i2++) {
+ let { $from, $to } = ranges[i2];
+ $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
+ if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {
+ if (pos + 1 > $from.pos) result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));
+ $from = $from.doc.resolve(pos + 1 + node.content.size);
+ return false;
+ }
+ });
+ if ($from.pos < $to.pos) result.push(new SelectionRange($from, $to));
+ }
+ return result;
+ }
+ function toggleMark(markType, attrs2 = null, options) {
+ let removeWhenPresent = (options && options.removeWhenPresent) !== false;
+ let enterAtoms = (options && options.enterInlineAtoms) !== false;
+ let dropSpace = !(options && options.includeWhitespace);
+ return function(state, dispatch) {
+ let { empty: empty2, $cursor, ranges } = state.selection;
+ if (empty2 && !$cursor || !markApplies(state.doc, ranges, markType, enterAtoms)) return false;
+ if (dispatch) {
+ if ($cursor) {
+ if (markType.isInSet(state.storedMarks || $cursor.marks()))
+ dispatch(state.tr.removeStoredMark(markType));
+ else
+ dispatch(state.tr.addStoredMark(markType.create(attrs2)));
+ } else {
+ let add2, tr = state.tr;
+ if (!enterAtoms) ranges = removeInlineAtoms(ranges);
+ if (removeWhenPresent) {
+ add2 = !ranges.some((r) => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));
+ } else {
+ add2 = !ranges.every((r) => {
+ let missing = false;
+ tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {
+ if (missing) return false;
+ missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) && !(node.isText && /^\s*$/.test(node.textBetween(
+ Math.max(0, r.$from.pos - pos),
+ Math.min(node.nodeSize, r.$to.pos - pos)
+ )));
+ });
+ return !missing;
+ });
+ }
+ for (let i2 = 0; i2 < ranges.length; i2++) {
+ let { $from, $to } = ranges[i2];
+ if (!add2) {
+ tr.removeMark($from.pos, $to.pos, markType);
+ } else {
+ let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;
+ let spaceStart = dropSpace && start && start.isText ? /^\s*/.exec(start.text)[0].length : 0;
+ let spaceEnd = dropSpace && end && end.isText ? /\s*$/.exec(end.text)[0].length : 0;
+ if (from + spaceStart < to) {
+ from += spaceStart;
+ to -= spaceEnd;
+ }
+ tr.addMark(from, to, markType.create(attrs2));
+ }
+ }
+ dispatch(tr.scrollIntoView());
+ }
+ }
+ return true;
+ };
+ }
+ function chainCommands(...commands) {
+ return function(state, dispatch, view) {
+ for (let i2 = 0; i2 < commands.length; i2++)
+ if (commands[i2](state, dispatch, view)) return true;
+ return false;
+ };
+ }
+ var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
+ var del = chainCommands(deleteSelection, joinForward, selectNodeForward);
+ var pcBaseKeymap = {
+ "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
+ "Mod-Enter": exitCode,
+ "Backspace": backspace,
+ "Mod-Backspace": backspace,
+ "Shift-Backspace": backspace,
+ "Delete": del,
+ "Mod-Delete": del,
+ "Mod-a": selectAll
+ };
+ var macBaseKeymap = {
+ "Ctrl-h": pcBaseKeymap["Backspace"],
+ "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
+ "Ctrl-d": pcBaseKeymap["Delete"],
+ "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
+ "Alt-Delete": pcBaseKeymap["Mod-Delete"],
+ "Alt-d": pcBaseKeymap["Mod-Delete"],
+ "Ctrl-a": selectTextblockStart,
+ "Ctrl-e": selectTextblockEnd
+ };
+ for (let key in pcBaseKeymap) macBaseKeymap[key] = pcBaseKeymap[key];
+ var mac4 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;
+ var baseKeymap = mac4 ? macBaseKeymap : pcBaseKeymap;
+
+ // third_party/editor/prosemirror-schema-list/src/schema-list.ts
+ function wrapInList(listType, attrs2 = null) {
+ return function(state, dispatch) {
+ let { $from, $to } = state.selection;
+ let range = $from.blockRange($to);
+ if (!range) return false;
+ let tr = dispatch ? state.tr : null;
+ if (!wrapRangeInList(tr, range, listType, attrs2)) return false;
+ if (dispatch) dispatch(tr.scrollIntoView());
+ return true;
+ };
+ }
+ function wrapRangeInList(tr, range, listType, attrs2 = null) {
+ let doJoin = false, outerRange = range, doc3 = range.$from.doc;
+ if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {
+ if (range.$from.index(range.depth - 1) == 0) return false;
+ let $insert = doc3.resolve(range.start - 2);
+ outerRange = new NodeRange($insert, $insert, range.depth);
+ if (range.endIndex < range.parent.childCount)
+ range = new NodeRange(range.$from, doc3.resolve(range.$to.end(range.depth)), range.depth);
+ doJoin = true;
+ }
+ let wrap2 = findWrapping(outerRange, listType, attrs2, range);
+ if (!wrap2) return false;
+ if (tr) doWrapInList(tr, range, wrap2, doJoin, listType);
+ return true;
+ }
+ function doWrapInList(tr, range, wrappers, joinBefore, listType) {
+ let content = Fragment.empty;
+ for (let i2 = wrappers.length - 1; i2 >= 0; i2--)
+ content = Fragment.from(wrappers[i2].type.create(wrappers[i2].attrs, content));
+ tr.step(new ReplaceAroundStep(
+ range.start - (joinBefore ? 2 : 0),
+ range.end,
+ range.start,
+ range.end,
+ new Slice(content, 0, 0),
+ wrappers.length,
+ true
+ ));
+ let found2 = 0;
+ for (let i2 = 0; i2 < wrappers.length; i2++) if (wrappers[i2].type == listType) found2 = i2 + 1;
+ let splitDepth = wrappers.length - found2;
+ let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;
+ for (let i2 = range.startIndex, e = range.endIndex, first = true; i2 < e; i2++, first = false) {
+ if (!first && canSplit(tr.doc, splitPos, splitDepth)) {
+ tr.split(splitPos, splitDepth);
+ splitPos += 2 * splitDepth;
+ }
+ splitPos += parent.child(i2).nodeSize;
+ }
+ return tr;
+ }
+ function splitListItem(itemType, itemAttrs) {
+ return function(state, dispatch) {
+ let { $from, $to, node } = state.selection;
+ if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) return false;
+ let grandParent = $from.node(-1);
+ if (grandParent.type != itemType) return false;
+ if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {
+ if ($from.depth == 3 || $from.node(-3).type != itemType || $from.index(-2) != $from.node(-2).childCount - 1) return false;
+ if (dispatch) {
+ let wrap2 = Fragment.empty;
+ let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
+ for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d--)
+ wrap2 = Fragment.from($from.node(d).copy(wrap2));
+ let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;
+ wrap2 = wrap2.append(Fragment.from(itemType.createAndFill()));
+ let start = $from.before($from.depth - (depthBefore - 1));
+ let tr2 = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0));
+ let sel = -1;
+ tr2.doc.nodesBetween(start, tr2.doc.content.size, (node2, pos) => {
+ if (sel > -1) return false;
+ if (node2.isTextblock && node2.content.size == 0) sel = pos + 1;
+ });
+ if (sel > -1) tr2.setSelection(Selection.near(tr2.doc.resolve(sel)));
+ dispatch(tr2.scrollIntoView());
+ }
+ return true;
+ }
+ let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
+ let tr = state.tr.delete($from.pos, $to.pos);
+ let types = nextType ? [itemAttrs ? { type: itemType, attrs: itemAttrs } : null, { type: nextType }] : void 0;
+ if (!canSplit(tr.doc, $from.pos, 2, types)) return false;
+ if (dispatch) dispatch(tr.split($from.pos, 2, types).scrollIntoView());
+ return true;
+ };
+ }
+ function liftListItem(itemType) {
+ return function(state, dispatch) {
+ let { $from, $to } = state.selection;
+ let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
+ if (!range) return false;
+ if (!dispatch) return true;
+ if ($from.node(range.depth - 1).type == itemType)
+ return liftToOuterList(state, dispatch, itemType, range);
+ else
+ return liftOutOfList(state, dispatch, range);
+ };
+ }
+ function liftToOuterList(state, dispatch, itemType, range) {
+ let tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth);
+ if (end < endOfList) {
+ tr.step(new ReplaceAroundStep(
+ end - 1,
+ endOfList,
+ end,
+ endOfList,
+ new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0),
+ 1,
+ true
+ ));
+ range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);
+ }
+ const target = liftTarget(range);
+ if (target == null) return false;
+ tr.lift(range, target);
+ let $after = tr.doc.resolve(tr.mapping.map(end, -1) - 1);
+ if (canJoin(tr.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type) tr.join($after.pos);
+ dispatch(tr.scrollIntoView());
+ return true;
+ }
+ function liftOutOfList(state, dispatch, range) {
+ let tr = state.tr, list2 = range.parent;
+ for (let pos = range.end, i2 = range.endIndex - 1, e = range.startIndex; i2 > e; i2--) {
+ pos -= list2.child(i2).nodeSize;
+ tr.delete(pos - 1, pos + 1);
+ }
+ let $start = tr.doc.resolve(range.start), item = $start.nodeAfter;
+ if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) return false;
+ let atStart = range.startIndex == 0, atEnd = range.endIndex == list2.childCount;
+ let parent = $start.node(-1), indexBefore = $start.index(-1);
+ if (!parent.canReplace(
+ indexBefore + (atStart ? 0 : 1),
+ indexBefore + 1,
+ item.content.append(atEnd ? Fragment.empty : Fragment.from(list2))
+ ))
+ return false;
+ let start = $start.pos, end = start + item.nodeSize;
+ tr.step(new ReplaceAroundStep(
+ start - (atStart ? 1 : 0),
+ end + (atEnd ? 1 : 0),
+ start + 1,
+ end - 1,
+ new Slice(
+ (atStart ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))),
+ atStart ? 0 : 1,
+ atEnd ? 0 : 1
+ ),
+ atStart ? 0 : 1
+ ));
+ dispatch(tr.scrollIntoView());
+ return true;
+ }
+ function sinkListItem(itemType) {
+ return function(state, dispatch) {
+ let { $from, $to } = state.selection;
+ let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
+ if (!range) return false;
+ let startIndex = range.startIndex;
+ if (startIndex == 0) return false;
+ let parent = range.parent, nodeBefore = parent.child(startIndex - 1);
+ if (nodeBefore.type != itemType) return false;
+ if (dispatch) {
+ let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;
+ let inner = Fragment.from(nestedBefore ? itemType.create() : null);
+ let slice = new Slice(
+ Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))),
+ nestedBefore ? 3 : 1,
+ 0
+ );
+ let before = range.start, after = range.end;
+ dispatch(state.tr.step(new ReplaceAroundStep(
+ before - (nestedBefore ? 3 : 1),
+ after,
+ before,
+ after,
+ slice,
+ 1,
+ true
+ )).scrollIntoView());
+ }
+ return true;
+ };
+ }
+
+ // third_party/editor/prosemirror-inputrules/src/inputrules.ts
+ var InputRule = class {
+ /// Create an input rule. The rule applies when the user typed
+ /// something and the text directly in front of the cursor matches
+ /// `match`, which should end with `$`.
+ ///
+ /// The `handler` can be a string, in which case the matched text, or
+ /// the first matched group in the regexp, is replaced by that
+ /// string.
+ ///
+ /// Or a it can be a function, which will be called with the match
+ /// array produced by
+ /// [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),
+ /// as well as the start and end of the matched range, and which can
+ /// return a [transaction](#state.Transaction) that describes the
+ /// rule's effect, or null to indicate the input was not handled.
+ constructor(match2, handler, options = {}) {
+ this.match = match2;
+ this.match = match2;
+ this.handler = typeof handler == "string" ? stringHandler(handler) : handler;
+ this.undoable = options.undoable !== false;
+ this.inCode = options.inCode || false;
+ this.inCodeMark = options.inCodeMark !== false;
+ }
+ match;
+ /// @internal
+ handler;
+ /// @internal
+ undoable;
+ inCode;
+ inCodeMark;
+ };
+ function stringHandler(string) {
+ return function(state, match2, start, end) {
+ let insert = string;
+ if (match2[1]) {
+ let offset = match2[0].lastIndexOf(match2[1]);
+ insert += match2[0].slice(offset + match2[1].length);
+ start += offset;
+ let cutOff = start - end;
+ if (cutOff > 0) {
+ insert = match2[0].slice(offset - cutOff, offset) + insert;
+ start = end;
+ }
+ }
+ return state.tr.insertText(insert, start, end);
+ };
+ }
+ var MAX_MATCH = 500;
+ function inputRules({ rules: rules2 }) {
+ let plugin = new Plugin({
+ state: {
+ init() {
+ return null;
+ },
+ apply(tr, prev) {
+ let stored = tr.getMeta(this);
+ if (stored) return stored;
+ return tr.selectionSet || tr.docChanged ? null : prev;
+ }
+ },
+ props: {
+ handleTextInput(view, from, to, text2) {
+ return run(view, from, to, text2, rules2, plugin);
+ },
+ handleDOMEvents: {
+ compositionend: (view) => {
+ setTimeout(() => {
+ let { $cursor } = view.state.selection;
+ if ($cursor) run(view, $cursor.pos, $cursor.pos, "", rules2, plugin);
+ });
+ }
+ }
+ },
+ isInputRules: true
+ });
+ return plugin;
+ }
+ function run(view, from, to, text2, rules2, plugin) {
+ if (view.composing) return false;
+ let state = view.state, $from = state.doc.resolve(from);
+ let textBefore = $from.parent.textBetween(
+ Math.max(0, $from.parentOffset - MAX_MATCH),
+ $from.parentOffset,
+ null,
+ "\uFFFC"
+ ) + text2;
+ for (let i2 = 0; i2 < rules2.length; i2++) {
+ let rule = rules2[i2];
+ if (!rule.inCodeMark && $from.marks().some((m) => m.type.spec.code)) continue;
+ if ($from.parent.type.spec.code) {
+ if (!rule.inCode) continue;
+ } else if (rule.inCode === "only") {
+ continue;
+ }
+ let match2 = rule.match.exec(textBefore);
+ if (!match2 || match2[0].length < text2.length) continue;
+ let startPos = from - (match2[0].length - text2.length);
+ if (!rule.inCodeMark) {
+ let hasMark = false;
+ state.doc.nodesBetween(startPos, $from.pos, (node) => {
+ if (node.isInline && node.marks.some((m) => m.type.spec.code)) hasMark = true;
+ });
+ if (hasMark) continue;
+ }
+ let tr = rule.handler(state, match2, startPos, to);
+ if (!tr) continue;
+ if (rule.undoable) tr.setMeta(plugin, { transform: tr, from, to, text: text2 });
+ view.dispatch(tr);
+ return true;
+ }
+ return false;
+ }
+ var undoInputRule = (state, dispatch) => {
+ let plugins = state.plugins;
+ for (let i2 = 0; i2 < plugins.length; i2++) {
+ let plugin = plugins[i2], undoable;
+ if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
+ if (dispatch) {
+ let tr = state.tr, toUndo = undoable.transform;
+ for (let j = toUndo.steps.length - 1; j >= 0; j--)
+ tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
+ if (undoable.text) {
+ let marks = tr.doc.resolve(undoable.from).marks();
+ tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
+ } else {
+ tr.delete(undoable.from, undoable.to);
+ }
+ dispatch(tr);
+ }
+ return true;
+ }
+ }
+ return false;
+ };
+
+ // third_party/editor/prosemirror-inputrules/src/rulebuilders.ts
+ function wrappingInputRule(regexp, nodeType, getAttrs = null, joinPredicate) {
+ return new InputRule(regexp, (state, match2, start, end) => {
+ let attrs2 = getAttrs instanceof Function ? getAttrs(match2) : getAttrs;
+ let tr = state.tr.delete(start, end);
+ let $start = tr.doc.resolve(start), range = $start.blockRange(), wrapping = range && findWrapping(range, nodeType, attrs2);
+ if (!wrapping) return null;
+ tr.wrap(range, wrapping);
+ let before = tr.doc.resolve(start - 1).nodeBefore;
+ if (before && before.type == nodeType && canJoin(tr.doc, start - 1) && (!joinPredicate || joinPredicate(match2, before)))
+ tr.join(start - 1);
+ return tr;
+ });
+ }
+ function textblockTypeInputRule(regexp, nodeType, getAttrs = null) {
+ return new InputRule(regexp, (state, match2, start, end) => {
+ let $start = state.doc.resolve(start);
+ let attrs2 = getAttrs instanceof Function ? getAttrs(match2) : getAttrs;
+ if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), nodeType)) return null;
+ return state.tr.delete(start, end).setBlockType(start, start, nodeType, attrs2);
+ });
+ }
+
+ // third_party/editor/prosemirror-markdown/src/schema.ts
+ var schema = new Schema({
+ nodes: {
+ doc: {
+ content: "block+"
+ },
+ paragraph: {
+ content: "inline*",
+ group: "block",
+ parseDOM: [{ tag: "p" }],
+ toDOM() {
+ return ["p", 0];
+ }
+ },
+ blockquote: {
+ content: "block+",
+ group: "block",
+ parseDOM: [{ tag: "blockquote" }],
+ toDOM() {
+ return ["blockquote", 0];
+ }
+ },
+ horizontal_rule: {
+ group: "block",
+ parseDOM: [{ tag: "hr" }],
+ toDOM() {
+ return ["div", ["hr"]];
+ }
+ },
+ heading: {
+ attrs: { level: { default: 1, validate: "number" } },
+ content: "(text | image)*",
+ group: "block",
+ defining: true,
+ parseDOM: [
+ { tag: "h1", attrs: { level: 1 } },
+ { tag: "h2", attrs: { level: 2 } },
+ { tag: "h3", attrs: { level: 3 } },
+ { tag: "h4", attrs: { level: 4 } },
+ { tag: "h5", attrs: { level: 5 } },
+ { tag: "h6", attrs: { level: 6 } }
+ ],
+ toDOM(node) {
+ return ["h" + +node.attrs.level, 0];
+ }
+ },
+ code_block: {
+ content: "text*",
+ group: "block",
+ code: true,
+ defining: true,
+ marks: "",
+ attrs: { params: { default: "" } },
+ parseDOM: [{ tag: "pre", preserveWhitespace: "full", getAttrs: (node) => ({ params: node.getAttribute("data-params") || "" }) }],
+ toDOM(node) {
+ return ["pre", node.attrs.params ? { "data-params": node.attrs.params } : {}, ["code", 0]];
+ }
+ },
+ ordered_list: {
+ content: "list_item+",
+ group: "block",
+ attrs: { order: { default: 1 }, tight: { default: false } },
+ parseDOM: [{ tag: "ol", getAttrs(dom) {
+ return {
+ order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1,
+ tight: dom.hasAttribute("data-tight")
+ };
+ } }],
+ toDOM(node) {
+ return ["ol", {
+ start: node.attrs.order == 1 ? null : node.attrs.order,
+ "data-tight": node.attrs.tight ? "true" : null
+ }, 0];
+ }
+ },
+ bullet_list: {
+ content: "list_item+",
+ group: "block",
+ attrs: { tight: { default: false } },
+ parseDOM: [{ tag: "ul", getAttrs: (dom) => ({ tight: dom.hasAttribute("data-tight") }) }],
+ toDOM(node) {
+ return ["ul", { "data-tight": node.attrs.tight ? "true" : null }, 0];
+ }
+ },
+ list_item: {
+ content: "block+",
+ defining: true,
+ parseDOM: [{ tag: "li" }],
+ toDOM() {
+ return ["li", 0];
+ }
+ },
+ text: {
+ group: "inline"
+ },
+ image: {
+ inline: true,
+ attrs: {
+ src: {},
+ alt: { default: null },
+ title: { default: null }
+ },
+ group: "inline",
+ draggable: true,
+ parseDOM: [{ tag: "img[src]", getAttrs(dom) {
+ return {
+ src: dom.getAttribute("src"),
+ title: dom.getAttribute("title"),
+ alt: dom.getAttribute("alt")
+ };
+ } }],
+ toDOM(node) {
+ return ["img", node.attrs];
+ }
+ },
+ hard_break: {
+ inline: true,
+ group: "inline",
+ selectable: false,
+ parseDOM: [{ tag: "br" }],
+ toDOM() {
+ return ["br"];
+ }
+ }
+ },
+ marks: {
+ em: {
+ parseDOM: [
+ { tag: "i" },
+ { tag: "em" },
+ { style: "font-style=italic" },
+ { style: "font-style=normal", clearMark: (m) => m.type.name == "em" }
+ ],
+ toDOM() {
+ return ["em"];
+ }
+ },
+ strong: {
+ parseDOM: [
+ { tag: "strong" },
+ { tag: "b", getAttrs: (node) => node.style.fontWeight != "normal" && null },
+ { style: "font-weight=400", clearMark: (m) => m.type.name == "strong" },
+ { style: "font-weight", getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null }
+ ],
+ toDOM() {
+ return ["strong"];
+ }
+ },
+ link: {
+ attrs: {
+ href: {},
+ title: { default: null }
+ },
+ inclusive: false,
+ parseDOM: [{ tag: "a[href]", getAttrs(dom) {
+ return { href: dom.getAttribute("href"), title: dom.getAttribute("title") };
+ } }],
+ toDOM(node) {
+ return ["a", node.attrs];
+ }
+ },
+ code: {
+ code: true,
+ parseDOM: [{ tag: "code" }],
+ toDOM() {
+ return ["code"];
+ }
+ }
+ }
+ });
+
+ // third_party/editor/markdown-it/lib/common/utils.mjs
+ var utils_exports = {};
+ __export(utils_exports, {
+ arrayReplaceAt: () => arrayReplaceAt,
+ asciiTrim: () => asciiTrim,
+ assign: () => assign,
+ escapeHtml: () => escapeHtml,
+ escapeRE: () => escapeRE,
+ fromCodePoint: () => fromCodePoint2,
+ has: () => has,
+ isMdAsciiPunct: () => isMdAsciiPunct,
+ isPunctChar: () => isPunctChar,
+ isPunctCharCode: () => isPunctCharCode,
+ isSpace: () => isSpace,
+ isString: () => isString,
+ isValidEntityCode: () => isValidEntityCode,
+ isWhiteSpace: () => isWhiteSpace,
+ lib: () => lib,
+ normalizeReference: () => normalizeReference,
+ unescapeAll: () => unescapeAll,
+ unescapeMd: () => unescapeMd
+ });
+
+ // third_party/editor/mdurl/index.mjs
+ var mdurl_exports = {};
+ __export(mdurl_exports, {
+ decode: () => decode_default,
+ encode: () => encode_default,
+ format: () => format,
+ parse: () => parse_default
+ });
+
+ // third_party/editor/mdurl/lib/decode.mjs
+ var decodeCache = {};
+ function getDecodeCache(exclude) {
+ let cache = decodeCache[exclude];
+ if (cache) {
+ return cache;
+ }
+ cache = decodeCache[exclude] = [];
+ for (let i2 = 0; i2 < 128; i2++) {
+ const ch = String.fromCharCode(i2);
+ cache.push(ch);
+ }
+ for (let i2 = 0; i2 < exclude.length; i2++) {
+ const ch = exclude.charCodeAt(i2);
+ cache[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2);
+ }
+ return cache;
+ }
+ function decode(string, exclude) {
+ if (typeof exclude !== "string") {
+ exclude = decode.defaultChars;
+ }
+ const cache = getDecodeCache(exclude);
+ return string.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
+ let result = "";
+ for (let i2 = 0, l = seq.length; i2 < l; i2 += 3) {
+ const b1 = parseInt(seq.slice(i2 + 1, i2 + 3), 16);
+ if (b1 < 128) {
+ result += cache[b1];
+ continue;
+ }
+ if ((b1 & 224) === 192 && i2 + 3 < l) {
+ const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
+ if ((b2 & 192) === 128) {
+ const chr = b1 << 6 & 1984 | b2 & 63;
+ if (chr < 128) {
+ result += "\uFFFD\uFFFD";
+ } else {
+ result += String.fromCharCode(chr);
+ }
+ i2 += 3;
+ continue;
+ }
+ }
+ if ((b1 & 240) === 224 && i2 + 6 < l) {
+ const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
+ const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
+ if ((b2 & 192) === 128 && (b3 & 192) === 128) {
+ const chr = b1 << 12 & 61440 | b2 << 6 & 4032 | b3 & 63;
+ if (chr < 2048 || chr >= 55296 && chr <= 57343) {
+ result += "\uFFFD\uFFFD\uFFFD";
+ } else {
+ result += String.fromCharCode(chr);
+ }
+ i2 += 6;
+ continue;
+ }
+ }
+ if ((b1 & 248) === 240 && i2 + 9 < l) {
+ const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
+ const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
+ const b4 = parseInt(seq.slice(i2 + 10, i2 + 12), 16);
+ if ((b2 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
+ let chr = b1 << 18 & 1835008 | b2 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
+ if (chr < 65536 || chr > 1114111) {
+ result += "\uFFFD\uFFFD\uFFFD\uFFFD";
+ } else {
+ chr -= 65536;
+ result += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
+ }
+ i2 += 9;
+ continue;
+ }
+ }
+ result += "\uFFFD";
+ }
+ return result;
+ });
+ }
+ decode.defaultChars = ";/?:@&=+$,#";
+ decode.componentChars = "";
+ var decode_default = decode;
+
+ // third_party/editor/mdurl/lib/encode.mjs
+ var encodeCache = {};
+ function getEncodeCache(exclude) {
+ let cache = encodeCache[exclude];
+ if (cache) {
+ return cache;
+ }
+ cache = encodeCache[exclude] = [];
+ for (let i2 = 0; i2 < 128; i2++) {
+ const ch = String.fromCharCode(i2);
+ if (/^[0-9a-z]$/i.test(ch)) {
+ cache.push(ch);
+ } else {
+ cache.push("%" + ("0" + i2.toString(16).toUpperCase()).slice(-2));
+ }
+ }
+ for (let i2 = 0; i2 < exclude.length; i2++) {
+ cache[exclude.charCodeAt(i2)] = exclude[i2];
+ }
+ return cache;
+ }
+ function encode(string, exclude, keepEscaped) {
+ if (typeof exclude !== "string") {
+ keepEscaped = exclude;
+ exclude = encode.defaultChars;
+ }
+ if (typeof keepEscaped === "undefined") {
+ keepEscaped = true;
+ }
+ const cache = getEncodeCache(exclude);
+ let result = "";
+ for (let i2 = 0, l = string.length; i2 < l; i2++) {
+ const code4 = string.charCodeAt(i2);
+ if (keepEscaped && code4 === 37 && i2 + 2 < l) {
+ if (/^[0-9a-f]{2}$/i.test(string.slice(i2 + 1, i2 + 3))) {
+ result += string.slice(i2, i2 + 3);
+ i2 += 2;
+ continue;
+ }
+ }
+ if (code4 < 128) {
+ result += cache[code4];
+ continue;
+ }
+ if (code4 >= 55296 && code4 <= 57343) {
+ if (code4 >= 55296 && code4 <= 56319 && i2 + 1 < l) {
+ const nextCode = string.charCodeAt(i2 + 1);
+ if (nextCode >= 56320 && nextCode <= 57343) {
+ result += encodeURIComponent(string[i2] + string[i2 + 1]);
+ i2++;
+ continue;
+ }
+ }
+ result += "%EF%BF%BD";
+ continue;
+ }
+ result += encodeURIComponent(string[i2]);
+ }
+ return result;
+ }
+ encode.defaultChars = ";/?:@&=+$,-_.!~*'()#";
+ encode.componentChars = "-_.!~*'()";
+ var encode_default = encode;
+
+ // third_party/editor/mdurl/lib/format.mjs
+ function format(url) {
+ let result = "";
+ result += url.protocol || "";
+ result += url.slashes ? "//" : "";
+ result += url.auth ? url.auth + "@" : "";
+ if (url.hostname && url.hostname.indexOf(":") !== -1) {
+ result += "[" + url.hostname + "]";
+ } else {
+ result += url.hostname || "";
+ }
+ result += url.port ? ":" + url.port : "";
+ result += url.pathname || "";
+ result += url.search || "";
+ result += url.hash || "";
+ return result;
+ }
+
+ // third_party/editor/mdurl/lib/parse.mjs
+ function Url() {
+ this.protocol = null;
+ this.slashes = null;
+ this.auth = null;
+ this.port = null;
+ this.hostname = null;
+ this.hash = null;
+ this.search = null;
+ this.pathname = null;
+ }
+ var protocolPattern = /^([a-z0-9.+-]+:)/i;
+ var portPattern = /:[0-9]*$/;
+ var simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
+ var delims = ["<", ">", '"', "`", " ", "\r", "\n", " "];
+ var unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims);
+ var autoEscape = ["'"].concat(unwise);
+ var nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape);
+ var hostEndingChars = ["/", "?", "#"];
+ var hostnameMaxLen = 255;
+ var hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/;
+ var hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
+ var hostlessProtocol = {
+ javascript: true,
+ "javascript:": true
+ };
+ var slashedProtocol = {
+ http: true,
+ https: true,
+ ftp: true,
+ gopher: true,
+ file: true,
+ "http:": true,
+ "https:": true,
+ "ftp:": true,
+ "gopher:": true,
+ "file:": true
+ };
+ function urlParse(url, slashesDenoteHost) {
+ if (url && url instanceof Url) return url;
+ const u = new Url();
+ u.parse(url, slashesDenoteHost);
+ return u;
+ }
+ Url.prototype.parse = function(url, slashesDenoteHost) {
+ let lowerProto, hec, slashes;
+ let rest = url;
+ rest = rest.trim();
+ if (!slashesDenoteHost && url.split("#").length === 1) {
+ const simplePath = simplePathPattern.exec(rest);
+ if (simplePath) {
+ this.pathname = simplePath[1];
+ if (simplePath[2]) {
+ this.search = simplePath[2];
+ }
+ return this;
+ }
+ }
+ let proto = protocolPattern.exec(rest);
+ if (proto) {
+ proto = proto[0];
+ lowerProto = proto.toLowerCase();
+ this.protocol = proto;
+ rest = rest.substr(proto.length);
+ }
+ if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
+ slashes = rest.substr(0, 2) === "//";
+ if (slashes && !(proto && hostlessProtocol[proto])) {
+ rest = rest.substr(2);
+ this.slashes = true;
+ }
+ }
+ if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
+ let hostEnd = -1;
+ for (let i2 = 0; i2 < hostEndingChars.length; i2++) {
+ hec = rest.indexOf(hostEndingChars[i2]);
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
+ hostEnd = hec;
+ }
+ }
+ let auth, atSign;
+ if (hostEnd === -1) {
+ atSign = rest.lastIndexOf("@");
+ } else {
+ atSign = rest.lastIndexOf("@", hostEnd);
+ }
+ if (atSign !== -1) {
+ auth = rest.slice(0, atSign);
+ rest = rest.slice(atSign + 1);
+ this.auth = auth;
+ }
+ hostEnd = -1;
+ for (let i2 = 0; i2 < nonHostChars.length; i2++) {
+ hec = rest.indexOf(nonHostChars[i2]);
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
+ hostEnd = hec;
+ }
+ }
+ if (hostEnd === -1) {
+ hostEnd = rest.length;
+ }
+ if (rest[hostEnd - 1] === ":") {
+ hostEnd--;
+ }
+ const host = rest.slice(0, hostEnd);
+ rest = rest.slice(hostEnd);
+ this.parseHost(host);
+ this.hostname = this.hostname || "";
+ const ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
+ if (!ipv6Hostname) {
+ const hostparts = this.hostname.split(/\./);
+ for (let i2 = 0, l = hostparts.length; i2 < l; i2++) {
+ const part = hostparts[i2];
+ if (!part) {
+ continue;
+ }
+ if (!part.match(hostnamePartPattern)) {
+ let newpart = "";
+ for (let j = 0, k = part.length; j < k; j++) {
+ if (part.charCodeAt(j) > 127) {
+ newpart += "x";
+ } else {
+ newpart += part[j];
+ }
+ }
+ if (!newpart.match(hostnamePartPattern)) {
+ const validParts = hostparts.slice(0, i2);
+ const notHost = hostparts.slice(i2 + 1);
+ const bit = part.match(hostnamePartStart);
+ if (bit) {
+ validParts.push(bit[1]);
+ notHost.unshift(bit[2]);
+ }
+ if (notHost.length) {
+ rest = notHost.join(".") + rest;
+ }
+ this.hostname = validParts.join(".");
+ break;
+ }
+ }
+ }
+ }
+ if (this.hostname.length > hostnameMaxLen) {
+ this.hostname = "";
+ }
+ if (ipv6Hostname) {
+ this.hostname = this.hostname.substr(1, this.hostname.length - 2);
+ }
+ }
+ const hash = rest.indexOf("#");
+ if (hash !== -1) {
+ this.hash = rest.substr(hash);
+ rest = rest.slice(0, hash);
+ }
+ const qm = rest.indexOf("?");
+ if (qm !== -1) {
+ this.search = rest.substr(qm);
+ rest = rest.slice(0, qm);
+ }
+ if (rest) {
+ this.pathname = rest;
+ }
+ if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
+ this.pathname = "";
+ }
+ return this;
+ };
+ Url.prototype.parseHost = function(host) {
+ let port = portPattern.exec(host);
+ if (port) {
+ port = port[0];
+ if (port !== ":") {
+ this.port = port.substr(1);
+ }
+ host = host.substr(0, host.length - port.length);
+ }
+ if (host) {
+ this.hostname = host;
+ }
+ };
+ var parse_default = urlParse;
+
+ // third_party/editor/uc.micro/index.mjs
+ var uc_exports = {};
+ __export(uc_exports, {
+ Any: () => regex_default,
+ Cc: () => regex_default2,
+ Cf: () => regex_default3,
+ P: () => regex_default4,
+ S: () => regex_default5,
+ Z: () => regex_default6
+ });
+
+ // third_party/editor/uc.micro/properties/Any/regex.mjs
+ var regex_default = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
+
+ // third_party/editor/uc.micro/categories/Cc/regex.mjs
+ var regex_default2 = /[\0-\x1F\x7F-\x9F]/;
+
+ // third_party/editor/uc.micro/categories/Cf/regex.mjs
+ var regex_default3 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;
+
+ // third_party/editor/uc.micro/categories/P/regex.mjs
+ var regex_default4 = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/;
+
+ // third_party/editor/uc.micro/categories/S/regex.mjs
+ var regex_default5 = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/;
+
+ // third_party/editor/uc.micro/categories/Z/regex.mjs
+ var regex_default6 = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
+
+ // third_party/editor/entities/src/generated/decode-data-html.ts
+ var decode_data_html_default = new Uint16Array(
+ // prettier-ignore
+ '\u1D41<\xD5\u0131\u028A\u049D\u057B\u05D0\u0675\u06DE\u07A2\u07D6\u080F\u0A4A\u0A91\u0DA1\u0E6D\u0F09\u0F26\u10CA\u1228\u12E1\u1415\u149D\u14C3\u14DF\u1525\0\0\0\0\0\0\u156B\u16CD\u198D\u1C12\u1DDD\u1F7E\u2060\u21B0\u228D\u23C0\u23FB\u2442\u2824\u2912\u2D08\u2E48\u2FCE\u3016\u32BA\u3639\u37AC\u38FE\u3A28\u3A71\u3AE0\u3B2E\u0800EMabcfglmnoprstu\\bfms\x7F\x84\x8B\x90\x95\x98\xA6\xB3\xB9\xC8\xCFlig\u803B\xC6\u40C6P\u803B&\u4026cute\u803B\xC1\u40C1reve;\u4102\u0100iyx}rc\u803B\xC2\u40C2;\u4410r;\uC000\u{1D504}rave\u803B\xC0\u40C0pha;\u4391acr;\u4100d;\u6A53\u0100gp\x9D\xA1on;\u4104f;\uC000\u{1D538}plyFunction;\u6061ing\u803B\xC5\u40C5\u0100cs\xBE\xC3r;\uC000\u{1D49C}ign;\u6254ilde\u803B\xC3\u40C3ml\u803B\xC4\u40C4\u0400aceforsu\xE5\xFB\xFE\u0117\u011C\u0122\u0127\u012A\u0100cr\xEA\xF2kslash;\u6216\u0176\xF6\xF8;\u6AE7ed;\u6306y;\u4411\u0180crt\u0105\u010B\u0114ause;\u6235noullis;\u612Ca;\u4392r;\uC000\u{1D505}pf;\uC000\u{1D539}eve;\u42D8c\xF2\u0113mpeq;\u624E\u0700HOacdefhilorsu\u014D\u0151\u0156\u0180\u019E\u01A2\u01B5\u01B7\u01BA\u01DC\u0215\u0273\u0278\u027Ecy;\u4427PY\u803B\xA9\u40A9\u0180cpy\u015D\u0162\u017Aute;\u4106\u0100;i\u0167\u0168\u62D2talDifferentialD;\u6145leys;\u612D\u0200aeio\u0189\u018E\u0194\u0198ron;\u410Cdil\u803B\xC7\u40C7rc;\u4108nint;\u6230ot;\u410A\u0100dn\u01A7\u01ADilla;\u40B8terDot;\u40B7\xF2\u017Fi;\u43A7rcle\u0200DMPT\u01C7\u01CB\u01D1\u01D6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01E2\u01F8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020FoubleQuote;\u601Duote;\u6019\u0200lnpu\u021E\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6A74\u0180git\u022F\u0236\u023Aruent;\u6261nt;\u622FourIntegral;\u622E\u0100fr\u024C\u024E;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6A2Fcr;\uC000\u{1D49E}p\u0100;C\u0284\u0285\u62D3ap;\u624D\u0580DJSZacefios\u02A0\u02AC\u02B0\u02B4\u02B8\u02CB\u02D7\u02E1\u02E6\u0333\u048D\u0100;o\u0179\u02A5trahd;\u6911cy;\u4402cy;\u4405cy;\u440F\u0180grs\u02BF\u02C4\u02C7ger;\u6021r;\u61A1hv;\u6AE4\u0100ay\u02D0\u02D5ron;\u410E;\u4414l\u0100;t\u02DD\u02DE\u6207a;\u4394r;\uC000\u{1D507}\u0100af\u02EB\u0327\u0100cm\u02F0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031Ccute;\u40B4o\u0174\u030B\u030D;\u42D9bleAcute;\u42DDrave;\u4060ilde;\u42DCond;\u62C4ferentialD;\u6146\u0470\u033D\0\0\0\u0342\u0354\0\u0405f;\uC000\u{1D53B}\u0180;DE\u0348\u0349\u034D\u40A8ot;\u60DCqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03CF\u03E2\u03F8ontourIntegra\xEC\u0239o\u0274\u0379\0\0\u037B\xBB\u0349nArrow;\u61D3\u0100eo\u0387\u03A4ft\u0180ART\u0390\u0396\u03A1rrow;\u61D0ightArrow;\u61D4e\xE5\u02CAng\u0100LR\u03AB\u03C4eft\u0100AR\u03B3\u03B9rrow;\u67F8ightArrow;\u67FAightArrow;\u67F9ight\u0100AT\u03D8\u03DErrow;\u61D2ee;\u62A8p\u0241\u03E9\0\0\u03EFrrow;\u61D1ownArrow;\u61D5erticalBar;\u6225n\u0300ABLRTa\u0412\u042A\u0430\u045E\u047F\u037Crrow\u0180;BU\u041D\u041E\u0422\u6193ar;\u6913pArrow;\u61F5reve;\u4311eft\u02D2\u043A\0\u0446\0\u0450ightVector;\u6950eeVector;\u695Eector\u0100;B\u0459\u045A\u61BDar;\u6956ight\u01D4\u0467\0\u0471eeVector;\u695Fector\u0100;B\u047A\u047B\u61C1ar;\u6957ee\u0100;A\u0486\u0487\u62A4rrow;\u61A7\u0100ct\u0492\u0497r;\uC000\u{1D49F}rok;\u4110\u0800NTacdfglmopqstux\u04BD\u04C0\u04C4\u04CB\u04DE\u04E2\u04E7\u04EE\u04F5\u0521\u052F\u0536\u0552\u055D\u0560\u0565G;\u414AH\u803B\xD0\u40D0cute\u803B\xC9\u40C9\u0180aiy\u04D2\u04D7\u04DCron;\u411Arc\u803B\xCA\u40CA;\u442Dot;\u4116r;\uC000\u{1D508}rave\u803B\xC8\u40C8ement;\u6208\u0100ap\u04FA\u04FEcr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65FBerySmallSquare;\u65AB\u0100gp\u0526\u052Aon;\u4118f;\uC000\u{1D53C}silon;\u4395u\u0100ai\u053C\u0549l\u0100;T\u0542\u0543\u6A75ilde;\u6242librium;\u61CC\u0100ci\u0557\u055Ar;\u6130m;\u6A73a;\u4397ml\u803B\xCB\u40CB\u0100ip\u056A\u056Fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058D\u05B2\u05CCy;\u4424r;\uC000\u{1D509}lled\u0253\u0597\0\0\u05A3mallSquare;\u65FCerySmallSquare;\u65AA\u0370\u05BA\0\u05BF\0\0\u05C4f;\uC000\u{1D53D}All;\u6200riertrf;\u6131c\xF2\u05CB\u0600JTabcdfgorst\u05E8\u05EC\u05EF\u05FA\u0600\u0612\u0616\u061B\u061D\u0623\u066C\u0672cy;\u4403\u803B>\u403Emma\u0100;d\u05F7\u05F8\u4393;\u43DCreve;\u411E\u0180eiy\u0607\u060C\u0610dil;\u4122rc;\u411C;\u4413ot;\u4120r;\uC000\u{1D50A};\u62D9pf;\uC000\u{1D53E}eater\u0300EFGLST\u0635\u0644\u064E\u0656\u065B\u0666qual\u0100;L\u063E\u063F\u6265ess;\u62DBullEqual;\u6267reater;\u6AA2ess;\u6277lantEqual;\u6A7Eilde;\u6273cr;\uC000\u{1D4A2};\u626B\u0400Aacfiosu\u0685\u068B\u0696\u069B\u069E\u06AA\u06BE\u06CARDcy;\u442A\u0100ct\u0690\u0694ek;\u42C7;\u405Eirc;\u4124r;\u610ClbertSpace;\u610B\u01F0\u06AF\0\u06B2f;\u610DizontalLine;\u6500\u0100ct\u06C3\u06C5\xF2\u06A9rok;\u4126mp\u0144\u06D0\u06D8ownHum\xF0\u012Fqual;\u624F\u0700EJOacdfgmnostu\u06FA\u06FE\u0703\u0707\u070E\u071A\u071E\u0721\u0728\u0744\u0778\u078B\u078F\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803B\xCD\u40CD\u0100iy\u0713\u0718rc\u803B\xCE\u40CE;\u4418ot;\u4130r;\u6111rave\u803B\xCC\u40CC\u0180;ap\u0720\u072F\u073F\u0100cg\u0734\u0737r;\u412AinaryI;\u6148lie\xF3\u03DD\u01F4\u0749\0\u0762\u0100;e\u074D\u074E\u622C\u0100gr\u0753\u0758ral;\u622Bsection;\u62C2isible\u0100CT\u076C\u0772omma;\u6063imes;\u6062\u0180gpt\u077F\u0783\u0788on;\u412Ef;\uC000\u{1D540}a;\u4399cr;\u6110ilde;\u4128\u01EB\u079A\0\u079Ecy;\u4406l\u803B\xCF\u40CF\u0280cfosu\u07AC\u07B7\u07BC\u07C2\u07D0\u0100iy\u07B1\u07B5rc;\u4134;\u4419r;\uC000\u{1D50D}pf;\uC000\u{1D541}\u01E3\u07C7\0\u07CCr;\uC000\u{1D4A5}rcy;\u4408kcy;\u4404\u0380HJacfos\u07E4\u07E8\u07EC\u07F1\u07FD\u0802\u0808cy;\u4425cy;\u440Cppa;\u439A\u0100ey\u07F6\u07FBdil;\u4136;\u441Ar;\uC000\u{1D50E}pf;\uC000\u{1D542}cr;\uC000\u{1D4A6}\u0580JTaceflmost\u0825\u0829\u082C\u0850\u0863\u09B3\u09B8\u09C7\u09CD\u0A37\u0A47cy;\u4409\u803B<\u403C\u0280cmnpr\u0837\u083C\u0841\u0844\u084Dute;\u4139bda;\u439Bg;\u67EAlacetrf;\u6112r;\u619E\u0180aey\u0857\u085C\u0861ron;\u413Ddil;\u413B;\u441B\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087E\u08A9\u08B1\u08E0\u08E6\u08FC\u092F\u095B\u0390\u096A\u0100nr\u0883\u088FgleBracket;\u67E8row\u0180;BR\u0899\u089A\u089E\u6190ar;\u61E4ightArrow;\u61C6eiling;\u6308o\u01F5\u08B7\0\u08C3bleBracket;\u67E6n\u01D4\u08C8\0\u08D2eeVector;\u6961ector\u0100;B\u08DB\u08DC\u61C3ar;\u6959loor;\u630Aight\u0100AV\u08EF\u08F5rrow;\u6194ector;\u694E\u0100er\u0901\u0917e\u0180;AV\u0909\u090A\u0910\u62A3rrow;\u61A4ector;\u695Aiangle\u0180;BE\u0924\u0925\u0929\u62B2ar;\u69CFqual;\u62B4p\u0180DTV\u0937\u0942\u094CownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61BFar;\u6958ector\u0100;B\u0965\u0966\u61BCar;\u6952ight\xE1\u039Cs\u0300EFGLST\u097E\u098B\u0995\u099D\u09A2\u09ADqualGreater;\u62DAullEqual;\u6266reater;\u6276ess;\u6AA1lantEqual;\u6A7Dilde;\u6272r;\uC000\u{1D50F}\u0100;e\u09BD\u09BE\u62D8ftarrow;\u61DAidot;\u413F\u0180npw\u09D4\u0A16\u0A1Bg\u0200LRlr\u09DE\u09F7\u0A02\u0A10eft\u0100AR\u09E6\u09ECrrow;\u67F5ightArrow;\u67F7ightArrow;\u67F6eft\u0100ar\u03B3\u0A0Aight\xE1\u03BFight\xE1\u03CAf;\uC000\u{1D543}er\u0100LR\u0A22\u0A2CeftArrow;\u6199ightArrow;\u6198\u0180cht\u0A3E\u0A40\u0A42\xF2\u084C;\u61B0rok;\u4141;\u626A\u0400acefiosu\u0A5A\u0A5D\u0A60\u0A77\u0A7C\u0A85\u0A8B\u0A8Ep;\u6905y;\u441C\u0100dl\u0A65\u0A6FiumSpace;\u605Flintrf;\u6133r;\uC000\u{1D510}nusPlus;\u6213pf;\uC000\u{1D544}c\xF2\u0A76;\u439C\u0480Jacefostu\u0AA3\u0AA7\u0AAD\u0AC0\u0B14\u0B19\u0D91\u0D97\u0D9Ecy;\u440Acute;\u4143\u0180aey\u0AB4\u0AB9\u0ABEron;\u4147dil;\u4145;\u441D\u0180gsw\u0AC7\u0AF0\u0B0Eative\u0180MTV\u0AD3\u0ADF\u0AE8ediumSpace;\u600Bhi\u0100cn\u0AE6\u0AD8\xEB\u0AD9eryThi\xEE\u0AD9ted\u0100GL\u0AF8\u0B06reaterGreate\xF2\u0673essLes\xF3\u0A48Line;\u400Ar;\uC000\u{1D511}\u0200Bnpt\u0B22\u0B28\u0B37\u0B3Areak;\u6060BreakingSpace;\u40A0f;\u6115\u0680;CDEGHLNPRSTV\u0B55\u0B56\u0B6A\u0B7C\u0BA1\u0BEB\u0C04\u0C5E\u0C84\u0CA6\u0CD8\u0D61\u0D85\u6AEC\u0100ou\u0B5B\u0B64ngruent;\u6262pCap;\u626DoubleVerticalBar;\u6226\u0180lqx\u0B83\u0B8A\u0B9Bement;\u6209ual\u0100;T\u0B92\u0B93\u6260ilde;\uC000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0BB6\u0BB7\u0BBD\u0BC9\u0BD3\u0BD8\u0BE5\u626Fqual;\u6271ullEqual;\uC000\u2267\u0338reater;\uC000\u226B\u0338ess;\u6279lantEqual;\uC000\u2A7E\u0338ilde;\u6275ump\u0144\u0BF2\u0BFDownHump;\uC000\u224E\u0338qual;\uC000\u224F\u0338e\u0100fs\u0C0A\u0C27tTriangle\u0180;BE\u0C1A\u0C1B\u0C21\u62EAar;\uC000\u29CF\u0338qual;\u62ECs\u0300;EGLST\u0C35\u0C36\u0C3C\u0C44\u0C4B\u0C58\u626Equal;\u6270reater;\u6278ess;\uC000\u226A\u0338lantEqual;\uC000\u2A7D\u0338ilde;\u6274ested\u0100GL\u0C68\u0C79reaterGreater;\uC000\u2AA2\u0338essLess;\uC000\u2AA1\u0338recedes\u0180;ES\u0C92\u0C93\u0C9B\u6280qual;\uC000\u2AAF\u0338lantEqual;\u62E0\u0100ei\u0CAB\u0CB9verseElement;\u620CghtTriangle\u0180;BE\u0CCB\u0CCC\u0CD2\u62EBar;\uC000\u29D0\u0338qual;\u62ED\u0100qu\u0CDD\u0D0CuareSu\u0100bp\u0CE8\u0CF9set\u0100;E\u0CF0\u0CF3\uC000\u228F\u0338qual;\u62E2erset\u0100;E\u0D03\u0D06\uC000\u2290\u0338qual;\u62E3\u0180bcp\u0D13\u0D24\u0D4Eset\u0100;E\u0D1B\u0D1E\uC000\u2282\u20D2qual;\u6288ceeds\u0200;EST\u0D32\u0D33\u0D3B\u0D46\u6281qual;\uC000\u2AB0\u0338lantEqual;\u62E1ilde;\uC000\u227F\u0338erset\u0100;E\u0D58\u0D5B\uC000\u2283\u20D2qual;\u6289ilde\u0200;EFT\u0D6E\u0D6F\u0D75\u0D7F\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uC000\u{1D4A9}ilde\u803B\xD1\u40D1;\u439D\u0700Eacdfgmoprstuv\u0DBD\u0DC2\u0DC9\u0DD5\u0DDB\u0DE0\u0DE7\u0DFC\u0E02\u0E20\u0E22\u0E32\u0E3F\u0E44lig;\u4152cute\u803B\xD3\u40D3\u0100iy\u0DCE\u0DD3rc\u803B\xD4\u40D4;\u441Eblac;\u4150r;\uC000\u{1D512}rave\u803B\xD2\u40D2\u0180aei\u0DEE\u0DF2\u0DF6cr;\u414Cga;\u43A9cron;\u439Fpf;\uC000\u{1D546}enCurly\u0100DQ\u0E0E\u0E1AoubleQuote;\u601Cuote;\u6018;\u6A54\u0100cl\u0E27\u0E2Cr;\uC000\u{1D4AA}ash\u803B\xD8\u40D8i\u016C\u0E37\u0E3Cde\u803B\xD5\u40D5es;\u6A37ml\u803B\xD6\u40D6er\u0100BP\u0E4B\u0E60\u0100ar\u0E50\u0E53r;\u603Eac\u0100ek\u0E5A\u0E5C;\u63DEet;\u63B4arenthesis;\u63DC\u0480acfhilors\u0E7F\u0E87\u0E8A\u0E8F\u0E92\u0E94\u0E9D\u0EB0\u0EFCrtialD;\u6202y;\u441Fr;\uC000\u{1D513}i;\u43A6;\u43A0usMinus;\u40B1\u0100ip\u0EA2\u0EADncareplan\xE5\u069Df;\u6119\u0200;eio\u0EB9\u0EBA\u0EE0\u0EE4\u6ABBcedes\u0200;EST\u0EC8\u0EC9\u0ECF\u0EDA\u627Aqual;\u6AAFlantEqual;\u627Cilde;\u627Eme;\u6033\u0100dp\u0EE9\u0EEEuct;\u620Fortion\u0100;a\u0225\u0EF9l;\u621D\u0100ci\u0F01\u0F06r;\uC000\u{1D4AB};\u43A8\u0200Ufos\u0F11\u0F16\u0F1B\u0F1FOT\u803B"\u4022r;\uC000\u{1D514}pf;\u611Acr;\uC000\u{1D4AC}\u0600BEacefhiorsu\u0F3E\u0F43\u0F47\u0F60\u0F73\u0FA7\u0FAA\u0FAD\u1096\u10A9\u10B4\u10BEarr;\u6910G\u803B\xAE\u40AE\u0180cnr\u0F4E\u0F53\u0F56ute;\u4154g;\u67EBr\u0100;t\u0F5C\u0F5D\u61A0l;\u6916\u0180aey\u0F67\u0F6C\u0F71ron;\u4158dil;\u4156;\u4420\u0100;v\u0F78\u0F79\u611Cerse\u0100EU\u0F82\u0F99\u0100lq\u0F87\u0F8Eement;\u620Builibrium;\u61CBpEquilibrium;\u696Fr\xBB\u0F79o;\u43A1ght\u0400ACDFTUVa\u0FC1\u0FEB\u0FF3\u1022\u1028\u105B\u1087\u03D8\u0100nr\u0FC6\u0FD2gleBracket;\u67E9row\u0180;BL\u0FDC\u0FDD\u0FE1\u6192ar;\u61E5eftArrow;\u61C4eiling;\u6309o\u01F5\u0FF9\0\u1005bleBracket;\u67E7n\u01D4\u100A\0\u1014eeVector;\u695Dector\u0100;B\u101D\u101E\u61C2ar;\u6955loor;\u630B\u0100er\u102D\u1043e\u0180;AV\u1035\u1036\u103C\u62A2rrow;\u61A6ector;\u695Biangle\u0180;BE\u1050\u1051\u1055\u62B3ar;\u69D0qual;\u62B5p\u0180DTV\u1063\u106E\u1078ownVector;\u694FeeVector;\u695Cector\u0100;B\u1082\u1083\u61BEar;\u6954ector\u0100;B\u1091\u1092\u61C0ar;\u6953\u0100pu\u109B\u109Ef;\u611DndImplies;\u6970ightarrow;\u61DB\u0100ch\u10B9\u10BCr;\u611B;\u61B1leDelayed;\u69F4\u0680HOacfhimoqstu\u10E4\u10F1\u10F7\u10FD\u1119\u111E\u1151\u1156\u1161\u1167\u11B5\u11BB\u11BF\u0100Cc\u10E9\u10EEHcy;\u4429y;\u4428FTcy;\u442Ccute;\u415A\u0280;aeiy\u1108\u1109\u110E\u1113\u1117\u6ABCron;\u4160dil;\u415Erc;\u415C;\u4421r;\uC000\u{1D516}ort\u0200DLRU\u112A\u1134\u113E\u1149ownArrow\xBB\u041EeftArrow\xBB\u089AightArrow\xBB\u0FDDpArrow;\u6191gma;\u43A3allCircle;\u6218pf;\uC000\u{1D54A}\u0272\u116D\0\0\u1170t;\u621Aare\u0200;ISU\u117B\u117C\u1189\u11AF\u65A1ntersection;\u6293u\u0100bp\u118F\u119Eset\u0100;E\u1197\u1198\u628Fqual;\u6291erset\u0100;E\u11A8\u11A9\u6290qual;\u6292nion;\u6294cr;\uC000\u{1D4AE}ar;\u62C6\u0200bcmp\u11C8\u11DB\u1209\u120B\u0100;s\u11CD\u11CE\u62D0et\u0100;E\u11CD\u11D5qual;\u6286\u0100ch\u11E0\u1205eeds\u0200;EST\u11ED\u11EE\u11F4\u11FF\u627Bqual;\u6AB0lantEqual;\u627Dilde;\u627FTh\xE1\u0F8C;\u6211\u0180;es\u1212\u1213\u1223\u62D1rset\u0100;E\u121C\u121D\u6283qual;\u6287et\xBB\u1213\u0580HRSacfhiors\u123E\u1244\u1249\u1255\u125E\u1271\u1276\u129F\u12C2\u12C8\u12D1ORN\u803B\xDE\u40DEADE;\u6122\u0100Hc\u124E\u1252cy;\u440By;\u4426\u0100bu\u125A\u125C;\u4009;\u43A4\u0180aey\u1265\u126A\u126Fron;\u4164dil;\u4162;\u4422r;\uC000\u{1D517}\u0100ei\u127B\u1289\u01F2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128E\u1298kSpace;\uC000\u205F\u200ASpace;\u6009lde\u0200;EFT\u12AB\u12AC\u12B2\u12BC\u623Cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uC000\u{1D54B}ipleDot;\u60DB\u0100ct\u12D6\u12DBr;\uC000\u{1D4AF}rok;\u4166\u0AE1\u12F7\u130E\u131A\u1326\0\u132C\u1331\0\0\0\0\0\u1338\u133D\u1377\u1385\0\u13FF\u1404\u140A\u1410\u0100cr\u12FB\u1301ute\u803B\xDA\u40DAr\u0100;o\u1307\u1308\u619Fcir;\u6949r\u01E3\u1313\0\u1316y;\u440Eve;\u416C\u0100iy\u131E\u1323rc\u803B\xDB\u40DB;\u4423blac;\u4170r;\uC000\u{1D518}rave\u803B\xD9\u40D9acr;\u416A\u0100di\u1341\u1369er\u0100BP\u1348\u135D\u0100ar\u134D\u1350r;\u405Fac\u0100ek\u1357\u1359;\u63DFet;\u63B5arenthesis;\u63DDon\u0100;P\u1370\u1371\u62C3lus;\u628E\u0100gp\u137B\u137Fon;\u4172f;\uC000\u{1D54C}\u0400ADETadps\u1395\u13AE\u13B8\u13C4\u03E8\u13D2\u13D7\u13F3rrow\u0180;BD\u1150\u13A0\u13A4ar;\u6912ownArrow;\u61C5ownArrow;\u6195quilibrium;\u696Eee\u0100;A\u13CB\u13CC\u62A5rrow;\u61A5own\xE1\u03F3er\u0100LR\u13DE\u13E8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13F9\u13FA\u43D2on;\u43A5ing;\u416Ecr;\uC000\u{1D4B0}ilde;\u4168ml\u803B\xDC\u40DC\u0480Dbcdefosv\u1427\u142C\u1430\u1433\u143E\u1485\u148A\u1490\u1496ash;\u62ABar;\u6AEBy;\u4412ash\u0100;l\u143B\u143C\u62A9;\u6AE6\u0100er\u1443\u1445;\u62C1\u0180bty\u144C\u1450\u147Aar;\u6016\u0100;i\u144F\u1455cal\u0200BLST\u1461\u1465\u146A\u1474ar;\u6223ine;\u407Ceparator;\u6758ilde;\u6240ThinSpace;\u600Ar;\uC000\u{1D519}pf;\uC000\u{1D54D}cr;\uC000\u{1D4B1}dash;\u62AA\u0280cefos\u14A7\u14AC\u14B1\u14B6\u14BCirc;\u4174dge;\u62C0r;\uC000\u{1D51A}pf;\uC000\u{1D54E}cr;\uC000\u{1D4B2}\u0200fios\u14CB\u14D0\u14D2\u14D8r;\uC000\u{1D51B};\u439Epf;\uC000\u{1D54F}cr;\uC000\u{1D4B3}\u0480AIUacfosu\u14F1\u14F5\u14F9\u14FD\u1504\u150F\u1514\u151A\u1520cy;\u442Fcy;\u4407cy;\u442Ecute\u803B\xDD\u40DD\u0100iy\u1509\u150Drc;\u4176;\u442Br;\uC000\u{1D51C}pf;\uC000\u{1D550}cr;\uC000\u{1D4B4}ml;\u4178\u0400Hacdefos\u1535\u1539\u153F\u154B\u154F\u155D\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417D;\u4417ot;\u417B\u01F2\u1554\0\u155BoWidt\xE8\u0AD9a;\u4396r;\u6128pf;\u6124cr;\uC000\u{1D4B5}\u0BE1\u1583\u158A\u1590\0\u15B0\u15B6\u15BF\0\0\0\0\u15C6\u15DB\u15EB\u165F\u166D\0\u1695\u169B\u16B2\u16B9\0\u16BEcute\u803B\xE1\u40E1reve;\u4103\u0300;Ediuy\u159C\u159D\u15A1\u15A3\u15A8\u15AD\u623E;\uC000\u223E\u0333;\u623Frc\u803B\xE2\u40E2te\u80BB\xB4\u0306;\u4430lig\u803B\xE6\u40E6\u0100;r\xB2\u15BA;\uC000\u{1D51E}rave\u803B\xE0\u40E0\u0100ep\u15CA\u15D6\u0100fp\u15CF\u15D4sym;\u6135\xE8\u15D3ha;\u43B1\u0100ap\u15DFc\u0100cl\u15E4\u15E7r;\u4101g;\u6A3F\u0264\u15F0\0\0\u160A\u0280;adsv\u15FA\u15FB\u15FF\u1601\u1607\u6227nd;\u6A55;\u6A5Clope;\u6A58;\u6A5A\u0380;elmrsz\u1618\u1619\u161B\u161E\u163F\u164F\u1659\u6220;\u69A4e\xBB\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163A\u163C\u163E;\u69A8;\u69A9;\u69AA;\u69AB;\u69AC;\u69AD;\u69AE;\u69AFt\u0100;v\u1645\u1646\u621Fb\u0100;d\u164C\u164D\u62BE;\u699D\u0100pt\u1654\u1657h;\u6222\xBB\xB9arr;\u637C\u0100gp\u1663\u1667on;\u4105f;\uC000\u{1D552}\u0380;Eaeiop\u12C1\u167B\u167D\u1682\u1684\u1687\u168A;\u6A70cir;\u6A6F;\u624Ad;\u624Bs;\u4027rox\u0100;e\u12C1\u1692\xF1\u1683ing\u803B\xE5\u40E5\u0180cty\u16A1\u16A6\u16A8r;\uC000\u{1D4B6};\u402Amp\u0100;e\u12C1\u16AF\xF1\u0288ilde\u803B\xE3\u40E3ml\u803B\xE4\u40E4\u0100ci\u16C2\u16C8onin\xF4\u0272nt;\u6A11\u0800Nabcdefiklnoprsu\u16ED\u16F1\u1730\u173C\u1743\u1748\u1778\u177D\u17E0\u17E6\u1839\u1850\u170D\u193D\u1948\u1970ot;\u6AED\u0100cr\u16F6\u171Ek\u0200ceps\u1700\u1705\u170D\u1713ong;\u624Cpsilon;\u43F6rime;\u6035im\u0100;e\u171A\u171B\u623Dq;\u62CD\u0176\u1722\u1726ee;\u62BDed\u0100;g\u172C\u172D\u6305e\xBB\u172Drk\u0100;t\u135C\u1737brk;\u63B6\u0100oy\u1701\u1741;\u4431quo;\u601E\u0280cmprt\u1753\u175B\u1761\u1764\u1768aus\u0100;e\u010A\u0109ptyv;\u69B0s\xE9\u170Cno\xF5\u0113\u0180ahw\u176F\u1771\u1773;\u43B2;\u6136een;\u626Cr;\uC000\u{1D51F}g\u0380costuvw\u178D\u179D\u17B3\u17C1\u17D5\u17DB\u17DE\u0180aiu\u1794\u1796\u179A\xF0\u0760rc;\u65EFp\xBB\u1371\u0180dpt\u17A4\u17A8\u17ADot;\u6A00lus;\u6A01imes;\u6A02\u0271\u17B9\0\0\u17BEcup;\u6A06ar;\u6605riangle\u0100du\u17CD\u17D2own;\u65BDp;\u65B3plus;\u6A04e\xE5\u1444\xE5\u14ADarow;\u690D\u0180ako\u17ED\u1826\u1835\u0100cn\u17F2\u1823k\u0180lst\u17FA\u05AB\u1802ozenge;\u69EBriangle\u0200;dlr\u1812\u1813\u1818\u181D\u65B4own;\u65BEeft;\u65C2ight;\u65B8k;\u6423\u01B1\u182B\0\u1833\u01B2\u182F\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183E\u184D\u0100;q\u1843\u1846\uC000=\u20E5uiv;\uC000\u2261\u20E5t;\u6310\u0200ptwx\u1859\u185E\u1867\u186Cf;\uC000\u{1D553}\u0100;t\u13CB\u1863om\xBB\u13CCtie;\u62C8\u0600DHUVbdhmptuv\u1885\u1896\u18AA\u18BB\u18D7\u18DB\u18EC\u18FF\u1905\u190A\u1910\u1921\u0200LRlr\u188E\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18A1\u18A2\u18A4\u18A6\u18A8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18B3\u18B5\u18B7\u18B9;\u655D;\u655A;\u655C;\u6559\u0380;HLRhlr\u18CA\u18CB\u18CD\u18CF\u18D1\u18D3\u18D5\u6551;\u656C;\u6563;\u6560;\u656B;\u6562;\u655Fox;\u69C9\u0200LRlr\u18E4\u18E6\u18E8\u18EA;\u6555;\u6552;\u6510;\u650C\u0280;DUdu\u06BD\u18F7\u18F9\u18FB\u18FD;\u6565;\u6568;\u652C;\u6534inus;\u629Flus;\u629Eimes;\u62A0\u0200LRlr\u1919\u191B\u191D\u191F;\u655B;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193B\u6502;\u656A;\u6561;\u655E;\u653C;\u6524;\u651C\u0100ev\u0123\u1942bar\u803B\xA6\u40A6\u0200ceio\u1951\u1956\u195A\u1960r;\uC000\u{1D4B7}mi;\u604Fm\u0100;e\u171A\u171Cl\u0180;bh\u1968\u1969\u196B\u405C;\u69C5sub;\u67C8\u016C\u1974\u197El\u0100;e\u1979\u197A\u6022t\xBB\u197Ap\u0180;Ee\u012F\u1985\u1987;\u6AAE\u0100;q\u06DC\u06DB\u0CE1\u19A7\0\u19E8\u1A11\u1A15\u1A32\0\u1A37\u1A50\0\0\u1AB4\0\0\u1AC1\0\0\u1B21\u1B2E\u1B4D\u1B52\0\u1BFD\0\u1C0C\u0180cpr\u19AD\u19B2\u19DDute;\u4107\u0300;abcds\u19BF\u19C0\u19C4\u19CA\u19D5\u19D9\u6229nd;\u6A44rcup;\u6A49\u0100au\u19CF\u19D2p;\u6A4Bp;\u6A47ot;\u6A40;\uC000\u2229\uFE00\u0100eo\u19E2\u19E5t;\u6041\xEE\u0693\u0200aeiu\u19F0\u19FB\u1A01\u1A05\u01F0\u19F5\0\u19F8s;\u6A4Don;\u410Ddil\u803B\xE7\u40E7rc;\u4109ps\u0100;s\u1A0C\u1A0D\u6A4Cm;\u6A50ot;\u410B\u0180dmn\u1A1B\u1A20\u1A26il\u80BB\xB8\u01ADptyv;\u69B2t\u8100\xA2;e\u1A2D\u1A2E\u40A2r\xE4\u01B2r;\uC000\u{1D520}\u0180cei\u1A3D\u1A40\u1A4Dy;\u4447ck\u0100;m\u1A47\u1A48\u6713ark\xBB\u1A48;\u43C7r\u0380;Ecefms\u1A5F\u1A60\u1A62\u1A6B\u1AA4\u1AAA\u1AAE\u65CB;\u69C3\u0180;el\u1A69\u1A6A\u1A6D\u42C6q;\u6257e\u0261\u1A74\0\0\u1A88rrow\u0100lr\u1A7C\u1A81eft;\u61BAight;\u61BB\u0280RSacd\u1A92\u1A94\u1A96\u1A9A\u1A9F\xBB\u0F47;\u64C8st;\u629Birc;\u629Aash;\u629Dnint;\u6A10id;\u6AEFcir;\u69C2ubs\u0100;u\u1ABB\u1ABC\u6663it\xBB\u1ABC\u02EC\u1AC7\u1AD4\u1AFA\0\u1B0Aon\u0100;e\u1ACD\u1ACE\u403A\u0100;q\xC7\xC6\u026D\u1AD9\0\0\u1AE2a\u0100;t\u1ADE\u1ADF\u402C;\u4040\u0180;fl\u1AE8\u1AE9\u1AEB\u6201\xEE\u1160e\u0100mx\u1AF1\u1AF6ent\xBB\u1AE9e\xF3\u024D\u01E7\u1AFE\0\u1B07\u0100;d\u12BB\u1B02ot;\u6A6Dn\xF4\u0246\u0180fry\u1B10\u1B14\u1B17;\uC000\u{1D554}o\xE4\u0254\u8100\xA9;s\u0155\u1B1Dr;\u6117\u0100ao\u1B25\u1B29rr;\u61B5ss;\u6717\u0100cu\u1B32\u1B37r;\uC000\u{1D4B8}\u0100bp\u1B3C\u1B44\u0100;e\u1B41\u1B42\u6ACF;\u6AD1\u0100;e\u1B49\u1B4A\u6AD0;\u6AD2dot;\u62EF\u0380delprvw\u1B60\u1B6C\u1B77\u1B82\u1BAC\u1BD4\u1BF9arr\u0100lr\u1B68\u1B6A;\u6938;\u6935\u0270\u1B72\0\0\u1B75r;\u62DEc;\u62DFarr\u0100;p\u1B7F\u1B80\u61B6;\u693D\u0300;bcdos\u1B8F\u1B90\u1B96\u1BA1\u1BA5\u1BA8\u622Arcap;\u6A48\u0100au\u1B9B\u1B9Ep;\u6A46p;\u6A4Aot;\u628Dr;\u6A45;\uC000\u222A\uFE00\u0200alrv\u1BB5\u1BBF\u1BDE\u1BE3rr\u0100;m\u1BBC\u1BBD\u61B7;\u693Cy\u0180evw\u1BC7\u1BD4\u1BD8q\u0270\u1BCE\0\0\u1BD2re\xE3\u1B73u\xE3\u1B75ee;\u62CEedge;\u62CFen\u803B\xA4\u40A4earrow\u0100lr\u1BEE\u1BF3eft\xBB\u1B80ight\xBB\u1BBDe\xE4\u1BDD\u0100ci\u1C01\u1C07onin\xF4\u01F7nt;\u6231lcty;\u632D\u0980AHabcdefhijlorstuwz\u1C38\u1C3B\u1C3F\u1C5D\u1C69\u1C75\u1C8A\u1C9E\u1CAC\u1CB7\u1CFB\u1CFF\u1D0D\u1D7B\u1D91\u1DAB\u1DBB\u1DC6\u1DCDr\xF2\u0381ar;\u6965\u0200glrs\u1C48\u1C4D\u1C52\u1C54ger;\u6020eth;\u6138\xF2\u1133h\u0100;v\u1C5A\u1C5B\u6010\xBB\u090A\u016B\u1C61\u1C67arow;\u690Fa\xE3\u0315\u0100ay\u1C6E\u1C73ron;\u410F;\u4434\u0180;ao\u0332\u1C7C\u1C84\u0100gr\u02BF\u1C81r;\u61CAtseq;\u6A77\u0180glm\u1C91\u1C94\u1C98\u803B\xB0\u40B0ta;\u43B4ptyv;\u69B1\u0100ir\u1CA3\u1CA8sht;\u697F;\uC000\u{1D521}ar\u0100lr\u1CB3\u1CB5\xBB\u08DC\xBB\u101E\u0280aegsv\u1CC2\u0378\u1CD6\u1CDC\u1CE0m\u0180;os\u0326\u1CCA\u1CD4nd\u0100;s\u0326\u1CD1uit;\u6666amma;\u43DDin;\u62F2\u0180;io\u1CE7\u1CE8\u1CF8\u40F7de\u8100\xF7;o\u1CE7\u1CF0ntimes;\u62C7n\xF8\u1CF7cy;\u4452c\u026F\u1D06\0\0\u1D0Arn;\u631Eop;\u630D\u0280lptuw\u1D18\u1D1D\u1D22\u1D49\u1D55lar;\u4024f;\uC000\u{1D555}\u0280;emps\u030B\u1D2D\u1D37\u1D3D\u1D42q\u0100;d\u0352\u1D33ot;\u6251inus;\u6238lus;\u6214quare;\u62A1blebarwedg\xE5\xFAn\u0180adh\u112E\u1D5D\u1D67ownarrow\xF3\u1C83arpoon\u0100lr\u1D72\u1D76ef\xF4\u1CB4igh\xF4\u1CB6\u0162\u1D7F\u1D85karo\xF7\u0F42\u026F\u1D8A\0\0\u1D8Ern;\u631Fop;\u630C\u0180cot\u1D98\u1DA3\u1DA6\u0100ry\u1D9D\u1DA1;\uC000\u{1D4B9};\u4455l;\u69F6rok;\u4111\u0100dr\u1DB0\u1DB4ot;\u62F1i\u0100;f\u1DBA\u1816\u65BF\u0100ah\u1DC0\u1DC3r\xF2\u0429a\xF2\u0FA6angle;\u69A6\u0100ci\u1DD2\u1DD5y;\u445Fgrarr;\u67FF\u0900Dacdefglmnopqrstux\u1E01\u1E09\u1E19\u1E38\u0578\u1E3C\u1E49\u1E61\u1E7E\u1EA5\u1EAF\u1EBD\u1EE1\u1F2A\u1F37\u1F44\u1F4E\u1F5A\u0100Do\u1E06\u1D34o\xF4\u1C89\u0100cs\u1E0E\u1E14ute\u803B\xE9\u40E9ter;\u6A6E\u0200aioy\u1E22\u1E27\u1E31\u1E36ron;\u411Br\u0100;c\u1E2D\u1E2E\u6256\u803B\xEA\u40EAlon;\u6255;\u444Dot;\u4117\u0100Dr\u1E41\u1E45ot;\u6252;\uC000\u{1D522}\u0180;rs\u1E50\u1E51\u1E57\u6A9Aave\u803B\xE8\u40E8\u0100;d\u1E5C\u1E5D\u6A96ot;\u6A98\u0200;ils\u1E6A\u1E6B\u1E72\u1E74\u6A99nters;\u63E7;\u6113\u0100;d\u1E79\u1E7A\u6A95ot;\u6A97\u0180aps\u1E85\u1E89\u1E97cr;\u4113ty\u0180;sv\u1E92\u1E93\u1E95\u6205et\xBB\u1E93p\u01001;\u1E9D\u1EA4\u0133\u1EA1\u1EA3;\u6004;\u6005\u6003\u0100gs\u1EAA\u1EAC;\u414Bp;\u6002\u0100gp\u1EB4\u1EB8on;\u4119f;\uC000\u{1D556}\u0180als\u1EC4\u1ECE\u1ED2r\u0100;s\u1ECA\u1ECB\u62D5l;\u69E3us;\u6A71i\u0180;lv\u1EDA\u1EDB\u1EDF\u43B5on\xBB\u1EDB;\u43F5\u0200csuv\u1EEA\u1EF3\u1F0B\u1F23\u0100io\u1EEF\u1E31rc\xBB\u1E2E\u0269\u1EF9\0\0\u1EFB\xED\u0548ant\u0100gl\u1F02\u1F06tr\xBB\u1E5Dess\xBB\u1E7A\u0180aei\u1F12\u1F16\u1F1Als;\u403Dst;\u625Fv\u0100;D\u0235\u1F20D;\u6A78parsl;\u69E5\u0100Da\u1F2F\u1F33ot;\u6253rr;\u6971\u0180cdi\u1F3E\u1F41\u1EF8r;\u612Fo\xF4\u0352\u0100ah\u1F49\u1F4B;\u43B7\u803B\xF0\u40F0\u0100mr\u1F53\u1F57l\u803B\xEB\u40EBo;\u60AC\u0180cip\u1F61\u1F64\u1F67l;\u4021s\xF4\u056E\u0100eo\u1F6C\u1F74ctatio\xEE\u0559nential\xE5\u0579\u09E1\u1F92\0\u1F9E\0\u1FA1\u1FA7\0\0\u1FC6\u1FCC\0\u1FD3\0\u1FE6\u1FEA\u2000\0\u2008\u205Allingdotse\xF1\u1E44y;\u4444male;\u6640\u0180ilr\u1FAD\u1FB3\u1FC1lig;\u8000\uFB03\u0269\u1FB9\0\0\u1FBDg;\u8000\uFB00ig;\u8000\uFB04;\uC000\u{1D523}lig;\u8000\uFB01lig;\uC000fj\u0180alt\u1FD9\u1FDC\u1FE1t;\u666Dig;\u8000\uFB02ns;\u65B1of;\u4192\u01F0\u1FEE\0\u1FF3f;\uC000\u{1D557}\u0100ak\u05BF\u1FF7\u0100;v\u1FFC\u1FFD\u62D4;\u6AD9artint;\u6A0D\u0100ao\u200C\u2055\u0100cs\u2011\u2052\u03B1\u201A\u2030\u2038\u2045\u2048\0\u2050\u03B2\u2022\u2025\u2027\u202A\u202C\0\u202E\u803B\xBD\u40BD;\u6153\u803B\xBC\u40BC;\u6155;\u6159;\u615B\u01B3\u2034\0\u2036;\u6154;\u6156\u02B4\u203E\u2041\0\0\u2043\u803B\xBE\u40BE;\u6157;\u615C5;\u6158\u01B6\u204C\0\u204E;\u615A;\u615D8;\u615El;\u6044wn;\u6322cr;\uC000\u{1D4BB}\u0880Eabcdefgijlnorstv\u2082\u2089\u209F\u20A5\u20B0\u20B4\u20F0\u20F5\u20FA\u20FF\u2103\u2112\u2138\u0317\u213E\u2152\u219E\u0100;l\u064D\u2087;\u6A8C\u0180cmp\u2090\u2095\u209Dute;\u41F5ma\u0100;d\u209C\u1CDA\u43B3;\u6A86reve;\u411F\u0100iy\u20AA\u20AErc;\u411D;\u4433ot;\u4121\u0200;lqs\u063E\u0642\u20BD\u20C9\u0180;qs\u063E\u064C\u20C4lan\xF4\u0665\u0200;cdl\u0665\u20D2\u20D5\u20E5c;\u6AA9ot\u0100;o\u20DC\u20DD\u6A80\u0100;l\u20E2\u20E3\u6A82;\u6A84\u0100;e\u20EA\u20ED\uC000\u22DB\uFE00s;\u6A94r;\uC000\u{1D524}\u0100;g\u0673\u061Bmel;\u6137cy;\u4453\u0200;Eaj\u065A\u210C\u210E\u2110;\u6A92;\u6AA5;\u6AA4\u0200Eaes\u211B\u211D\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6A8Arox\xBB\u2124\u0100;q\u212E\u212F\u6A88\u0100;q\u212E\u211Bim;\u62E7pf;\uC000\u{1D558}\u0100ci\u2143\u2146r;\u610Am\u0180;el\u066B\u214E\u2150;\u6A8E;\u6A90\u8300>;cdlqr\u05EE\u2160\u216A\u216E\u2173\u2179\u0100ci\u2165\u2167;\u6AA7r;\u6A7Aot;\u62D7Par;\u6995uest;\u6A7C\u0280adels\u2184\u216A\u2190\u0656\u219B\u01F0\u2189\0\u218Epro\xF8\u209Er;\u6978q\u0100lq\u063F\u2196les\xF3\u2088i\xED\u066B\u0100en\u21A3\u21ADrtneqq;\uC000\u2269\uFE00\xC5\u21AA\u0500Aabcefkosy\u21C4\u21C7\u21F1\u21F5\u21FA\u2218\u221D\u222F\u2268\u227Dr\xF2\u03A0\u0200ilmr\u21D0\u21D4\u21D7\u21DBrs\xF0\u1484f\xBB\u2024il\xF4\u06A9\u0100dr\u21E0\u21E4cy;\u444A\u0180;cw\u08F4\u21EB\u21EFir;\u6948;\u61ADar;\u610Firc;\u4125\u0180alr\u2201\u220E\u2213rts\u0100;u\u2209\u220A\u6665it\xBB\u220Alip;\u6026con;\u62B9r;\uC000\u{1D525}s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223A\u223E\u2243\u225E\u2263rr;\u61FFtht;\u623Bk\u0100lr\u2249\u2253eftarrow;\u61A9ightarrow;\u61AAf;\uC000\u{1D559}bar;\u6015\u0180clt\u226F\u2274\u2278r;\uC000\u{1D4BD}as\xE8\u21F4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xBB\u1C5B\u0AE1\u22A3\0\u22AA\0\u22B8\u22C5\u22CE\0\u22D5\u22F3\0\0\u22F8\u2322\u2367\u2362\u237F\0\u2386\u23AA\u23B4cute\u803B\xED\u40ED\u0180;iy\u0771\u22B0\u22B5rc\u803B\xEE\u40EE;\u4438\u0100cx\u22BC\u22BFy;\u4435cl\u803B\xA1\u40A1\u0100fr\u039F\u22C9;\uC000\u{1D526}rave\u803B\xEC\u40EC\u0200;ino\u073E\u22DD\u22E9\u22EE\u0100in\u22E2\u22E6nt;\u6A0Ct;\u622Dfin;\u69DCta;\u6129lig;\u4133\u0180aop\u22FE\u231A\u231D\u0180cgt\u2305\u2308\u2317r;\u412B\u0180elp\u071F\u230F\u2313in\xE5\u078Ear\xF4\u0720h;\u4131f;\u62B7ed;\u41B5\u0280;cfot\u04F4\u232C\u2331\u233D\u2341are;\u6105in\u0100;t\u2338\u2339\u621Eie;\u69DDdo\xF4\u2319\u0280;celp\u0757\u234C\u2350\u235B\u2361al;\u62BA\u0100gr\u2355\u2359er\xF3\u1563\xE3\u234Darhk;\u6A17rod;\u6A3C\u0200cgpt\u236F\u2372\u2376\u237By;\u4451on;\u412Ff;\uC000\u{1D55A}a;\u43B9uest\u803B\xBF\u40BF\u0100ci\u238A\u238Fr;\uC000\u{1D4BE}n\u0280;Edsv\u04F4\u239B\u239D\u23A1\u04F3;\u62F9ot;\u62F5\u0100;v\u23A6\u23A7\u62F4;\u62F3\u0100;i\u0777\u23AElde;\u4129\u01EB\u23B8\0\u23BCcy;\u4456l\u803B\xEF\u40EF\u0300cfmosu\u23CC\u23D7\u23DC\u23E1\u23E7\u23F5\u0100iy\u23D1\u23D5rc;\u4135;\u4439r;\uC000\u{1D527}ath;\u4237pf;\uC000\u{1D55B}\u01E3\u23EC\0\u23F1r;\uC000\u{1D4BF}rcy;\u4458kcy;\u4454\u0400acfghjos\u240B\u2416\u2422\u2427\u242D\u2431\u2435\u243Bppa\u0100;v\u2413\u2414\u43BA;\u43F0\u0100ey\u241B\u2420dil;\u4137;\u443Ar;\uC000\u{1D528}reen;\u4138cy;\u4445cy;\u445Cpf;\uC000\u{1D55C}cr;\uC000\u{1D4C0}\u0B80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248D\u2491\u250E\u253D\u255A\u2580\u264E\u265E\u2665\u2679\u267D\u269A\u26B2\u26D8\u275D\u2768\u278B\u27C0\u2801\u2812\u0180art\u2477\u247A\u247Cr\xF2\u09C6\xF2\u0395ail;\u691Barr;\u690E\u0100;g\u0994\u248B;\u6A8Bar;\u6962\u0963\u24A5\0\u24AA\0\u24B1\0\0\0\0\0\u24B5\u24BA\0\u24C6\u24C8\u24CD\0\u24F9ute;\u413Amptyv;\u69B4ra\xEE\u084Cbda;\u43BBg\u0180;dl\u088E\u24C1\u24C3;\u6991\xE5\u088E;\u6A85uo\u803B\xAB\u40ABr\u0400;bfhlpst\u0899\u24DE\u24E6\u24E9\u24EB\u24EE\u24F1\u24F5\u0100;f\u089D\u24E3s;\u691Fs;\u691D\xEB\u2252p;\u61ABl;\u6939im;\u6973l;\u61A2\u0180;ae\u24FF\u2500\u2504\u6AABil;\u6919\u0100;s\u2509\u250A\u6AAD;\uC000\u2AAD\uFE00\u0180abr\u2515\u2519\u251Drr;\u690Crk;\u6772\u0100ak\u2522\u252Cc\u0100ek\u2528\u252A;\u407B;\u405B\u0100es\u2531\u2533;\u698Bl\u0100du\u2539\u253B;\u698F;\u698D\u0200aeuy\u2546\u254B\u2556\u2558ron;\u413E\u0100di\u2550\u2554il;\u413C\xEC\u08B0\xE2\u2529;\u443B\u0200cqrs\u2563\u2566\u256D\u257Da;\u6936uo\u0100;r\u0E19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694Bh;\u61B2\u0280;fgqs\u258B\u258C\u0989\u25F3\u25FF\u6264t\u0280ahlrt\u2598\u25A4\u25B7\u25C2\u25E8rrow\u0100;t\u0899\u25A1a\xE9\u24F6arpoon\u0100du\u25AF\u25B4own\xBB\u045Ap\xBB\u0966eftarrows;\u61C7ight\u0180ahs\u25CD\u25D6\u25DErrow\u0100;s\u08F4\u08A7arpoon\xF3\u0F98quigarro\xF7\u21F0hreetimes;\u62CB\u0180;qs\u258B\u0993\u25FAlan\xF4\u09AC\u0280;cdgs\u09AC\u260A\u260D\u261D\u2628c;\u6AA8ot\u0100;o\u2614\u2615\u6A7F\u0100;r\u261A\u261B\u6A81;\u6A83\u0100;e\u2622\u2625\uC000\u22DA\uFE00s;\u6A93\u0280adegs\u2633\u2639\u263D\u2649\u264Bppro\xF8\u24C6ot;\u62D6q\u0100gq\u2643\u2645\xF4\u0989gt\xF2\u248C\xF4\u099Bi\xED\u09B2\u0180ilr\u2655\u08E1\u265Asht;\u697C;\uC000\u{1D529}\u0100;E\u099C\u2663;\u6A91\u0161\u2669\u2676r\u0100du\u25B2\u266E\u0100;l\u0965\u2673;\u696Alk;\u6584cy;\u4459\u0280;acht\u0A48\u2688\u268B\u2691\u2696r\xF2\u25C1orne\xF2\u1D08ard;\u696Bri;\u65FA\u0100io\u269F\u26A4dot;\u4140ust\u0100;a\u26AC\u26AD\u63B0che\xBB\u26AD\u0200Eaes\u26BB\u26BD\u26C9\u26D4;\u6268p\u0100;p\u26C3\u26C4\u6A89rox\xBB\u26C4\u0100;q\u26CE\u26CF\u6A87\u0100;q\u26CE\u26BBim;\u62E6\u0400abnoptwz\u26E9\u26F4\u26F7\u271A\u272F\u2741\u2747\u2750\u0100nr\u26EE\u26F1g;\u67ECr;\u61FDr\xEB\u08C1g\u0180lmr\u26FF\u270D\u2714eft\u0100ar\u09E6\u2707ight\xE1\u09F2apsto;\u67FCight\xE1\u09FDparrow\u0100lr\u2725\u2729ef\xF4\u24EDight;\u61AC\u0180afl\u2736\u2739\u273Dr;\u6985;\uC000\u{1D55D}us;\u6A2Dimes;\u6A34\u0161\u274B\u274Fst;\u6217\xE1\u134E\u0180;ef\u2757\u2758\u1800\u65CAnge\xBB\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277C\u2785\u2787r\xF2\u08A8orne\xF2\u1D8Car\u0100;d\u0F98\u2783;\u696D;\u600Eri;\u62BF\u0300achiqt\u2798\u279D\u0A40\u27A2\u27AE\u27BBquo;\u6039r;\uC000\u{1D4C1}m\u0180;eg\u09B2\u27AA\u27AC;\u6A8D;\u6A8F\u0100bu\u252A\u27B3o\u0100;r\u0E1F\u27B9;\u601Arok;\u4142\u8400<;cdhilqr\u082B\u27D2\u2639\u27DC\u27E0\u27E5\u27EA\u27F0\u0100ci\u27D7\u27D9;\u6AA6r;\u6A79re\xE5\u25F2mes;\u62C9arr;\u6976uest;\u6A7B\u0100Pi\u27F5\u27F9ar;\u6996\u0180;ef\u2800\u092D\u181B\u65C3r\u0100du\u2807\u280Dshar;\u694Ahar;\u6966\u0100en\u2817\u2821rtneqq;\uC000\u2268\uFE00\xC5\u281E\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288E\u2893\u28A0\u28A5\u28A8\u28DA\u28E2\u28E4\u0A83\u28F3\u2902Dot;\u623A\u0200clpr\u284E\u2852\u2863\u287Dr\u803B\xAF\u40AF\u0100et\u2857\u2859;\u6642\u0100;e\u285E\u285F\u6720se\xBB\u285F\u0100;s\u103B\u2868to\u0200;dlu\u103B\u2873\u2877\u287Bow\xEE\u048Cef\xF4\u090F\xF0\u13D1ker;\u65AE\u0100oy\u2887\u288Cmma;\u6A29;\u443Cash;\u6014asuredangle\xBB\u1626r;\uC000\u{1D52A}o;\u6127\u0180cdn\u28AF\u28B4\u28C9ro\u803B\xB5\u40B5\u0200;acd\u1464\u28BD\u28C0\u28C4s\xF4\u16A7ir;\u6AF0ot\u80BB\xB7\u01B5us\u0180;bd\u28D2\u1903\u28D3\u6212\u0100;u\u1D3C\u28D8;\u6A2A\u0163\u28DE\u28E1p;\u6ADB\xF2\u2212\xF0\u0A81\u0100dp\u28E9\u28EEels;\u62A7f;\uC000\u{1D55E}\u0100ct\u28F8\u28FDr;\uC000\u{1D4C2}pos\xBB\u159D\u0180;lm\u2909\u290A\u290D\u43BCtimap;\u62B8\u0C00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297E\u2989\u2998\u29DA\u29E9\u2A15\u2A1A\u2A58\u2A5D\u2A83\u2A95\u2AA4\u2AA8\u2B04\u2B07\u2B44\u2B7F\u2BAE\u2C34\u2C67\u2C7C\u2CE9\u0100gt\u2947\u294B;\uC000\u22D9\u0338\u0100;v\u2950\u0BCF\uC000\u226B\u20D2\u0180elt\u295A\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61CDightarrow;\u61CE;\uC000\u22D8\u0338\u0100;v\u297B\u0C47\uC000\u226A\u20D2ightarrow;\u61CF\u0100Dd\u298E\u2993ash;\u62AFash;\u62AE\u0280bcnpt\u29A3\u29A7\u29AC\u29B1\u29CCla\xBB\u02DEute;\u4144g;\uC000\u2220\u20D2\u0280;Eiop\u0D84\u29BC\u29C0\u29C5\u29C8;\uC000\u2A70\u0338d;\uC000\u224B\u0338s;\u4149ro\xF8\u0D84ur\u0100;a\u29D3\u29D4\u666El\u0100;s\u29D3\u0B38\u01F3\u29DF\0\u29E3p\u80BB\xA0\u0B37mp\u0100;e\u0BF9\u0C00\u0280aeouy\u29F4\u29FE\u2A03\u2A10\u2A13\u01F0\u29F9\0\u29FB;\u6A43on;\u4148dil;\u4146ng\u0100;d\u0D7E\u2A0Aot;\uC000\u2A6D\u0338p;\u6A42;\u443Dash;\u6013\u0380;Aadqsx\u0B92\u2A29\u2A2D\u2A3B\u2A41\u2A45\u2A50rr;\u61D7r\u0100hr\u2A33\u2A36k;\u6924\u0100;o\u13F2\u13F0ot;\uC000\u2250\u0338ui\xF6\u0B63\u0100ei\u2A4A\u2A4Ear;\u6928\xED\u0B98ist\u0100;s\u0BA0\u0B9Fr;\uC000\u{1D52B}\u0200Eest\u0BC5\u2A66\u2A79\u2A7C\u0180;qs\u0BBC\u2A6D\u0BE1\u0180;qs\u0BBC\u0BC5\u2A74lan\xF4\u0BE2i\xED\u0BEA\u0100;r\u0BB6\u2A81\xBB\u0BB7\u0180Aap\u2A8A\u2A8D\u2A91r\xF2\u2971rr;\u61AEar;\u6AF2\u0180;sv\u0F8D\u2A9C\u0F8C\u0100;d\u2AA1\u2AA2\u62FC;\u62FAcy;\u445A\u0380AEadest\u2AB7\u2ABA\u2ABE\u2AC2\u2AC5\u2AF6\u2AF9r\xF2\u2966;\uC000\u2266\u0338rr;\u619Ar;\u6025\u0200;fqs\u0C3B\u2ACE\u2AE3\u2AEFt\u0100ar\u2AD4\u2AD9rro\xF7\u2AC1ightarro\xF7\u2A90\u0180;qs\u0C3B\u2ABA\u2AEAlan\xF4\u0C55\u0100;s\u0C55\u2AF4\xBB\u0C36i\xED\u0C5D\u0100;r\u0C35\u2AFEi\u0100;e\u0C1A\u0C25i\xE4\u0D90\u0100pt\u2B0C\u2B11f;\uC000\u{1D55F}\u8180\xAC;in\u2B19\u2B1A\u2B36\u40ACn\u0200;Edv\u0B89\u2B24\u2B28\u2B2E;\uC000\u22F9\u0338ot;\uC000\u22F5\u0338\u01E1\u0B89\u2B33\u2B35;\u62F7;\u62F6i\u0100;v\u0CB8\u2B3C\u01E1\u0CB8\u2B41\u2B43;\u62FE;\u62FD\u0180aor\u2B4B\u2B63\u2B69r\u0200;ast\u0B7B\u2B55\u2B5A\u2B5Flle\xEC\u0B7Bl;\uC000\u2AFD\u20E5;\uC000\u2202\u0338lint;\u6A14\u0180;ce\u0C92\u2B70\u2B73u\xE5\u0CA5\u0100;c\u0C98\u2B78\u0100;e\u0C92\u2B7D\xF1\u0C98\u0200Aait\u2B88\u2B8B\u2B9D\u2BA7r\xF2\u2988rr\u0180;cw\u2B94\u2B95\u2B99\u619B;\uC000\u2933\u0338;\uC000\u219D\u0338ghtarrow\xBB\u2B95ri\u0100;e\u0CCB\u0CD6\u0380chimpqu\u2BBD\u2BCD\u2BD9\u2B04\u0B78\u2BE4\u2BEF\u0200;cer\u0D32\u2BC6\u0D37\u2BC9u\xE5\u0D45;\uC000\u{1D4C3}ort\u026D\u2B05\0\0\u2BD6ar\xE1\u2B56m\u0100;e\u0D6E\u2BDF\u0100;q\u0D74\u0D73su\u0100bp\u2BEB\u2BED\xE5\u0CF8\xE5\u0D0B\u0180bcp\u2BF6\u2C11\u2C19\u0200;Ees\u2BFF\u2C00\u0D22\u2C04\u6284;\uC000\u2AC5\u0338et\u0100;e\u0D1B\u2C0Bq\u0100;q\u0D23\u2C00c\u0100;e\u0D32\u2C17\xF1\u0D38\u0200;Ees\u2C22\u2C23\u0D5F\u2C27\u6285;\uC000\u2AC6\u0338et\u0100;e\u0D58\u2C2Eq\u0100;q\u0D60\u2C23\u0200gilr\u2C3D\u2C3F\u2C45\u2C47\xEC\u0BD7lde\u803B\xF1\u40F1\xE7\u0C43iangle\u0100lr\u2C52\u2C5Ceft\u0100;e\u0C1A\u2C5A\xF1\u0C26ight\u0100;e\u0CCB\u2C65\xF1\u0CD7\u0100;m\u2C6C\u2C6D\u43BD\u0180;es\u2C74\u2C75\u2C79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2C8F\u2C94\u2C99\u2C9E\u2CA3\u2CB0\u2CB6\u2CD3\u2CE3ash;\u62ADarr;\u6904p;\uC000\u224D\u20D2ash;\u62AC\u0100et\u2CA8\u2CAC;\uC000\u2265\u20D2;\uC000>\u20D2nfin;\u69DE\u0180Aet\u2CBD\u2CC1\u2CC5rr;\u6902;\uC000\u2264\u20D2\u0100;r\u2CCA\u2CCD\uC000<\u20D2ie;\uC000\u22B4\u20D2\u0100At\u2CD8\u2CDCrr;\u6903rie;\uC000\u22B5\u20D2im;\uC000\u223C\u20D2\u0180Aan\u2CF0\u2CF4\u2D02rr;\u61D6r\u0100hr\u2CFA\u2CFDk;\u6923\u0100;o\u13E7\u13E5ear;\u6927\u1253\u1A95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2D2D\0\u2D38\u2D48\u2D60\u2D65\u2D72\u2D84\u1B07\0\0\u2D8D\u2DAB\0\u2DC8\u2DCE\0\u2DDC\u2E19\u2E2B\u2E3E\u2E43\u0100cs\u2D31\u1A97ute\u803B\xF3\u40F3\u0100iy\u2D3C\u2D45r\u0100;c\u1A9E\u2D42\u803B\xF4\u40F4;\u443E\u0280abios\u1AA0\u2D52\u2D57\u01C8\u2D5Alac;\u4151v;\u6A38old;\u69BClig;\u4153\u0100cr\u2D69\u2D6Dir;\u69BF;\uC000\u{1D52C}\u036F\u2D79\0\0\u2D7C\0\u2D82n;\u42DBave\u803B\xF2\u40F2;\u69C1\u0100bm\u2D88\u0DF4ar;\u69B5\u0200acit\u2D95\u2D98\u2DA5\u2DA8r\xF2\u1A80\u0100ir\u2D9D\u2DA0r;\u69BEoss;\u69BBn\xE5\u0E52;\u69C0\u0180aei\u2DB1\u2DB5\u2DB9cr;\u414Dga;\u43C9\u0180cdn\u2DC0\u2DC5\u01CDron;\u43BF;\u69B6pf;\uC000\u{1D560}\u0180ael\u2DD4\u2DD7\u01D2r;\u69B7rp;\u69B9\u0380;adiosv\u2DEA\u2DEB\u2DEE\u2E08\u2E0D\u2E10\u2E16\u6228r\xF2\u1A86\u0200;efm\u2DF7\u2DF8\u2E02\u2E05\u6A5Dr\u0100;o\u2DFE\u2DFF\u6134f\xBB\u2DFF\u803B\xAA\u40AA\u803B\xBA\u40BAgof;\u62B6r;\u6A56lope;\u6A57;\u6A5B\u0180clo\u2E1F\u2E21\u2E27\xF2\u2E01ash\u803B\xF8\u40F8l;\u6298i\u016C\u2E2F\u2E34de\u803B\xF5\u40F5es\u0100;a\u01DB\u2E3As;\u6A36ml\u803B\xF6\u40F6bar;\u633D\u0AE1\u2E5E\0\u2E7D\0\u2E80\u2E9D\0\u2EA2\u2EB9\0\0\u2ECB\u0E9C\0\u2F13\0\0\u2F2B\u2FBC\0\u2FC8r\u0200;ast\u0403\u2E67\u2E72\u0E85\u8100\xB6;l\u2E6D\u2E6E\u40B6le\xEC\u0403\u0269\u2E78\0\0\u2E7Bm;\u6AF3;\u6AFDy;\u443Fr\u0280cimpt\u2E8B\u2E8F\u2E93\u1865\u2E97nt;\u4025od;\u402Eil;\u6030enk;\u6031r;\uC000\u{1D52D}\u0180imo\u2EA8\u2EB0\u2EB4\u0100;v\u2EAD\u2EAE\u43C6;\u43D5ma\xF4\u0A76ne;\u660E\u0180;tv\u2EBF\u2EC0\u2EC8\u43C0chfork\xBB\u1FFD;\u43D6\u0100au\u2ECF\u2EDFn\u0100ck\u2ED5\u2EDDk\u0100;h\u21F4\u2EDB;\u610E\xF6\u21F4s\u0480;abcdemst\u2EF3\u2EF4\u1908\u2EF9\u2EFD\u2F04\u2F06\u2F0A\u2F0E\u402Bcir;\u6A23ir;\u6A22\u0100ou\u1D40\u2F02;\u6A25;\u6A72n\u80BB\xB1\u0E9Dim;\u6A26wo;\u6A27\u0180ipu\u2F19\u2F20\u2F25ntint;\u6A15f;\uC000\u{1D561}nd\u803B\xA3\u40A3\u0500;Eaceinosu\u0EC8\u2F3F\u2F41\u2F44\u2F47\u2F81\u2F89\u2F92\u2F7E\u2FB6;\u6AB3p;\u6AB7u\xE5\u0ED9\u0100;c\u0ECE\u2F4C\u0300;acens\u0EC8\u2F59\u2F5F\u2F66\u2F68\u2F7Eppro\xF8\u2F43urlye\xF1\u0ED9\xF1\u0ECE\u0180aes\u2F6F\u2F76\u2F7Approx;\u6AB9qq;\u6AB5im;\u62E8i\xED\u0EDFme\u0100;s\u2F88\u0EAE\u6032\u0180Eas\u2F78\u2F90\u2F7A\xF0\u2F75\u0180dfp\u0EEC\u2F99\u2FAF\u0180als\u2FA0\u2FA5\u2FAAlar;\u632Eine;\u6312urf;\u6313\u0100;t\u0EFB\u2FB4\xEF\u0EFBrel;\u62B0\u0100ci\u2FC0\u2FC5r;\uC000\u{1D4C5};\u43C8ncsp;\u6008\u0300fiopsu\u2FDA\u22E2\u2FDF\u2FE5\u2FEB\u2FF1r;\uC000\u{1D52E}pf;\uC000\u{1D562}rime;\u6057cr;\uC000\u{1D4C6}\u0180aeo\u2FF8\u3009\u3013t\u0100ei\u2FFE\u3005rnion\xF3\u06B0nt;\u6A16st\u0100;e\u3010\u3011\u403F\xF1\u1F19\xF4\u0F14\u0A80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30E0\u310E\u312B\u3147\u3162\u3172\u318E\u3206\u3215\u3224\u3229\u3258\u326E\u3272\u3290\u32B0\u32B7\u0180art\u3047\u304A\u304Cr\xF2\u10B3\xF2\u03DDail;\u691Car\xF2\u1C65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307F\u308F\u3094\u30CC\u0100eu\u306D\u3071;\uC000\u223D\u0331te;\u4155i\xE3\u116Emptyv;\u69B3g\u0200;del\u0FD1\u3089\u308B\u308D;\u6992;\u69A5\xE5\u0FD1uo\u803B\xBB\u40BBr\u0580;abcfhlpstw\u0FDC\u30AC\u30AF\u30B7\u30B9\u30BC\u30BE\u30C0\u30C3\u30C7\u30CAp;\u6975\u0100;f\u0FE0\u30B4s;\u6920;\u6933s;\u691E\xEB\u225D\xF0\u272El;\u6945im;\u6974l;\u61A3;\u619D\u0100ai\u30D1\u30D5il;\u691Ao\u0100;n\u30DB\u30DC\u6236al\xF3\u0F1E\u0180abr\u30E7\u30EA\u30EEr\xF2\u17E5rk;\u6773\u0100ak\u30F3\u30FDc\u0100ek\u30F9\u30FB;\u407D;\u405D\u0100es\u3102\u3104;\u698Cl\u0100du\u310A\u310C;\u698E;\u6990\u0200aeuy\u3117\u311C\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xEC\u0FF2\xE2\u30FA;\u4440\u0200clqs\u3134\u3137\u313D\u3144a;\u6937dhar;\u6969uo\u0100;r\u020E\u020Dh;\u61B3\u0180acg\u314E\u315F\u0F44l\u0200;ips\u0F78\u3158\u315B\u109Cn\xE5\u10BBar\xF4\u0FA9t;\u65AD\u0180ilr\u3169\u1023\u316Esht;\u697D;\uC000\u{1D52F}\u0100ao\u3177\u3186r\u0100du\u317D\u317F\xBB\u047B\u0100;l\u1091\u3184;\u696C\u0100;v\u318B\u318C\u43C1;\u43F1\u0180gns\u3195\u31F9\u31FCht\u0300ahlrst\u31A4\u31B0\u31C2\u31D8\u31E4\u31EErrow\u0100;t\u0FDC\u31ADa\xE9\u30C8arpoon\u0100du\u31BB\u31BFow\xEE\u317Ep\xBB\u1092eft\u0100ah\u31CA\u31D0rrow\xF3\u0FEAarpoon\xF3\u0551ightarrows;\u61C9quigarro\xF7\u30CBhreetimes;\u62CCg;\u42DAingdotse\xF1\u1F32\u0180ahm\u320D\u3210\u3213r\xF2\u0FEAa\xF2\u0551;\u600Foust\u0100;a\u321E\u321F\u63B1che\xBB\u321Fmid;\u6AEE\u0200abpt\u3232\u323D\u3240\u3252\u0100nr\u3237\u323Ag;\u67EDr;\u61FEr\xEB\u1003\u0180afl\u3247\u324A\u324Er;\u6986;\uC000\u{1D563}us;\u6A2Eimes;\u6A35\u0100ap\u325D\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6A12ar\xF2\u31E3\u0200achq\u327B\u3280\u10BC\u3285quo;\u603Ar;\uC000\u{1D4C7}\u0100bu\u30FB\u328Ao\u0100;r\u0214\u0213\u0180hir\u3297\u329B\u32A0re\xE5\u31F8mes;\u62CAi\u0200;efl\u32AA\u1059\u1821\u32AB\u65B9tri;\u69CEluhar;\u6968;\u611E\u0D61\u32D5\u32DB\u32DF\u332C\u3338\u3371\0\u337A\u33A4\0\0\u33EC\u33F0\0\u3428\u3448\u345A\u34AD\u34B1\u34CA\u34F1\0\u3616\0\0\u3633cute;\u415Bqu\xEF\u27BA\u0500;Eaceinpsy\u11ED\u32F3\u32F5\u32FF\u3302\u330B\u330F\u331F\u3326\u3329;\u6AB4\u01F0\u32FA\0\u32FC;\u6AB8on;\u4161u\xE5\u11FE\u0100;d\u11F3\u3307il;\u415Frc;\u415D\u0180Eas\u3316\u3318\u331B;\u6AB6p;\u6ABAim;\u62E9olint;\u6A13i\xED\u1204;\u4441ot\u0180;be\u3334\u1D47\u3335\u62C5;\u6A66\u0380Aacmstx\u3346\u334A\u3357\u335B\u335E\u3363\u336Drr;\u61D8r\u0100hr\u3350\u3352\xEB\u2228\u0100;o\u0A36\u0A34t\u803B\xA7\u40A7i;\u403Bwar;\u6929m\u0100in\u3369\xF0nu\xF3\xF1t;\u6736r\u0100;o\u3376\u2055\uC000\u{1D530}\u0200acoy\u3382\u3386\u3391\u33A0rp;\u666F\u0100hy\u338B\u338Fcy;\u4449;\u4448rt\u026D\u3399\0\0\u339Ci\xE4\u1464ara\xEC\u2E6F\u803B\xAD\u40AD\u0100gm\u33A8\u33B4ma\u0180;fv\u33B1\u33B2\u33B2\u43C3;\u43C2\u0400;deglnpr\u12AB\u33C5\u33C9\u33CE\u33D6\u33DE\u33E1\u33E6ot;\u6A6A\u0100;q\u12B1\u12B0\u0100;E\u33D3\u33D4\u6A9E;\u6AA0\u0100;E\u33DB\u33DC\u6A9D;\u6A9Fe;\u6246lus;\u6A24arr;\u6972ar\xF2\u113D\u0200aeit\u33F8\u3408\u340F\u3417\u0100ls\u33FD\u3404lsetm\xE9\u336Ahp;\u6A33parsl;\u69E4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341C\u341D\u6AAA\u0100;s\u3422\u3423\u6AAC;\uC000\u2AAC\uFE00\u0180flp\u342E\u3433\u3442tcy;\u444C\u0100;b\u3438\u3439\u402F\u0100;a\u343E\u343F\u69C4r;\u633Ff;\uC000\u{1D564}a\u0100dr\u344D\u0402es\u0100;u\u3454\u3455\u6660it\xBB\u3455\u0180csu\u3460\u3479\u349F\u0100au\u3465\u346Fp\u0100;s\u1188\u346B;\uC000\u2293\uFE00p\u0100;s\u11B4\u3475;\uC000\u2294\uFE00u\u0100bp\u347F\u348F\u0180;es\u1197\u119C\u3486et\u0100;e\u1197\u348D\xF1\u119D\u0180;es\u11A8\u11AD\u3496et\u0100;e\u11A8\u349D\xF1\u11AE\u0180;af\u117B\u34A6\u05B0r\u0165\u34AB\u05B1\xBB\u117Car\xF2\u1148\u0200cemt\u34B9\u34BE\u34C2\u34C5r;\uC000\u{1D4C8}tm\xEE\xF1i\xEC\u3415ar\xE6\u11BE\u0100ar\u34CE\u34D5r\u0100;f\u34D4\u17BF\u6606\u0100an\u34DA\u34EDight\u0100ep\u34E3\u34EApsilo\xEE\u1EE0h\xE9\u2EAFs\xBB\u2852\u0280bcmnp\u34FB\u355E\u1209\u358B\u358E\u0480;Edemnprs\u350E\u350F\u3511\u3515\u351E\u3523\u352C\u3531\u3536\u6282;\u6AC5ot;\u6ABD\u0100;d\u11DA\u351Aot;\u6AC3ult;\u6AC1\u0100Ee\u3528\u352A;\u6ACB;\u628Alus;\u6ABFarr;\u6979\u0180eiu\u353D\u3552\u3555t\u0180;en\u350E\u3545\u354Bq\u0100;q\u11DA\u350Feq\u0100;q\u352B\u3528m;\u6AC7\u0100bp\u355A\u355C;\u6AD5;\u6AD3c\u0300;acens\u11ED\u356C\u3572\u3579\u357B\u3326ppro\xF8\u32FAurlye\xF1\u11FE\xF1\u11F3\u0180aes\u3582\u3588\u331Bppro\xF8\u331Aq\xF1\u3317g;\u666A\u0680123;Edehlmnps\u35A9\u35AC\u35AF\u121C\u35B2\u35B4\u35C0\u35C9\u35D5\u35DA\u35DF\u35E8\u35ED\u803B\xB9\u40B9\u803B\xB2\u40B2\u803B\xB3\u40B3;\u6AC6\u0100os\u35B9\u35BCt;\u6ABEub;\u6AD8\u0100;d\u1222\u35C5ot;\u6AC4s\u0100ou\u35CF\u35D2l;\u67C9b;\u6AD7arr;\u697Bult;\u6AC2\u0100Ee\u35E4\u35E6;\u6ACC;\u628Blus;\u6AC0\u0180eiu\u35F4\u3609\u360Ct\u0180;en\u121C\u35FC\u3602q\u0100;q\u1222\u35B2eq\u0100;q\u35E7\u35E4m;\u6AC8\u0100bp\u3611\u3613;\u6AD4;\u6AD6\u0180Aan\u361C\u3620\u362Drr;\u61D9r\u0100hr\u3626\u3628\xEB\u222E\u0100;o\u0A2B\u0A29war;\u692Alig\u803B\xDF\u40DF\u0BE1\u3651\u365D\u3660\u12CE\u3673\u3679\0\u367E\u36C2\0\0\0\0\0\u36DB\u3703\0\u3709\u376C\0\0\0\u3787\u0272\u3656\0\0\u365Bget;\u6316;\u43C4r\xEB\u0E5F\u0180aey\u3666\u366B\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uC000\u{1D531}\u0200eiko\u3686\u369D\u36B5\u36BC\u01F2\u368B\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369B\u43B8ym;\u43D1\u0100cn\u36A2\u36B2k\u0100as\u36A8\u36AEppro\xF8\u12C1im\xBB\u12ACs\xF0\u129E\u0100as\u36BA\u36AE\xF0\u12C1rn\u803B\xFE\u40FE\u01EC\u031F\u36C6\u22E7es\u8180\xD7;bd\u36CF\u36D0\u36D8\u40D7\u0100;a\u190F\u36D5r;\u6A31;\u6A30\u0180eps\u36E1\u36E3\u3700\xE1\u2A4D\u0200;bcf\u0486\u36EC\u36F0\u36F4ot;\u6336ir;\u6AF1\u0100;o\u36F9\u36FC\uC000\u{1D565}rk;\u6ADA\xE1\u3362rime;\u6034\u0180aip\u370F\u3712\u3764d\xE5\u1248\u0380adempst\u3721\u374D\u3740\u3751\u3757\u375C\u375Fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65B5own\xBB\u1DBBeft\u0100;e\u2800\u373E\xF1\u092E;\u625Cight\u0100;e\u32AA\u374B\xF1\u105Aot;\u65ECinus;\u6A3Alus;\u6A39b;\u69CDime;\u6A3Bezium;\u63E2\u0180cht\u3772\u377D\u3781\u0100ry\u3777\u377B;\uC000\u{1D4C9};\u4446cy;\u445Brok;\u4167\u0100io\u378B\u378Ex\xF4\u1777head\u0100lr\u3797\u37A0eftarro\xF7\u084Fightarrow\xBB\u0F5D\u0900AHabcdfghlmoprstuw\u37D0\u37D3\u37D7\u37E4\u37F0\u37FC\u380E\u381C\u3823\u3834\u3851\u385D\u386B\u38A9\u38CC\u38D2\u38EA\u38F6r\xF2\u03EDar;\u6963\u0100cr\u37DC\u37E2ute\u803B\xFA\u40FA\xF2\u1150r\u01E3\u37EA\0\u37EDy;\u445Eve;\u416D\u0100iy\u37F5\u37FArc\u803B\xFB\u40FB;\u4443\u0180abh\u3803\u3806\u380Br\xF2\u13ADlac;\u4171a\xF2\u13C3\u0100ir\u3813\u3818sht;\u697E;\uC000\u{1D532}rave\u803B\xF9\u40F9\u0161\u3827\u3831r\u0100lr\u382C\u382E\xBB\u0957\xBB\u1083lk;\u6580\u0100ct\u3839\u384D\u026F\u383F\0\0\u384Arn\u0100;e\u3845\u3846\u631Cr\xBB\u3846op;\u630Fri;\u65F8\u0100al\u3856\u385Acr;\u416B\u80BB\xA8\u0349\u0100gp\u3862\u3866on;\u4173f;\uC000\u{1D566}\u0300adhlsu\u114B\u3878\u387D\u1372\u3891\u38A0own\xE1\u13B3arpoon\u0100lr\u3888\u388Cef\xF4\u382Digh\xF4\u382Fi\u0180;hl\u3899\u389A\u389C\u43C5\xBB\u13FAon\xBB\u389Aparrows;\u61C8\u0180cit\u38B0\u38C4\u38C8\u026F\u38B6\0\0\u38C1rn\u0100;e\u38BC\u38BD\u631Dr\xBB\u38BDop;\u630Eng;\u416Fri;\u65F9cr;\uC000\u{1D4CA}\u0180dir\u38D9\u38DD\u38E2ot;\u62F0lde;\u4169i\u0100;f\u3730\u38E8\xBB\u1813\u0100am\u38EF\u38F2r\xF2\u38A8l\u803B\xFC\u40FCangle;\u69A7\u0780ABDacdeflnoprsz\u391C\u391F\u3929\u392D\u39B5\u39B8\u39BD\u39DF\u39E4\u39E8\u39F3\u39F9\u39FD\u3A01\u3A20r\xF2\u03F7ar\u0100;v\u3926\u3927\u6AE8;\u6AE9as\xE8\u03E1\u0100nr\u3932\u3937grt;\u699C\u0380eknprst\u34E3\u3946\u394B\u3952\u395D\u3964\u3996app\xE1\u2415othin\xE7\u1E96\u0180hir\u34EB\u2EC8\u3959op\xF4\u2FB5\u0100;h\u13B7\u3962\xEF\u318D\u0100iu\u3969\u396Dgm\xE1\u33B3\u0100bp\u3972\u3984setneq\u0100;q\u397D\u3980\uC000\u228A\uFE00;\uC000\u2ACB\uFE00setneq\u0100;q\u398F\u3992\uC000\u228B\uFE00;\uC000\u2ACC\uFE00\u0100hr\u399B\u399Fet\xE1\u369Ciangle\u0100lr\u39AA\u39AFeft\xBB\u0925ight\xBB\u1051y;\u4432ash\xBB\u1036\u0180elr\u39C4\u39D2\u39D7\u0180;be\u2DEA\u39CB\u39CFar;\u62BBq;\u625Alip;\u62EE\u0100bt\u39DC\u1468a\xF2\u1469r;\uC000\u{1D533}tr\xE9\u39AEsu\u0100bp\u39EF\u39F1\xBB\u0D1C\xBB\u0D59pf;\uC000\u{1D567}ro\xF0\u0EFBtr\xE9\u39B4\u0100cu\u3A06\u3A0Br;\uC000\u{1D4CB}\u0100bp\u3A10\u3A18n\u0100Ee\u3980\u3A16\xBB\u397En\u0100Ee\u3992\u3A1E\xBB\u3990igzag;\u699A\u0380cefoprs\u3A36\u3A3B\u3A56\u3A5B\u3A54\u3A61\u3A6Airc;\u4175\u0100di\u3A40\u3A51\u0100bg\u3A45\u3A49ar;\u6A5Fe\u0100;q\u15FA\u3A4F;\u6259erp;\u6118r;\uC000\u{1D534}pf;\uC000\u{1D568}\u0100;e\u1479\u3A66at\xE8\u1479cr;\uC000\u{1D4CC}\u0AE3\u178E\u3A87\0\u3A8B\0\u3A90\u3A9B\0\0\u3A9D\u3AA8\u3AAB\u3AAF\0\0\u3AC3\u3ACE\0\u3AD8\u17DC\u17DFtr\xE9\u17D1r;\uC000\u{1D535}\u0100Aa\u3A94\u3A97r\xF2\u03C3r\xF2\u09F6;\u43BE\u0100Aa\u3AA1\u3AA4r\xF2\u03B8r\xF2\u09EBa\xF0\u2713is;\u62FB\u0180dpt\u17A4\u3AB5\u3ABE\u0100fl\u3ABA\u17A9;\uC000\u{1D569}im\xE5\u17B2\u0100Aa\u3AC7\u3ACAr\xF2\u03CEr\xF2\u0A01\u0100cq\u3AD2\u17B8r;\uC000\u{1D4CD}\u0100pt\u17D6\u3ADCr\xE9\u17D4\u0400acefiosu\u3AF0\u3AFD\u3B08\u3B0C\u3B11\u3B15\u3B1B\u3B21c\u0100uy\u3AF6\u3AFBte\u803B\xFD\u40FD;\u444F\u0100iy\u3B02\u3B06rc;\u4177;\u444Bn\u803B\xA5\u40A5r;\uC000\u{1D536}cy;\u4457pf;\uC000\u{1D56A}cr;\uC000\u{1D4CE}\u0100cm\u3B26\u3B29y;\u444El\u803B\xFF\u40FF\u0500acdefhiosw\u3B42\u3B48\u3B54\u3B58\u3B64\u3B69\u3B6D\u3B74\u3B7A\u3B80cute;\u417A\u0100ay\u3B4D\u3B52ron;\u417E;\u4437ot;\u417C\u0100et\u3B5D\u3B61tr\xE6\u155Fa;\u43B6r;\uC000\u{1D537}cy;\u4436grarr;\u61DDpf;\uC000\u{1D56B}cr;\uC000\u{1D4CF}\u0100jn\u3B85\u3B87;\u600Dj;\u600C'.split("").map((c) => c.charCodeAt(0))
+ );
+
+ // third_party/editor/entities/src/generated/decode-data-xml.ts
+ var decode_data_xml_default = new Uint16Array(
+ // prettier-ignore
+ "\u0200aglq \x1B\u026D\0\0p;\u4026os;\u4027t;\u403Et;\u403Cuot;\u4022".split("").map((c) => c.charCodeAt(0))
+ );
+
+ // third_party/editor/entities/src/decode_codepoint.ts
+ var decodeMap = /* @__PURE__ */ new Map([
+ [0, 65533],
+ // C1 Unicode control character reference replacements
+ [128, 8364],
+ [130, 8218],
+ [131, 402],
+ [132, 8222],
+ [133, 8230],
+ [134, 8224],
+ [135, 8225],
+ [136, 710],
+ [137, 8240],
+ [138, 352],
+ [139, 8249],
+ [140, 338],
+ [142, 381],
+ [145, 8216],
+ [146, 8217],
+ [147, 8220],
+ [148, 8221],
+ [149, 8226],
+ [150, 8211],
+ [151, 8212],
+ [152, 732],
+ [153, 8482],
+ [154, 353],
+ [155, 8250],
+ [156, 339],
+ [158, 382],
+ [159, 376]
+ ]);
+ var fromCodePoint = (
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
+ String.fromCodePoint ?? function(codePoint) {
+ let output = "";
+ if (codePoint > 65535) {
+ codePoint -= 65536;
+ output += String.fromCharCode(
+ codePoint >>> 10 & 1023 | 55296
+ );
+ codePoint = 56320 | codePoint & 1023;
+ }
+ output += String.fromCharCode(codePoint);
+ return output;
+ }
+ );
+ function replaceCodePoint(codePoint) {
+ if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
+ return 65533;
+ }
+ return decodeMap.get(codePoint) ?? codePoint;
+ }
+
+ // third_party/editor/entities/src/decode.ts
+ var TO_LOWER_BIT = 32;
+ function isNumber(code4) {
+ return code4 >= 48 /* ZERO */ && code4 <= 57 /* NINE */;
+ }
+ function isHexadecimalCharacter(code4) {
+ return code4 >= 65 /* UPPER_A */ && code4 <= 70 /* UPPER_F */ || code4 >= 97 /* LOWER_A */ && code4 <= 102 /* LOWER_F */;
+ }
+ function isAsciiAlphaNumeric(code4) {
+ return code4 >= 65 /* UPPER_A */ && code4 <= 90 /* UPPER_Z */ || code4 >= 97 /* LOWER_A */ && code4 <= 122 /* LOWER_Z */ || isNumber(code4);
+ }
+ function isEntityInAttributeInvalidEnd(code4) {
+ return code4 === 61 /* EQUALS */ || isAsciiAlphaNumeric(code4);
+ }
+ var EntityDecoder = class {
+ constructor(decodeTree, emitCodePoint, errors) {
+ this.decodeTree = decodeTree;
+ this.emitCodePoint = emitCodePoint;
+ this.errors = errors;
+ }
+ decodeTree;
+ emitCodePoint;
+ errors;
+ /** The current state of the decoder. */
+ state = 0 /* EntityStart */;
+ /** Characters that were consumed while parsing an entity. */
+ consumed = 1;
+ /**
+ * The result of the entity.
+ *
+ * Either the result index of a numeric entity, or the codepoint of a
+ * numeric entity.
+ */
+ result = 0;
+ /** The current index in the decode tree. */
+ treeIndex = 0;
+ /** The number of characters that were consumed in excess. */
+ excess = 1;
+ /** The mode in which the decoder is operating. */
+ decodeMode = 1 /* Strict */;
+ /** Resets the instance to make it reusable. */
+ startEntity(decodeMode) {
+ this.decodeMode = decodeMode;
+ this.state = 0 /* EntityStart */;
+ this.result = 0;
+ this.treeIndex = 0;
+ this.excess = 1;
+ this.consumed = 1;
+ }
+ /**
+ * Write an entity to the decoder. This can be called multiple times with partial entities.
+ * If the entity is incomplete, the decoder will return -1.
+ *
+ * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
+ * entity is incomplete, and resume when the next string is written.
+ *
+ * @param string The string containing the entity (or a continuation of the entity).
+ * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ write(str, offset) {
+ switch (this.state) {
+ case 0 /* EntityStart */: {
+ if (str.charCodeAt(offset) === 35 /* NUM */) {
+ this.state = 1 /* NumericStart */;
+ this.consumed += 1;
+ return this.stateNumericStart(str, offset + 1);
+ }
+ this.state = 4 /* NamedEntity */;
+ return this.stateNamedEntity(str, offset);
+ }
+ case 1 /* NumericStart */: {
+ return this.stateNumericStart(str, offset);
+ }
+ case 2 /* NumericDecimal */: {
+ return this.stateNumericDecimal(str, offset);
+ }
+ case 3 /* NumericHex */: {
+ return this.stateNumericHex(str, offset);
+ }
+ case 4 /* NamedEntity */: {
+ return this.stateNamedEntity(str, offset);
+ }
+ }
+ }
+ /**
+ * Switches between the numeric decimal and hexadecimal states.
+ *
+ * Equivalent to the `Numeric character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNumericStart(str, offset) {
+ if (offset >= str.length) {
+ return -1;
+ }
+ if ((str.charCodeAt(offset) | TO_LOWER_BIT) === 120 /* LOWER_X */) {
+ this.state = 3 /* NumericHex */;
+ this.consumed += 1;
+ return this.stateNumericHex(str, offset + 1);
+ }
+ this.state = 2 /* NumericDecimal */;
+ return this.stateNumericDecimal(str, offset);
+ }
+ addToNumericResult(str, start, end, base2) {
+ if (start !== end) {
+ const digitCount = end - start;
+ this.result = this.result * Math.pow(base2, digitCount) + parseInt(str.substr(start, digitCount), base2);
+ this.consumed += digitCount;
+ }
+ }
+ /**
+ * Parses a hexadecimal numeric entity.
+ *
+ * Equivalent to the `Hexademical character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNumericHex(str, offset) {
+ const startIdx = offset;
+ while (offset < str.length) {
+ const char = str.charCodeAt(offset);
+ if (isNumber(char) || isHexadecimalCharacter(char)) {
+ offset += 1;
+ } else {
+ this.addToNumericResult(str, startIdx, offset, 16);
+ return this.emitNumericEntity(char, 3);
+ }
+ }
+ this.addToNumericResult(str, startIdx, offset, 16);
+ return -1;
+ }
+ /**
+ * Parses a decimal numeric entity.
+ *
+ * Equivalent to the `Decimal character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNumericDecimal(str, offset) {
+ const startIdx = offset;
+ while (offset < str.length) {
+ const char = str.charCodeAt(offset);
+ if (isNumber(char)) {
+ offset += 1;
+ } else {
+ this.addToNumericResult(str, startIdx, offset, 10);
+ return this.emitNumericEntity(char, 2);
+ }
+ }
+ this.addToNumericResult(str, startIdx, offset, 10);
+ return -1;
+ }
+ /**
+ * Validate and emit a numeric entity.
+ *
+ * Implements the logic from the `Hexademical character reference start
+ * state` and `Numeric character reference end state` in the HTML spec.
+ *
+ * @param lastCp The last code point of the entity. Used to see if the
+ * entity was terminated with a semicolon.
+ * @param expectedLength The minimum number of characters that should be
+ * consumed. Used to validate that at least one digit
+ * was consumed.
+ * @returns The number of characters that were consumed.
+ */
+ emitNumericEntity(lastCp, expectedLength) {
+ if (this.consumed <= expectedLength) {
+ this.errors?.absenceOfDigitsInNumericCharacterReference(
+ this.consumed
+ );
+ return 0;
+ }
+ if (lastCp === 59 /* SEMI */) {
+ this.consumed += 1;
+ } else if (this.decodeMode === 1 /* Strict */) {
+ return 0;
+ }
+ this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
+ if (this.errors) {
+ if (lastCp !== 59 /* SEMI */) {
+ this.errors.missingSemicolonAfterCharacterReference();
+ }
+ this.errors.validateNumericCharacterReference(this.result);
+ }
+ return this.consumed;
+ }
+ /**
+ * Parses a named entity.
+ *
+ * Equivalent to the `Named character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNamedEntity(str, offset) {
+ const { decodeTree } = this;
+ let current = decodeTree[this.treeIndex];
+ let valueLength = (current & 49152 /* VALUE_LENGTH */) >> 14;
+ for (; offset < str.length; offset++, this.excess++) {
+ const char = str.charCodeAt(offset);
+ this.treeIndex = determineBranch(
+ decodeTree,
+ current,
+ this.treeIndex + Math.max(1, valueLength),
+ char
+ );
+ if (this.treeIndex < 0) {
+ return this.result === 0 || // If we are parsing an attribute
+ this.decodeMode === 2 /* Attribute */ && // We shouldn't have consumed any characters after the entity,
+ (valueLength === 0 || // And there should be no invalid characters.
+ isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
+ }
+ current = decodeTree[this.treeIndex];
+ valueLength = (current & 49152 /* VALUE_LENGTH */) >> 14;
+ if (valueLength !== 0) {
+ if (char === 59 /* SEMI */) {
+ return this.emitNamedEntityData(
+ this.treeIndex,
+ valueLength,
+ this.consumed + this.excess
+ );
+ }
+ if (this.decodeMode !== 1 /* Strict */) {
+ this.result = this.treeIndex;
+ this.consumed += this.excess;
+ this.excess = 0;
+ }
+ }
+ }
+ return -1;
+ }
+ /**
+ * Emit a named entity that was not terminated with a semicolon.
+ *
+ * @returns The number of characters consumed.
+ */
+ emitNotTerminatedNamedEntity() {
+ const { result, decodeTree } = this;
+ const valueLength = (decodeTree[result] & 49152 /* VALUE_LENGTH */) >> 14;
+ this.emitNamedEntityData(result, valueLength, this.consumed);
+ this.errors?.missingSemicolonAfterCharacterReference();
+ return this.consumed;
+ }
+ /**
+ * Emit a named entity.
+ *
+ * @param result The index of the entity in the decode tree.
+ * @param valueLength The number of bytes in the entity.
+ * @param consumed The number of characters consumed.
+ *
+ * @returns The number of characters consumed.
+ */
+ emitNamedEntityData(result, valueLength, consumed) {
+ const { decodeTree } = this;
+ this.emitCodePoint(
+ valueLength === 1 ? decodeTree[result] & ~49152 /* VALUE_LENGTH */ : decodeTree[result + 1],
+ consumed
+ );
+ if (valueLength === 3) {
+ this.emitCodePoint(decodeTree[result + 2], consumed);
+ }
+ return consumed;
+ }
+ /**
+ * Signal to the parser that the end of the input was reached.
+ *
+ * Remaining data will be emitted and relevant errors will be produced.
+ *
+ * @returns The number of characters consumed.
+ */
+ end() {
+ switch (this.state) {
+ case 4 /* NamedEntity */: {
+ return this.result !== 0 && (this.decodeMode !== 2 /* Attribute */ || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
+ }
+ // Otherwise, emit a numeric entity if we have one.
+ case 2 /* NumericDecimal */: {
+ return this.emitNumericEntity(0, 2);
+ }
+ case 3 /* NumericHex */: {
+ return this.emitNumericEntity(0, 3);
+ }
+ case 1 /* NumericStart */: {
+ this.errors?.absenceOfDigitsInNumericCharacterReference(
+ this.consumed
+ );
+ return 0;
+ }
+ case 0 /* EntityStart */: {
+ return 0;
+ }
+ }
+ }
+ };
+ function getDecoder(decodeTree) {
+ let ret = "";
+ const decoder = new EntityDecoder(
+ decodeTree,
+ (str) => ret += fromCodePoint(str)
+ );
+ return function decodeWithTrie(str, decodeMode) {
+ let lastIndex = 0;
+ let offset = 0;
+ while ((offset = str.indexOf("&", offset)) >= 0) {
+ ret += str.slice(lastIndex, offset);
+ decoder.startEntity(decodeMode);
+ const len = decoder.write(
+ str,
+ // Skip the "&"
+ offset + 1
+ );
+ if (len < 0) {
+ lastIndex = offset + decoder.end();
+ break;
+ }
+ lastIndex = offset + len;
+ offset = len === 0 ? lastIndex + 1 : lastIndex;
+ }
+ const result = ret + str.slice(lastIndex);
+ ret = "";
+ return result;
+ };
+ }
+ function determineBranch(decodeTree, current, nodeIdx, char) {
+ const branchCount = (current & 16256 /* BRANCH_LENGTH */) >> 7;
+ const jumpOffset = current & 127 /* JUMP_TABLE */;
+ if (branchCount === 0) {
+ return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
+ }
+ if (jumpOffset) {
+ const value = char - jumpOffset;
+ return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIdx + value] - 1;
+ }
+ let lo = nodeIdx;
+ let hi = lo + branchCount - 1;
+ while (lo <= hi) {
+ const mid = lo + hi >>> 1;
+ const midVal = decodeTree[mid];
+ if (midVal < char) {
+ lo = mid + 1;
+ } else if (midVal > char) {
+ hi = mid - 1;
+ } else {
+ return decodeTree[mid + branchCount];
+ }
+ }
+ return -1;
+ }
+ var htmlDecoder = getDecoder(decode_data_html_default);
+ var xmlDecoder = getDecoder(decode_data_xml_default);
+ function decodeHTML(str, mode = 0 /* Legacy */) {
+ return htmlDecoder(str, mode);
+ }
+ function decodeHTMLStrict(str) {
+ return htmlDecoder(str, 1 /* Strict */);
+ }
+
+ // third_party/editor/markdown-it/lib/common/utils.mjs
+ function _class(obj) {
+ return Object.prototype.toString.call(obj);
+ }
+ function isString(obj) {
+ return _class(obj) === "[object String]";
+ }
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
+ function has(object, key) {
+ return _hasOwnProperty.call(object, key);
+ }
+ function assign(obj) {
+ const sources = Array.prototype.slice.call(arguments, 1);
+ sources.forEach(function(source) {
+ if (!source) {
+ return;
+ }
+ if (typeof source !== "object") {
+ throw new TypeError(source + "must be object");
+ }
+ Object.keys(source).forEach(function(key) {
+ obj[key] = source[key];
+ });
+ });
+ return obj;
+ }
+ function arrayReplaceAt(src, pos, newElements) {
+ return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
+ }
+ function isValidEntityCode(c) {
+ if (c >= 55296 && c <= 57343) {
+ return false;
+ }
+ if (c >= 64976 && c <= 65007) {
+ return false;
+ }
+ if ((c & 65535) === 65535 || (c & 65535) === 65534) {
+ return false;
+ }
+ if (c >= 0 && c <= 8) {
+ return false;
+ }
+ if (c === 11) {
+ return false;
+ }
+ if (c >= 14 && c <= 31) {
+ return false;
+ }
+ if (c >= 127 && c <= 159) {
+ return false;
+ }
+ if (c > 1114111) {
+ return false;
+ }
+ return true;
+ }
+ function fromCodePoint2(c) {
+ if (c > 65535) {
+ c -= 65536;
+ const surrogate1 = 55296 + (c >> 10);
+ const surrogate2 = 56320 + (c & 1023);
+ return String.fromCharCode(surrogate1, surrogate2);
+ }
+ return String.fromCharCode(c);
+ }
+ var UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
+ var ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;
+ var UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, "gi");
+ var DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;
+ function replaceEntityPattern(match2, name) {
+ if (name.charCodeAt(0) === 35 && DIGITAL_ENTITY_TEST_RE.test(name)) {
+ const code4 = name[1].toLowerCase() === "x" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
+ if (isValidEntityCode(code4)) {
+ return fromCodePoint2(code4);
+ }
+ return match2;
+ }
+ const decoded = decodeHTML(match2);
+ if (decoded !== match2) {
+ return decoded;
+ }
+ return match2;
+ }
+ function unescapeMd(str) {
+ if (str.indexOf("\\") < 0) {
+ return str;
+ }
+ return str.replace(UNESCAPE_MD_RE, "$1");
+ }
+ function unescapeAll(str) {
+ if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) {
+ return str;
+ }
+ return str.replace(UNESCAPE_ALL_RE, function(match2, escaped, entity2) {
+ if (escaped) {
+ return escaped;
+ }
+ return replaceEntityPattern(match2, entity2);
+ });
+ }
+ var HTML_ESCAPE_TEST_RE = /[&<>"]/;
+ var HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
+ var HTML_REPLACEMENTS = {
+ "&": "&",
+ "<": "<",
+ ">": ">",
+ '"': """
+ };
+ function replaceUnsafeChar(ch) {
+ return HTML_REPLACEMENTS[ch];
+ }
+ function escapeHtml(str) {
+ if (HTML_ESCAPE_TEST_RE.test(str)) {
+ return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
+ }
+ return str;
+ }
+ var REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g;
+ function escapeRE(str) {
+ return str.replace(REGEXP_ESCAPE_RE, "\\$&");
+ }
+ function isSpace(code4) {
+ switch (code4) {
+ case 9:
+ case 32:
+ return true;
+ }
+ return false;
+ }
+ function isWhiteSpace(code4) {
+ if (code4 >= 8192 && code4 <= 8202) {
+ return true;
+ }
+ switch (code4) {
+ case 9:
+ // \t
+ case 10:
+ // \n
+ case 11:
+ // \v
+ case 12:
+ // \f
+ case 13:
+ // \r
+ case 32:
+ case 160:
+ case 5760:
+ case 8239:
+ case 8287:
+ case 12288:
+ return true;
+ }
+ return false;
+ }
+ function isPunctChar(ch) {
+ return regex_default4.test(ch) || regex_default5.test(ch);
+ }
+ function isPunctCharCode(code4) {
+ return isPunctChar(fromCodePoint2(code4));
+ }
+ function isMdAsciiPunct(ch) {
+ switch (ch) {
+ case 33:
+ case 34:
+ case 35:
+ case 36:
+ case 37:
+ case 38:
+ case 39:
+ case 40:
+ case 41:
+ case 42:
+ case 43:
+ case 44:
+ case 45:
+ case 46:
+ case 47:
+ case 58:
+ case 59:
+ case 60:
+ case 61:
+ case 62:
+ case 63:
+ case 64:
+ case 91:
+ case 92:
+ case 93:
+ case 94:
+ case 95:
+ case 96:
+ case 123:
+ case 124:
+ case 125:
+ case 126:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function normalizeReference(str) {
+ str = str.trim().replace(/\s+/g, " ");
+ if ("\u1E9E".toLowerCase() === "\u1E7E") {
+ str = str.replace(/ẞ/g, "\xDF");
+ }
+ return str.toLowerCase().toUpperCase();
+ }
+ function isAsciiTrimmable(c) {
+ return c === 32 || c === 9 || c === 10 || c === 13;
+ }
+ function asciiTrim(str) {
+ let start = 0;
+ for (; start < str.length; start++) {
+ if (!isAsciiTrimmable(str.charCodeAt(start))) {
+ break;
+ }
+ }
+ let end = str.length - 1;
+ for (; end >= start; end--) {
+ if (!isAsciiTrimmable(str.charCodeAt(end))) {
+ break;
+ }
+ }
+ return str.slice(start, end + 1);
+ }
+ var lib = { mdurl: mdurl_exports, ucmicro: uc_exports };
+
+ // third_party/editor/markdown-it/lib/helpers/index.mjs
+ var helpers_exports = {};
+ __export(helpers_exports, {
+ parseLinkDestination: () => parseLinkDestination,
+ parseLinkLabel: () => parseLinkLabel,
+ parseLinkTitle: () => parseLinkTitle
+ });
+
+ // third_party/editor/markdown-it/lib/helpers/parse_link_label.mjs
+ function parseLinkLabel(state, start, disableNested) {
+ let level, found2, marker, prevPos;
+ const max = state.posMax;
+ const oldPos = state.pos;
+ state.pos = start + 1;
+ level = 1;
+ while (state.pos < max) {
+ marker = state.src.charCodeAt(state.pos);
+ if (marker === 93) {
+ level--;
+ if (level === 0) {
+ found2 = true;
+ break;
+ }
+ }
+ prevPos = state.pos;
+ state.md.inline.skipToken(state);
+ if (marker === 91) {
+ if (prevPos === state.pos - 1) {
+ level++;
+ } else if (disableNested) {
+ state.pos = oldPos;
+ return -1;
+ }
+ }
+ }
+ let labelEnd = -1;
+ if (found2) {
+ labelEnd = state.pos;
+ }
+ state.pos = oldPos;
+ return labelEnd;
+ }
+
+ // third_party/editor/markdown-it/lib/helpers/parse_link_destination.mjs
+ function parseLinkDestination(str, start, max) {
+ let code4;
+ let pos = start;
+ const result = {
+ ok: false,
+ pos: 0,
+ str: ""
+ };
+ if (str.charCodeAt(pos) === 60) {
+ pos++;
+ while (pos < max) {
+ code4 = str.charCodeAt(pos);
+ if (code4 === 10) {
+ return result;
+ }
+ if (code4 === 60) {
+ return result;
+ }
+ if (code4 === 62) {
+ result.pos = pos + 1;
+ result.str = unescapeAll(str.slice(start + 1, pos));
+ result.ok = true;
+ return result;
+ }
+ if (code4 === 92 && pos + 1 < max) {
+ pos += 2;
+ continue;
+ }
+ pos++;
+ }
+ return result;
+ }
+ let level = 0;
+ while (pos < max) {
+ code4 = str.charCodeAt(pos);
+ if (code4 === 32) {
+ break;
+ }
+ if (code4 < 32 || code4 === 127) {
+ break;
+ }
+ if (code4 === 92 && pos + 1 < max) {
+ if (str.charCodeAt(pos + 1) === 32) {
+ pos++;
+ continue;
+ }
+ pos += 2;
+ continue;
+ }
+ if (code4 === 40) {
+ level++;
+ if (level > 32) {
+ return result;
+ }
+ }
+ if (code4 === 41) {
+ if (level === 0) {
+ break;
+ }
+ level--;
+ }
+ pos++;
+ }
+ if (start === pos) {
+ return result;
+ }
+ if (level !== 0) {
+ return result;
+ }
+ result.str = unescapeAll(str.slice(start, pos));
+ result.pos = pos;
+ result.ok = true;
+ return result;
+ }
+
+ // third_party/editor/markdown-it/lib/helpers/parse_link_title.mjs
+ function parseLinkTitle(str, start, max, prev_state) {
+ let code4;
+ let pos = start;
+ const state = {
+ // if `true`, this is a valid link title
+ ok: false,
+ // if `true`, this link can be continued on the next line
+ can_continue: false,
+ // if `ok`, it's the position of the first character after the closing marker
+ pos: 0,
+ // if `ok`, it's the unescaped title
+ str: "",
+ // expected closing marker character code
+ marker: 0
+ };
+ if (prev_state) {
+ state.str = prev_state.str;
+ state.marker = prev_state.marker;
+ } else {
+ if (pos >= max) {
+ return state;
+ }
+ let marker = str.charCodeAt(pos);
+ if (marker !== 34 && marker !== 39 && marker !== 40) {
+ return state;
+ }
+ start++;
+ pos++;
+ if (marker === 40) {
+ marker = 41;
+ }
+ state.marker = marker;
+ }
+ while (pos < max) {
+ code4 = str.charCodeAt(pos);
+ if (code4 === state.marker) {
+ state.pos = pos + 1;
+ state.str += unescapeAll(str.slice(start, pos));
+ state.ok = true;
+ return state;
+ } else if (code4 === 40 && state.marker === 41) {
+ return state;
+ } else if (code4 === 92 && pos + 1 < max) {
+ pos++;
+ }
+ pos++;
+ }
+ state.can_continue = true;
+ state.str += unescapeAll(str.slice(start, pos));
+ return state;
+ }
+
+ // third_party/editor/markdown-it/lib/renderer.mjs
+ var default_rules = {};
+ default_rules.code_inline = function(tokens, idx, options, env, slf) {
+ const token = tokens[idx];
+ return "" + escapeHtml(token.content) + "";
+ };
+ default_rules.code_block = function(tokens, idx, options, env, slf) {
+ const token = tokens[idx];
+ return "" + escapeHtml(tokens[idx].content) + " \n";
+ };
+ default_rules.fence = function(tokens, idx, options, env, slf) {
+ const token = tokens[idx];
+ const info = token.info ? unescapeAll(token.info).trim() : "";
+ let langName = "";
+ let langAttrs = "";
+ if (info) {
+ const arr = info.split(/(\s+)/g);
+ langName = arr[0];
+ langAttrs = arr.slice(2).join("");
+ }
+ let highlighted;
+ if (options.highlight) {
+ highlighted = options.highlight(token.content, langName, langAttrs) || escapeHtml(token.content);
+ } else {
+ highlighted = escapeHtml(token.content);
+ }
+ if (highlighted.indexOf("${highlighted}
+`;
+ }
+ return `${highlighted}
+`;
+ };
+ default_rules.image = function(tokens, idx, options, env, slf) {
+ const token = tokens[idx];
+ token.attrs[token.attrIndex("alt")][1] = slf.renderInlineAsText(token.children, options, env);
+ return slf.renderToken(tokens, idx, options);
+ };
+ default_rules.hardbreak = function(tokens, idx, options) {
+ return options.xhtmlOut ? " \n" : " \n";
+ };
+ default_rules.softbreak = function(tokens, idx, options) {
+ return options.breaks ? options.xhtmlOut ? " \n" : " \n" : "\n";
+ };
+ default_rules.text = function(tokens, idx) {
+ return escapeHtml(tokens[idx].content);
+ };
+ default_rules.html_block = function(tokens, idx) {
+ return tokens[idx].content;
+ };
+ default_rules.html_inline = function(tokens, idx) {
+ return tokens[idx].content;
+ };
+ function Renderer() {
+ this.rules = assign({}, default_rules);
+ }
+ Renderer.prototype.renderAttrs = function renderAttrs(token) {
+ let i2, l, result;
+ if (!token.attrs) {
+ return "";
+ }
+ result = "";
+ for (i2 = 0, l = token.attrs.length; i2 < l; i2++) {
+ result += " " + escapeHtml(token.attrs[i2][0]) + '="' + escapeHtml(token.attrs[i2][1]) + '"';
+ }
+ return result;
+ };
+ Renderer.prototype.renderToken = function renderToken(tokens, idx, options) {
+ const token = tokens[idx];
+ let result = "";
+ if (token.hidden) {
+ return "";
+ }
+ if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) {
+ result += "\n";
+ }
+ result += (token.nesting === -1 ? "" : "<") + token.tag;
+ result += this.renderAttrs(token);
+ if (token.nesting === 0 && options.xhtmlOut) {
+ result += " /";
+ }
+ let needLf = false;
+ if (token.block) {
+ needLf = true;
+ if (token.nesting === 1) {
+ if (idx + 1 < tokens.length) {
+ const nextToken = tokens[idx + 1];
+ if (nextToken.type === "inline" || nextToken.hidden) {
+ needLf = false;
+ } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) {
+ needLf = false;
+ }
+ }
+ }
+ }
+ result += needLf ? ">\n" : ">";
+ return result;
+ };
+ Renderer.prototype.renderInline = function(tokens, options, env) {
+ let result = "";
+ const rules2 = this.rules;
+ for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
+ const type = tokens[i2].type;
+ if (typeof rules2[type] !== "undefined") {
+ result += rules2[type](tokens, i2, options, env, this);
+ } else {
+ result += this.renderToken(tokens, i2, options);
+ }
+ }
+ return result;
+ };
+ Renderer.prototype.renderInlineAsText = function(tokens, options, env) {
+ let result = "";
+ for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
+ switch (tokens[i2].type) {
+ case "text":
+ result += tokens[i2].content;
+ break;
+ case "image":
+ result += this.renderInlineAsText(tokens[i2].children, options, env);
+ break;
+ case "html_inline":
+ case "html_block":
+ result += tokens[i2].content;
+ break;
+ case "softbreak":
+ case "hardbreak":
+ result += "\n";
+ break;
+ default:
+ }
+ }
+ return result;
+ };
+ Renderer.prototype.render = function(tokens, options, env) {
+ let result = "";
+ const rules2 = this.rules;
+ for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
+ const type = tokens[i2].type;
+ if (type === "inline") {
+ result += this.renderInline(tokens[i2].children, options, env);
+ } else if (typeof rules2[type] !== "undefined") {
+ result += rules2[type](tokens, i2, options, env, this);
+ } else {
+ result += this.renderToken(tokens, i2, options, env);
+ }
+ }
+ return result;
+ };
+ var renderer_default = Renderer;
+
+ // third_party/editor/markdown-it/lib/ruler.mjs
+ function Ruler() {
+ this.__rules__ = [];
+ this.__cache__ = null;
+ }
+ Ruler.prototype.__find__ = function(name) {
+ for (let i2 = 0; i2 < this.__rules__.length; i2++) {
+ if (this.__rules__[i2].name === name) {
+ return i2;
+ }
+ }
+ return -1;
+ };
+ Ruler.prototype.__compile__ = function() {
+ const self = this;
+ const chains = [""];
+ self.__rules__.forEach(function(rule) {
+ if (!rule.enabled) {
+ return;
+ }
+ rule.alt.forEach(function(altName) {
+ if (chains.indexOf(altName) < 0) {
+ chains.push(altName);
+ }
+ });
+ });
+ self.__cache__ = {};
+ chains.forEach(function(chain) {
+ self.__cache__[chain] = [];
+ self.__rules__.forEach(function(rule) {
+ if (!rule.enabled) {
+ return;
+ }
+ if (chain && rule.alt.indexOf(chain) < 0) {
+ return;
+ }
+ self.__cache__[chain].push(rule.fn);
+ });
+ });
+ };
+ Ruler.prototype.at = function(name, fn, options) {
+ const index = this.__find__(name);
+ const opt = options || {};
+ if (index === -1) {
+ throw new Error("Parser rule not found: " + name);
+ }
+ this.__rules__[index].fn = fn;
+ this.__rules__[index].alt = opt.alt || [];
+ this.__cache__ = null;
+ };
+ Ruler.prototype.before = function(beforeName, ruleName, fn, options) {
+ const index = this.__find__(beforeName);
+ const opt = options || {};
+ if (index === -1) {
+ throw new Error("Parser rule not found: " + beforeName);
+ }
+ this.__rules__.splice(index, 0, {
+ name: ruleName,
+ enabled: true,
+ fn,
+ alt: opt.alt || []
+ });
+ this.__cache__ = null;
+ };
+ Ruler.prototype.after = function(afterName, ruleName, fn, options) {
+ const index = this.__find__(afterName);
+ const opt = options || {};
+ if (index === -1) {
+ throw new Error("Parser rule not found: " + afterName);
+ }
+ this.__rules__.splice(index + 1, 0, {
+ name: ruleName,
+ enabled: true,
+ fn,
+ alt: opt.alt || []
+ });
+ this.__cache__ = null;
+ };
+ Ruler.prototype.push = function(ruleName, fn, options) {
+ const opt = options || {};
+ this.__rules__.push({
+ name: ruleName,
+ enabled: true,
+ fn,
+ alt: opt.alt || []
+ });
+ this.__cache__ = null;
+ };
+ Ruler.prototype.enable = function(list2, ignoreInvalid) {
+ if (!Array.isArray(list2)) {
+ list2 = [list2];
+ }
+ const result = [];
+ list2.forEach(function(name) {
+ const idx = this.__find__(name);
+ if (idx < 0) {
+ if (ignoreInvalid) {
+ return;
+ }
+ throw new Error("Rules manager: invalid rule name " + name);
+ }
+ this.__rules__[idx].enabled = true;
+ result.push(name);
+ }, this);
+ this.__cache__ = null;
+ return result;
+ };
+ Ruler.prototype.enableOnly = function(list2, ignoreInvalid) {
+ if (!Array.isArray(list2)) {
+ list2 = [list2];
+ }
+ this.__rules__.forEach(function(rule) {
+ rule.enabled = false;
+ });
+ this.enable(list2, ignoreInvalid);
+ };
+ Ruler.prototype.disable = function(list2, ignoreInvalid) {
+ if (!Array.isArray(list2)) {
+ list2 = [list2];
+ }
+ const result = [];
+ list2.forEach(function(name) {
+ const idx = this.__find__(name);
+ if (idx < 0) {
+ if (ignoreInvalid) {
+ return;
+ }
+ throw new Error("Rules manager: invalid rule name " + name);
+ }
+ this.__rules__[idx].enabled = false;
+ result.push(name);
+ }, this);
+ this.__cache__ = null;
+ return result;
+ };
+ Ruler.prototype.getRules = function(chainName) {
+ if (this.__cache__ === null) {
+ this.__compile__();
+ }
+ return this.__cache__[chainName] || [];
+ };
+ var ruler_default = Ruler;
+
+ // third_party/editor/markdown-it/lib/token.mjs
+ function Token(type, tag, nesting) {
+ this.type = type;
+ this.tag = tag;
+ this.attrs = null;
+ this.map = null;
+ this.nesting = nesting;
+ this.level = 0;
+ this.children = null;
+ this.content = "";
+ this.markup = "";
+ this.info = "";
+ this.meta = null;
+ this.block = false;
+ this.hidden = false;
+ }
+ Token.prototype.attrIndex = function attrIndex(name) {
+ if (!this.attrs) {
+ return -1;
+ }
+ const attrs2 = this.attrs;
+ for (let i2 = 0, len = attrs2.length; i2 < len; i2++) {
+ if (attrs2[i2][0] === name) {
+ return i2;
+ }
+ }
+ return -1;
+ };
+ Token.prototype.attrPush = function attrPush(attrData) {
+ if (this.attrs) {
+ this.attrs.push(attrData);
+ } else {
+ this.attrs = [attrData];
+ }
+ };
+ Token.prototype.attrSet = function attrSet(name, value) {
+ const idx = this.attrIndex(name);
+ const attrData = [name, value];
+ if (idx < 0) {
+ this.attrPush(attrData);
+ } else {
+ this.attrs[idx] = attrData;
+ }
+ };
+ Token.prototype.attrGet = function attrGet(name) {
+ const idx = this.attrIndex(name);
+ let value = null;
+ if (idx >= 0) {
+ value = this.attrs[idx][1];
+ }
+ return value;
+ };
+ Token.prototype.attrJoin = function attrJoin(name, value) {
+ const idx = this.attrIndex(name);
+ if (idx < 0) {
+ this.attrPush([name, value]);
+ } else {
+ this.attrs[idx][1] = this.attrs[idx][1] + " " + value;
+ }
+ };
+ var token_default = Token;
+
+ // third_party/editor/markdown-it/lib/rules_core/state_core.mjs
+ function StateCore(src, md, env) {
+ this.src = src;
+ this.env = env;
+ this.tokens = [];
+ this.inlineMode = false;
+ this.md = md;
+ }
+ StateCore.prototype.Token = token_default;
+ var state_core_default = StateCore;
+
+ // third_party/editor/markdown-it/lib/rules_core/normalize.mjs
+ var NEWLINES_RE = /\r\n?|\n/g;
+ var NULL_RE = /\0/g;
+ function normalize2(state) {
+ let str;
+ str = state.src.replace(NEWLINES_RE, "\n");
+ str = str.replace(NULL_RE, "\uFFFD");
+ state.src = str;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_core/block.mjs
+ function block(state) {
+ let token;
+ if (state.inlineMode) {
+ token = new state.Token("inline", "", 0);
+ token.content = state.src;
+ token.map = [0, 1];
+ token.children = [];
+ state.tokens.push(token);
+ } else {
+ state.md.block.parse(state.src, state.md, state.env, state.tokens);
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/rules_core/inline.mjs
+ function inline(state) {
+ const tokens = state.tokens;
+ for (let i2 = 0, l = tokens.length; i2 < l; i2++) {
+ const tok = tokens[i2];
+ if (tok.type === "inline") {
+ state.md.inline.parse(tok.content, state.md, state.env, tok.children);
+ }
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/rules_core/linkify.mjs
+ function isLinkOpen(str) {
+ return /^\s]/i.test(str);
+ }
+ function isLinkClose(str) {
+ return /^<\/a\s*>/i.test(str);
+ }
+ function linkify(state) {
+ const blockTokens = state.tokens;
+ if (!state.md.options.linkify) {
+ return;
+ }
+ for (let j = 0, l = blockTokens.length; j < l; j++) {
+ if (blockTokens[j].type !== "inline" || !state.md.linkify.pretest(blockTokens[j].content)) {
+ continue;
+ }
+ const tokens = blockTokens[j].children;
+ const replacements = [];
+ let htmlLinkLevel = 0;
+ for (let i2 = tokens.length - 1; i2 >= 0; i2--) {
+ const currentToken = tokens[i2];
+ if (currentToken.type === "link_close") {
+ i2--;
+ while (tokens[i2].level !== currentToken.level && tokens[i2].type !== "link_open") {
+ i2--;
+ }
+ continue;
+ }
+ if (currentToken.type === "html_inline") {
+ if (isLinkOpen(currentToken.content) && htmlLinkLevel > 0) {
+ htmlLinkLevel--;
+ }
+ if (isLinkClose(currentToken.content)) {
+ htmlLinkLevel++;
+ }
+ }
+ if (htmlLinkLevel > 0) {
+ continue;
+ }
+ if (currentToken.type === "text" && state.md.linkify.test(currentToken.content)) {
+ const text2 = currentToken.content;
+ let links = state.md.linkify.match(text2);
+ const nodes = [];
+ let level = currentToken.level;
+ let lastPos = 0;
+ if (links.length > 0 && links[0].index === 0 && i2 > 0 && tokens[i2 - 1].type === "text_special") {
+ links = links.slice(1);
+ }
+ for (let ln = 0; ln < links.length; ln++) {
+ const url = links[ln].url;
+ const fullUrl = state.md.normalizeLink(url);
+ if (!state.md.validateLink(fullUrl)) {
+ continue;
+ }
+ let urlText = links[ln].text;
+ if (!links[ln].schema) {
+ urlText = state.md.normalizeLinkText("http://" + urlText).replace(/^http:\/\//, "");
+ } else if (links[ln].schema === "mailto:" && !/^mailto:/i.test(urlText)) {
+ urlText = state.md.normalizeLinkText("mailto:" + urlText).replace(/^mailto:/, "");
+ } else {
+ urlText = state.md.normalizeLinkText(urlText);
+ }
+ const pos = links[ln].index;
+ if (pos > lastPos) {
+ const token = new state.Token("text", "", 0);
+ token.content = text2.slice(lastPos, pos);
+ token.level = level;
+ nodes.push(token);
+ }
+ const token_o = new state.Token("link_open", "a", 1);
+ token_o.attrs = [["href", fullUrl]];
+ token_o.level = level++;
+ token_o.markup = "linkify";
+ token_o.info = "auto";
+ nodes.push(token_o);
+ const token_t = new state.Token("text", "", 0);
+ token_t.content = urlText;
+ token_t.level = level;
+ nodes.push(token_t);
+ const token_c = new state.Token("link_close", "a", -1);
+ token_c.level = --level;
+ token_c.markup = "linkify";
+ token_c.info = "auto";
+ nodes.push(token_c);
+ lastPos = links[ln].lastIndex;
+ }
+ if (lastPos < text2.length) {
+ const token = new state.Token("text", "", 0);
+ token.content = text2.slice(lastPos);
+ token.level = level;
+ nodes.push(token);
+ }
+ replacements.push({ index: i2, nodes });
+ }
+ }
+ if (replacements.length > 0) {
+ let newTokensLength = tokens.length;
+ for (const replacement of replacements) {
+ newTokensLength += replacement.nodes.length - 1;
+ }
+ const newTokens = new Array(newTokensLength);
+ let replacementIndex = 0;
+ let newTokenIndex = 0;
+ replacements.reverse();
+ for (let i2 = 0; i2 < tokens.length; i2++) {
+ const replacement = replacements[replacementIndex];
+ if (replacement?.index === i2) {
+ for (const node of replacement.nodes) {
+ newTokens[newTokenIndex++] = node;
+ }
+ replacementIndex++;
+ } else {
+ newTokens[newTokenIndex++] = tokens[i2];
+ }
+ }
+ blockTokens[j].children = newTokens;
+ }
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/rules_core/replacements.mjs
+ var RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
+ var SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i;
+ var SCOPED_ABBR_RE = /\((c|tm|r)\)/ig;
+ var SCOPED_ABBR = {
+ c: "\xA9",
+ r: "\xAE",
+ tm: "\u2122"
+ };
+ function replaceFn(match2, name) {
+ return SCOPED_ABBR[name.toLowerCase()];
+ }
+ function replace_scoped(inlineTokens) {
+ let inside_autolink = 0;
+ for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
+ const token = inlineTokens[i2];
+ if (token.type === "text" && !inside_autolink) {
+ token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn);
+ }
+ if (token.type === "link_open" && token.info === "auto") {
+ inside_autolink--;
+ }
+ if (token.type === "link_close" && token.info === "auto") {
+ inside_autolink++;
+ }
+ }
+ }
+ function replace_rare(inlineTokens) {
+ let inside_autolink = 0;
+ for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
+ const token = inlineTokens[i2];
+ if (token.type === "text" && !inside_autolink) {
+ if (RARE_RE.test(token.content)) {
+ token.content = token.content.replace(/\+-/g, "\xB1").replace(/\.{2,}/g, "\u2026").replace(/([?!])…/g, "$1..").replace(/([?!]){4,}/g, "$1$1$1").replace(/,{2,}/g, ",").replace(/(^|[^-])---(?=[^-]|$)/mg, "$1\u2014").replace(/(^|\s)--(?=\s|$)/mg, "$1\u2013").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, "$1\u2013");
+ }
+ }
+ if (token.type === "link_open" && token.info === "auto") {
+ inside_autolink--;
+ }
+ if (token.type === "link_close" && token.info === "auto") {
+ inside_autolink++;
+ }
+ }
+ }
+ function replace2(state) {
+ let blkIdx;
+ if (!state.md.options.typographer) {
+ return;
+ }
+ for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
+ if (state.tokens[blkIdx].type !== "inline") {
+ continue;
+ }
+ if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
+ replace_scoped(state.tokens[blkIdx].children);
+ }
+ if (RARE_RE.test(state.tokens[blkIdx].content)) {
+ replace_rare(state.tokens[blkIdx].children);
+ }
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/rules_core/smartquotes.mjs
+ var QUOTE_TEST_RE = /['"]/;
+ var QUOTE_RE = /['"]/g;
+ var APOSTROPHE = "\u2019";
+ var MAX_OPENERS = 1e3;
+ function truncateStack(stack, heads, length) {
+ while (stack.length > length) {
+ const item = stack.pop();
+ if (item.isSingleQuote) {
+ heads.single = item.prevSameQuoteIdx;
+ } else {
+ heads.double = item.prevSameQuoteIdx;
+ }
+ }
+ }
+ function addReplacement(replacements, tokenIdx, pos, ch) {
+ if (!replacements[tokenIdx]) {
+ replacements[tokenIdx] = [];
+ }
+ replacements[tokenIdx].push({ pos, ch });
+ }
+ function applyReplacements(str, replacements) {
+ let result = "";
+ let lastPos = 0;
+ replacements.sort((a, b) => a.pos - b.pos);
+ for (let i2 = 0; i2 < replacements.length; i2++) {
+ const replacement = replacements[i2];
+ result += str.slice(lastPos, replacement.pos) + replacement.ch;
+ lastPos = replacement.pos + 1;
+ }
+ return result + str.slice(lastPos);
+ }
+ function process_inlines(tokens, state) {
+ let j;
+ const stack = [];
+ const heads = { single: -1, double: -1 };
+ const replacements = {};
+ for (let i2 = 0; i2 < tokens.length; i2++) {
+ const token = tokens[i2];
+ const thisLevel = tokens[i2].level;
+ for (j = stack.length - 1; j >= 0; j--) {
+ if (stack[j].level <= thisLevel) {
+ break;
+ }
+ }
+ truncateStack(stack, heads, j + 1);
+ if (token.type !== "text") {
+ continue;
+ }
+ const text2 = token.content;
+ let pos = 0;
+ const max = text2.length;
+ OUTER:
+ while (pos < max) {
+ QUOTE_RE.lastIndex = pos;
+ const t = QUOTE_RE.exec(text2);
+ if (!t) {
+ break;
+ }
+ let canOpen = true;
+ let canClose = true;
+ pos = t.index + 1;
+ const isSingle = t[0] === "'";
+ let lastChar = 32;
+ if (t.index - 1 >= 0) {
+ lastChar = text2.charCodeAt(t.index - 1);
+ } else {
+ for (j = i2 - 1; j >= 0; j--) {
+ if (tokens[j].type === "softbreak" || tokens[j].type === "hardbreak") break;
+ if (!tokens[j].content) continue;
+ lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1);
+ break;
+ }
+ }
+ let nextChar = 32;
+ if (pos < max) {
+ nextChar = text2.charCodeAt(pos);
+ } else {
+ for (j = i2 + 1; j < tokens.length; j++) {
+ if (tokens[j].type === "softbreak" || tokens[j].type === "hardbreak") break;
+ if (!tokens[j].content) continue;
+ nextChar = tokens[j].content.charCodeAt(0);
+ break;
+ }
+ }
+ const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctCharCode(lastChar);
+ const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctCharCode(nextChar);
+ const isLastWhiteSpace = isWhiteSpace(lastChar);
+ const isNextWhiteSpace = isWhiteSpace(nextChar);
+ if (isNextWhiteSpace) {
+ canOpen = false;
+ } else if (isNextPunctChar) {
+ if (!(isLastWhiteSpace || isLastPunctChar)) {
+ canOpen = false;
+ }
+ }
+ if (isLastWhiteSpace) {
+ canClose = false;
+ } else if (isLastPunctChar) {
+ if (!(isNextWhiteSpace || isNextPunctChar)) {
+ canClose = false;
+ }
+ }
+ if (nextChar === 34 && t[0] === '"') {
+ if (lastChar >= 48 && lastChar <= 57) {
+ canClose = canOpen = false;
+ }
+ }
+ if (canOpen && canClose) {
+ canOpen = isLastPunctChar;
+ canClose = isNextPunctChar;
+ }
+ if (!canOpen && !canClose) {
+ if (isSingle) {
+ addReplacement(replacements, i2, t.index, APOSTROPHE);
+ }
+ continue;
+ }
+ if (canClose) {
+ j = isSingle ? heads.single : heads.double;
+ if (j >= 0 && stack[j].level === thisLevel) {
+ const item = stack[j];
+ let openQuote;
+ let closeQuote;
+ if (isSingle) {
+ openQuote = state.md.options.quotes[2];
+ closeQuote = state.md.options.quotes[3];
+ } else {
+ openQuote = state.md.options.quotes[0];
+ closeQuote = state.md.options.quotes[1];
+ }
+ addReplacement(replacements, i2, t.index, closeQuote);
+ addReplacement(replacements, item.tokenIdx, item.contentPos, openQuote);
+ truncateStack(stack, heads, j);
+ continue OUTER;
+ }
+ }
+ if (canOpen) {
+ if (stack.length >= MAX_OPENERS) {
+ return;
+ }
+ stack.push({
+ tokenIdx: i2,
+ contentPos: t.index,
+ isSingleQuote: isSingle,
+ level: thisLevel,
+ // stack index of the previous opener of the same quote type, -1 if none
+ prevSameQuoteIdx: isSingle ? heads.single : heads.double
+ });
+ if (isSingle) {
+ heads.single = stack.length - 1;
+ } else {
+ heads.double = stack.length - 1;
+ }
+ } else if (canClose && isSingle) {
+ addReplacement(replacements, i2, t.index, APOSTROPHE);
+ }
+ }
+ }
+ Object.keys(replacements).forEach(function(tokenIdx) {
+ tokens[tokenIdx].content = applyReplacements(tokens[tokenIdx].content, replacements[tokenIdx]);
+ });
+ }
+ function smartquotes(state) {
+ if (!state.md.options.typographer) {
+ return;
+ }
+ for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
+ if (state.tokens[blkIdx].type !== "inline" || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
+ continue;
+ }
+ process_inlines(state.tokens[blkIdx].children, state);
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/rules_core/text_join.mjs
+ function text_join(state) {
+ let curr, last;
+ const blockTokens = state.tokens;
+ const l = blockTokens.length;
+ for (let j = 0; j < l; j++) {
+ if (blockTokens[j].type !== "inline") continue;
+ const tokens = blockTokens[j].children;
+ const max = tokens.length;
+ for (curr = 0; curr < max; curr++) {
+ if (tokens[curr].type === "text_special") {
+ tokens[curr].type = "text";
+ }
+ }
+ for (curr = last = 0; curr < max; curr++) {
+ if (tokens[curr].type === "text" && curr + 1 < max && tokens[curr + 1].type === "text") {
+ tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
+ } else {
+ if (curr !== last) {
+ tokens[last] = tokens[curr];
+ }
+ last++;
+ }
+ }
+ if (curr !== last) {
+ tokens.length = last;
+ }
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/parser_core.mjs
+ var _rules = [
+ ["normalize", normalize2],
+ ["block", block],
+ ["inline", inline],
+ ["linkify", linkify],
+ ["replacements", replace2],
+ ["smartquotes", smartquotes],
+ // `text_join` finds `text_special` tokens (for escape sequences)
+ // and joins them with the rest of the text
+ ["text_join", text_join]
+ ];
+ function Core() {
+ this.ruler = new ruler_default();
+ for (let i2 = 0; i2 < _rules.length; i2++) {
+ this.ruler.push(_rules[i2][0], _rules[i2][1]);
+ }
+ }
+ Core.prototype.process = function(state) {
+ const rules2 = this.ruler.getRules("");
+ for (let i2 = 0, l = rules2.length; i2 < l; i2++) {
+ rules2[i2](state);
+ }
+ };
+ Core.prototype.State = state_core_default;
+ var parser_core_default = Core;
+
+ // third_party/editor/markdown-it/lib/rules_block/state_block.mjs
+ function StateBlock(src, md, env, tokens) {
+ this.src = src;
+ this.md = md;
+ this.env = env;
+ this.tokens = tokens;
+ this.bMarks = [];
+ this.eMarks = [];
+ this.tShift = [];
+ this.sCount = [];
+ this.bsCount = [];
+ this.blkIndent = 0;
+ this.line = 0;
+ this.lineMax = 0;
+ this.tight = false;
+ this.ddIndent = -1;
+ this.listIndent = -1;
+ this.parentType = "root";
+ this.level = 0;
+ const s = this.src;
+ for (let start = 0, pos = 0, indent = 0, offset = 0, len = s.length, indent_found = false; pos < len; pos++) {
+ const ch = s.charCodeAt(pos);
+ if (!indent_found) {
+ if (isSpace(ch)) {
+ indent++;
+ if (ch === 9) {
+ offset += 4 - offset % 4;
+ } else {
+ offset++;
+ }
+ continue;
+ } else {
+ indent_found = true;
+ }
+ }
+ if (ch === 10 || pos === len - 1) {
+ if (ch !== 10) {
+ pos++;
+ }
+ this.bMarks.push(start);
+ this.eMarks.push(pos);
+ this.tShift.push(indent);
+ this.sCount.push(offset);
+ this.bsCount.push(0);
+ indent_found = false;
+ indent = 0;
+ offset = 0;
+ start = pos + 1;
+ }
+ }
+ this.bMarks.push(s.length);
+ this.eMarks.push(s.length);
+ this.tShift.push(0);
+ this.sCount.push(0);
+ this.bsCount.push(0);
+ this.lineMax = this.bMarks.length - 1;
+ }
+ StateBlock.prototype.push = function(type, tag, nesting) {
+ const token = new token_default(type, tag, nesting);
+ token.block = true;
+ if (nesting < 0) this.level--;
+ token.level = this.level;
+ if (nesting > 0) this.level++;
+ this.tokens.push(token);
+ return token;
+ };
+ StateBlock.prototype.isEmpty = function isEmpty(line) {
+ return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];
+ };
+ StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) {
+ for (let max = this.lineMax; from < max; from++) {
+ if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) {
+ break;
+ }
+ }
+ return from;
+ };
+ StateBlock.prototype.skipSpaces = function skipSpaces(pos) {
+ for (let max = this.src.length; pos < max; pos++) {
+ const ch = this.src.charCodeAt(pos);
+ if (!isSpace(ch)) {
+ break;
+ }
+ }
+ return pos;
+ };
+ StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min) {
+ if (pos <= min) {
+ return pos;
+ }
+ while (pos > min) {
+ if (!isSpace(this.src.charCodeAt(--pos))) {
+ return pos + 1;
+ }
+ }
+ return pos;
+ };
+ StateBlock.prototype.skipChars = function skipChars(pos, code4) {
+ for (let max = this.src.length; pos < max; pos++) {
+ if (this.src.charCodeAt(pos) !== code4) {
+ break;
+ }
+ }
+ return pos;
+ };
+ StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code4, min) {
+ if (pos <= min) {
+ return pos;
+ }
+ while (pos > min) {
+ if (code4 !== this.src.charCodeAt(--pos)) {
+ return pos + 1;
+ }
+ }
+ return pos;
+ };
+ StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) {
+ if (begin >= end) {
+ return "";
+ }
+ const queue = new Array(end - begin);
+ for (let i2 = 0, line = begin; line < end; line++, i2++) {
+ let lineIndent = 0;
+ const lineStart = this.bMarks[line];
+ let first = lineStart;
+ let last;
+ if (line + 1 < end || keepLastLF) {
+ last = this.eMarks[line] + 1;
+ } else {
+ last = this.eMarks[line];
+ }
+ while (first < last && lineIndent < indent) {
+ const ch = this.src.charCodeAt(first);
+ if (isSpace(ch)) {
+ if (ch === 9) {
+ lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4;
+ } else {
+ lineIndent++;
+ }
+ } else if (first - lineStart < this.tShift[line]) {
+ lineIndent++;
+ } else {
+ break;
+ }
+ first++;
+ }
+ if (lineIndent > indent) {
+ queue[i2] = new Array(lineIndent - indent + 1).join(" ") + this.src.slice(first, last);
+ } else {
+ queue[i2] = this.src.slice(first, last);
+ }
+ }
+ return queue.join("");
+ };
+ StateBlock.prototype.Token = token_default;
+ var state_block_default = StateBlock;
+
+ // third_party/editor/markdown-it/lib/rules_block/table.mjs
+ var MAX_AUTOCOMPLETED_CELLS = 65536;
+ function getLine(state, line) {
+ const pos = state.bMarks[line] + state.tShift[line];
+ const max = state.eMarks[line];
+ return state.src.slice(pos, max);
+ }
+ function escapedSplit(str) {
+ const result = [];
+ const max = str.length;
+ let pos = 0;
+ let ch = str.charCodeAt(pos);
+ let isEscaped = false;
+ let lastPos = 0;
+ let current = "";
+ while (pos < max) {
+ if (ch === 124) {
+ if (!isEscaped) {
+ result.push(current + str.substring(lastPos, pos));
+ current = "";
+ lastPos = pos + 1;
+ } else {
+ current += str.substring(lastPos, pos - 1);
+ lastPos = pos;
+ }
+ }
+ isEscaped = ch === 92;
+ pos++;
+ ch = str.charCodeAt(pos);
+ }
+ result.push(current + str.substring(lastPos));
+ return result;
+ }
+ function table(state, startLine, endLine, silent) {
+ if (startLine + 2 > endLine) {
+ return false;
+ }
+ let nextLine = startLine + 1;
+ if (state.sCount[nextLine] < state.blkIndent) {
+ return false;
+ }
+ if (state.sCount[nextLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ let pos = state.bMarks[nextLine] + state.tShift[nextLine];
+ if (pos >= state.eMarks[nextLine]) {
+ return false;
+ }
+ const firstCh = state.src.charCodeAt(pos++);
+ if (firstCh !== 124 && firstCh !== 45 && firstCh !== 58) {
+ return false;
+ }
+ if (pos >= state.eMarks[nextLine]) {
+ return false;
+ }
+ const secondCh = state.src.charCodeAt(pos++);
+ if (secondCh !== 124 && secondCh !== 45 && secondCh !== 58 && !isSpace(secondCh)) {
+ return false;
+ }
+ if (firstCh === 45 && isSpace(secondCh)) {
+ return false;
+ }
+ while (pos < state.eMarks[nextLine]) {
+ const ch = state.src.charCodeAt(pos);
+ if (ch !== 124 && ch !== 45 && ch !== 58 && !isSpace(ch)) {
+ return false;
+ }
+ pos++;
+ }
+ let lineText = getLine(state, startLine + 1);
+ let columns = lineText.split("|");
+ const aligns = [];
+ for (let i2 = 0; i2 < columns.length; i2++) {
+ const t = columns[i2].trim();
+ if (!t) {
+ if (i2 === 0 || i2 === columns.length - 1) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+ if (!/^:?-+:?$/.test(t)) {
+ return false;
+ }
+ if (t.charCodeAt(t.length - 1) === 58) {
+ aligns.push(t.charCodeAt(0) === 58 ? "center" : "right");
+ } else if (t.charCodeAt(0) === 58) {
+ aligns.push("left");
+ } else {
+ aligns.push("");
+ }
+ }
+ lineText = getLine(state, startLine).trim();
+ if (lineText.indexOf("|") === -1) {
+ return false;
+ }
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ columns = escapedSplit(lineText);
+ if (columns.length && columns[0] === "") columns.shift();
+ if (columns.length && columns[columns.length - 1] === "") columns.pop();
+ const columnCount = columns.length;
+ if (columnCount === 0 || columnCount !== aligns.length) {
+ return false;
+ }
+ if (silent) {
+ return true;
+ }
+ const oldParentType = state.parentType;
+ state.parentType = "table";
+ const terminatorRules = state.md.block.ruler.getRules("blockquote");
+ const token_to = state.push("table_open", "table", 1);
+ const tableLines = [startLine, 0];
+ token_to.map = tableLines;
+ const token_tho = state.push("thead_open", "thead", 1);
+ token_tho.map = [startLine, startLine + 1];
+ const token_htro = state.push("tr_open", "tr", 1);
+ token_htro.map = [startLine, startLine + 1];
+ for (let i2 = 0; i2 < columns.length; i2++) {
+ const token_ho = state.push("th_open", "th", 1);
+ if (aligns[i2]) {
+ token_ho.attrs = [["style", "text-align:" + aligns[i2]]];
+ }
+ const token_il = state.push("inline", "", 0);
+ token_il.content = columns[i2].trim();
+ token_il.children = [];
+ state.push("th_close", "th", -1);
+ }
+ state.push("tr_close", "tr", -1);
+ state.push("thead_close", "thead", -1);
+ let tbodyLines;
+ let autocompletedCells = 0;
+ for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
+ if (state.sCount[nextLine] < state.blkIndent) {
+ break;
+ }
+ let terminate = false;
+ for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
+ if (terminatorRules[i2](state, nextLine, endLine, true)) {
+ terminate = true;
+ break;
+ }
+ }
+ if (terminate) {
+ break;
+ }
+ lineText = getLine(state, nextLine).trim();
+ if (!lineText) {
+ break;
+ }
+ if (state.sCount[nextLine] - state.blkIndent >= 4) {
+ break;
+ }
+ columns = escapedSplit(lineText);
+ if (columns.length && columns[0] === "") columns.shift();
+ if (columns.length && columns[columns.length - 1] === "") columns.pop();
+ autocompletedCells += columnCount - columns.length;
+ if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) {
+ break;
+ }
+ if (nextLine === startLine + 2) {
+ const token_tbo = state.push("tbody_open", "tbody", 1);
+ token_tbo.map = tbodyLines = [startLine + 2, 0];
+ }
+ const token_tro = state.push("tr_open", "tr", 1);
+ token_tro.map = [nextLine, nextLine + 1];
+ for (let i2 = 0; i2 < columnCount; i2++) {
+ const token_tdo = state.push("td_open", "td", 1);
+ if (aligns[i2]) {
+ token_tdo.attrs = [["style", "text-align:" + aligns[i2]]];
+ }
+ const token_il = state.push("inline", "", 0);
+ token_il.content = columns[i2] ? columns[i2].trim() : "";
+ token_il.children = [];
+ state.push("td_close", "td", -1);
+ }
+ state.push("tr_close", "tr", -1);
+ }
+ if (tbodyLines) {
+ state.push("tbody_close", "tbody", -1);
+ tbodyLines[1] = nextLine;
+ }
+ state.push("table_close", "table", -1);
+ tableLines[1] = nextLine;
+ state.parentType = oldParentType;
+ state.line = nextLine;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/code.mjs
+ function code2(state, startLine, endLine) {
+ if (state.sCount[startLine] - state.blkIndent < 4) {
+ return false;
+ }
+ let nextLine = startLine + 1;
+ let last = nextLine;
+ while (nextLine < endLine) {
+ if (state.isEmpty(nextLine)) {
+ nextLine++;
+ continue;
+ }
+ if (state.sCount[nextLine] - state.blkIndent >= 4) {
+ nextLine++;
+ last = nextLine;
+ continue;
+ }
+ break;
+ }
+ state.line = last;
+ const token = state.push("code_block", "code", 0);
+ token.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + "\n";
+ token.map = [startLine, state.line];
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/fence.mjs
+ function fence(state, startLine, endLine, silent) {
+ let pos = state.bMarks[startLine] + state.tShift[startLine];
+ let max = state.eMarks[startLine];
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ if (pos + 3 > max) {
+ return false;
+ }
+ const marker = state.src.charCodeAt(pos);
+ if (marker !== 126 && marker !== 96) {
+ return false;
+ }
+ let mem = pos;
+ pos = state.skipChars(pos, marker);
+ let len = pos - mem;
+ if (len < 3) {
+ return false;
+ }
+ const markup = state.src.slice(mem, pos);
+ const params = state.src.slice(pos, max);
+ if (marker === 96) {
+ if (params.indexOf(String.fromCharCode(marker)) >= 0) {
+ return false;
+ }
+ }
+ if (silent) {
+ return true;
+ }
+ let nextLine = startLine;
+ let haveEndMarker = false;
+ for (; ; ) {
+ nextLine++;
+ if (nextLine >= endLine) {
+ break;
+ }
+ pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
+ max = state.eMarks[nextLine];
+ if (pos < max && state.sCount[nextLine] < state.blkIndent) {
+ break;
+ }
+ if (state.src.charCodeAt(pos) !== marker) {
+ continue;
+ }
+ if (state.sCount[nextLine] - state.blkIndent >= 4) {
+ continue;
+ }
+ pos = state.skipChars(pos, marker);
+ if (pos - mem < len) {
+ continue;
+ }
+ pos = state.skipSpaces(pos);
+ if (pos < max) {
+ continue;
+ }
+ haveEndMarker = true;
+ break;
+ }
+ len = state.sCount[startLine];
+ state.line = nextLine + (haveEndMarker ? 1 : 0);
+ const token = state.push("fence", "code", 0);
+ token.info = params;
+ token.content = state.getLines(startLine + 1, nextLine, len, true);
+ token.markup = markup;
+ token.map = [startLine, state.line];
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/blockquote.mjs
+ function blockquote(state, startLine, endLine, silent) {
+ let pos = state.bMarks[startLine] + state.tShift[startLine];
+ let max = state.eMarks[startLine];
+ const oldLineMax = state.lineMax;
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ if (state.src.charCodeAt(pos) !== 62) {
+ return false;
+ }
+ if (silent) {
+ return true;
+ }
+ const oldBMarks = [];
+ const oldBSCount = [];
+ const oldSCount = [];
+ const oldTShift = [];
+ const terminatorRules = state.md.block.ruler.getRules("blockquote");
+ const oldParentType = state.parentType;
+ state.parentType = "blockquote";
+ let lastLineEmpty = false;
+ let nextLine;
+ for (nextLine = startLine; nextLine < endLine; nextLine++) {
+ const isOutdented = state.sCount[nextLine] < state.blkIndent;
+ pos = state.bMarks[nextLine] + state.tShift[nextLine];
+ max = state.eMarks[nextLine];
+ if (pos >= max) {
+ break;
+ }
+ if (state.src.charCodeAt(pos++) === 62 && !isOutdented) {
+ let initial = state.sCount[nextLine] + 1;
+ let spaceAfterMarker;
+ let adjustTab;
+ if (state.src.charCodeAt(pos) === 32) {
+ pos++;
+ initial++;
+ adjustTab = false;
+ spaceAfterMarker = true;
+ } else if (state.src.charCodeAt(pos) === 9) {
+ spaceAfterMarker = true;
+ if ((state.bsCount[nextLine] + initial) % 4 === 3) {
+ pos++;
+ initial++;
+ adjustTab = false;
+ } else {
+ adjustTab = true;
+ }
+ } else {
+ spaceAfterMarker = false;
+ }
+ let offset = initial;
+ oldBMarks.push(state.bMarks[nextLine]);
+ state.bMarks[nextLine] = pos;
+ while (pos < max) {
+ const ch = state.src.charCodeAt(pos);
+ if (isSpace(ch)) {
+ if (ch === 9) {
+ offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
+ } else {
+ offset++;
+ }
+ } else {
+ break;
+ }
+ pos++;
+ }
+ lastLineEmpty = pos >= max;
+ oldBSCount.push(state.bsCount[nextLine]);
+ state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
+ oldSCount.push(state.sCount[nextLine]);
+ state.sCount[nextLine] = offset - initial;
+ oldTShift.push(state.tShift[nextLine]);
+ state.tShift[nextLine] = pos - state.bMarks[nextLine];
+ continue;
+ }
+ if (lastLineEmpty) {
+ break;
+ }
+ let terminate = false;
+ for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
+ if (terminatorRules[i2](state, nextLine, endLine, true)) {
+ terminate = true;
+ break;
+ }
+ }
+ if (terminate) {
+ state.lineMax = nextLine;
+ if (state.blkIndent !== 0) {
+ oldBMarks.push(state.bMarks[nextLine]);
+ oldBSCount.push(state.bsCount[nextLine]);
+ oldTShift.push(state.tShift[nextLine]);
+ oldSCount.push(state.sCount[nextLine]);
+ state.sCount[nextLine] -= state.blkIndent;
+ }
+ break;
+ }
+ oldBMarks.push(state.bMarks[nextLine]);
+ oldBSCount.push(state.bsCount[nextLine]);
+ oldTShift.push(state.tShift[nextLine]);
+ oldSCount.push(state.sCount[nextLine]);
+ state.sCount[nextLine] = -1;
+ }
+ const oldIndent = state.blkIndent;
+ state.blkIndent = 0;
+ const token_o = state.push("blockquote_open", "blockquote", 1);
+ token_o.markup = ">";
+ const lines = [startLine, 0];
+ token_o.map = lines;
+ state.md.block.tokenize(state, startLine, nextLine);
+ const token_c = state.push("blockquote_close", "blockquote", -1);
+ token_c.markup = ">";
+ state.lineMax = oldLineMax;
+ state.parentType = oldParentType;
+ lines[1] = state.line;
+ for (let i2 = 0; i2 < oldTShift.length; i2++) {
+ state.bMarks[i2 + startLine] = oldBMarks[i2];
+ state.tShift[i2 + startLine] = oldTShift[i2];
+ state.sCount[i2 + startLine] = oldSCount[i2];
+ state.bsCount[i2 + startLine] = oldBSCount[i2];
+ }
+ state.blkIndent = oldIndent;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/hr.mjs
+ function hr(state, startLine, endLine, silent) {
+ const max = state.eMarks[startLine];
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ let pos = state.bMarks[startLine] + state.tShift[startLine];
+ const marker = state.src.charCodeAt(pos++);
+ if (marker !== 42 && marker !== 45 && marker !== 95) {
+ return false;
+ }
+ let cnt = 1;
+ while (pos < max) {
+ const ch = state.src.charCodeAt(pos++);
+ if (ch !== marker && !isSpace(ch)) {
+ return false;
+ }
+ if (ch === marker) {
+ cnt++;
+ }
+ }
+ if (cnt < 3) {
+ return false;
+ }
+ if (silent) {
+ return true;
+ }
+ state.line = startLine + 1;
+ const token = state.push("hr", "hr", 0);
+ token.map = [startLine, state.line];
+ token.markup = Array(cnt + 1).join(String.fromCharCode(marker));
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/list.mjs
+ function skipBulletListMarker(state, startLine) {
+ const max = state.eMarks[startLine];
+ let pos = state.bMarks[startLine] + state.tShift[startLine];
+ const marker = state.src.charCodeAt(pos++);
+ if (marker !== 42 && marker !== 45 && marker !== 43) {
+ return -1;
+ }
+ if (pos < max) {
+ const ch = state.src.charCodeAt(pos);
+ if (!isSpace(ch)) {
+ return -1;
+ }
+ }
+ return pos;
+ }
+ function skipOrderedListMarker(state, startLine) {
+ const start = state.bMarks[startLine] + state.tShift[startLine];
+ const max = state.eMarks[startLine];
+ let pos = start;
+ if (pos + 1 >= max) {
+ return -1;
+ }
+ let ch = state.src.charCodeAt(pos++);
+ if (ch < 48 || ch > 57) {
+ return -1;
+ }
+ for (; ; ) {
+ if (pos >= max) {
+ return -1;
+ }
+ ch = state.src.charCodeAt(pos++);
+ if (ch >= 48 && ch <= 57) {
+ if (pos - start >= 10) {
+ return -1;
+ }
+ continue;
+ }
+ if (ch === 41 || ch === 46) {
+ break;
+ }
+ return -1;
+ }
+ if (pos < max) {
+ ch = state.src.charCodeAt(pos);
+ if (!isSpace(ch)) {
+ return -1;
+ }
+ }
+ return pos;
+ }
+ function markTightParagraphs(state, idx) {
+ const level = state.level + 2;
+ for (let i2 = idx + 2, l = state.tokens.length - 2; i2 < l; i2++) {
+ if (state.tokens[i2].level === level && state.tokens[i2].type === "paragraph_open") {
+ state.tokens[i2 + 2].hidden = true;
+ state.tokens[i2].hidden = true;
+ i2 += 2;
+ }
+ }
+ }
+ function list(state, startLine, endLine, silent) {
+ let max, pos, start, token;
+ let nextLine = startLine;
+ let tight2 = true;
+ if (state.sCount[nextLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) {
+ return false;
+ }
+ let isTerminatingParagraph = false;
+ if (silent && state.parentType === "paragraph") {
+ if (state.sCount[nextLine] >= state.blkIndent) {
+ isTerminatingParagraph = true;
+ }
+ }
+ let isOrdered;
+ let markerValue;
+ let posAfterMarker;
+ if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) {
+ isOrdered = true;
+ start = state.bMarks[nextLine] + state.tShift[nextLine];
+ markerValue = Number(state.src.slice(start, posAfterMarker - 1));
+ if (isTerminatingParagraph && markerValue !== 1) return false;
+ } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) {
+ isOrdered = false;
+ } else {
+ return false;
+ }
+ if (isTerminatingParagraph) {
+ if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false;
+ }
+ if (silent) {
+ return true;
+ }
+ const markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
+ const listTokIdx = state.tokens.length;
+ if (isOrdered) {
+ token = state.push("ordered_list_open", "ol", 1);
+ if (markerValue !== 1) {
+ token.attrs = [["start", markerValue]];
+ }
+ } else {
+ token = state.push("bullet_list_open", "ul", 1);
+ }
+ const listLines = [nextLine, 0];
+ token.map = listLines;
+ token.markup = String.fromCharCode(markerCharCode);
+ let prevEmptyEnd = false;
+ const terminatorRules = state.md.block.ruler.getRules("list");
+ const oldParentType = state.parentType;
+ state.parentType = "list";
+ while (nextLine < endLine) {
+ pos = posAfterMarker;
+ max = state.eMarks[nextLine];
+ const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]);
+ let offset = initial;
+ while (pos < max) {
+ const ch = state.src.charCodeAt(pos);
+ if (ch === 9) {
+ offset += 4 - (offset + state.bsCount[nextLine]) % 4;
+ } else if (ch === 32) {
+ offset++;
+ } else {
+ break;
+ }
+ pos++;
+ }
+ const contentStart = pos;
+ let indentAfterMarker;
+ if (contentStart >= max) {
+ indentAfterMarker = 1;
+ } else {
+ indentAfterMarker = offset - initial;
+ }
+ if (indentAfterMarker > 4) {
+ indentAfterMarker = 1;
+ }
+ const indent = initial + indentAfterMarker;
+ token = state.push("list_item_open", "li", 1);
+ token.markup = String.fromCharCode(markerCharCode);
+ const itemLines = [nextLine, 0];
+ token.map = itemLines;
+ if (isOrdered) {
+ token.info = state.src.slice(start, posAfterMarker - 1);
+ }
+ const oldTight = state.tight;
+ const oldTShift = state.tShift[nextLine];
+ const oldSCount = state.sCount[nextLine];
+ const oldListIndent = state.listIndent;
+ state.listIndent = state.blkIndent;
+ state.blkIndent = indent;
+ state.tight = true;
+ state.tShift[nextLine] = contentStart - state.bMarks[nextLine];
+ state.sCount[nextLine] = offset;
+ if (contentStart >= max && state.isEmpty(nextLine + 1)) {
+ state.line = Math.min(state.line + 2, endLine);
+ } else {
+ state.md.block.tokenize(state, nextLine, endLine, true);
+ }
+ if (!state.tight || prevEmptyEnd) {
+ tight2 = false;
+ }
+ prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1);
+ state.blkIndent = state.listIndent;
+ state.listIndent = oldListIndent;
+ state.tShift[nextLine] = oldTShift;
+ state.sCount[nextLine] = oldSCount;
+ state.tight = oldTight;
+ token = state.push("list_item_close", "li", -1);
+ token.markup = String.fromCharCode(markerCharCode);
+ nextLine = state.line;
+ itemLines[1] = nextLine;
+ if (nextLine >= endLine) {
+ break;
+ }
+ if (state.sCount[nextLine] < state.blkIndent) {
+ break;
+ }
+ if (state.sCount[nextLine] - state.blkIndent >= 4) {
+ break;
+ }
+ let terminate = false;
+ for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
+ if (terminatorRules[i2](state, nextLine, endLine, true)) {
+ terminate = true;
+ break;
+ }
+ }
+ if (terminate) {
+ break;
+ }
+ if (isOrdered) {
+ posAfterMarker = skipOrderedListMarker(state, nextLine);
+ if (posAfterMarker < 0) {
+ break;
+ }
+ start = state.bMarks[nextLine] + state.tShift[nextLine];
+ } else {
+ posAfterMarker = skipBulletListMarker(state, nextLine);
+ if (posAfterMarker < 0) {
+ break;
+ }
+ }
+ if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) {
+ break;
+ }
+ }
+ if (isOrdered) {
+ token = state.push("ordered_list_close", "ol", -1);
+ } else {
+ token = state.push("bullet_list_close", "ul", -1);
+ }
+ token.markup = String.fromCharCode(markerCharCode);
+ listLines[1] = nextLine;
+ state.line = nextLine;
+ state.parentType = oldParentType;
+ if (tight2) {
+ markTightParagraphs(state, listTokIdx);
+ }
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/reference.mjs
+ var MAX_LABEL_LENGTH = 999;
+ function countCodePoints(str) {
+ let length = str.length;
+ for (let i2 = 0; i2 < str.length - 1; i2++) {
+ const high = str.charCodeAt(i2);
+ if (high < 55296 || high > 56319) {
+ continue;
+ }
+ const low = str.charCodeAt(i2 + 1);
+ if (low >= 56320 && low <= 57343) {
+ length--;
+ i2++;
+ }
+ }
+ return length;
+ }
+ function lineEnd(state, line) {
+ return Math.min(state.eMarks[line] + 1, state.src.length);
+ }
+ function getNextLinePos(state, nextLine) {
+ const endLine = state.lineMax;
+ if (nextLine >= endLine || state.isEmpty(nextLine)) {
+ return -1;
+ }
+ let isContinuation = false;
+ if (state.sCount[nextLine] - state.blkIndent > 3) {
+ isContinuation = true;
+ }
+ if (state.sCount[nextLine] < 0) {
+ isContinuation = true;
+ }
+ if (!isContinuation) {
+ const terminatorRules = state.md.block.ruler.getRules("reference");
+ const oldParentType = state.parentType;
+ state.parentType = "reference";
+ let terminate = false;
+ for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
+ if (terminatorRules[i2](state, nextLine, endLine, true)) {
+ terminate = true;
+ break;
+ }
+ }
+ state.parentType = oldParentType;
+ if (terminate) {
+ return -1;
+ }
+ }
+ return state.bMarks[nextLine] + state.tShift[nextLine];
+ }
+ function reference(state, startLine, _endLine, silent) {
+ const src = state.src;
+ let pos = state.bMarks[startLine] + state.tShift[startLine];
+ let nextLine = startLine + 1;
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ if (src.charCodeAt(pos) !== 91) {
+ return false;
+ }
+ let max = lineEnd(state, startLine);
+ let rawLabel = "";
+ let labelEnd = -1;
+ let segmentStart = ++pos;
+ while (pos < max) {
+ if (rawLabel.length + pos - segmentStart > MAX_LABEL_LENGTH * 2) {
+ return false;
+ }
+ let ch = src.charCodeAt(pos);
+ if (ch === 91) {
+ return false;
+ }
+ if (ch === 93) {
+ labelEnd = pos;
+ break;
+ }
+ if (ch === 92) {
+ ch = src.charCodeAt(++pos);
+ }
+ if (ch === 10 && pos < max) {
+ const nextPos = getNextLinePos(state, nextLine);
+ if (nextPos < 0) {
+ return false;
+ }
+ rawLabel += src.slice(segmentStart, max);
+ pos = segmentStart = nextPos;
+ max = lineEnd(state, nextLine++);
+ continue;
+ }
+ pos++;
+ }
+ if (labelEnd < 0 || src.charCodeAt(labelEnd + 1) !== 58) {
+ return false;
+ }
+ rawLabel += src.slice(segmentStart, labelEnd);
+ if (rawLabel.length > MAX_LABEL_LENGTH && countCodePoints(rawLabel) > MAX_LABEL_LENGTH) {
+ return false;
+ }
+ pos = labelEnd + 2;
+ while (pos < max) {
+ const ch = src.charCodeAt(pos);
+ if (ch === 10) {
+ const nextPos = getNextLinePos(state, nextLine);
+ if (nextPos < 0) {
+ break;
+ }
+ pos = nextPos;
+ max = lineEnd(state, nextLine++);
+ } else if (isSpace(ch)) {
+ pos++;
+ } else {
+ break;
+ }
+ }
+ const destRes = state.md.helpers.parseLinkDestination(src, pos, max);
+ if (!destRes.ok) {
+ return false;
+ }
+ const href = state.md.normalizeLink(destRes.str);
+ if (!state.md.validateLink(href)) {
+ return false;
+ }
+ pos = destRes.pos;
+ const destEndPos = pos;
+ const destEndMax = max;
+ const destEndLineNo = nextLine;
+ while (pos < max) {
+ const ch = src.charCodeAt(pos);
+ if (ch === 10) {
+ const nextPos = getNextLinePos(state, nextLine);
+ if (nextPos < 0) {
+ break;
+ }
+ pos = nextPos;
+ max = lineEnd(state, nextLine++);
+ } else if (isSpace(ch)) {
+ pos++;
+ } else {
+ break;
+ }
+ }
+ const titleStart = pos;
+ let titleRes = state.md.helpers.parseLinkTitle(src, pos, max);
+ while (titleRes.can_continue) {
+ const nextPos = getNextLinePos(state, nextLine);
+ if (nextPos < 0) break;
+ pos = nextPos;
+ max = lineEnd(state, nextLine++);
+ titleRes = state.md.helpers.parseLinkTitle(src, pos, max, titleRes);
+ }
+ let title;
+ if (titleStart !== destEndPos && titleRes.ok) {
+ title = titleRes.str;
+ pos = titleRes.pos;
+ } else {
+ title = "";
+ pos = destEndPos;
+ max = destEndMax;
+ nextLine = destEndLineNo;
+ }
+ while (pos < max) {
+ const ch = src.charCodeAt(pos);
+ if (!isSpace(ch)) {
+ break;
+ }
+ pos++;
+ }
+ if (pos < max && src.charCodeAt(pos) !== 10) {
+ if (title) {
+ title = "";
+ pos = destEndPos;
+ max = destEndMax;
+ nextLine = destEndLineNo;
+ while (pos < max) {
+ const ch = src.charCodeAt(pos);
+ if (!isSpace(ch)) {
+ break;
+ }
+ pos++;
+ }
+ }
+ }
+ if (pos < max && src.charCodeAt(pos) !== 10) {
+ return false;
+ }
+ const label = normalizeReference(rawLabel);
+ if (!label) {
+ return false;
+ }
+ if (silent) {
+ return true;
+ }
+ if (typeof state.env.references === "undefined") {
+ state.env.references = {};
+ }
+ if (typeof state.env.references[label] === "undefined") {
+ state.env.references[label] = { title, href };
+ }
+ state.line = nextLine;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/common/html_blocks.mjs
+ var html_blocks_default = [
+ "address",
+ "article",
+ "aside",
+ "base",
+ "basefont",
+ "blockquote",
+ "body",
+ "caption",
+ "center",
+ "col",
+ "colgroup",
+ "dd",
+ "details",
+ "dialog",
+ "dir",
+ "div",
+ "dl",
+ "dt",
+ "fieldset",
+ "figcaption",
+ "figure",
+ "footer",
+ "form",
+ "frame",
+ "frameset",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "head",
+ "header",
+ "hr",
+ "html",
+ "iframe",
+ "legend",
+ "li",
+ "link",
+ "main",
+ "menu",
+ "menuitem",
+ "nav",
+ "noframes",
+ "ol",
+ "optgroup",
+ "option",
+ "p",
+ "param",
+ "search",
+ "section",
+ "summary",
+ "table",
+ "tbody",
+ "td",
+ "tfoot",
+ "th",
+ "thead",
+ "title",
+ "tr",
+ "track",
+ "ul"
+ ];
+
+ // third_party/editor/markdown-it/lib/common/html_re.mjs
+ var attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
+ var unquoted = "[^\"'=<>`\\x00-\\x20]+";
+ var single_quoted = "'[^']*'";
+ var double_quoted = '"[^"]*"';
+ var attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")";
+ var attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)";
+ var open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>";
+ var close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";
+ var comment = "";
+ var processing = "<[?][\\s\\S]*?[?]>";
+ var declaration = "]*>";
+ var cdata = "";
+ var HTML_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + "|" + comment + "|" + processing + "|" + declaration + "|" + cdata + ")");
+ var HTML_OPEN_CLOSE_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + ")");
+
+ // third_party/editor/markdown-it/lib/rules_block/html_block.mjs
+ var HTML_SEQUENCES = [
+ [/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true],
+ [/^/, true],
+ [/^<\?/, /\?>/, true],
+ [/^/, true],
+ [/^/, true],
+ [new RegExp("^?(" + html_blocks_default.join("|") + ")(?=(\\s|/?>|$))", "i"), /^$/, true],
+ [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false]
+ ];
+ function html_block(state, startLine, endLine, silent) {
+ let pos = state.bMarks[startLine] + state.tShift[startLine];
+ let max = state.eMarks[startLine];
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ if (!state.md.options.html) {
+ return false;
+ }
+ if (state.src.charCodeAt(pos) !== 60) {
+ return false;
+ }
+ let lineText = state.src.slice(pos, max);
+ let i2 = 0;
+ for (; i2 < HTML_SEQUENCES.length; i2++) {
+ if (HTML_SEQUENCES[i2][0].test(lineText)) {
+ break;
+ }
+ }
+ if (i2 === HTML_SEQUENCES.length) {
+ return false;
+ }
+ if (silent) {
+ return HTML_SEQUENCES[i2][2];
+ }
+ let nextLine = startLine + 1;
+ const endsOnBlankLine = HTML_SEQUENCES[i2][1].test("");
+ if (!HTML_SEQUENCES[i2][1].test(lineText)) {
+ for (; nextLine < endLine; nextLine++) {
+ if (state.sCount[nextLine] < state.blkIndent) {
+ if (endsOnBlankLine || !state.isEmpty(nextLine)) {
+ break;
+ }
+ }
+ pos = state.bMarks[nextLine] + state.tShift[nextLine];
+ max = state.eMarks[nextLine];
+ lineText = state.src.slice(pos, max);
+ if (HTML_SEQUENCES[i2][1].test(lineText)) {
+ if (lineText.length !== 0) {
+ nextLine++;
+ }
+ break;
+ }
+ }
+ }
+ state.line = nextLine;
+ const token = state.push("html_block", "", 0);
+ token.map = [startLine, nextLine];
+ token.content = state.getLines(startLine, nextLine, state.blkIndent, true);
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/heading.mjs
+ function heading(state, startLine, endLine, silent) {
+ let pos = state.bMarks[startLine] + state.tShift[startLine];
+ let max = state.eMarks[startLine];
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ let ch = state.src.charCodeAt(pos);
+ if (ch !== 35 || pos >= max) {
+ return false;
+ }
+ let level = 1;
+ ch = state.src.charCodeAt(++pos);
+ while (ch === 35 && pos < max && level <= 6) {
+ level++;
+ ch = state.src.charCodeAt(++pos);
+ }
+ if (level > 6 || pos < max && !isSpace(ch)) {
+ return false;
+ }
+ if (silent) {
+ return true;
+ }
+ max = state.skipSpacesBack(max, pos);
+ const tmp = state.skipCharsBack(max, 35, pos);
+ if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) {
+ max = tmp;
+ }
+ state.line = startLine + 1;
+ const token_o = state.push("heading_open", "h" + String(level), 1);
+ token_o.markup = "########".slice(0, level);
+ token_o.map = [startLine, state.line];
+ const token_i = state.push("inline", "", 0);
+ token_i.content = asciiTrim(state.src.slice(pos, max));
+ token_i.map = [startLine, state.line];
+ token_i.children = [];
+ const token_c = state.push("heading_close", "h" + String(level), -1);
+ token_c.markup = "########".slice(0, level);
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/lheading.mjs
+ function lheading(state, startLine, endLine) {
+ const terminatorRules = state.md.block.ruler.getRules("paragraph");
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
+ return false;
+ }
+ const oldParentType = state.parentType;
+ state.parentType = "paragraph";
+ let level = 0;
+ let marker;
+ let nextLine = startLine + 1;
+ for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
+ if (state.sCount[nextLine] - state.blkIndent > 3) {
+ continue;
+ }
+ if (state.sCount[nextLine] >= state.blkIndent) {
+ let pos = state.bMarks[nextLine] + state.tShift[nextLine];
+ const max = state.eMarks[nextLine];
+ if (pos < max) {
+ marker = state.src.charCodeAt(pos);
+ if (marker === 45 || marker === 61) {
+ pos = state.skipChars(pos, marker);
+ pos = state.skipSpaces(pos);
+ if (pos >= max) {
+ level = marker === 61 ? 1 : 2;
+ break;
+ }
+ }
+ }
+ }
+ if (state.sCount[nextLine] < 0) {
+ continue;
+ }
+ let terminate = false;
+ for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
+ if (terminatorRules[i2](state, nextLine, endLine, true)) {
+ terminate = true;
+ break;
+ }
+ }
+ if (terminate) {
+ break;
+ }
+ }
+ if (!level) {
+ state.parentType = oldParentType;
+ return false;
+ }
+ const content = asciiTrim(state.getLines(startLine, nextLine, state.blkIndent, false));
+ state.line = nextLine + 1;
+ const token_o = state.push("heading_open", "h" + String(level), 1);
+ token_o.markup = String.fromCharCode(marker);
+ token_o.map = [startLine, state.line];
+ const token_i = state.push("inline", "", 0);
+ token_i.content = content;
+ token_i.map = [startLine, state.line - 1];
+ token_i.children = [];
+ const token_c = state.push("heading_close", "h" + String(level), -1);
+ token_c.markup = String.fromCharCode(marker);
+ state.parentType = oldParentType;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_block/paragraph.mjs
+ function paragraph(state, startLine, endLine) {
+ const terminatorRules = state.md.block.ruler.getRules("paragraph");
+ const oldParentType = state.parentType;
+ let nextLine = startLine + 1;
+ state.parentType = "paragraph";
+ for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
+ if (state.sCount[nextLine] - state.blkIndent > 3) {
+ continue;
+ }
+ if (state.sCount[nextLine] < 0) {
+ continue;
+ }
+ let terminate = false;
+ for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
+ if (terminatorRules[i2](state, nextLine, endLine, true)) {
+ terminate = true;
+ break;
+ }
+ }
+ if (terminate) {
+ break;
+ }
+ }
+ const content = asciiTrim(state.getLines(startLine, nextLine, state.blkIndent, false));
+ state.line = nextLine;
+ const token_o = state.push("paragraph_open", "p", 1);
+ token_o.map = [startLine, state.line];
+ const token_i = state.push("inline", "", 0);
+ token_i.content = content;
+ token_i.map = [startLine, state.line];
+ token_i.children = [];
+ state.push("paragraph_close", "p", -1);
+ state.parentType = oldParentType;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/parser_block.mjs
+ var _rules2 = [
+ // First 2 params - rule name & source. Secondary array - list of rules,
+ // which can be terminated by this one.
+ ["table", table, ["paragraph", "reference"]],
+ ["code", code2],
+ ["fence", fence, ["paragraph", "reference", "blockquote", "list"]],
+ ["blockquote", blockquote, ["paragraph", "reference", "blockquote", "list"]],
+ ["hr", hr, ["paragraph", "reference", "blockquote", "list"]],
+ ["list", list, ["paragraph", "reference", "blockquote"]],
+ ["reference", reference],
+ ["html_block", html_block, ["paragraph", "reference", "blockquote"]],
+ ["heading", heading, ["paragraph", "reference", "blockquote"]],
+ ["lheading", lheading],
+ ["paragraph", paragraph]
+ ];
+ function ParserBlock() {
+ this.ruler = new ruler_default();
+ for (let i2 = 0; i2 < _rules2.length; i2++) {
+ this.ruler.push(_rules2[i2][0], _rules2[i2][1], { alt: (_rules2[i2][2] || []).slice() });
+ }
+ }
+ ParserBlock.prototype.tokenize = function(state, startLine, endLine) {
+ const rules2 = this.ruler.getRules("");
+ const len = rules2.length;
+ const maxNesting = state.md.options.maxNesting;
+ let line = startLine;
+ let hasEmptyLines = false;
+ while (line < endLine) {
+ state.line = line = state.skipEmptyLines(line);
+ if (line >= endLine) {
+ break;
+ }
+ if (state.sCount[line] < state.blkIndent) {
+ break;
+ }
+ if (state.level >= maxNesting) {
+ state.line = endLine;
+ break;
+ }
+ const prevLine = state.line;
+ let ok = false;
+ for (let i2 = 0; i2 < len; i2++) {
+ ok = rules2[i2](state, line, endLine, false);
+ if (ok) {
+ if (prevLine >= state.line) {
+ throw new Error("block rule didn't increment state.line");
+ }
+ break;
+ }
+ }
+ if (!ok) throw new Error("none of the block rules matched");
+ state.tight = !hasEmptyLines;
+ if (state.isEmpty(state.line - 1)) {
+ hasEmptyLines = true;
+ }
+ line = state.line;
+ if (line < endLine && state.isEmpty(line)) {
+ hasEmptyLines = true;
+ line++;
+ state.line = line;
+ }
+ }
+ };
+ ParserBlock.prototype.parse = function(src, md, env, outTokens) {
+ if (!src) {
+ return;
+ }
+ const state = new this.State(src, md, env, outTokens);
+ this.tokenize(state, state.line, state.lineMax);
+ };
+ ParserBlock.prototype.State = state_block_default;
+ var parser_block_default = ParserBlock;
+
+ // third_party/editor/markdown-it/lib/rules_inline/state_inline.mjs
+ function StateInline(src, md, env, outTokens) {
+ this.src = src;
+ this.env = env;
+ this.md = md;
+ this.tokens = outTokens;
+ this.tokens_meta = Array(outTokens.length);
+ this.pos = 0;
+ this.posMax = this.src.length;
+ this.level = 0;
+ this.pending = "";
+ this.pendingLevel = 0;
+ this.cache = {};
+ this.delimiters = [];
+ this._prev_delimiters = [];
+ this.backticks = {};
+ this.backticksScanned = false;
+ this.skipHtmlSpecial = false;
+ this.linkLevel = 0;
+ }
+ StateInline.prototype.pushPending = function() {
+ const token = new token_default("text", "", 0);
+ token.content = this.pending;
+ token.level = this.pendingLevel;
+ this.tokens.push(token);
+ this.pending = "";
+ return token;
+ };
+ StateInline.prototype.push = function(type, tag, nesting) {
+ if (this.pending) {
+ this.pushPending();
+ }
+ const token = new token_default(type, tag, nesting);
+ let token_meta = null;
+ if (nesting < 0) {
+ this.level--;
+ this.delimiters = this._prev_delimiters.pop();
+ }
+ token.level = this.level;
+ if (nesting > 0) {
+ this.level++;
+ this._prev_delimiters.push(this.delimiters);
+ this.delimiters = [];
+ token_meta = { delimiters: this.delimiters };
+ }
+ this.pendingLevel = this.level;
+ this.tokens.push(token);
+ this.tokens_meta.push(token_meta);
+ return token;
+ };
+ StateInline.prototype.scanDelims = function(start, canSplitWord) {
+ const max = this.posMax;
+ const marker = this.src.charCodeAt(start);
+ let lastChar;
+ if (start === 0) {
+ lastChar = 32;
+ } else if (start === 1) {
+ lastChar = this.src.charCodeAt(0);
+ if ((lastChar & 63488) === 55296) {
+ lastChar = 65533;
+ }
+ } else {
+ lastChar = this.src.charCodeAt(start - 1);
+ if ((lastChar & 64512) === 56320) {
+ const highSurr = this.src.charCodeAt(start - 2);
+ lastChar = (highSurr & 64512) === 55296 ? 65536 + (highSurr - 55296 << 10) + (lastChar - 56320) : 65533;
+ } else if ((lastChar & 64512) === 55296) {
+ lastChar = 65533;
+ }
+ }
+ let pos = start;
+ while (pos < max && this.src.charCodeAt(pos) === marker) {
+ pos++;
+ }
+ const count = pos - start;
+ let nextChar = pos < max ? this.src.charCodeAt(pos) : 32;
+ if ((nextChar & 64512) === 55296) {
+ const lowSurr = this.src.charCodeAt(pos + 1);
+ nextChar = (lowSurr & 64512) === 56320 ? 65536 + (nextChar - 55296 << 10) + (lowSurr - 56320) : 65533;
+ } else if ((nextChar & 64512) === 56320) {
+ nextChar = 65533;
+ }
+ const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctCharCode(lastChar);
+ const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctCharCode(nextChar);
+ const isLastWhiteSpace = isWhiteSpace(lastChar);
+ const isNextWhiteSpace = isWhiteSpace(nextChar);
+ const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar);
+ const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar);
+ const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar);
+ const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar);
+ return { can_open, can_close, length: count };
+ };
+ StateInline.prototype.Token = token_default;
+ var state_inline_default = StateInline;
+
+ // third_party/editor/markdown-it/lib/rules_inline/text.mjs
+ function isTerminatorChar(ch) {
+ switch (ch) {
+ case 10:
+ case 33:
+ case 35:
+ case 36:
+ case 37:
+ case 38:
+ case 42:
+ case 43:
+ case 45:
+ case 58:
+ case 60:
+ case 61:
+ case 62:
+ case 64:
+ case 91:
+ case 92:
+ case 93:
+ case 94:
+ case 95:
+ case 96:
+ case 123:
+ case 125:
+ case 126:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function text(state, silent) {
+ let pos = state.pos;
+ while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) {
+ pos++;
+ }
+ if (pos === state.pos) {
+ return false;
+ }
+ if (!silent) {
+ state.pending += state.src.slice(state.pos, pos);
+ }
+ state.pos = pos;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/linkify.mjs
+ function isAsciiAlpha(code4) {
+ return code4 >= 65 && code4 <= 90 || code4 >= 97 && code4 <= 122;
+ }
+ function isSchemeChar(code4) {
+ return code4 >= 65 && code4 <= 90 || code4 >= 97 && code4 <= 122 || code4 >= 48 && code4 <= 57 || code4 === 43 || code4 === 45 || code4 === 46;
+ }
+ function linkify2(state, silent) {
+ if (!state.md.options.linkify) return false;
+ if (state.linkLevel > 0) return false;
+ const pos = state.pos;
+ const max = state.posMax;
+ if (pos + 3 > max) return false;
+ if (state.src.charCodeAt(pos) !== 58) return false;
+ if (state.src.charCodeAt(pos + 1) !== 47) return false;
+ if (state.src.charCodeAt(pos + 2) !== 47) return false;
+ const protoMin = pos - Math.min(10, state.pending.length, pos);
+ let protoStart = pos;
+ while (protoStart > protoMin && isSchemeChar(state.src.charCodeAt(protoStart - 1))) {
+ protoStart--;
+ }
+ if (protoStart === pos || !isAsciiAlpha(state.src.charCodeAt(protoStart))) return false;
+ const protoLength = pos - protoStart;
+ const link4 = state.md.linkify.matchAtStart(state.src.slice(protoStart));
+ if (!link4) return false;
+ let url = link4.url;
+ if (url.length <= protoLength) return false;
+ let urlEnd = url.length;
+ while (urlEnd > 0 && url.charCodeAt(urlEnd - 1) === 42) {
+ urlEnd--;
+ }
+ if (urlEnd !== url.length) {
+ url = url.slice(0, urlEnd);
+ }
+ const fullUrl = state.md.normalizeLink(url);
+ if (!state.md.validateLink(fullUrl)) return false;
+ if (!silent) {
+ state.pending = state.pending.slice(0, -protoLength);
+ const token_o = state.push("link_open", "a", 1);
+ token_o.attrs = [["href", fullUrl]];
+ token_o.markup = "linkify";
+ token_o.info = "auto";
+ const token_t = state.push("text", "", 0);
+ token_t.content = state.md.normalizeLinkText(url);
+ const token_c = state.push("link_close", "a", -1);
+ token_c.markup = "linkify";
+ token_c.info = "auto";
+ }
+ state.pos += url.length - protoLength;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/newline.mjs
+ function newline(state, silent) {
+ let pos = state.pos;
+ if (state.src.charCodeAt(pos) !== 10) {
+ return false;
+ }
+ const pmax = state.pending.length - 1;
+ const max = state.posMax;
+ if (!silent) {
+ if (pmax >= 0 && state.pending.charCodeAt(pmax) === 32) {
+ if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 32) {
+ let ws = pmax - 1;
+ while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 32) ws--;
+ state.pending = state.pending.slice(0, ws);
+ state.push("hardbreak", "br", 0);
+ } else {
+ state.pending = state.pending.slice(0, -1);
+ state.push("softbreak", "br", 0);
+ }
+ } else {
+ state.push("softbreak", "br", 0);
+ }
+ }
+ pos++;
+ while (pos < max && isSpace(state.src.charCodeAt(pos))) {
+ pos++;
+ }
+ state.pos = pos;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/escape.mjs
+ var ESCAPED = [];
+ for (let i2 = 0; i2 < 256; i2++) {
+ ESCAPED.push(0);
+ }
+ "\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(ch) {
+ ESCAPED[ch.charCodeAt(0)] = 1;
+ });
+ function escape(state, silent) {
+ let pos = state.pos;
+ const max = state.posMax;
+ if (state.src.charCodeAt(pos) !== 92) return false;
+ pos++;
+ if (pos >= max) return false;
+ let ch1 = state.src.charCodeAt(pos);
+ if (ch1 === 10) {
+ if (!silent) {
+ state.push("hardbreak", "br", 0);
+ }
+ pos++;
+ while (pos < max) {
+ ch1 = state.src.charCodeAt(pos);
+ if (!isSpace(ch1)) break;
+ pos++;
+ }
+ state.pos = pos;
+ return true;
+ }
+ if (ch1 === 32) {
+ if (!silent) {
+ const token = state.push("text_special", "", 0);
+ token.content = "\\";
+ token.markup = "\\";
+ token.info = "escape";
+ }
+ state.pos = pos;
+ return true;
+ }
+ let escapedStr = state.src[pos];
+ if (ch1 >= 55296 && ch1 <= 56319 && pos + 1 < max) {
+ const ch2 = state.src.charCodeAt(pos + 1);
+ if (ch2 >= 56320 && ch2 <= 57343) {
+ escapedStr += state.src[pos + 1];
+ pos++;
+ }
+ }
+ const origStr = "\\" + escapedStr;
+ if (!silent) {
+ const token = state.push("text_special", "", 0);
+ if (ch1 < 256 && ESCAPED[ch1] !== 0) {
+ token.content = escapedStr;
+ } else {
+ token.content = origStr;
+ }
+ token.markup = origStr;
+ token.info = "escape";
+ }
+ state.pos = pos + 1;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/backticks.mjs
+ function backtick(state, silent) {
+ let pos = state.pos;
+ const ch = state.src.charCodeAt(pos);
+ if (ch !== 96) {
+ return false;
+ }
+ const start = pos;
+ pos++;
+ const max = state.posMax;
+ while (pos < max && state.src.charCodeAt(pos) === 96) {
+ pos++;
+ }
+ const marker = state.src.slice(start, pos);
+ const openerLength = marker.length;
+ if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) {
+ if (!silent) state.pending += marker;
+ state.pos += openerLength;
+ return true;
+ }
+ let matchEnd = pos;
+ let matchStart;
+ while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) {
+ matchEnd = matchStart + 1;
+ while (matchEnd < max && state.src.charCodeAt(matchEnd) === 96) {
+ matchEnd++;
+ }
+ const closerLength = matchEnd - matchStart;
+ if (closerLength === openerLength) {
+ if (!silent) {
+ const token = state.push("code_inline", "code", 0);
+ token.markup = marker;
+ token.content = state.src.slice(pos, matchStart).replace(/\n/g, " ").replace(/^ (.+) $/, "$1");
+ }
+ state.pos = matchEnd;
+ return true;
+ }
+ state.backticks[closerLength] = matchStart;
+ }
+ state.backticksScanned = true;
+ if (!silent) state.pending += marker;
+ state.pos += openerLength;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/strikethrough.mjs
+ function strikethrough_tokenize(state, silent) {
+ const start = state.pos;
+ const marker = state.src.charCodeAt(start);
+ if (silent) {
+ return false;
+ }
+ if (marker !== 126) {
+ return false;
+ }
+ const scanned = state.scanDelims(state.pos, true);
+ let len = scanned.length;
+ const ch = String.fromCharCode(marker);
+ if (len < 2) {
+ return false;
+ }
+ let token;
+ if (len % 2) {
+ token = state.push("text", "", 0);
+ token.content = ch;
+ len--;
+ }
+ for (let i2 = 0; i2 < len; i2 += 2) {
+ token = state.push("text", "", 0);
+ token.content = ch + ch;
+ state.delimiters.push({
+ marker,
+ length: 0,
+ // disable "rule of 3" length checks meant for emphasis
+ token: state.tokens.length - 1,
+ end: -1,
+ open: scanned.can_open,
+ close: scanned.can_close
+ });
+ }
+ state.pos += scanned.length;
+ return true;
+ }
+ function postProcess(state, delimiters) {
+ let token;
+ const loneMarkers = [];
+ const max = delimiters.length;
+ for (let i2 = 0; i2 < max; i2++) {
+ const startDelim = delimiters[i2];
+ if (startDelim.marker !== 126) {
+ continue;
+ }
+ if (startDelim.end === -1) {
+ continue;
+ }
+ const endDelim = delimiters[startDelim.end];
+ token = state.tokens[startDelim.token];
+ token.type = "s_open";
+ token.tag = "s";
+ token.nesting = 1;
+ token.markup = "~~";
+ token.content = "";
+ token = state.tokens[endDelim.token];
+ token.type = "s_close";
+ token.tag = "s";
+ token.nesting = -1;
+ token.markup = "~~";
+ token.content = "";
+ if (state.tokens[endDelim.token - 1].type === "text" && state.tokens[endDelim.token - 1].content === "~") {
+ loneMarkers.push(endDelim.token - 1);
+ }
+ }
+ while (loneMarkers.length) {
+ const i2 = loneMarkers.pop();
+ let j = i2 + 1;
+ while (j < state.tokens.length && state.tokens[j].type === "s_close") {
+ j++;
+ }
+ j--;
+ if (i2 !== j) {
+ token = state.tokens[j];
+ state.tokens[j] = state.tokens[i2];
+ state.tokens[i2] = token;
+ }
+ }
+ }
+ function strikethrough_postProcess(state) {
+ const tokens_meta = state.tokens_meta;
+ const max = state.tokens_meta.length;
+ postProcess(state, state.delimiters);
+ for (let curr = 0; curr < max; curr++) {
+ if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
+ postProcess(state, tokens_meta[curr].delimiters);
+ }
+ }
+ }
+ var strikethrough_default = {
+ tokenize: strikethrough_tokenize,
+ postProcess: strikethrough_postProcess
+ };
+
+ // third_party/editor/markdown-it/lib/rules_inline/emphasis.mjs
+ function emphasis_tokenize(state, silent) {
+ const start = state.pos;
+ const marker = state.src.charCodeAt(start);
+ if (silent) {
+ return false;
+ }
+ if (marker !== 95 && marker !== 42) {
+ return false;
+ }
+ const scanned = state.scanDelims(state.pos, marker === 42);
+ for (let i2 = 0; i2 < scanned.length; i2++) {
+ const token = state.push("text", "", 0);
+ token.content = String.fromCharCode(marker);
+ state.delimiters.push({
+ // Char code of the starting marker (number).
+ //
+ marker,
+ // Total length of these series of delimiters.
+ //
+ length: scanned.length,
+ // A position of the token this delimiter corresponds to.
+ //
+ token: state.tokens.length - 1,
+ // If this delimiter is matched as a valid opener, `end` will be
+ // equal to its position, otherwise it's `-1`.
+ //
+ end: -1,
+ // Boolean flags that determine if this delimiter could open or close
+ // an emphasis.
+ //
+ open: scanned.can_open,
+ close: scanned.can_close
+ });
+ }
+ state.pos += scanned.length;
+ return true;
+ }
+ function postProcess2(state, delimiters) {
+ const max = delimiters.length;
+ for (let i2 = max - 1; i2 >= 0; i2--) {
+ const startDelim = delimiters[i2];
+ if (startDelim.marker !== 95 && startDelim.marker !== 42) {
+ continue;
+ }
+ if (startDelim.end === -1) {
+ continue;
+ }
+ const endDelim = delimiters[startDelim.end];
+ const isStrong = i2 > 0 && delimiters[i2 - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent
+ delimiters[i2 - 1].marker === startDelim.marker && delimiters[i2 - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match)
+ delimiters[startDelim.end + 1].token === endDelim.token + 1;
+ const ch = String.fromCharCode(startDelim.marker);
+ const token_o = state.tokens[startDelim.token];
+ token_o.type = isStrong ? "strong_open" : "em_open";
+ token_o.tag = isStrong ? "strong" : "em";
+ token_o.nesting = 1;
+ token_o.markup = isStrong ? ch + ch : ch;
+ token_o.content = "";
+ const token_c = state.tokens[endDelim.token];
+ token_c.type = isStrong ? "strong_close" : "em_close";
+ token_c.tag = isStrong ? "strong" : "em";
+ token_c.nesting = -1;
+ token_c.markup = isStrong ? ch + ch : ch;
+ token_c.content = "";
+ if (isStrong) {
+ state.tokens[delimiters[i2 - 1].token].content = "";
+ state.tokens[delimiters[startDelim.end + 1].token].content = "";
+ i2--;
+ }
+ }
+ }
+ function emphasis_post_process(state) {
+ const tokens_meta = state.tokens_meta;
+ const max = state.tokens_meta.length;
+ postProcess2(state, state.delimiters);
+ for (let curr = 0; curr < max; curr++) {
+ if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
+ postProcess2(state, tokens_meta[curr].delimiters);
+ }
+ }
+ }
+ var emphasis_default = {
+ tokenize: emphasis_tokenize,
+ postProcess: emphasis_post_process
+ };
+
+ // third_party/editor/markdown-it/lib/rules_inline/link.mjs
+ function link(state, silent) {
+ let code4, label, res, ref;
+ let href = "";
+ let title = "";
+ let start = state.pos;
+ let parseReference = true;
+ if (state.src.charCodeAt(state.pos) !== 91) {
+ return false;
+ }
+ const oldPos = state.pos;
+ const max = state.posMax;
+ const labelStart = state.pos + 1;
+ const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
+ if (labelEnd < 0) {
+ return false;
+ }
+ let pos = labelEnd + 1;
+ if (pos < max && state.src.charCodeAt(pos) === 40) {
+ parseReference = false;
+ pos++;
+ for (; pos < max; pos++) {
+ code4 = state.src.charCodeAt(pos);
+ if (!isSpace(code4) && code4 !== 10) {
+ break;
+ }
+ }
+ if (pos >= max) {
+ return false;
+ }
+ start = pos;
+ res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
+ if (res.ok) {
+ href = state.md.normalizeLink(res.str);
+ if (state.md.validateLink(href)) {
+ pos = res.pos;
+ } else {
+ href = "";
+ }
+ start = pos;
+ for (; pos < max; pos++) {
+ code4 = state.src.charCodeAt(pos);
+ if (!isSpace(code4) && code4 !== 10) {
+ break;
+ }
+ }
+ res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
+ if (pos < max && start !== pos && res.ok) {
+ title = res.str;
+ pos = res.pos;
+ for (; pos < max; pos++) {
+ code4 = state.src.charCodeAt(pos);
+ if (!isSpace(code4) && code4 !== 10) {
+ break;
+ }
+ }
+ }
+ }
+ if (pos >= max || state.src.charCodeAt(pos) !== 41) {
+ parseReference = true;
+ }
+ pos++;
+ }
+ if (parseReference) {
+ if (typeof state.env.references === "undefined") {
+ return false;
+ }
+ if (pos < max && state.src.charCodeAt(pos) === 91) {
+ start = pos + 1;
+ pos = state.md.helpers.parseLinkLabel(state, pos);
+ if (pos >= 0) {
+ label = state.src.slice(start, pos++);
+ } else {
+ pos = labelEnd + 1;
+ }
+ } else {
+ pos = labelEnd + 1;
+ }
+ if (!label) {
+ label = state.src.slice(labelStart, labelEnd);
+ }
+ ref = state.env.references[normalizeReference(label)];
+ if (!ref) {
+ state.pos = oldPos;
+ return false;
+ }
+ href = ref.href;
+ title = ref.title;
+ }
+ if (!silent) {
+ state.pos = labelStart;
+ state.posMax = labelEnd;
+ const token_o = state.push("link_open", "a", 1);
+ const attrs2 = [["href", href]];
+ token_o.attrs = attrs2;
+ if (title) {
+ attrs2.push(["title", title]);
+ }
+ state.linkLevel++;
+ state.md.inline.tokenize(state);
+ state.linkLevel--;
+ state.push("link_close", "a", -1);
+ }
+ state.pos = pos;
+ state.posMax = max;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/image.mjs
+ function image(state, silent) {
+ let code4, content, label, pos, ref, res, title, start;
+ let href = "";
+ const oldPos = state.pos;
+ const max = state.posMax;
+ if (state.src.charCodeAt(state.pos) !== 33) {
+ return false;
+ }
+ if (state.src.charCodeAt(state.pos + 1) !== 91) {
+ return false;
+ }
+ const labelStart = state.pos + 2;
+ const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
+ if (labelEnd < 0) {
+ return false;
+ }
+ pos = labelEnd + 1;
+ if (pos < max && state.src.charCodeAt(pos) === 40) {
+ pos++;
+ for (; pos < max; pos++) {
+ code4 = state.src.charCodeAt(pos);
+ if (!isSpace(code4) && code4 !== 10) {
+ break;
+ }
+ }
+ if (pos >= max) {
+ return false;
+ }
+ start = pos;
+ res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
+ if (res.ok) {
+ href = state.md.normalizeLink(res.str);
+ if (state.md.validateLink(href)) {
+ pos = res.pos;
+ } else {
+ href = "";
+ }
+ }
+ start = pos;
+ for (; pos < max; pos++) {
+ code4 = state.src.charCodeAt(pos);
+ if (!isSpace(code4) && code4 !== 10) {
+ break;
+ }
+ }
+ res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
+ if (pos < max && start !== pos && res.ok) {
+ title = res.str;
+ pos = res.pos;
+ for (; pos < max; pos++) {
+ code4 = state.src.charCodeAt(pos);
+ if (!isSpace(code4) && code4 !== 10) {
+ break;
+ }
+ }
+ } else {
+ title = "";
+ }
+ if (pos >= max || state.src.charCodeAt(pos) !== 41) {
+ state.pos = oldPos;
+ return false;
+ }
+ pos++;
+ } else {
+ if (typeof state.env.references === "undefined") {
+ return false;
+ }
+ if (pos < max && state.src.charCodeAt(pos) === 91) {
+ start = pos + 1;
+ pos = state.md.helpers.parseLinkLabel(state, pos);
+ if (pos >= 0) {
+ label = state.src.slice(start, pos++);
+ } else {
+ pos = labelEnd + 1;
+ }
+ } else {
+ pos = labelEnd + 1;
+ }
+ if (!label) {
+ label = state.src.slice(labelStart, labelEnd);
+ }
+ ref = state.env.references[normalizeReference(label)];
+ if (!ref) {
+ state.pos = oldPos;
+ return false;
+ }
+ href = ref.href;
+ title = ref.title;
+ }
+ if (!silent) {
+ content = state.src.slice(labelStart, labelEnd);
+ const tokens = [];
+ state.md.inline.parse(
+ content,
+ state.md,
+ state.env,
+ tokens
+ );
+ const token = state.push("image", "img", 0);
+ const attrs2 = [["src", href], ["alt", ""]];
+ token.attrs = attrs2;
+ token.children = tokens;
+ token.content = content;
+ if (title) {
+ attrs2.push(["title", title]);
+ }
+ }
+ state.pos = pos;
+ state.posMax = max;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/autolink.mjs
+ var EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;
+ var AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;
+ function autolink(state, silent) {
+ let pos = state.pos;
+ if (state.src.charCodeAt(pos) !== 60) {
+ return false;
+ }
+ const start = state.pos;
+ const max = state.posMax;
+ for (; ; ) {
+ if (++pos >= max) return false;
+ const ch = state.src.charCodeAt(pos);
+ if (ch === 60) return false;
+ if (ch === 62) break;
+ }
+ const url = state.src.slice(start + 1, pos);
+ if (AUTOLINK_RE.test(url)) {
+ const fullUrl = state.md.normalizeLink(url);
+ if (!state.md.validateLink(fullUrl)) {
+ return false;
+ }
+ if (!silent) {
+ const token_o = state.push("link_open", "a", 1);
+ token_o.attrs = [["href", fullUrl]];
+ token_o.markup = "autolink";
+ token_o.info = "auto";
+ const token_t = state.push("text", "", 0);
+ token_t.content = state.md.normalizeLinkText(url);
+ const token_c = state.push("link_close", "a", -1);
+ token_c.markup = "autolink";
+ token_c.info = "auto";
+ }
+ state.pos += url.length + 2;
+ return true;
+ }
+ if (EMAIL_RE.test(url)) {
+ const fullUrl = state.md.normalizeLink("mailto:" + url);
+ if (!state.md.validateLink(fullUrl)) {
+ return false;
+ }
+ if (!silent) {
+ const token_o = state.push("link_open", "a", 1);
+ token_o.attrs = [["href", fullUrl]];
+ token_o.markup = "autolink";
+ token_o.info = "auto";
+ const token_t = state.push("text", "", 0);
+ token_t.content = state.md.normalizeLinkText(url);
+ const token_c = state.push("link_close", "a", -1);
+ token_c.markup = "autolink";
+ token_c.info = "auto";
+ }
+ state.pos += url.length + 2;
+ return true;
+ }
+ return false;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/html_inline.mjs
+ function isLinkOpen2(str) {
+ return /^ \s]/i.test(str);
+ }
+ function isLinkClose2(str) {
+ return /^<\/a\s*>/i.test(str);
+ }
+ function isLetter(ch) {
+ const lc = ch | 32;
+ return lc >= 97 && lc <= 122;
+ }
+ function scanSpecial(state, pos) {
+ const src = state.src;
+ let start;
+ let terminator;
+ if (src.startsWith("";
+ } else if (src.startsWith("";
+ } else if (src.charCodeAt(pos + 1) === 63) {
+ start = pos + 2;
+ terminator = "?>";
+ } else if (isLetter(src.charCodeAt(pos + 2))) {
+ start = pos + 3;
+ terminator = ">";
+ } else {
+ return -1;
+ }
+ if (state.skipHtmlSpecial) {
+ return -1;
+ }
+ const end = src.indexOf(terminator, start);
+ if (end < 0) {
+ state.skipHtmlSpecial = true;
+ return -1;
+ }
+ return end + terminator.length;
+ }
+ function html_inline(state, silent) {
+ if (!state.md.options.html) {
+ return false;
+ }
+ const max = state.posMax;
+ const pos = state.pos;
+ if (state.src.charCodeAt(pos) !== 60 || pos + 2 >= max) {
+ return false;
+ }
+ let end;
+ const ch = state.src.charCodeAt(pos + 1);
+ if (ch === 33 || ch === 63) {
+ end = scanSpecial(state, pos);
+ } else if (ch === 47 || isLetter(ch)) {
+ const match2 = state.src.slice(pos).match(HTML_OPEN_CLOSE_TAG_RE);
+ end = match2 ? pos + match2[0].length : -1;
+ } else {
+ return false;
+ }
+ if (end < 0) {
+ return false;
+ }
+ if (!silent) {
+ const token = state.push("html_inline", "", 0);
+ token.content = state.src.slice(pos, end);
+ if (isLinkOpen2(token.content)) state.linkLevel++;
+ if (isLinkClose2(token.content)) state.linkLevel--;
+ }
+ state.pos = end;
+ return true;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/entity.mjs
+ var DIGITAL_RE = /^((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
+ var NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
+ function entity(state, silent) {
+ const pos = state.pos;
+ const max = state.posMax;
+ if (state.src.charCodeAt(pos) !== 38) return false;
+ if (pos + 1 >= max) return false;
+ const ch = state.src.charCodeAt(pos + 1);
+ if (ch === 35) {
+ const match2 = state.src.slice(pos).match(DIGITAL_RE);
+ if (match2) {
+ if (!silent) {
+ const code4 = match2[1][0].toLowerCase() === "x" ? parseInt(match2[1].slice(1), 16) : parseInt(match2[1], 10);
+ const token = state.push("text_special", "", 0);
+ token.content = isValidEntityCode(code4) ? fromCodePoint2(code4) : fromCodePoint2(65533);
+ token.markup = match2[0];
+ token.info = "entity";
+ }
+ state.pos += match2[0].length;
+ return true;
+ }
+ } else {
+ const match2 = state.src.slice(pos).match(NAMED_RE);
+ if (match2) {
+ const decoded = decodeHTMLStrict(match2[0]);
+ if (decoded !== match2[0]) {
+ if (!silent) {
+ const token = state.push("text_special", "", 0);
+ token.content = decoded;
+ token.markup = match2[0];
+ token.info = "entity";
+ }
+ state.pos += match2[0].length;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/balance_pairs.mjs
+ function processDelimiters(delimiters) {
+ const openersBottom = {};
+ const max = delimiters.length;
+ if (!max) return;
+ let headerIdx = 0;
+ let lastTokenIdx = -2;
+ const jumps = [];
+ for (let closerIdx = 0; closerIdx < max; closerIdx++) {
+ const closer = delimiters[closerIdx];
+ jumps.push(0);
+ if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) {
+ headerIdx = closerIdx;
+ }
+ lastTokenIdx = closer.token;
+ closer.length = closer.length || 0;
+ if (!closer.close) continue;
+ if (!openersBottom.hasOwnProperty(closer.marker)) {
+ openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1];
+ }
+ const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3];
+ let openerIdx = headerIdx - jumps[headerIdx] - 1;
+ let newMinOpenerIdx = openerIdx;
+ for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) {
+ const opener = delimiters[openerIdx];
+ if (opener.marker !== closer.marker) continue;
+ if (opener.open && opener.end < 0) {
+ let isOddMatch = false;
+ if (opener.close || closer.open) {
+ if ((opener.length + closer.length) % 3 === 0) {
+ if (opener.length % 3 !== 0 || closer.length % 3 !== 0) {
+ isOddMatch = true;
+ }
+ }
+ }
+ if (!isOddMatch) {
+ const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0;
+ jumps[closerIdx] = closerIdx - openerIdx + lastJump;
+ jumps[openerIdx] = lastJump;
+ closer.open = false;
+ opener.end = closerIdx;
+ opener.close = false;
+ newMinOpenerIdx = -1;
+ lastTokenIdx = -2;
+ break;
+ }
+ }
+ }
+ if (newMinOpenerIdx !== -1) {
+ openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx;
+ }
+ }
+ }
+ function link_pairs(state) {
+ const tokens_meta = state.tokens_meta;
+ const max = state.tokens_meta.length;
+ processDelimiters(state.delimiters);
+ for (let curr = 0; curr < max; curr++) {
+ if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
+ processDelimiters(tokens_meta[curr].delimiters);
+ }
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/rules_inline/fragments_join.mjs
+ function fragments_join(state) {
+ let curr, last;
+ let level = 0;
+ const tokens = state.tokens;
+ const max = state.tokens.length;
+ for (curr = last = 0; curr < max; curr++) {
+ if (tokens[curr].nesting < 0) level--;
+ tokens[curr].level = level;
+ if (tokens[curr].nesting > 0) level++;
+ if (tokens[curr].type === "text" && curr + 1 < max && tokens[curr + 1].type === "text") {
+ tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
+ } else {
+ if (curr !== last) {
+ tokens[last] = tokens[curr];
+ }
+ last++;
+ }
+ }
+ if (curr !== last) {
+ tokens.length = last;
+ }
+ }
+
+ // third_party/editor/markdown-it/lib/parser_inline.mjs
+ var _rules3 = [
+ ["text", text],
+ ["linkify", linkify2],
+ ["newline", newline],
+ ["escape", escape],
+ ["backticks", backtick],
+ ["strikethrough", strikethrough_default.tokenize],
+ ["emphasis", emphasis_default.tokenize],
+ ["link", link],
+ ["image", image],
+ ["autolink", autolink],
+ ["html_inline", html_inline],
+ ["entity", entity]
+ ];
+ var _rules22 = [
+ ["balance_pairs", link_pairs],
+ ["strikethrough", strikethrough_default.postProcess],
+ ["emphasis", emphasis_default.postProcess],
+ // rules for pairs separate '**' into its own text tokens, which may be left unused,
+ // rule below merges unused segments back with the rest of the text
+ ["fragments_join", fragments_join]
+ ];
+ function ParserInline() {
+ this.ruler = new ruler_default();
+ for (let i2 = 0; i2 < _rules3.length; i2++) {
+ this.ruler.push(_rules3[i2][0], _rules3[i2][1]);
+ }
+ this.ruler2 = new ruler_default();
+ for (let i2 = 0; i2 < _rules22.length; i2++) {
+ this.ruler2.push(_rules22[i2][0], _rules22[i2][1]);
+ }
+ }
+ ParserInline.prototype.skipToken = function(state) {
+ const pos = state.pos;
+ const rules2 = this.ruler.getRules("");
+ const len = rules2.length;
+ const maxNesting = state.md.options.maxNesting;
+ const cache = state.cache;
+ if (typeof cache[pos] !== "undefined") {
+ state.pos = cache[pos];
+ return;
+ }
+ let ok = false;
+ if (state.level < maxNesting) {
+ for (let i2 = 0; i2 < len; i2++) {
+ state.level++;
+ ok = rules2[i2](state, true);
+ state.level--;
+ if (ok) {
+ if (pos >= state.pos) {
+ throw new Error("inline rule didn't increment state.pos");
+ }
+ break;
+ }
+ }
+ } else {
+ state.pos = state.posMax;
+ }
+ if (!ok) {
+ state.pos++;
+ }
+ cache[pos] = state.pos;
+ };
+ ParserInline.prototype.tokenize = function(state) {
+ const rules2 = this.ruler.getRules("");
+ const len = rules2.length;
+ const end = state.posMax;
+ const maxNesting = state.md.options.maxNesting;
+ while (state.pos < end) {
+ const prevPos = state.pos;
+ let ok = false;
+ if (state.level < maxNesting) {
+ for (let i2 = 0; i2 < len; i2++) {
+ ok = rules2[i2](state, false);
+ if (ok) {
+ if (prevPos >= state.pos) {
+ throw new Error("inline rule didn't increment state.pos");
+ }
+ break;
+ }
+ }
+ }
+ if (ok) {
+ if (state.pos >= end) {
+ break;
+ }
+ continue;
+ }
+ state.pending += state.src[state.pos++];
+ }
+ if (state.pending) {
+ state.pushPending();
+ }
+ };
+ ParserInline.prototype.parse = function(str, md, env, outTokens) {
+ const state = new this.State(str, md, env, outTokens);
+ this.tokenize(state);
+ const rules2 = this.ruler2.getRules("");
+ const len = rules2.length;
+ for (let i2 = 0; i2 < len; i2++) {
+ rules2[i2](state);
+ }
+ };
+ ParserInline.prototype.State = state_inline_default;
+ var parser_inline_default = ParserInline;
+
+ // third_party/editor/linkify-it/lib/re.mjs
+ function re_default(opts) {
+ const re = {};
+ opts = opts || {};
+ re.src_Any = regex_default.source;
+ re.src_Cc = regex_default2.source;
+ re.src_Z = regex_default6.source;
+ re.src_P = regex_default4.source;
+ re.src_ZPCc = [re.src_Z, re.src_P, re.src_Cc].join("|");
+ re.src_ZCc = [re.src_Z, re.src_Cc].join("|");
+ const text_separators = "[><\uFF5C]";
+ re.src_pseudo_letter = `(?:(?!${text_separators}|${re.src_ZPCc})${re.src_Any})`;
+ re.src_ip4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
+ re.src_auth = `(?:(?:(?!${re.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`;
+ re.src_port = "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?";
+ re.src_host_terminator = `(?=$|${text_separators}|${re.src_ZPCc})(?!${opts["---"] ? "-(?!--)|" : "-|"}_|:\\d|\\.-|\\.(?!$|${re.src_ZPCc}))`;
+ re.src_path = `(?:[/?#](?:(?!${re.src_ZCc}|${text_separators}|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!${re.src_ZCc}|\\]).)*\\]|\\((?:(?!${re.src_ZCc}|[)]).)*\\)|\\{(?:(?!${re.src_ZCc}|[}]).)*\\}|\\"(?:(?!${re.src_ZCc}|["]).)+\\"|\\'(?:(?!${re.src_ZCc}|[']).)+\\'|\\'(?=${re.src_pseudo_letter}|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!${re.src_ZCc}|[.]|$)|` + (opts["---"] ? "\\-(?!--(?:[^-]|$))(?:-*)|" : "\\-+|") + // allow `,,,` in paths
+ `,(?!${re.src_ZCc}|$)|;(?!${re.src_ZCc}|$)|\\!+(?!${re.src_ZCc}|[!]|$)|\\?(?!${re.src_ZCc}|[?]|$))+|\\/)?`;
+ re.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]{0,63}';
+ re.src_xn = "xn--[a-z0-9\\-]{1,59}";
+ re.src_domain_root = // Allow letters & digits (http://test1)
+ "(?:" + re.src_xn + `|${re.src_pseudo_letter}{1,63})`;
+ re.src_domain = "(?:" + re.src_xn + `|(?:${re.src_pseudo_letter})|(?:${re.src_pseudo_letter}(?:-|${re.src_pseudo_letter}){0,61}${re.src_pseudo_letter}))`;
+ re.src_host = `(?:(?:(?:(?:${re.src_domain})\\.)*${re.src_domain}))`;
+ re.tpl_host_fuzzy = "(?:" + re.src_ip4 + `|(?:(?:(?:${re.src_domain})\\.)+(?:%TLDS%)))`;
+ re.tpl_host_no_ip_fuzzy = `(?:(?:(?:${re.src_domain})\\.)+(?:%TLDS%))`;
+ re.src_host_strict = re.src_host + re.src_host_terminator;
+ re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator;
+ re.src_host_port_strict = re.src_host + re.src_port + re.src_host_terminator;
+ re.tpl_host_port_fuzzy_strict = re.tpl_host_fuzzy + re.src_port + re.src_host_terminator;
+ re.tpl_host_port_no_ip_fuzzy_strict = re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator;
+ re.tpl_host_fuzzy_test = `localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:${re.src_ZPCc}|>|$))`;
+ re.tpl_email_fuzzy = `(^|${text_separators}|"|\\(|${re.src_ZCc})(${re.src_email_name}@${re.tpl_host_fuzzy_strict})`;
+ re.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
+ // but can start with > (markdown blockquote)
+ `(^|(?![.:/\\-_@])(?:[$+<=>^\`|\uFF5C]|${re.src_ZPCc}))((?![$+<=>^\`|\uFF5C])${re.tpl_host_port_fuzzy_strict}${re.src_path})`;
+ re.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
+ // but can start with > (markdown blockquote)
+ `(^|(?![.:/\\-_@])(?:[$+<=>^\`|\uFF5C]|${re.src_ZPCc}))((?![$+<=>^\`|\uFF5C])${re.tpl_host_port_no_ip_fuzzy_strict}${re.src_path})`;
+ return re;
+ }
+
+ // third_party/editor/linkify-it/index.mjs
+ function assign2(obj) {
+ const sources = Array.prototype.slice.call(arguments, 1);
+ sources.forEach(function(source) {
+ if (!source) {
+ return;
+ }
+ Object.keys(source).forEach(function(key) {
+ obj[key] = source[key];
+ });
+ });
+ return obj;
+ }
+ function _class2(obj) {
+ return Object.prototype.toString.call(obj);
+ }
+ function isString2(obj) {
+ return _class2(obj) === "[object String]";
+ }
+ function isObject(obj) {
+ return _class2(obj) === "[object Object]";
+ }
+ function isRegExp(obj) {
+ return _class2(obj) === "[object RegExp]";
+ }
+ function isFunction(obj) {
+ return _class2(obj) === "[object Function]";
+ }
+ function escapeRE2(str) {
+ return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
+ }
+ var defaultOptions = {
+ fuzzyLink: true,
+ fuzzyEmail: true,
+ fuzzyIP: false
+ };
+ function isOptionsObj(obj) {
+ return Object.keys(obj || {}).reduce(function(acc, k) {
+ return acc || defaultOptions.hasOwnProperty(k);
+ }, false);
+ }
+ var defaultSchemas = {
+ "http:": {
+ validate: function(text2, pos, self) {
+ const tail = text2.slice(pos);
+ if (!self.re.http) {
+ self.re.http = new RegExp(
+ `^\\/\\/${self.re.src_auth}${self.re.src_host_port_strict}${self.re.src_path}`,
+ "i"
+ );
+ }
+ if (self.re.http.test(tail)) {
+ return tail.match(self.re.http)[0].length;
+ }
+ return 0;
+ }
+ },
+ "https:": "http:",
+ "ftp:": "http:",
+ "//": {
+ validate: function(text2, pos, self) {
+ const tail = text2.slice(pos);
+ if (!self.re.no_http) {
+ self.re.no_http = new RegExp(
+ "^" + self.re.src_auth + // Don't allow single-level domains, because of false positives like '//test'
+ // with code comments
+ `(?:localhost|(?:(?:${self.re.src_domain})\\.)+${self.re.src_domain_root})` + self.re.src_port + self.re.src_host_terminator + self.re.src_path,
+ "i"
+ );
+ }
+ if (self.re.no_http.test(tail)) {
+ if (pos >= 3 && text2[pos - 3] === ":") {
+ return 0;
+ }
+ if (pos >= 3 && text2[pos - 3] === "/") {
+ return 0;
+ }
+ return tail.match(self.re.no_http)[0].length;
+ }
+ return 0;
+ }
+ },
+ "mailto:": {
+ validate: function(text2, pos, self) {
+ const tail = text2.slice(pos);
+ if (!self.re.mailto) {
+ self.re.mailto = new RegExp(
+ `^${self.re.src_email_name}@${self.re.src_host_strict}`,
+ "i"
+ );
+ }
+ if (self.re.mailto.test(tail)) {
+ return tail.match(self.re.mailto)[0].length;
+ }
+ return 0;
+ }
+ }
+ };
+ var tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]";
+ var tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|\u0440\u0444".split("|");
+ function createValidator(re) {
+ return function(text2, pos) {
+ const tail = text2.slice(pos);
+ if (re.test(tail)) {
+ return tail.match(re)[0].length;
+ }
+ return 0;
+ };
+ }
+ function createNormalizer() {
+ return function(match2, self) {
+ self.normalize(match2);
+ };
+ }
+ function compile(self) {
+ const re = self.re = re_default(self.__opts__);
+ const tlds2 = self.__tlds__.slice();
+ self.onCompile();
+ if (!self.__tlds_replaced__) {
+ tlds2.push(tlds_2ch_src_re);
+ }
+ tlds2.push(re.src_xn);
+ re.src_tlds = tlds2.join("|");
+ function untpl(tpl) {
+ return tpl.replace("%TLDS%", re.src_tlds);
+ }
+ re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), "i");
+ re.email_fuzzy_global = RegExp(untpl(re.tpl_email_fuzzy), "ig");
+ re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), "i");
+ re.link_fuzzy_global = RegExp(untpl(re.tpl_link_fuzzy), "ig");
+ re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), "i");
+ re.link_no_ip_fuzzy_global = RegExp(untpl(re.tpl_link_no_ip_fuzzy), "ig");
+ re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), "i");
+ const aliases = [];
+ self.__compiled__ = {};
+ function schemaError(name, val) {
+ throw new Error(`(LinkifyIt) Invalid schema "${name}": ${val}`);
+ }
+ Object.keys(self.__schemas__).forEach(function(name) {
+ const val = self.__schemas__[name];
+ if (val === null) {
+ return;
+ }
+ const compiled = { validate: null, link: null };
+ self.__compiled__[name] = compiled;
+ if (isObject(val)) {
+ if (isRegExp(val.validate)) {
+ compiled.validate = createValidator(val.validate);
+ } else if (isFunction(val.validate)) {
+ compiled.validate = val.validate;
+ } else {
+ schemaError(name, val);
+ }
+ if (isFunction(val.normalize)) {
+ compiled.normalize = val.normalize;
+ } else if (!val.normalize) {
+ compiled.normalize = createNormalizer();
+ } else {
+ schemaError(name, val);
+ }
+ return;
+ }
+ if (isString2(val)) {
+ aliases.push(name);
+ return;
+ }
+ schemaError(name, val);
+ });
+ aliases.forEach(function(alias) {
+ if (!self.__compiled__[self.__schemas__[alias]]) {
+ return;
+ }
+ self.__compiled__[alias].validate = self.__compiled__[self.__schemas__[alias]].validate;
+ self.__compiled__[alias].normalize = self.__compiled__[self.__schemas__[alias]].normalize;
+ });
+ self.__compiled__[""] = { validate: null, normalize: createNormalizer() };
+ const slist = Object.keys(self.__compiled__).filter(function(name) {
+ return name.length > 0 && self.__compiled__[name];
+ }).map(escapeRE2).join("|");
+ self.re.schema_test = RegExp(`(^|(?!_)(?:[><\uFF5C]|${re.src_ZPCc}))(${slist})`, "i");
+ self.re.schema_search = RegExp(`(^|(?!_)(?:[><\uFF5C]|${re.src_ZPCc}))(${slist})`, "ig");
+ self.re.schema_at_start = RegExp(`^${self.re.schema_search.source}`, "i");
+ self.re.pretest = RegExp(
+ `(${self.re.schema_test.source})|(${self.re.host_fuzzy_test.source})|@`,
+ "i"
+ );
+ }
+ function Match(text2, schema3, index, lastIndex) {
+ const raw = text2.slice(index, lastIndex);
+ this.schema = schema3.toLowerCase();
+ this.index = index;
+ this.lastIndex = lastIndex;
+ this.raw = raw;
+ this.text = raw;
+ this.url = raw;
+ }
+ function LinkifyIt(schemas, options) {
+ if (!(this instanceof LinkifyIt)) {
+ return new LinkifyIt(schemas, options);
+ }
+ if (!options) {
+ if (isOptionsObj(schemas)) {
+ options = schemas;
+ schemas = {};
+ }
+ }
+ this.__opts__ = assign2({}, defaultOptions, options);
+ this.__schemas__ = assign2({}, defaultSchemas, schemas);
+ this.__compiled__ = {};
+ this.__tlds__ = tlds_default;
+ this.__tlds_replaced__ = false;
+ this.re = {};
+ compile(this);
+ }
+ LinkifyIt.prototype.add = function add(schema3, definition) {
+ this.__schemas__[schema3] = definition;
+ compile(this);
+ return this;
+ };
+ LinkifyIt.prototype.set = function set(options) {
+ this.__opts__ = assign2(this.__opts__, options);
+ return this;
+ };
+ LinkifyIt.prototype.test = function test(text2) {
+ if (!text2.length) {
+ return false;
+ }
+ let m, re;
+ if (this.re.schema_test.test(text2)) {
+ re = this.re.schema_search;
+ re.lastIndex = 0;
+ while ((m = re.exec(text2)) !== null) {
+ if (this.testSchemaAt(text2, m[2], re.lastIndex)) {
+ return true;
+ }
+ }
+ }
+ if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
+ if (text2.search(this.re.host_fuzzy_test) >= 0) {
+ if (text2.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy) !== null) {
+ return true;
+ }
+ }
+ }
+ if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
+ if (text2.indexOf("@") >= 0) {
+ if (text2.match(this.re.email_fuzzy) !== null) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+ LinkifyIt.prototype.pretest = function pretest(text2) {
+ return this.re.pretest.test(text2);
+ };
+ LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text2, schema3, pos) {
+ if (!this.__compiled__[schema3.toLowerCase()]) {
+ return 0;
+ }
+ return this.__compiled__[schema3.toLowerCase()].validate(text2, pos, this);
+ };
+ LinkifyIt.prototype.match = function match(text2) {
+ const result = [];
+ const type_schemed = [];
+ const type_fuzzy_link = [];
+ const type_fuzzy_email = [];
+ let m, len, re;
+ function choose(a, b) {
+ if (!a) {
+ return b;
+ }
+ if (!b) {
+ return a;
+ }
+ if (a.index !== b.index) {
+ return a.index < b.index ? a : b;
+ }
+ return a.lastIndex >= b.lastIndex ? a : b;
+ }
+ if (!text2.length) {
+ return null;
+ }
+ if (this.re.schema_test.test(text2)) {
+ re = this.re.schema_search;
+ re.lastIndex = 0;
+ while ((m = re.exec(text2)) !== null) {
+ len = this.testSchemaAt(text2, m[2], re.lastIndex);
+ if (len) {
+ type_schemed.push({
+ schema: m[2],
+ index: m.index + m[1].length,
+ lastIndex: m.index + m[0].length + len
+ });
+ }
+ }
+ }
+ if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
+ re = this.__opts__.fuzzyIP ? this.re.link_fuzzy_global : this.re.link_no_ip_fuzzy_global;
+ re.lastIndex = 0;
+ while ((m = re.exec(text2)) !== null) {
+ type_fuzzy_link.push({
+ schema: "",
+ index: m.index + m[1].length,
+ lastIndex: m.index + m[0].length
+ });
+ }
+ }
+ if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
+ re = this.re.email_fuzzy_global;
+ re.lastIndex = 0;
+ while ((m = re.exec(text2)) !== null) {
+ type_fuzzy_email.push({
+ schema: "mailto:",
+ index: m.index + m[1].length,
+ lastIndex: m.index + m[0].length
+ });
+ }
+ }
+ const indexes = [0, 0, 0];
+ let lastIndex = 0;
+ for (; ; ) {
+ const candidates = [
+ type_schemed[indexes[0]],
+ type_fuzzy_email[indexes[1]],
+ type_fuzzy_link[indexes[2]]
+ ];
+ const candidate = choose(choose(candidates[0], candidates[1]), candidates[2]);
+ if (!candidate) {
+ break;
+ }
+ if (candidate === candidates[0]) {
+ indexes[0]++;
+ } else if (candidate === candidates[1]) {
+ indexes[1]++;
+ } else {
+ indexes[2]++;
+ }
+ if (candidate.index < lastIndex) {
+ continue;
+ }
+ const match2 = new Match(text2, candidate.schema, candidate.index, candidate.lastIndex);
+ this.__compiled__[match2.schema].normalize(match2, this);
+ result.push(match2);
+ lastIndex = candidate.lastIndex;
+ }
+ if (result.length) {
+ return result;
+ }
+ return null;
+ };
+ LinkifyIt.prototype.matchAtStart = function matchAtStart(text2) {
+ if (!text2.length) return null;
+ const m = this.re.schema_at_start.exec(text2);
+ if (!m) return null;
+ const len = this.testSchemaAt(text2, m[2], m[0].length);
+ if (!len) return null;
+ const match2 = new Match(text2, m[2], m.index + m[1].length, m.index + m[0].length + len);
+ this.__compiled__[match2.schema].normalize(match2, this);
+ return match2;
+ };
+ LinkifyIt.prototype.tlds = function tlds(list2, keepOld) {
+ list2 = Array.isArray(list2) ? list2 : [list2];
+ if (!keepOld) {
+ this.__tlds__ = list2.slice();
+ this.__tlds_replaced__ = true;
+ compile(this);
+ return this;
+ }
+ this.__tlds__ = this.__tlds__.concat(list2).sort().filter(function(el, idx, arr) {
+ return el !== arr[idx - 1];
+ }).reverse();
+ compile(this);
+ return this;
+ };
+ LinkifyIt.prototype.normalize = function normalize3(match2) {
+ if (!match2.schema) {
+ match2.url = `http://${match2.url}`;
+ }
+ if (match2.schema === "mailto:" && !/^mailto:/i.test(match2.url)) {
+ match2.url = `mailto:${match2.url}`;
+ }
+ };
+ LinkifyIt.prototype.onCompile = function onCompile() {
+ };
+ var linkify_it_default = LinkifyIt;
+
+ // third_party/editor/markdown-it/lib/index.mjs
+ var import_punycode = __toESM(require_punycode(), 1);
+
+ // third_party/editor/markdown-it/lib/presets/default.mjs
+ var default_default = {
+ options: {
+ // Enable HTML tags in source
+ html: false,
+ // Use '/' to close single tags ( )
+ xhtmlOut: false,
+ // Convert '\n' in paragraphs into
+ breaks: false,
+ // CSS language prefix for fenced blocks
+ langPrefix: "language-",
+ // autoconvert URL-like texts to links
+ linkify: false,
+ // Enable some language-neutral replacements + quotes beautification
+ typographer: false,
+ // Double + single quotes replacement pairs, when typographer enabled,
+ // and smartquotes on. Could be either a String or an Array.
+ //
+ // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
+ // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
+ quotes: "\u201C\u201D\u2018\u2019",
+ /* “”‘’ */
+ // Highlighter function. Should return escaped HTML,
+ // or '' if the source string is not changed and should be escaped externaly.
+ // If result starts with )
+ xhtmlOut: false,
+ // Convert '\n' in paragraphs into
+ breaks: false,
+ // CSS language prefix for fenced blocks
+ langPrefix: "language-",
+ // autoconvert URL-like texts to links
+ linkify: false,
+ // Enable some language-neutral replacements + quotes beautification
+ typographer: false,
+ // Double + single quotes replacement pairs, when typographer enabled,
+ // and smartquotes on. Could be either a String or an Array.
+ //
+ // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
+ // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
+ quotes: "\u201C\u201D\u2018\u2019",
+ /* “”‘’ */
+ // Highlighter function. Should return escaped HTML,
+ // or '' if the source string is not changed and should be escaped externaly.
+ // If result starts with )
+ xhtmlOut: true,
+ // Convert '\n' in paragraphs into
+ breaks: false,
+ // CSS language prefix for fenced blocks
+ langPrefix: "language-",
+ // autoconvert URL-like texts to links
+ linkify: false,
+ // Enable some language-neutral replacements + quotes beautification
+ typographer: false,
+ // Double + single quotes replacement pairs, when typographer enabled,
+ // and smartquotes on. Could be either a String or an Array.
+ //
+ // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
+ // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
+ quotes: "\u201C\u201D\u2018\u2019",
+ /* “”‘’ */
+ // Highlighter function. Should return escaped HTML,
+ // or '' if the source string is not changed and should be escaped externaly.
+ // If result starts with = 0) {
+ try {
+ parsed.hostname = import_punycode.default.toASCII(parsed.hostname);
+ } catch (er) {
+ }
+ }
+ }
+ return encode_default(format(parsed));
+ }
+ function normalizeLinkText(url) {
+ const parsed = parse_default(url, true);
+ if (parsed.hostname) {
+ if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
+ try {
+ parsed.hostname = import_punycode.default.toUnicode(parsed.hostname);
+ } catch (er) {
+ }
+ }
+ }
+ return decode_default(format(parsed), decode_default.defaultChars + "%");
+ }
+ function MarkdownIt(presetName, options) {
+ if (!(this instanceof MarkdownIt)) {
+ return new MarkdownIt(presetName, options);
+ }
+ if (!options) {
+ if (!isString(presetName)) {
+ options = presetName || {};
+ presetName = "default";
+ }
+ }
+ this.inline = new parser_inline_default();
+ this.block = new parser_block_default();
+ this.core = new parser_core_default();
+ this.renderer = new renderer_default();
+ this.linkify = new linkify_it_default();
+ this.validateLink = validateLink;
+ this.normalizeLink = normalizeLink;
+ this.normalizeLinkText = normalizeLinkText;
+ this.utils = utils_exports;
+ this.helpers = assign({}, helpers_exports);
+ this.options = {};
+ this.configure(presetName);
+ if (options) {
+ this.set(options);
+ }
+ }
+ MarkdownIt.prototype.set = function(options) {
+ assign(this.options, options);
+ return this;
+ };
+ MarkdownIt.prototype.configure = function(presets) {
+ const self = this;
+ if (isString(presets)) {
+ const presetName = presets;
+ presets = config[presetName];
+ if (!presets) {
+ throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
+ }
+ }
+ if (!presets) {
+ throw new Error("Wrong `markdown-it` preset, can't be empty");
+ }
+ if (presets.options) {
+ self.set(presets.options);
+ }
+ if (presets.components) {
+ Object.keys(presets.components).forEach(function(name) {
+ if (presets.components[name].rules) {
+ self[name].ruler.enableOnly(presets.components[name].rules);
+ }
+ if (presets.components[name].rules2) {
+ self[name].ruler2.enableOnly(presets.components[name].rules2);
+ }
+ });
+ }
+ return this;
+ };
+ MarkdownIt.prototype.enable = function(list2, ignoreInvalid) {
+ let result = [];
+ if (!Array.isArray(list2)) {
+ list2 = [list2];
+ }
+ ["core", "block", "inline"].forEach(function(chain) {
+ result = result.concat(this[chain].ruler.enable(list2, true));
+ }, this);
+ result = result.concat(this.inline.ruler2.enable(list2, true));
+ const missed = list2.filter(function(name) {
+ return result.indexOf(name) < 0;
+ });
+ if (missed.length && !ignoreInvalid) {
+ throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
+ }
+ return this;
+ };
+ MarkdownIt.prototype.disable = function(list2, ignoreInvalid) {
+ let result = [];
+ if (!Array.isArray(list2)) {
+ list2 = [list2];
+ }
+ ["core", "block", "inline"].forEach(function(chain) {
+ result = result.concat(this[chain].ruler.disable(list2, true));
+ }, this);
+ result = result.concat(this.inline.ruler2.disable(list2, true));
+ const missed = list2.filter(function(name) {
+ return result.indexOf(name) < 0;
+ });
+ if (missed.length && !ignoreInvalid) {
+ throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
+ }
+ return this;
+ };
+ MarkdownIt.prototype.use = function(plugin) {
+ const args = [this].concat(Array.prototype.slice.call(arguments, 1));
+ plugin.apply(plugin, args);
+ return this;
+ };
+ MarkdownIt.prototype.parse = function(src, env) {
+ if (typeof src !== "string") {
+ throw new Error("Input data should be a String");
+ }
+ const state = new this.core.State(src, this, env);
+ this.core.process(state);
+ return state.tokens;
+ };
+ MarkdownIt.prototype.render = function(src, env) {
+ env = env || {};
+ return this.renderer.render(this.parse(src, env), this.options, env);
+ };
+ MarkdownIt.prototype.parseInline = function(src, env) {
+ const state = new this.core.State(src, this, env);
+ state.inlineMode = true;
+ this.core.process(state);
+ return state.tokens;
+ };
+ MarkdownIt.prototype.renderInline = function(src, env) {
+ env = env || {};
+ return this.renderer.render(this.parseInline(src, env), this.options, env);
+ };
+ var lib_default = MarkdownIt;
+
+ // third_party/editor/prosemirror-markdown/src/from_markdown.ts
+ function maybeMerge(a, b) {
+ if (a.isText && b.isText && Mark.sameSet(a.marks, b.marks))
+ return a.withText(a.text + b.text);
+ }
+ var MarkdownParseState = class {
+ constructor(schema3, tokenHandlers2) {
+ this.schema = schema3;
+ this.tokenHandlers = tokenHandlers2;
+ this.stack = [{ type: schema3.topNodeType, attrs: null, content: [], marks: Mark.none }];
+ }
+ schema;
+ tokenHandlers;
+ stack;
+ top() {
+ return this.stack[this.stack.length - 1];
+ }
+ push(elt) {
+ if (this.stack.length) this.top().content.push(elt);
+ }
+ // Adds the given text to the current position in the document,
+ // using the current marks as styling.
+ addText(text2) {
+ if (!text2) return;
+ let top = this.top(), nodes = top.content, last = nodes[nodes.length - 1];
+ let node = this.schema.text(text2, top.marks), merged;
+ if (last && (merged = maybeMerge(last, node))) nodes[nodes.length - 1] = merged;
+ else nodes.push(node);
+ }
+ // Adds the given mark to the set of active marks.
+ openMark(mark) {
+ let top = this.top();
+ top.marks = mark.addToSet(top.marks);
+ }
+ // Removes the given mark from the set of active marks.
+ closeMark(mark) {
+ let top = this.top();
+ top.marks = mark.removeFromSet(top.marks);
+ }
+ parseTokens(toks) {
+ for (let i2 = 0; i2 < toks.length; i2++) {
+ let tok = toks[i2];
+ let handler = this.tokenHandlers[tok.type];
+ if (!handler)
+ throw new Error("Token type `" + tok.type + "` not supported by Markdown parser");
+ handler(this, tok, toks, i2);
+ }
+ }
+ // Add a node at the current position.
+ addNode(type, attrs2, content) {
+ let top = this.top();
+ let node = type.createAndFill(attrs2, content, top ? top.marks : []);
+ if (!node) return null;
+ this.push(node);
+ return node;
+ }
+ // Wrap subsequent content in a node of the given type.
+ openNode(type, attrs2) {
+ this.stack.push({ type, attrs: attrs2, content: [], marks: Mark.none });
+ }
+ // Close and return the node that is currently on top of the stack.
+ closeNode() {
+ let info = this.stack.pop();
+ return this.addNode(info.type, info.attrs, info.content);
+ }
+ };
+ function attrs(spec, token, tokens, i2) {
+ if (spec.getAttrs) return spec.getAttrs(token, tokens, i2);
+ else if (spec.attrs instanceof Function) return spec.attrs(token);
+ else return spec.attrs;
+ }
+ function noCloseToken(spec, type) {
+ return spec.noCloseToken || type == "code_inline" || type == "code_block" || type == "fence";
+ }
+ function withoutTrailingNewline(str) {
+ return str[str.length - 1] == "\n" ? str.slice(0, str.length - 1) : str;
+ }
+ function noOp() {
+ }
+ function tokenHandlers(schema3, tokens) {
+ let handlers2 = /* @__PURE__ */ Object.create(null);
+ for (let type in tokens) {
+ let spec = tokens[type];
+ if (spec.block) {
+ let nodeType = schema3.nodeType(spec.block);
+ if (noCloseToken(spec, type)) {
+ handlers2[type] = (state, tok, tokens2, i2) => {
+ state.openNode(nodeType, attrs(spec, tok, tokens2, i2));
+ state.addText(withoutTrailingNewline(tok.content));
+ state.closeNode();
+ };
+ } else {
+ handlers2[type + "_open"] = (state, tok, tokens2, i2) => state.openNode(nodeType, attrs(spec, tok, tokens2, i2));
+ handlers2[type + "_close"] = (state) => state.closeNode();
+ }
+ } else if (spec.node) {
+ let nodeType = schema3.nodeType(spec.node);
+ handlers2[type] = (state, tok, tokens2, i2) => state.addNode(nodeType, attrs(spec, tok, tokens2, i2));
+ } else if (spec.mark) {
+ let markType = schema3.marks[spec.mark];
+ if (noCloseToken(spec, type)) {
+ handlers2[type] = (state, tok, tokens2, i2) => {
+ state.openMark(markType.create(attrs(spec, tok, tokens2, i2)));
+ state.addText(withoutTrailingNewline(tok.content));
+ state.closeMark(markType);
+ };
+ } else {
+ handlers2[type + "_open"] = (state, tok, tokens2, i2) => state.openMark(markType.create(attrs(spec, tok, tokens2, i2)));
+ handlers2[type + "_close"] = (state) => state.closeMark(markType);
+ }
+ } else if (spec.ignore) {
+ if (noCloseToken(spec, type)) {
+ handlers2[type] = noOp;
+ } else {
+ handlers2[type + "_open"] = noOp;
+ handlers2[type + "_close"] = noOp;
+ }
+ } else {
+ throw new RangeError("Unrecognized parsing spec " + JSON.stringify(spec));
+ }
+ }
+ handlers2.text = (state, tok) => state.addText(tok.content);
+ handlers2.inline = (state, tok) => state.parseTokens(tok.children);
+ handlers2.softbreak = handlers2.softbreak || ((state) => state.addText(" "));
+ return handlers2;
+ }
+ var MarkdownParser = class {
+ /// Create a parser with the given configuration. You can configure
+ /// the markdown-it parser to parse the dialect you want, and provide
+ /// a description of the ProseMirror entities those tokens map to in
+ /// the `tokens` object, which maps token names to descriptions of
+ /// what to do with them. Such a description is an object, and may
+ /// have the following properties:
+ constructor(schema3, tokenizer2, tokens) {
+ this.schema = schema3;
+ this.tokenizer = tokenizer2;
+ this.tokens = tokens;
+ this.tokenHandlers = tokenHandlers(schema3, tokens);
+ }
+ schema;
+ tokenizer;
+ tokens;
+ /// @internal
+ tokenHandlers;
+ /// Parse a string as [CommonMark](http://commonmark.org/) markup,
+ /// and create a ProseMirror document as prescribed by this parser's
+ /// rules.
+ ///
+ /// The second argument, when given, is passed through to the
+ /// [Markdown
+ /// parser](https://markdown-it.github.io/markdown-it/#MarkdownIt.parse).
+ parse(text2, markdownEnv = {}) {
+ let state = new MarkdownParseState(this.schema, this.tokenHandlers), doc3;
+ state.parseTokens(this.tokenizer.parse(text2, markdownEnv));
+ do {
+ doc3 = state.closeNode();
+ } while (state.stack.length);
+ return doc3 || this.schema.topNodeType.createAndFill();
+ }
+ };
+ function listIsTight(tokens, i2) {
+ while (++i2 < tokens.length)
+ if (tokens[i2].type != "list_item_open") return tokens[i2].hidden;
+ return false;
+ }
+ var defaultMarkdownParser = new MarkdownParser(schema, lib_default("commonmark", { html: false }), {
+ blockquote: { block: "blockquote" },
+ paragraph: { block: "paragraph" },
+ list_item: { block: "list_item" },
+ bullet_list: { block: "bullet_list", getAttrs: (_, tokens, i2) => ({ tight: listIsTight(tokens, i2) }) },
+ ordered_list: { block: "ordered_list", getAttrs: (tok, tokens, i2) => ({
+ order: +tok.attrGet("start") || 1,
+ tight: listIsTight(tokens, i2)
+ }) },
+ heading: { block: "heading", getAttrs: (tok) => ({ level: +tok.tag.slice(1) }) },
+ code_block: { block: "code_block", noCloseToken: true },
+ fence: { block: "code_block", getAttrs: (tok) => ({ params: tok.info || "" }), noCloseToken: true },
+ hr: { node: "horizontal_rule" },
+ image: { node: "image", getAttrs: (tok) => ({
+ src: tok.attrGet("src"),
+ title: tok.attrGet("title") || null,
+ alt: tok.children[0] && tok.children[0].content || null
+ }) },
+ hardbreak: { node: "hard_break" },
+ em: { mark: "em" },
+ strong: { mark: "strong" },
+ link: { mark: "link", getAttrs: (tok) => ({
+ href: tok.attrGet("href"),
+ title: tok.attrGet("title") || null
+ }) },
+ code_inline: { mark: "code", noCloseToken: true }
+ });
+
+ // third_party/editor/prosemirror-markdown/src/to_markdown.ts
+ var blankMark = { open: "", close: "", mixable: true };
+ var MarkdownSerializer = class {
+ /// Construct a serializer with the given configuration. The `nodes`
+ /// object should map node names in a given schema to function that
+ /// take a serializer state and such a node, and serialize the node.
+ constructor(nodes, marks, options = {}) {
+ this.nodes = nodes;
+ this.marks = marks;
+ this.options = options;
+ }
+ nodes;
+ marks;
+ options;
+ /// Serialize the content of the given node to
+ /// [CommonMark](http://commonmark.org/).
+ serialize(content, options = {}) {
+ options = Object.assign({}, this.options, options);
+ let state = new MarkdownSerializerState(this.nodes, this.marks, options);
+ state.renderContent(content);
+ return state.out;
+ }
+ };
+ var defaultMarkdownSerializer = new MarkdownSerializer({
+ blockquote(state, node) {
+ state.wrapBlock("> ", null, node, () => state.renderContent(node));
+ },
+ code_block(state, node) {
+ const backticks = node.textContent.match(/`{3,}/gm);
+ const fence2 = backticks ? backticks.sort().slice(-1)[0] + "`" : "```";
+ state.write(fence2 + (node.attrs.params || "") + "\n");
+ state.text(node.textContent, false);
+ state.write("\n");
+ state.write(fence2);
+ state.closeBlock(node);
+ },
+ heading(state, node) {
+ state.write(state.repeat("#", node.attrs.level) + " ");
+ state.renderInline(node, false);
+ state.closeBlock(node);
+ },
+ horizontal_rule(state, node) {
+ state.write(node.attrs.markup || "---");
+ state.closeBlock(node);
+ },
+ bullet_list(state, node) {
+ state.renderList(node, " ", () => (node.attrs.bullet || "*") + " ");
+ },
+ ordered_list(state, node) {
+ let start = node.attrs.order ?? 1;
+ let maxW = String(start + node.childCount - 1).length;
+ let space = state.repeat(" ", maxW + 2);
+ state.renderList(node, space, (i2) => {
+ let nStr = String(start + i2);
+ return state.repeat(" ", maxW - nStr.length) + nStr + ". ";
+ });
+ },
+ list_item(state, node) {
+ state.renderContent(node);
+ },
+ paragraph(state, node) {
+ state.renderInline(node);
+ state.closeBlock(node);
+ },
+ image(state, node) {
+ state.write("]/g, "\\$&") + (node.attrs.title ? ' "' + node.attrs.title.replace(/"/g, '\\"') + '"' : "") + ")");
+ },
+ hard_break(state, node, parent, index) {
+ for (let i2 = index + 1; i2 < parent.childCount; i2++)
+ if (parent.child(i2).type != node.type) {
+ state.write("\\\n");
+ return;
+ }
+ },
+ text(state, node) {
+ state.text(node.text, !state.inAutolink);
+ }
+ }, {
+ em: { open: "*", close: "*", mixable: true, expelEnclosingWhitespace: true },
+ strong: { open: "**", close: "**", mixable: true, expelEnclosingWhitespace: true },
+ link: {
+ open(state, mark, parent, index) {
+ state.inAutolink = isPlainURL(mark, parent, index);
+ return state.inAutolink ? "<" : "[";
+ },
+ close(state, mark, parent, index) {
+ let { inAutolink } = state;
+ state.inAutolink = void 0;
+ return inAutolink ? ">" : "](" + mark.attrs.href.replace(/[\(\)"]/g, "\\$&") + (mark.attrs.title ? ` "${mark.attrs.title.replace(/"/g, '\\"')}"` : "") + ")";
+ },
+ mixable: true
+ },
+ code: {
+ open(_state, _mark, parent, index) {
+ return backticksFor(parent.child(index), -1);
+ },
+ close(_state, _mark, parent, index) {
+ return backticksFor(parent.child(index - 1), 1);
+ },
+ escape: false
+ }
+ });
+ function backticksFor(node, side) {
+ let ticks = /`+/g, m, len = 0;
+ if (node.isText) while (m = ticks.exec(node.text)) len = Math.max(len, m[0].length);
+ let result = len > 0 && side > 0 ? " `" : "`";
+ for (let i2 = 0; i2 < len; i2++) result += "`";
+ if (len > 0 && side < 0) result += " ";
+ return result;
+ }
+ function isPlainURL(link4, parent, index) {
+ if (link4.attrs.title || !/^\w+:/.test(link4.attrs.href)) return false;
+ let content = parent.child(index);
+ if (!content.isText || content.text != link4.attrs.href || content.marks[content.marks.length - 1] != link4) return false;
+ return index == parent.childCount - 1 || !link4.isInSet(parent.child(index + 1).marks);
+ }
+ var MarkdownSerializerState = class {
+ /// @internal
+ constructor(nodes, marks, options) {
+ this.nodes = nodes;
+ this.marks = marks;
+ this.options = options;
+ if (typeof this.options.tightLists == "undefined")
+ this.options.tightLists = false;
+ if (typeof this.options.hardBreakNodeName == "undefined")
+ this.options.hardBreakNodeName = "hard_break";
+ }
+ nodes;
+ marks;
+ options;
+ /// @internal
+ delim = "";
+ /// @internal
+ out = "";
+ /// @internal
+ closed = null;
+ /// @internal
+ inAutolink = void 0;
+ /// @internal
+ atBlockStart = false;
+ /// @internal
+ inTightList = false;
+ /// @internal
+ flushClose(size = 2) {
+ if (this.closed) {
+ if (!this.atBlank()) this.out += "\n";
+ if (size > 1) {
+ let delimMin = this.delim;
+ let trim = /\s+$/.exec(delimMin);
+ if (trim) delimMin = delimMin.slice(0, delimMin.length - trim[0].length);
+ for (let i2 = 1; i2 < size; i2++)
+ this.out += delimMin + "\n";
+ }
+ this.closed = null;
+ }
+ }
+ /// @internal
+ getMark(name) {
+ let info = this.marks[name];
+ if (!info) {
+ if (this.options.strict !== false)
+ throw new Error(`Mark type \`${name}\` not supported by Markdown renderer`);
+ info = blankMark;
+ }
+ return info;
+ }
+ /// Render a block, prefixing each line with `delim`, and the first
+ /// line in `firstDelim`. `node` should be the node that is closed at
+ /// the end of the block, and `f` is a function that renders the
+ /// content of the block.
+ wrapBlock(delim, firstDelim, node, f) {
+ let old = this.delim;
+ this.write(firstDelim != null ? firstDelim : delim);
+ this.delim += delim;
+ f();
+ this.delim = old;
+ this.closeBlock(node);
+ }
+ /// @internal
+ atBlank() {
+ return /(^|\n)$/.test(this.out);
+ }
+ /// Ensure the current content ends with a newline.
+ ensureNewLine() {
+ if (!this.atBlank()) this.out += "\n";
+ }
+ /// Prepare the state for writing output (closing closed paragraphs,
+ /// adding delimiters, and so on), and then optionally add content
+ /// (unescaped) to the output.
+ write(content) {
+ this.flushClose();
+ if (this.delim && this.atBlank())
+ this.out += this.delim;
+ if (content) this.out += content;
+ }
+ /// Close the block for the given node.
+ closeBlock(node) {
+ this.closed = node;
+ }
+ /// Add the given text to the document. When escape is not `false`,
+ /// it will be escaped.
+ text(text2, escape2 = true) {
+ let lines = text2.split("\n");
+ for (let i2 = 0; i2 < lines.length; i2++) {
+ this.write();
+ if (!escape2 && lines[i2][0] == "[" && /(^|[^\\])\!$/.test(this.out))
+ this.out = this.out.slice(0, this.out.length - 1) + "\\!";
+ this.out += escape2 ? this.esc(lines[i2], this.atBlockStart) : lines[i2];
+ if (i2 != lines.length - 1) this.out += "\n";
+ }
+ }
+ /// Render the given node as a block.
+ render(node, parent, index) {
+ if (this.nodes[node.type.name]) {
+ this.nodes[node.type.name](this, node, parent, index);
+ } else {
+ if (this.options.strict !== false) {
+ throw new Error("Token type `" + node.type.name + "` not supported by Markdown renderer");
+ } else if (!node.type.isLeaf) {
+ if (node.type.inlineContent) this.renderInline(node);
+ else this.renderContent(node);
+ if (node.isBlock) this.closeBlock(node);
+ }
+ }
+ }
+ /// Render the contents of `parent` as block nodes.
+ renderContent(parent) {
+ parent.forEach((node, _, i2) => this.render(node, parent, i2));
+ }
+ /// Render the contents of `parent` as inline content.
+ renderInline(parent, fromBlockStart = true) {
+ this.atBlockStart = fromBlockStart;
+ let active = [], trailing = "";
+ let progress = (node, offset, index) => {
+ let marks = node ? node.marks : [];
+ if (node && node.type.name === this.options.hardBreakNodeName)
+ marks = marks.filter((m) => {
+ if (index + 1 == parent.childCount) return false;
+ let next = parent.child(index + 1);
+ return m.isInSet(next.marks) && (!next.isText || /\S/.test(next.text));
+ });
+ let inner = marks.length ? marks[marks.length - 1] : null;
+ let noEsc = inner && this.getMark(inner.type.name).escape === false;
+ let len = marks.length - (noEsc ? 1 : 0);
+ outer: for (let i2 = 0; i2 < len; i2++) {
+ let mark = marks[i2];
+ if (!this.getMark(mark.type.name).mixable) break;
+ for (let j = 0; j < active.length; j++) {
+ let other = active[j];
+ if (!this.getMark(other.type.name).mixable) break;
+ if (mark.eq(other)) {
+ if (i2 > j)
+ marks = marks.slice(0, j).concat(mark).concat(marks.slice(j, i2)).concat(marks.slice(i2 + 1, len));
+ else if (j > i2)
+ marks = marks.slice(0, i2).concat(marks.slice(i2 + 1, j)).concat(mark).concat(marks.slice(j, len));
+ continue outer;
+ }
+ }
+ }
+ let keep = 0;
+ while (keep < Math.min(active.length, len) && marks[keep].eq(active[keep])) ++keep;
+ let leading = trailing;
+ trailing = "";
+ if (node && node.isText && marks.some((mark) => {
+ let info = this.getMark(mark.type.name);
+ return info && info.expelEnclosingWhitespace && !active.some((m, i2) => i2 < keep && m.eq(mark));
+ })) {
+ let [_, lead, rest] = /^(\s*)(.*)$/m.exec(node.text);
+ if (lead) {
+ leading += lead;
+ node = rest ? node.withText(rest) : null;
+ if (!node) marks = active;
+ }
+ }
+ if (node && node.isText && marks.some((mark, i2) => {
+ let info = this.getMark(mark.type.name);
+ return info && info.expelEnclosingWhitespace && !this.isMarkAhead(parent, index + 1, marks.slice(0, i2 + 1));
+ })) {
+ let [_, rest, trail] = /^(.*?)(\s*)$/m.exec(node.text);
+ if (trail) {
+ trailing = trail;
+ node = rest ? node.withText(rest) : null;
+ if (!node) marks = active;
+ }
+ }
+ if (node || index == parent.childCount) while (keep < active.length)
+ this.text(this.markString(active.pop(), false, parent, index), false);
+ if (leading) this.text(leading);
+ if (node) {
+ while (active.length < len) {
+ let add2 = marks[active.length];
+ active.push(add2);
+ this.text(this.markString(add2, true, parent, index), false);
+ this.atBlockStart = false;
+ }
+ if (noEsc && node.isText)
+ this.text(this.markString(inner, true, parent, index) + node.text + this.markString(inner, false, parent, index + 1), false);
+ else
+ this.render(node, parent, index);
+ this.atBlockStart = false;
+ if (node.isText && node.nodeSize > 0) this.atBlockStart = false;
+ }
+ };
+ parent.forEach(progress);
+ progress(null, 0, parent.childCount);
+ this.atBlockStart = false;
+ }
+ /// Render a node's content as a list. `delim` should be the extra
+ /// indentation added to all lines except the first in an item,
+ /// `firstDelim` is a function going from an item index to a
+ /// delimiter for the first line of the item.
+ renderList(node, delim, firstDelim) {
+ if (this.closed && this.closed.type == node.type)
+ this.flushClose(3);
+ else if (this.inTightList)
+ this.flushClose(1);
+ let isTight = typeof node.attrs.tight != "undefined" ? node.attrs.tight : this.options.tightLists;
+ let prevTight = this.inTightList;
+ this.inTightList = isTight;
+ node.forEach((child, _, i2) => {
+ if (i2 && isTight) this.flushClose(1);
+ this.wrapBlock(delim, firstDelim(i2), node, () => this.render(child, node, i2));
+ });
+ this.inTightList = prevTight;
+ }
+ /// Escape the given string so that it can safely appear in Markdown
+ /// content. If `startOfLine` is true, also escape characters that
+ /// have special meaning only at the start of the line.
+ esc(str, startOfLine = false) {
+ str = str.replace(
+ /[`*\\~\[\]_]/g,
+ (m, i2) => m == "_" && i2 > 0 && i2 + 1 < str.length && str[i2 - 1].match(/\w/) && str[i2 + 1].match(/\w/) ? m : "\\" + m
+ );
+ if (startOfLine) str = str.replace(/^(\+[ ]|[\-*>])/, "\\$&").replace(/^(\s*)(#{1,6})(\s|$)/, "$1\\$2$3").replace(/^(\s*\d+)\.\s/, "$1\\. ");
+ if (this.options.escapeExtraCharacters) str = str.replace(this.options.escapeExtraCharacters, "\\$&");
+ return str;
+ }
+ /// @internal
+ quote(str) {
+ let wrap2 = str.indexOf('"') == -1 ? '""' : str.indexOf("'") == -1 ? "''" : "()";
+ return wrap2[0] + str + wrap2[1];
+ }
+ /// Repeat the given string `n` times.
+ repeat(str, n) {
+ let out = "";
+ for (let i2 = 0; i2 < n; i2++) out += str;
+ return out;
+ }
+ /// Get the markdown string for a given opening or closing mark.
+ markString(mark, open, parent, index) {
+ let info = this.getMark(mark.type.name);
+ let value = open ? info.open : info.close;
+ return typeof value == "string" ? value : value(this, mark, parent, index);
+ }
+ /// Get leading and trailing whitespace from a string. Values of
+ /// leading or trailing property of the return object will be undefined
+ /// if there is no match.
+ getEnclosingWhitespace(text2) {
+ return {
+ leading: (text2.match(/^(\s+)/) || [void 0])[0],
+ trailing: (text2.match(/(\s+)$/) || [void 0])[0]
+ };
+ }
+ /// @internal
+ isMarkAhead(parent, index, marks) {
+ for (; ; index++) {
+ if (index >= parent.childCount) return false;
+ let next = parent.child(index);
+ if (next.type.name != this.options.hardBreakNodeName) {
+ return next.marks.length >= marks.length && Mark.sameSet(next.marks.slice(0, marks.length), marks);
+ }
+ index++;
+ }
+ }
+ };
+
+ // editor/model.mjs
+ var linkTarget = (raw) => {
+ const gate = globalThis.MosaicMarkdown?.linkTarget;
+ return typeof gate === "function" ? gate(raw) : null;
+ };
+ var kept = { raw: { default: null }, sig: { default: null }, lead: { default: "" } };
+ var block2 = (attrs2) => ({ ...kept, ...attrs2 });
+ var schema2 = new Schema({
+ nodes: {
+ doc: { content: "block+", attrs: { tail: { default: "" } } },
+ paragraph: { content: "inline*", group: "block", attrs: block2({}), parseDOM: [{ tag: "p" }], toDOM() {
+ return ["p", 0];
+ } },
+ blockquote: { content: "block+", group: "block", attrs: block2({}), parseDOM: [{ tag: "blockquote" }], toDOM() {
+ return ["blockquote", 0];
+ } },
+ horizontal_rule: { group: "block", attrs: block2({}), parseDOM: [{ tag: "hr" }], toDOM() {
+ return ["div", ["hr"]];
+ } },
+ heading: {
+ attrs: block2({ level: { default: 1 } }),
+ content: "(text | image)*",
+ group: "block",
+ defining: true,
+ parseDOM: [1, 2, 3, 4, 5, 6].map((level) => ({ tag: "h" + level, attrs: { level } })),
+ toDOM(node) {
+ return ["h" + +node.attrs.level, 0];
+ }
+ },
+ code_block: {
+ content: "text*",
+ group: "block",
+ code: true,
+ defining: true,
+ marks: "",
+ attrs: block2({ params: { default: "" } }),
+ parseDOM: [{ tag: "pre", preserveWhitespace: "full", getAttrs: (dom) => ({ params: dom.getAttribute("data-params") || "" }) }],
+ toDOM(node) {
+ return ["pre", node.attrs.params ? { "data-params": node.attrs.params } : {}, ["code", 0]];
+ }
+ },
+ // Source the editor does not model. Edited as plain text, written back as typed.
+ raw_block: {
+ content: "text*",
+ group: "block",
+ code: true,
+ defining: true,
+ marks: "",
+ attrs: block2({}),
+ parseDOM: [{ tag: "pre.md-raw", preserveWhitespace: "full" }],
+ toDOM() {
+ return ["pre", { class: "md-raw", title: "Markdown the visual editor keeps as written" }, ["code", 0]];
+ }
+ },
+ ordered_list: {
+ content: "list_item+",
+ group: "block",
+ attrs: block2({ order: { default: 1 }, tight: { default: false } }),
+ parseDOM: [{ tag: "ol", getAttrs: (dom) => ({ order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1, tight: dom.hasAttribute("data-tight") }) }],
+ toDOM(node) {
+ return ["ol", { start: node.attrs.order === 1 ? null : node.attrs.order, "data-tight": node.attrs.tight ? "true" : null }, 0];
+ }
+ },
+ bullet_list: {
+ content: "list_item+",
+ group: "block",
+ attrs: block2({ tight: { default: false } }),
+ parseDOM: [{ tag: "ul", getAttrs: (dom) => ({ tight: dom.hasAttribute("data-tight") }) }],
+ toDOM(node) {
+ return ["ul", { "data-tight": node.attrs.tight ? "true" : null }, 0];
+ }
+ },
+ list_item: { content: "block+", defining: true, parseDOM: [{ tag: "li" }], toDOM() {
+ return ["li", 0];
+ } },
+ text: { group: "inline" },
+ // An image is never loaded: it is an atom drawn as the text `[image: alt] address`, as row 148's
+ // preview draws it. There is no in the schema and no rule that makes one from pasted HTML.
+ image: {
+ inline: true,
+ group: "inline",
+ atom: true,
+ draggable: true,
+ attrs: { src: {}, alt: { default: null }, title: { default: null } },
+ parseDOM: [{
+ tag: "span.md-image[data-src]",
+ // Pasted HTML gets an image atom only for a target the link gate accepts; a file's own image, whatever
+ // its target, stays on the load path, where it is drawn as text and never fetched.
+ getAttrs: (dom) => linkTarget(dom.getAttribute("data-src")) === null ? false : { src: dom.getAttribute("data-src"), alt: dom.getAttribute("data-alt"), title: dom.getAttribute("data-title") }
+ }],
+ toDOM(node) {
+ const a = node.attrs, shown = `[image: ${a.alt ?? ""}] ${a.src}`;
+ return ["span", { class: "md-image", "data-src": a.src, "data-alt": a.alt, "data-title": a.title }, shown];
+ }
+ },
+ hard_break: { inline: true, group: "inline", selectable: false, parseDOM: [{ tag: "br" }], toDOM() {
+ return ["br"];
+ } }
+ },
+ marks: {
+ em: {
+ parseDOM: [{ tag: "i" }, { tag: "em" }, { style: "font-style=italic" }, { style: "font-style=normal", clearMark: (m) => m.type.name === "em" }],
+ toDOM() {
+ return ["em"];
+ }
+ },
+ strong: {
+ parseDOM: [
+ { tag: "strong" },
+ { tag: "b", getAttrs: (dom) => dom.style.fontWeight !== "normal" && null },
+ { style: "font-weight=400", clearMark: (m) => m.type.name === "strong" },
+ { style: "font-weight", getAttrs: (v) => /^(bold(er)?|[5-9]\d{2,})$/.test(v) && null }
+ ],
+ toDOM() {
+ return ["strong"];
+ }
+ },
+ // A link mark exists only for a target the gate accepts, on load, on paste and in the link bar.
+ link: {
+ attrs: { href: {}, title: { default: null } },
+ inclusive: false,
+ parseDOM: [{
+ tag: "a[href]",
+ getAttrs: (dom) => {
+ const href = linkTarget(dom.getAttribute("href"));
+ return href ? { href, title: dom.getAttribute("title") } : false;
+ }
+ }],
+ toDOM(mark) {
+ const href = linkTarget(mark.attrs.href);
+ if (!href) return ["span", { class: "md-bad-link" }, 0];
+ const attrs2 = { href, rel: "noopener noreferrer", target: "_blank" };
+ if (mark.attrs.title) attrs2.title = mark.attrs.title;
+ return ["a", attrs2, 0];
+ }
+ },
+ code: { code: true, parseDOM: [{ tag: "code" }], toDOM() {
+ return ["code"];
+ } }
+ }
+ });
+ var splitter = lib_default("commonmark", { html: true }).enable("table").enable("strikethrough");
+ var tokenizer = lib_default("commonmark", { html: false }).enable("table").enable("strikethrough");
+ var refused = false;
+ var prepared = {
+ parse(text2, env) {
+ const tokens = tokenizer.parse(text2, env);
+ for (const t of tokens) {
+ for (const c of t.children ?? []) {
+ if (c.type === "softbreak") {
+ c.type = "text";
+ c.content = "\n";
+ } else if (c.type === "link_open" && !linkTarget(c.attrGet("href"))) refused = true;
+ }
+ }
+ return tokens;
+ }
+ };
+ var tight = (tokens, i2) => {
+ while (++i2 < tokens.length) if (tokens[i2].type !== "list_item_open") return tokens[i2].hidden;
+ return false;
+ };
+ var parser = new MarkdownParser(schema2, prepared, {
+ blockquote: { block: "blockquote" },
+ paragraph: { block: "paragraph" },
+ list_item: { block: "list_item" },
+ bullet_list: { block: "bullet_list", getAttrs: (_, tokens, i2) => ({ tight: tight(tokens, i2) }) },
+ ordered_list: { block: "ordered_list", getAttrs: (tok, tokens, i2) => ({ order: +tok.attrGet("start") || 1, tight: tight(tokens, i2) }) },
+ heading: { block: "heading", getAttrs: (tok) => ({ level: +tok.tag.slice(1) }) },
+ code_block: { block: "code_block", noCloseToken: true },
+ // A tilde fence may carry a backtick in its info string; the serialiser would drop that info, so the block stays source.
+ fence: { block: "code_block", getAttrs: (tok) => {
+ if (tok.info.includes("`")) refused = true;
+ return { params: tok.info || "" };
+ }, noCloseToken: true },
+ hr: { node: "horizontal_rule" },
+ image: { node: "image", getAttrs: (tok) => ({ src: tok.attrGet("src"), title: tok.attrGet("title") || null, alt: tok.content || null }) },
+ hardbreak: { node: "hard_break" },
+ em: { mark: "em" },
+ strong: { mark: "strong" },
+ link: { mark: "link", getAttrs: (tok) => ({ href: tok.attrGet("href"), title: tok.attrGet("title") || null }) },
+ code_inline: { mark: "code", noCloseToken: true }
+ });
+ var oneLine = (value) => typeof value === "string" ? value.replace(/[\r\n]+/g, " ") : value;
+ var titleBackslash = (value) => typeof value === "string" ? oneLine(value).replace(/\\/g, "\\\\") : value;
+ var fenceInfo = (value) => {
+ const info = typeof value === "string" ? value.split(/[\r\n]/, 1)[0] : "";
+ return info.includes("`") ? "" : info;
+ };
+ var link2 = defaultMarkdownSerializer.marks.link;
+ var serializer = new MarkdownSerializer({
+ ...defaultMarkdownSerializer.nodes,
+ code_block(state, node) {
+ const params = fenceInfo(node.attrs.params);
+ defaultMarkdownSerializer.nodes.code_block(state, params === node.attrs.params ? node : node.type.create({ ...node.attrs, params }, node.content));
+ },
+ text(state, node) {
+ const esc = state.esc;
+ state.esc = (str, start) => esc.call(state, str, start).replace(/[<&]/g, "\\$&");
+ try {
+ state.text(node.text, !state.inAutolink);
+ } finally {
+ delete state.esc;
+ }
+ },
+ bullet_list(state, node) {
+ state.renderList(node, " ", () => "- ");
+ },
+ image(state, node) {
+ const a = node.attrs;
+ const title = oneLine(a.title);
+ state.write("]/g, "\\$&") + (title ? ' "' + title.replace(/[\\"]/g, "\\$&") + '"' : "") + ")");
+ },
+ raw_block(state, node) {
+ state.text(node.textContent, false);
+ state.closeBlock(node);
+ }
+ }, {
+ ...defaultMarkdownSerializer.marks,
+ // Only `close` writes the title; `open` reads it just to tell an autolink, which a title rules out either way.
+ link: { ...link2, close: (state, mark, parent, index) => {
+ const title = titleBackslash(mark.attrs.title);
+ return link2.close(state, title === mark.attrs.title ? mark : mark.type.create({ ...mark.attrs, title }), parent, index);
+ } }
+ });
+ var written = /* @__PURE__ */ new WeakMap();
+ function canonical(node) {
+ let text2 = written.get(node);
+ if (text2 === void 0) {
+ text2 = node.type.name === "raw_block" ? node.textContent : serializer.serialize(schema2.nodes.doc.create(null, [node]));
+ written.set(node, text2);
+ }
+ return text2;
+ }
+ var STRUCTURED = /* @__PURE__ */ new Set(["paragraph", "heading", "blockquote", "bullet_list", "ordered_list", "fence", "hr"]);
+ var span = (lines, a, b) => a >= b ? "" : lines.slice(a, b).join("\n") + (b < lines.length ? "\n" : "");
+ function frontMatter(lines) {
+ if (lines[0] !== "---") return 0;
+ for (let i2 = 1; i2 < lines.length; i2++) if (lines[i2] === "---" || lines[i2] === "...") return i2 + 1;
+ return 0;
+ }
+ function blocks(lines) {
+ const found2 = [];
+ const fm = frontMatter(lines);
+ if (fm) found2.push({ from: 0, to: fm, kind: "raw" });
+ const rest = lines.slice(fm).join("\n"), env = {};
+ const tokens = splitter.parse(rest, env);
+ for (const t of tokens) {
+ if (t.level !== 0 || !t.map || t.nesting === -1) continue;
+ const kind = t.type.replace(/_open$/, "");
+ const from = t.map[0] + fm, to = t.map[1] + fm;
+ const plain = STRUCTURED.has(kind) && (kind !== "heading" || to - from <= 1);
+ found2.push({ from, to, kind: plain ? kind : "raw" });
+ }
+ const all = [];
+ let cursor = 0;
+ const gap = (to) => {
+ for (let i2 = cursor; i2 < to; i2++) {
+ if (!lines[i2].trim()) continue;
+ let j = i2;
+ while (j < to && lines[j].trim()) j++;
+ all.push({ from: i2, to: j, kind: "raw" });
+ i2 = j;
+ }
+ };
+ for (const b of found2) {
+ if (b.from < cursor) return null;
+ gap(b.from);
+ all.push(b);
+ cursor = b.to;
+ }
+ gap(lines.length);
+ return { all, env };
+ }
+ function nodeOf(kind, text2, env) {
+ if (kind !== "raw") {
+ refused = false;
+ try {
+ const doc3 = parser.parse(text2, env);
+ if (doc3.childCount === 1 && !refused) return doc3.firstChild;
+ } catch {
+ }
+ }
+ return schema2.nodes.raw_block.create(null, text2 ? schema2.text(text2) : null);
+ }
+ function parse(src) {
+ const lines = String(src).split("\n");
+ const found2 = blocks(lines) ?? { all: [{ from: 0, to: lines.length, kind: "raw" }], env: {} };
+ const children = [];
+ let cursor = 0;
+ for (const b of found2.all) {
+ const text2 = lines.slice(b.from, b.to).join("\n");
+ const node = nodeOf(b.kind, text2, found2.env);
+ const attrs2 = { ...node.attrs, raw: span(lines, b.from, b.to), lead: span(lines, cursor, b.from) };
+ let made = node.type.create(attrs2, node.content, node.marks);
+ made = node.type.create({ ...attrs2, sig: canonical(made) }, node.content, node.marks);
+ children.push(made);
+ cursor = b.to;
+ }
+ return schema2.nodes.doc.create({ tail: span(lines, cursor, lines.length) }, children.length ? children : [schema2.nodes.paragraph.create()]);
+ }
+ function serialise(doc3) {
+ let out = "";
+ doc3.forEach((node) => {
+ const text2 = canonical(node), lead = node.attrs.lead;
+ if (out && !out.endsWith("\n")) out += "\n";
+ if (node.attrs.raw !== null && node.attrs.sig === text2) {
+ out += lead + node.attrs.raw;
+ return;
+ }
+ if (!text2.trim()) return;
+ out += (out && !lead.includes("\n") ? "\n" : lead) + text2 + "\n";
+ });
+ return out + doc3.attrs.tail;
+ }
+
+ // editor/view.mjs
+ var { paragraph: paragraph2, heading: heading2, code_block, blockquote: blockquote2, bullet_list, ordered_list, list_item, hard_break, horizontal_rule } = schema2.nodes;
+ var { strong, em, code: code3, link: link3 } = schema2.marks;
+ function markActive(state, type) {
+ const { from, $from, to, empty: empty2 } = state.selection;
+ return empty2 ? !!type.isInSet(state.storedMarks || $from.marks()) : state.doc.rangeHasMark(from, to, type);
+ }
+ var insertBreak = chainCommands(exitCode, (state, dispatch) => {
+ if (dispatch) dispatch(state.tr.replaceSelectionWith(hard_break.create()).scrollIntoView());
+ return true;
+ });
+ var insertRule = (state, dispatch) => {
+ if (dispatch) dispatch(state.tr.replaceSelectionWith(horizontal_rule.create()).scrollIntoView());
+ return true;
+ };
+ var heading_ = (level) => setBlockType2(heading2, { level });
+ function applyLink(view, raw) {
+ const { state } = view, { from, to, empty: empty2 } = state.selection;
+ if (raw === "") {
+ if (!empty2) view.dispatch(state.tr.removeMark(from, to, link3));
+ return true;
+ }
+ const href = linkTarget(raw);
+ if (!href || empty2) return false;
+ view.dispatch(state.tr.removeMark(from, to, link3).addMark(from, to, link3.create({ href })));
+ return true;
+ }
+ var rules = [
+ textblockTypeInputRule(/^(#{1,6})\s$/, heading2, (m) => ({ level: m[1].length })),
+ textblockTypeInputRule(/^```$/, code_block),
+ wrappingInputRule(/^\s*>\s$/, blockquote2),
+ wrappingInputRule(/^\s*([-+*])\s$/, bullet_list),
+ wrappingInputRule(/^(\d+)\.\s$/, ordered_list, (m) => ({ order: +m[1] }), (m, node) => node.childCount + node.attrs.order === +m[1]),
+ new InputRule(/^(?:---|___)$/, (state, match2, start, end) => state.tr.replaceRangeWith(start, end, horizontal_rule.create()).scrollIntoView())
+ ];
+ var BUTTONS = [
+ ["strong", "B", "Bold (Ctrl+B)", toggleMark(strong), (s) => markActive(s, strong)],
+ ["em", "I", "Italic (Ctrl+I)", toggleMark(em), (s) => markActive(s, em)],
+ ["code", ">", "Code (Ctrl+`)", toggleMark(code3), (s) => markActive(s, code3)],
+ ["link", "Link", "Link (Ctrl+K)", null, (s) => markActive(s, link3)],
+ ["h1", "H1", "Heading 1", heading_(1), (s) => s.selection.$from.parent.hasMarkup(heading2, { level: 1 })],
+ ["h2", "H2", "Heading 2", heading_(2), (s) => s.selection.$from.parent.hasMarkup(heading2, { level: 2 })],
+ ["h3", "H3", "Heading 3", heading_(3), (s) => s.selection.$from.parent.hasMarkup(heading2, { level: 3 })],
+ ["p", "Text", "Paragraph", setBlockType2(paragraph2), (s) => s.selection.$from.parent.type === paragraph2],
+ ["ul", "\u2022 List", "Bulleted list", wrapInList(bullet_list), () => false],
+ ["ol", "1. List", "Numbered list", wrapInList(ordered_list), () => false],
+ ["quote", "\u275D", "Quote", wrapIn(blockquote2), () => false],
+ ["codeblock", "{ }", "Code block", setBlockType2(code_block), (s) => s.selection.$from.parent.type === code_block],
+ ["rule", "\u2015", "Horizontal rule", insertRule, () => false],
+ ["undo", "Undo", "Undo (Ctrl+Z)", undo, () => false],
+ ["redo", "Redo", "Redo (Ctrl+Y)", redo, () => false]
+ ];
+ function toolbar(getView, openLink) {
+ const bar = document.createElement("div");
+ bar.className = "ed-toolbar";
+ bar.setAttribute("role", "toolbar");
+ bar.setAttribute("aria-label", "Formatting");
+ const items = BUTTONS.map(([id, label, title, command, active]) => {
+ const b = document.createElement("button");
+ b.type = "button";
+ b.className = "ed-btn";
+ b.dataset.cmd = id;
+ b.title = title;
+ b.setAttribute("aria-label", title);
+ b.textContent = label;
+ b.addEventListener("mousedown", (e) => e.preventDefault());
+ b.addEventListener("click", () => {
+ const view = getView();
+ if (!view || view.editable === false) return;
+ if (id === "link") openLink();
+ else command(view.state, view.dispatch, view);
+ if (id !== "link") view.focus();
+ });
+ bar.appendChild(b);
+ return { b, command, active };
+ });
+ const sync = (state) => {
+ for (const { b, command, active } of items) {
+ b.classList.toggle("on", !!active(state));
+ b.disabled = command ? !command(state) : false;
+ b.setAttribute("aria-pressed", b.classList.contains("on") ? "true" : "false");
+ }
+ };
+ return { bar, sync };
+ }
+ function linkBar(getView) {
+ const form = document.createElement("form");
+ form.className = "ed-linkbar";
+ form.hidden = true;
+ const input = document.createElement("input");
+ input.type = "text";
+ input.className = "ed-link-input";
+ input.setAttribute("aria-label", "Link target (http, https or a relative path)");
+ input.placeholder = "https://\u2026 or a relative path; empty removes the link";
+ input.autocomplete = "off";
+ input.spellcheck = false;
+ const ok = document.createElement("button");
+ ok.type = "submit";
+ ok.className = "ed-btn";
+ ok.textContent = "Set";
+ const cancel = document.createElement("button");
+ cancel.type = "button";
+ cancel.className = "ed-btn";
+ cancel.textContent = "Cancel";
+ const note = document.createElement("span");
+ note.className = "ed-link-note";
+ note.setAttribute("role", "status");
+ form.append(input, ok, cancel, note);
+ const close2 = () => {
+ form.hidden = true;
+ note.textContent = "";
+ getView()?.focus();
+ };
+ cancel.addEventListener("click", close2);
+ input.addEventListener("keydown", (e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ close2();
+ }
+ });
+ form.addEventListener("submit", (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const view = getView();
+ if (!view) return;
+ if (applyLink(view, input.value.trim())) close2();
+ else note.textContent = "That target is not allowed. Use http, https or a relative path, and select the text first.";
+ });
+ const open = () => {
+ const view = getView();
+ if (!view) return;
+ const { from, to, empty: empty2, $from } = view.state.selection;
+ if (empty2 && !markActive(view.state, link3)) {
+ form.hidden = false;
+ input.value = "";
+ note.textContent = "Select the text to link first.";
+ return;
+ }
+ const at = view.state.doc.rangeHasMark(from, to, link3) ? view.state.doc.nodeAt(from)?.marks.find((m) => m.type === link3) : null;
+ input.value = at ? at.attrs.href : "";
+ note.textContent = "";
+ form.hidden = false;
+ input.focus();
+ input.select();
+ };
+ return { form, open };
+ }
+ function mount(host, { text: text2 = "", editable = true, onChange = () => {
+ } } = {}) {
+ let view = null;
+ const getView = () => view;
+ const wrap2 = document.createElement("div");
+ wrap2.className = "ed-wrap";
+ const link_ = linkBar(getView);
+ const tools = toolbar(getView, link_.open);
+ const surface = document.createElement("div");
+ surface.className = "ed-surface";
+ if (editable) wrap2.append(tools.bar, link_.form);
+ wrap2.appendChild(surface);
+ host.appendChild(wrap2);
+ const keys2 = {
+ "Mod-z": undo,
+ "Mod-y": redo,
+ "Shift-Mod-z": redo,
+ Backspace: undoInputRule,
+ "Mod-b": toggleMark(strong),
+ "Mod-i": toggleMark(em),
+ "Mod-`": toggleMark(code3),
+ "Mod-k": () => {
+ link_.open();
+ return true;
+ },
+ "Shift-Enter": insertBreak,
+ "Mod-Enter": insertBreak,
+ Enter: splitListItem(list_item),
+ Tab: sinkListItem(list_item),
+ "Shift-Tab": liftListItem(list_item)
+ };
+ const fresh = (src) => EditorState.create({
+ schema: schema2,
+ doc: parse(src),
+ plugins: [inputRules({ rules }), keymap(keys2), keymap(baseKeymap), history()]
+ });
+ view = new EditorView(surface, {
+ state: fresh(text2),
+ editable: () => editable,
+ attributes: { "aria-label": "Document", "aria-multiline": "true", role: "textbox", spellcheck: "true", "data-field": "doc-visual" },
+ dispatchTransaction(tr) {
+ const next = view.state.apply(tr);
+ view.updateState(next);
+ tools.sync(next);
+ if (tr.docChanged) onChange();
+ }
+ // Pasted and dropped content goes through the schema's parse rules only; nothing here adds to them.
+ });
+ tools.sync(view.state);
+ return {
+ view,
+ text: () => serialise(view.state.doc),
+ setText(src) {
+ view.updateState(fresh(src));
+ tools.sync(view.state);
+ },
+ focus: () => view.focus(),
+ destroy() {
+ view.destroy();
+ wrap2.remove();
+ }
+ };
+ }
+
+ // editor/entry.mjs
+ var roundTrip = (src) => serialise(parse(String(src)));
+ globalThis.MosaicEditor = Object.freeze({ mount, roundTrip });
+})();
diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html
index 4ab935041..5063f33ca 100644
--- a/packages/webui/src/public/index.html
+++ b/packages/webui/src/public/index.html
@@ -2,6 +2,7 @@
Mosaic Console
+
Skip to content