@usememos/editor 26.10.1 → 26.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ __export(commands_exports, {
14
14
  applyBlockInputRules: () => applyBlockInputRules,
15
15
  applyInlineInputRules: () => applyInlineInputRules,
16
16
  applyTokenInputRules: () => applyTokenInputRules,
17
+ clampListIndents: () => clampListIndents,
17
18
  cloneBlock: () => cloneBlock,
18
19
  deleteBackward: () => deleteBackward,
19
20
  deleteBlock: () => deleteBlock,
@@ -21,9 +22,11 @@ __export(commands_exports, {
21
22
  deleteForward: () => deleteForward,
22
23
  deleteRange: () => deleteRange,
23
24
  deleteSelection: () => deleteSelection,
25
+ dropBrokenTokens: () => dropBrokenTokens,
24
26
  duplicateBlock: () => duplicateBlock,
25
27
  duplicateBlocks: () => duplicateBlocks,
26
28
  exitBlock: () => exitBlock,
29
+ indentCode: () => indentCode,
27
30
  indentListItems: () => indentListItems,
28
31
  insertBlock: () => insertBlock,
29
32
  insertBlocks: () => insertBlocks,
@@ -862,7 +865,7 @@ function insertBlock(state, spec) {
862
865
  const at = isEmpty ? index : index + 1;
863
866
  return withBlocks(state, splice(state, at, isEmpty ? 1 : 0, ...blocks), { anchor: start, focus: start });
864
867
  }
865
- function indentListItems(state, delta) {
868
+ function indentListItems(state, delta2) {
866
869
  const { from, to } = orderedRange(state.doc, state.selection);
867
870
  const start = blockIndex(state.doc, from.blockId);
868
871
  const end = blockIndex(state.doc, to.blockId);
@@ -873,7 +876,7 @@ function indentListItems(state, delta) {
873
876
  if (b.type !== "listItem") continue;
874
877
  const prev = blocks[i - 1];
875
878
  const max = prev?.type === "listItem" ? Math.min(MAX_INDENT, prev.indent + 1) : 0;
876
- const indent = Math.max(0, Math.min(max, b.indent + delta));
879
+ const indent = Math.max(0, Math.min(max, b.indent + delta2));
877
880
  if (indent !== b.indent) {
878
881
  blocks[i] = { ...b, indent };
879
882
  changed = true;
@@ -881,6 +884,46 @@ function indentListItems(state, delta) {
881
884
  }
882
885
  return changed ? withBlocks(state, blocks) : state;
883
886
  }
887
+ var CODE_INDENT = " ";
888
+ function indentCode(state, delta2) {
889
+ const { anchor, focus } = state.selection;
890
+ if (anchor.blockId !== focus.blockId) return state;
891
+ const block3 = getBlock(state.doc, focus.blockId);
892
+ if (block3.type !== "code") return state;
893
+ if (delta2 === 1 && isCollapsed(state.selection)) return insertText(state, CODE_INDENT);
894
+ const text = inlineText(block3.content);
895
+ const from = Math.min(anchor.offset, focus.offset);
896
+ const to = Math.max(anchor.offset, focus.offset);
897
+ const edits = [];
898
+ for (let at = text.lastIndexOf("\n", from - 1) + 1; ; ) {
899
+ const lead = /^(?: {1,2}|\t)/.exec(text.slice(at))?.[0].length ?? 0;
900
+ edits.push({ at, remove: delta2 === 1 ? 0 : lead });
901
+ const next = text.indexOf("\n", at);
902
+ if (next < 0 || next >= to) break;
903
+ at = next + 1;
904
+ }
905
+ if (delta2 === -1 && edits.every((e) => e.remove === 0)) return state;
906
+ let out = "";
907
+ let last = 0;
908
+ for (const e of edits) {
909
+ out += text.slice(last, e.at) + (delta2 === 1 ? CODE_INDENT : "");
910
+ last = e.at + e.remove;
911
+ }
912
+ out += text.slice(last);
913
+ const map = (offset) => {
914
+ let shift = 0;
915
+ for (const e of edits) {
916
+ if (e.at > offset) break;
917
+ shift += delta2 === 1 ? CODE_INDENT.length : -Math.min(e.remove, offset - e.at);
918
+ }
919
+ return offset + shift;
920
+ };
921
+ const updated = withContent(block3, plain(out));
922
+ return replaceBlock(state, updated, {
923
+ anchor: { ...anchor, offset: map(anchor.offset) },
924
+ focus: { ...focus, offset: map(focus.offset) }
925
+ });
926
+ }
884
927
  function toggleTask(state, blockId) {
885
928
  const block3 = getBlock(state.doc, blockId);
886
929
  if (block3.type !== "listItem" || block3.listType !== "task") return state;
@@ -998,12 +1041,12 @@ function tableAction(state, action) {
998
1041
  const offset = Math.min(pos.offset, inlineLength(contentOf(table2, cell)));
999
1042
  return replaceBlock(state, table2, caret(table2.id, cell === pos.cell ? offset : 0, cell));
1000
1043
  }
1001
- function moveCell(state, delta) {
1044
+ function moveCell(state, delta2) {
1002
1045
  const pos = state.selection.focus;
1003
1046
  const block3 = getBlock(state.doc, pos.blockId);
1004
1047
  if (block3.type !== "table" || !pos.cell) return state;
1005
1048
  const cols = block3.align.length;
1006
- const index = pos.cell.row * cols + pos.cell.col + delta;
1049
+ const index = pos.cell.row * cols + pos.cell.col + delta2;
1007
1050
  if (index < 0) return state;
1008
1051
  let table2 = block3;
1009
1052
  if (index >= block3.rows.length * cols) table2 = addRow(block3, block3.rows.length);
@@ -1120,6 +1163,59 @@ function applyTokenInputRules(state, syntax) {
1120
1163
  }
1121
1164
  return null;
1122
1165
  }
1166
+ function dropBrokenTokens(state, before, syntax) {
1167
+ if (syntax.length === 0 || state.doc === before.doc) return state;
1168
+ const old = new Set(before.doc.blocks);
1169
+ let blocks = null;
1170
+ state.doc.blocks.forEach((block3, i) => {
1171
+ if (old.has(block3) || block3.type === "divider") return;
1172
+ const containers2 = block3.type === "table" ? block3.rows.flatMap((row, r) => row.map((_, c) => ({ row: r, col: c }))) : [void 0];
1173
+ let next = block3;
1174
+ for (const cell of containers2) {
1175
+ const content = containerContent(next, cell);
1176
+ if (!content?.some((s) => s.token)) continue;
1177
+ const fixed = untokenizeBroken(content, syntax);
1178
+ if (fixed !== content) next = withContainerContent(next, cell, fixed);
1179
+ }
1180
+ if (next !== block3) (blocks ??= [...state.doc.blocks])[i] = next;
1181
+ });
1182
+ return blocks ? { ...state, doc: { ...state.doc, blocks } } : state;
1183
+ }
1184
+ function clampListIndents(state, before) {
1185
+ if (state.doc === before.doc) return state;
1186
+ let blocks = null;
1187
+ let max = 0;
1188
+ state.doc.blocks.forEach((block3, i) => {
1189
+ if (block3.type !== "listItem") {
1190
+ max = 0;
1191
+ return;
1192
+ }
1193
+ if (block3.indent > max) (blocks ??= [...state.doc.blocks])[i] = { ...block3, indent: max };
1194
+ max = Math.min(block3.indent, max) + 1;
1195
+ });
1196
+ return blocks ? { ...state, doc: { ...state.doc, blocks } } : state;
1197
+ }
1198
+ function untokenizeBroken(content, syntax) {
1199
+ const text = inlineText(content);
1200
+ let out = content;
1201
+ let pos = 0;
1202
+ for (const span of content) {
1203
+ const start = pos;
1204
+ const end = pos += span.text.length;
1205
+ if (!span.token) continue;
1206
+ const s = span.marks.includes("code") ? void 0 : syntax.find((x) => x.name === span.token);
1207
+ let at = start;
1208
+ while (s && at < end) {
1209
+ const e = s.match(text, at);
1210
+ if (e <= at || e > end) break;
1211
+ at = e;
1212
+ }
1213
+ if (at === end) continue;
1214
+ const { token: _broken, ...plainSpan } = span;
1215
+ out = concatInline(sliceInline(out, 0, start), [plainSpan], sliceInline(out, end));
1216
+ }
1217
+ return out;
1218
+ }
1123
1219
  function applyAutolinkInputRule(state) {
1124
1220
  const at = inlineAtCaret(state);
1125
1221
  if (!at) return null;
@@ -1873,11 +1969,19 @@ var DEFAULT_LABELS = {
1873
1969
  bulletList: "Bulleted list",
1874
1970
  numberedList: "Numbered list",
1875
1971
  todoList: "To-do list",
1972
+ /** Accessible name of a task checkbox whose item has no text. */
1973
+ task: "Task",
1876
1974
  quote: "Quote",
1877
1975
  code: "Code block",
1878
1976
  table: "Table",
1879
1977
  divider: "Divider",
1880
1978
  noResults: "No results",
1979
+ /** Accessible name of an autocomplete popup without its own `label`. */
1980
+ suggestions: "Suggestions",
1981
+ /** Accessible name of the slash menu. */
1982
+ commands: "Commands",
1983
+ /** Shown in an autocomplete popup while its items are loading. */
1984
+ loading: "Loading\u2026",
1881
1985
  duplicate: "Duplicate",
1882
1986
  delete: "Delete",
1883
1987
  bold: "Bold",
@@ -1906,6 +2010,94 @@ var DEFAULT_LABELS = {
1906
2010
  tableSection: "Table"
1907
2011
  };
1908
2012
 
2013
+ // src/icons.ts
2014
+ var TRASH = ["M10 11v6", "M14 11v6", "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6", "M3 6h18", "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"];
2015
+ var ICONS = {
2016
+ /** `type` */
2017
+ text: ["M12 4v16", "M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2", "M9 20h6"],
2018
+ /** `heading-1` */
2019
+ heading1: ["M4 12h8", "M4 18V6", "M12 18V6", "m17 12 3-2v8"],
2020
+ /** `heading-2` */
2021
+ heading2: ["M4 12h8", "M4 18V6", "M12 18V6", "M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"],
2022
+ /** `heading-3` */
2023
+ heading3: ["M4 12h8", "M4 18V6", "M12 18V6", "M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2", "M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"],
2024
+ /** `list` */
2025
+ bulletList: ["M3 5h.01", "M3 12h.01", "M3 19h.01", "M8 5h13", "M8 12h13", "M8 19h13"],
2026
+ /** `list-ordered` */
2027
+ numberedList: ["M11 5h10", "M11 12h10", "M11 19h10", "M4 4h1v5", "M4 9h2", "M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02"],
2028
+ /** `list-todo` */
2029
+ todoList: ["M13 5h8", "M13 12h8", "M13 19h8", "m3 17 2 2 4-4", ["rect", { x: "3", y: "4", width: "6", height: "6", rx: "1" }]],
2030
+ /** `text-quote` */
2031
+ quote: ["M17 5H3", "M21 12H8", "M21 19H8", "M3 12v7"],
2032
+ /** `square-code` */
2033
+ code: ["m10 9-3 3 3 3", "m14 15 3-3-3-3", ["rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }]],
2034
+ /** `table` */
2035
+ table: ["M12 3v18", ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2" }], "M3 9h18", "M3 15h18"],
2036
+ /** `minus` */
2037
+ divider: ["M5 12h14"],
2038
+ /** `copy` */
2039
+ duplicate: [["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }], "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"],
2040
+ /** `trash` */
2041
+ delete: TRASH,
2042
+ /** `arrow-up` */
2043
+ addRowAbove: ["m5 12 7-7 7 7", "M12 19V5"],
2044
+ /** `arrow-down` */
2045
+ addRowBelow: ["M12 5v14", "m19 12-7 7-7-7"],
2046
+ /** `arrow-left` */
2047
+ addColumnLeft: ["m12 19-7-7 7-7", "M19 12H5"],
2048
+ /** `arrow-right` */
2049
+ addColumnRight: ["M5 12h14", "m12 5 7 7-7 7"],
2050
+ /** `text-align-start` */
2051
+ alignLeft: ["M21 5H3", "M15 12H3", "M17 19H3"],
2052
+ /** `text-align-center` */
2053
+ alignCenter: ["M21 5H3", "M17 12H7", "M19 19H5"],
2054
+ /** `text-align-end` */
2055
+ alignRight: ["M21 5H3", "M21 12H9", "M21 19H7"],
2056
+ /** `trash` */
2057
+ deleteRow: TRASH,
2058
+ /** `trash` */
2059
+ deleteColumn: TRASH,
2060
+ /** `bold` */
2061
+ bold: ["M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"],
2062
+ /** `italic` */
2063
+ italic: [["line", { x1: "19", x2: "10", y1: "4", y2: "4" }], ["line", { x1: "14", x2: "5", y1: "20", y2: "20" }], ["line", { x1: "15", x2: "9", y1: "4", y2: "20" }]],
2064
+ /** `strikethrough` */
2065
+ strike: ["M16 4H9a3 3 0 0 0-2.83 4", "M14 12a4 4 0 0 1 0 8H6", ["line", { x1: "4", x2: "20", y1: "12", y2: "12" }]],
2066
+ /** `code` */
2067
+ inlineCode: ["m16 18 6-6-6-6", "m8 6-6 6 6 6"],
2068
+ /** `link` */
2069
+ link: ["M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71", "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"],
2070
+ /** `grip-vertical` */
2071
+ blockHandle: [["circle", { cx: "9", cy: "12", r: "1" }], ["circle", { cx: "9", cy: "5", r: "1" }], ["circle", { cx: "9", cy: "19", r: "1" }], ["circle", { cx: "15", cy: "12", r: "1" }], ["circle", { cx: "15", cy: "5", r: "1" }], ["circle", { cx: "15", cy: "19", r: "1" }]]
2072
+ };
2073
+ var SVG_NS = "http://www.w3.org/2000/svg";
2074
+ var SVG_ATTRS = {
2075
+ viewBox: "0 0 24 24",
2076
+ fill: "none",
2077
+ stroke: "currentColor",
2078
+ "stroke-width": "2",
2079
+ "stroke-linecap": "round",
2080
+ "stroke-linejoin": "round",
2081
+ "aria-hidden": "true",
2082
+ focusable: "false"
2083
+ };
2084
+ function builtinIcon(doc, name) {
2085
+ const svg = doc.createElementNS(SVG_NS, "svg");
2086
+ svg.setAttribute("class", "mbe-icon");
2087
+ for (const [attr, value] of Object.entries(SVG_ATTRS)) svg.setAttribute(attr, value);
2088
+ for (const child of ICONS[name]) {
2089
+ const [tag, attrs] = typeof child === "string" ? ["path", { d: child }] : child;
2090
+ const el = doc.createElementNS(SVG_NS, tag);
2091
+ for (const [attr, value] of Object.entries(attrs)) el.setAttribute(attr, value);
2092
+ svg.appendChild(el);
2093
+ }
2094
+ return svg;
2095
+ }
2096
+ function iconNode(doc, icon) {
2097
+ if (icon === void 0 || icon === "") return null;
2098
+ return typeof icon === "string" ? doc.createTextNode(icon) : doc.importNode(icon, true);
2099
+ }
2100
+
1909
2101
  // src/markdown/inline.ts
1910
2102
  import { lookupEntity } from "#entities";
1911
2103
 
@@ -2094,9 +2286,17 @@ function parseInline(src, options) {
2094
2286
  return lowerInlines(parseInlines(src, /* @__PURE__ */ new Map(), o.inline, o.autolinks), options);
2095
2287
  }
2096
2288
  function parseInlines(src, refs, syntax = [], autolinks = false) {
2289
+ if (isPlain(src, syntax, autolinks)) return src ? [{ type: "text", value: src }] : [];
2097
2290
  const nodes = new InlineParser(src, refs, syntax, autolinks).parse();
2098
2291
  return autolinks ? linkEmails(nodes) : nodes;
2099
2292
  }
2293
+ var rePlain = /^[^\n`[\]\\!<&*_~]*$/;
2294
+ var reLiteralStart = /www\.|:\/\/|@/i;
2295
+ function isPlain(src, syntax, autolinks) {
2296
+ if (!rePlain.test(src) || autolinks && reLiteralStart.test(src)) return false;
2297
+ for (const s of syntax) for (const ch of s.triggers) if (src.includes(ch)) return false;
2298
+ return true;
2299
+ }
2100
2300
  function linkEmails(nodes) {
2101
2301
  let changed = false;
2102
2302
  const out = [];
@@ -2209,6 +2409,8 @@ var Node2 = class {
2209
2409
  depth = 0;
2210
2410
  destination = "";
2211
2411
  title = "";
2412
+ /** An escaped "@": kept apart from the text around it, so it does not join an e-mail literal. */
2413
+ apart = false;
2212
2414
  parent = null;
2213
2415
  first = null;
2214
2416
  last = null;
@@ -2249,15 +2451,22 @@ function innerDepth(from, to) {
2249
2451
  for (let n = from.next; n && n !== to; n = n.next) if (n.depth >= depth) depth = n.depth + 1;
2250
2452
  return depth;
2251
2453
  }
2454
+ function escapedText(value) {
2455
+ const text = new Node2("text", value);
2456
+ text.apart = value === "@";
2457
+ return text;
2458
+ }
2252
2459
  function toAst(parent) {
2253
2460
  const out = [];
2461
+ let apart = false;
2254
2462
  for (let n = parent.first; n; n = n.next) {
2255
2463
  switch (n.type) {
2256
2464
  case "text": {
2257
2465
  if (n.value === "") break;
2258
2466
  const prev = out[out.length - 1];
2259
- if (prev?.type === "text") out[out.length - 1] = { type: "text", value: prev.value + n.value };
2467
+ if (prev?.type === "text" && !apart && !n.apart) out[out.length - 1] = { type: "text", value: prev.value + n.value };
2260
2468
  else out.push({ type: "text", value: n.value });
2469
+ apart = n.apart;
2261
2470
  break;
2262
2471
  }
2263
2472
  case "softBreak":
@@ -2443,7 +2652,7 @@ var InlineParser = class {
2443
2652
  block3.append(new Node2("hardBreak"));
2444
2653
  this.skipLineStart();
2445
2654
  } else if (c !== -1 && reEscapable.test(this.subject[this.pos])) {
2446
- block3.append(new Node2("text", this.subject[this.pos]));
2655
+ block3.append(escapedText(this.subject[this.pos]));
2447
2656
  this.pos += 1;
2448
2657
  } else {
2449
2658
  block3.append(new Node2("text", "\\"));
@@ -2515,7 +2724,7 @@ var InlineParser = class {
2515
2724
  if (m) {
2516
2725
  const decoded = decodeEntity(m[0]);
2517
2726
  if (decoded !== null) {
2518
- block3.append(new Node2("text", decoded));
2727
+ block3.append(escapedText(decoded));
2519
2728
  return true;
2520
2729
  }
2521
2730
  this.pos = start;
@@ -2863,7 +3072,7 @@ function charAt(s, i) {
2863
3072
  function parseAst(src, options = DEFAULT_MARKDOWN) {
2864
3073
  return new BlockParser(resolveMarkdown(options)).parse(src);
2865
3074
  }
2866
- var CODE_INDENT = 4;
3075
+ var CODE_INDENT2 = 4;
2867
3076
  var MAX_NESTING = 100;
2868
3077
  var reHtmlBlockOpen = [
2869
3078
  /^$/,
@@ -3027,7 +3236,7 @@ var BlockParser = class {
3027
3236
  this.nextNonspace = i;
3028
3237
  this.nextNonspaceColumn = cols;
3029
3238
  this.indent = cols - this.column;
3030
- this.indented = this.indent >= CODE_INDENT;
3239
+ this.indented = this.indent >= CODE_INDENT2;
3031
3240
  }
3032
3241
  advanceNextNonspace() {
3033
3242
  this.offset = this.nextNonspace;
@@ -3190,8 +3399,8 @@ var BlockParser = class {
3190
3399
  }
3191
3400
  return 0 /* Matched */;
3192
3401
  }
3193
- if (this.indent >= CODE_INDENT) {
3194
- this.advanceOffset(CODE_INDENT, true);
3402
+ if (this.indent >= CODE_INDENT2) {
3403
+ this.advanceOffset(CODE_INDENT2, true);
3195
3404
  } else if (this.blank) {
3196
3405
  this.advanceNextNonspace();
3197
3406
  } else {
@@ -3407,7 +3616,7 @@ var BlockParser = class {
3407
3616
  }
3408
3617
  startIndentedCode() {
3409
3618
  if (!this.indented || this.tip.type === "paragraph" || this.blank) return 0 /* None */;
3410
- this.advanceOffset(CODE_INDENT, true);
3619
+ this.advanceOffset(CODE_INDENT2, true);
3411
3620
  this.closeUnmatchedBlocks();
3412
3621
  this.addChild("codeBlock");
3413
3622
  return 2 /* Leaf */;
@@ -3788,7 +3997,26 @@ function representableInline(inline3) {
3788
3997
  endRun();
3789
3998
  for (const [from, to] of removals) spans = setMarkInRange(spans, from, to, mark, false);
3790
3999
  }
3791
- return spans;
4000
+ return dropLineEndSpaces(spans);
4001
+ }
4002
+ var isPlainSpan = (s) => !s.link && !s.image && !s.token && !s.marks.includes("code") && !s.marks.includes("html");
4003
+ function dropLineEndSpaces(spans) {
4004
+ const text = spans.map((s) => s.text).join("");
4005
+ if (!/[ \t](\n|$)/.test(text)) return spans;
4006
+ const plain2 = [];
4007
+ for (const s of spans) for (let i = 0; i < s.text.length; i++) plain2.push(isPlainSpan(s));
4008
+ const removals = [];
4009
+ let lineStart = 0;
4010
+ for (let i = 0; i <= text.length; i++) {
4011
+ if (i < text.length && text[i] !== "\n") continue;
4012
+ let from = i;
4013
+ while (from > lineStart && (text[from - 1] === " " || text[from - 1] === " ") && plain2[from - 1]) from--;
4014
+ if (from < i && /[^ \t]/.test(text.slice(lineStart, from))) removals.push([from, i]);
4015
+ lineStart = i + 1;
4016
+ }
4017
+ let out = spans;
4018
+ for (let k = removals.length - 1; k >= 0; k--) out = deleteInline(out, removals[k][0], removals[k][1]);
4019
+ return normalizeInline(out);
3792
4020
  }
3793
4021
  function emphasisMarks(span) {
3794
4022
  return span.marks.filter(isEmphasis);
@@ -3826,7 +4054,7 @@ function tokenize(spans, ctx, italic, bare) {
3826
4054
  while (keep < stack.length && marks.includes(stack[keep].mark)) keep++;
3827
4055
  closeTo(keep);
3828
4056
  };
3829
- const emitSpan = (span, base, index, limit) => {
4057
+ const emitSpan = (span, base, index, limit, inLink = false) => {
3830
4058
  const target = emphasisMarks(span);
3831
4059
  closeExcept(target, base);
3832
4060
  openMarks(target, index, limit);
@@ -3837,7 +4065,7 @@ function tokenize(spans, ctx, italic, bare) {
3837
4065
  } else if (span.marks.includes("code")) {
3838
4066
  tokens.push({ kind: "raw", text: codeSpan(span.text) });
3839
4067
  } else {
3840
- tokens.push({ kind: "text", text: span.text, encodeFirst: false, encodeLast: false });
4068
+ tokens.push({ kind: "text", text: span.text, encodeFirst: false, encodeLast: false, inLink });
3841
4069
  }
3842
4070
  };
3843
4071
  let i = 0;
@@ -3859,7 +4087,7 @@ function tokenize(spans, ctx, italic, bare) {
3859
4087
  } else {
3860
4088
  tokens.push({ kind: "raw", text: "[" });
3861
4089
  const base = stack.length;
3862
- for (let k = i; k < j; k++) emitSpan(spans[k], base, k, j);
4090
+ for (let k = i; k < j; k++) emitSpan(spans[k], base, k, j, true);
3863
4091
  closeTo(base);
3864
4092
  tokens.push({ kind: "raw", text: `](${linkDestination(span.link)})` });
3865
4093
  }
@@ -3980,7 +4208,8 @@ function escapeText(tok, ctx, edges) {
3980
4208
  endsLine,
3981
4209
  blockSyntax: ctx.lineStart && startsLine,
3982
4210
  escape: ctx.options.escape,
3983
- inline: ctx.options.inline
4211
+ inline: ctx.options.inline,
4212
+ autolinks: ctx.options.autolinks && !tok.inLink
3984
4213
  });
3985
4214
  });
3986
4215
  return out;
@@ -3993,6 +4222,7 @@ function escapeLine(line, o) {
3993
4222
  if (o.encodeFirst || o.startsLine && (line[0] === " " || line[0] === " ")) encodeAt.add(0);
3994
4223
  if (o.encodeLast || o.endsLine && (line[lastIndex] === " " || line[lastIndex] === " ")) encodeAt.add(lastIndex);
3995
4224
  const blockEscape = o.blockSyntax && !encodeAt.has(0) ? blockSyntaxEscapeIndex(line) : -1;
4225
+ const urlEscapes = o.autolinks ? literalEscapes(line, o.before) : null;
3996
4226
  let out = "";
3997
4227
  for (let i = 0; i < line.length; i++) {
3998
4228
  if (encodeAt.has(i)) {
@@ -4004,7 +4234,7 @@ function escapeLine(line, o) {
4004
4234
  const ch = line[i];
4005
4235
  const prev = i > 0 ? encodeAt.has(i - 1) ? ";" : line[i - 1] : o.before;
4006
4236
  const next = i < line.length - 1 ? encodeAt.has(i + 1) ? "&" : line[i + 1] : o.after;
4007
- if (i === blockEscape) {
4237
+ if (i === blockEscape || urlEscapes?.has(i)) {
4008
4238
  out += bs(ch);
4009
4239
  continue;
4010
4240
  }
@@ -4039,6 +4269,18 @@ function escapeLine(line, o) {
4039
4269
  }
4040
4270
  return out;
4041
4271
  }
4272
+ function literalEscapes(line, before) {
4273
+ const emails = emailLiterals(line);
4274
+ if (!emails.length && !/www\.|:\/\//i.test(line)) return null;
4275
+ const out = /* @__PURE__ */ new Set();
4276
+ for (const c of line.matchAll(/www\.|(?:https?|ftp):\/\//gi)) {
4277
+ const at = c.index;
4278
+ if (!isLiteralBoundary(at > 0 ? line[at - 1] : before) || !urlLiteralAt(line, at)) continue;
4279
+ out.add(at + c[0].indexOf(c[0].startsWith("w") || c[0].startsWith("W") ? "." : ":"));
4280
+ }
4281
+ for (const { from } of emails) out.add(line.indexOf("@", from));
4282
+ return out;
4283
+ }
4042
4284
  function blockSyntaxEscapeIndex(line) {
4043
4285
  if (/^#{1,6}(?:[ \t]|$)/.test(line) || line[0] === ">") return 0;
4044
4286
  if (/^[-+](?:[ \t]|$)/.test(line) || /^-+[ \t]*$/.test(line) || /^(?:-[ \t]*){3,}$/.test(line)) return 0;
@@ -4148,6 +4390,7 @@ function joins(a, b) {
4148
4390
  }
4149
4391
  function saveWithSource(blocks, source, options) {
4150
4392
  const text = source.text;
4393
+ let firstBlocks;
4151
4394
  const chunks = [];
4152
4395
  for (let i = 0; i < blocks.length; ) {
4153
4396
  const block3 = blocks[i];
@@ -4157,6 +4400,13 @@ function saveWithSource(blocks, source, options) {
4157
4400
  i += group.blocks.length;
4158
4401
  continue;
4159
4402
  }
4403
+ firstBlocks ??= new Map(source.groups.map((g) => [g.blocks[0].id, g]));
4404
+ const ticked = tickedGroup(blocks, i, firstBlocks, source, options);
4405
+ if (ticked) {
4406
+ chunks.push(ticked);
4407
+ i += ticked.blocks.length;
4408
+ continue;
4409
+ }
4160
4410
  const last2 = chunks[chunks.length - 1];
4161
4411
  if (last2 && !last2.group) last2.blocks.push(block3);
4162
4412
  else chunks.push({ group: null, blocks: [block3] });
@@ -4203,7 +4453,7 @@ function saveWithSource(blocks, source, options) {
4203
4453
  let out = "";
4204
4454
  let prev;
4205
4455
  for (const chunk of chunks) {
4206
- const body = chunk.group ? text.slice(chunk.group.from, chunk.group.to) : serializeBlocks(chunk.blocks, options);
4456
+ const body = chunk.group ? chunk.text ?? text.slice(chunk.group.from, chunk.group.to) : serializeBlocks(chunk.blocks, options);
4207
4457
  if (body === "" && !chunk.group) continue;
4208
4458
  const g = chunk.group;
4209
4459
  const p = prev?.group;
@@ -4232,6 +4482,38 @@ function saveWithSource(blocks, source, options) {
4232
4482
  }
4233
4483
  return out + ending;
4234
4484
  }
4485
+ var reTaskLine = /^([ \t]*(?:[-+*]|\d{1,9}[.)])[ \t]+\[)([ xX])(?=\][ \t]|\]$)/gm;
4486
+ function tickedGroup(blocks, i, firstBlocks, source, options) {
4487
+ const loaded = firstBlocks.get(blocks[i].id);
4488
+ if (!loaded || loaded.open) return null;
4489
+ const current = blocks.slice(i, i + loaded.blocks.length);
4490
+ if (current.length !== loaded.blocks.length) return null;
4491
+ let changed = false;
4492
+ for (let k = 0; k < current.length; k++) {
4493
+ const a = loaded.blocks[k];
4494
+ const b = current[k];
4495
+ if (a === b) continue;
4496
+ if (!onlyChecked(a, b)) return null;
4497
+ changed = true;
4498
+ }
4499
+ if (!changed) return null;
4500
+ const tasks = current.filter((b) => b.type === "listItem" && b.listType === "task");
4501
+ const original = source.text.slice(loaded.from, loaded.to);
4502
+ let n = 0;
4503
+ const patched = original.replace(reTaskLine, (match, head, box) => {
4504
+ const block3 = tasks[n++];
4505
+ if (!block3 || block3.type !== "listItem") return match;
4506
+ const checked = box !== " ";
4507
+ return checked === block3.checked ? match : head + (block3.checked ? "x" : " ");
4508
+ });
4509
+ if (n !== tasks.length) return null;
4510
+ const reread = loadMarkdown(patched, options).doc.blocks;
4511
+ if (serializeBlocks(reread, options) !== serializeBlocks(current, options)) return null;
4512
+ return { group: loaded, blocks: current, text: patched };
4513
+ }
4514
+ function onlyChecked(a, b) {
4515
+ return a.type === "listItem" && b.type === "listItem" && a.listType === "task" && b.listType === "task" && a.id === b.id && a.indent === b.indent && a.content === b.content;
4516
+ }
4235
4517
  function squash(s) {
4236
4518
  return s.replace(/\s+/g, " ").trim();
4237
4519
  }
@@ -4254,9 +4536,31 @@ var THEME_VARS = [
4254
4536
  "--mbe-hover",
4255
4537
  "--mbe-accent",
4256
4538
  "--mbe-danger",
4257
- "--mbe-radius"
4539
+ "--mbe-radius",
4540
+ "--mbe-popup-z"
4258
4541
  ];
4542
+ var containers = /* @__PURE__ */ new WeakMap();
4543
+ function setPopupContainer(owner, container) {
4544
+ if (container) containers.set(owner, container);
4545
+ else containers.delete(owner);
4546
+ }
4547
+ function popupContainer(owner) {
4548
+ return containers.get(owner) ?? owner.closest('dialog[open], [aria-modal="true"]') ?? owner.ownerDocument.body;
4549
+ }
4550
+ function attach(el, owner) {
4551
+ const container = popupContainer(owner);
4552
+ if (el.parentElement !== container) container.appendChild(el);
4553
+ el.style.left = "0px";
4554
+ el.style.top = "0px";
4555
+ const rect = el.getBoundingClientRect();
4556
+ return { x: rect.left, y: rect.top };
4557
+ }
4558
+ function visibleViewport(view) {
4559
+ const vv = view.visualViewport;
4560
+ return vv ? { left: vv.offsetLeft, top: vv.offsetTop, width: vv.width, height: vv.height } : { left: 0, top: 0, width: view.innerWidth, height: view.innerHeight };
4561
+ }
4259
4562
  var isMac = typeof navigator !== "undefined" && /Mac|iP(hone|ad|od)/.test(navigator.platform);
4563
+ var isSafari = typeof navigator !== "undefined" && /AppleWebKit/.test(navigator.userAgent) && !/Chrome|Chromium|CriOS|Edg|Android/.test(navigator.userAgent);
4260
4564
  var isTouch = () => typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
4261
4565
  var Popup = class {
4262
4566
  constructor(owner, className) {
@@ -4271,24 +4575,50 @@ var Popup = class {
4271
4575
  }
4272
4576
  el;
4273
4577
  open = false;
4578
+ placed = "below";
4274
4579
  get isOpen() {
4275
4580
  return this.open;
4276
4581
  }
4277
- /** Shows the popup next to `rect` (viewport coordinates), flipping to stay on screen. */
4278
- show(rect, placement = "below", gap = 6) {
4582
+ /** The side of the anchor the popup was last shown on. */
4583
+ get side() {
4584
+ return this.placed;
4585
+ }
4586
+ /**
4587
+ * Shows the popup next to `rect` (viewport coordinates), flipping to stay
4588
+ * on screen. With `align: 'end'`, its right edge lines up with `rect.right`
4589
+ * (for right-to-left text).
4590
+ */
4591
+ show(rect, placement = "below", gap = 6, align = "start") {
4279
4592
  const doc = this.owner.ownerDocument;
4280
- if (!this.el.isConnected) doc.body.appendChild(this.el);
4281
4593
  if (!this.open) this.copyTheme();
4282
4594
  this.el.hidden = false;
4283
4595
  this.open = true;
4596
+ const offset = attach(this.el, this.owner);
4284
4597
  const view = doc.defaultView;
4285
- const { offsetWidth: w, offsetHeight: h } = this.el;
4286
- let top = placement === "below" ? rect.bottom + gap : rect.top - h - gap;
4287
- if (placement === "below" && top + h > view.innerHeight - 8 && rect.top - h - gap > 8) top = rect.top - h - gap;
4288
- if (placement === "above" && top < 8) top = rect.bottom + gap;
4289
- const left = Math.max(8, Math.min(rect.left, view.innerWidth - w - 8));
4290
- this.el.style.left = `${Math.round(left)}px`;
4291
- this.el.style.top = `${Math.round(top)}px`;
4598
+ const vp = visibleViewport(view);
4599
+ const scrolled = this.el.scrollTop;
4600
+ this.el.style.maxHeight = "";
4601
+ const w = this.el.offsetWidth;
4602
+ let h = this.el.offsetHeight;
4603
+ const below = vp.top + vp.height - 8 - (rect.bottom + gap);
4604
+ const above = rect.top - gap - 8 - vp.top;
4605
+ let side = placement;
4606
+ if (side === "below" && h > below && above > below) side = "above";
4607
+ else if (side === "above" && h > above && below > above) side = "below";
4608
+ const room = side === "below" ? below : above;
4609
+ if (h > room) {
4610
+ const cs = view.getComputedStyle(this.el);
4611
+ const extra = cs.boxSizing === "border-box" ? 0 : ["paddingTop", "paddingBottom", "borderTopWidth", "borderBottomWidth"].reduce((n, k) => n + parseFloat(cs[k]), 0);
4612
+ this.el.style.maxHeight = `${Math.max(Math.floor(room - extra), 80)}px`;
4613
+ h = this.el.offsetHeight;
4614
+ this.el.scrollTop = scrolled;
4615
+ }
4616
+ this.placed = side;
4617
+ const top = side === "below" ? rect.bottom + gap : rect.top - h - gap;
4618
+ const start = align === "end" ? (rect.right ?? rect.left) - w : rect.left;
4619
+ const left = Math.max(vp.left + 8, Math.min(start, vp.left + vp.width - w - 8));
4620
+ this.el.style.left = `${Math.round(left - offset.x)}px`;
4621
+ this.el.style.top = `${Math.round(top - offset.y)}px`;
4292
4622
  }
4293
4623
  hide() {
4294
4624
  if (!this.open) return;
@@ -4315,6 +4645,8 @@ var Menu = class {
4315
4645
  id = `mbe-menu-${++menuCounter}`;
4316
4646
  /** Called after an item runs. */
4317
4647
  onPicked = null;
4648
+ /** Called when the highlight moves, by key, by mouse or because the items changed. */
4649
+ onHighlight = null;
4318
4650
  constructor(owner, className, role = "listbox") {
4319
4651
  this.popup = new Popup(owner, `mbe-menu ${className}`);
4320
4652
  this.popup.el.setAttribute("role", role);
@@ -4329,12 +4661,12 @@ var Menu = class {
4329
4661
  get activeDescendant() {
4330
4662
  return this.items.length ? `${this.id}-${this.index}` : null;
4331
4663
  }
4332
- setSections(sections, emptyLabel) {
4664
+ setSections(sections2, emptyLabel) {
4333
4665
  const doc = this.el.ownerDocument;
4334
4666
  this.el.replaceChildren();
4335
4667
  this.items = [];
4336
4668
  this.index = 0;
4337
- for (const section of sections) {
4669
+ for (const section of sections2) {
4338
4670
  if (section.items.length === 0) continue;
4339
4671
  if (section.title) {
4340
4672
  const title = doc.createElement("div");
@@ -4353,11 +4685,18 @@ var Menu = class {
4353
4685
  if (item.danger) row.classList.add("mbe-danger");
4354
4686
  const icon = doc.createElement("span");
4355
4687
  icon.className = "mbe-menu-icon";
4356
- icon.textContent = item.icon ?? "";
4688
+ const content = iconNode(doc, item.icon);
4689
+ if (content) icon.appendChild(content);
4357
4690
  const label = doc.createElement("span");
4358
4691
  label.className = "mbe-menu-label";
4359
- label.textContent = item.label;
4692
+ setMarked(label, item.label, item.mark);
4360
4693
  row.append(icon, label);
4694
+ if (item.detail) {
4695
+ const detail = doc.createElement("span");
4696
+ detail.className = "mbe-menu-detail";
4697
+ detail.textContent = item.detail;
4698
+ row.appendChild(detail);
4699
+ }
4361
4700
  row.addEventListener("mousemove", () => this.highlight(i));
4362
4701
  row.addEventListener("click", () => this.pick(i));
4363
4702
  this.el.appendChild(row);
@@ -4371,9 +4710,41 @@ var Menu = class {
4371
4710
  }
4372
4711
  this.highlight(0);
4373
4712
  }
4713
+ /** Replaces the items with a line of text that is not an option, such as "Loading…". */
4714
+ setMessage(text, className) {
4715
+ const doc = this.el.ownerDocument;
4716
+ const line = doc.createElement("div");
4717
+ line.className = className;
4718
+ line.textContent = text;
4719
+ this.el.replaceChildren(line);
4720
+ this.items = [];
4721
+ this.index = 0;
4722
+ }
4723
+ /** Marks the list as waiting for newer items (`aria-busy`). */
4724
+ set busy(busy) {
4725
+ if (busy) this.el.setAttribute("aria-busy", "true");
4726
+ else this.el.removeAttribute("aria-busy");
4727
+ }
4374
4728
  get count() {
4375
4729
  return this.items.length;
4376
4730
  }
4731
+ /** The ID of the highlighted item. */
4732
+ get activeId() {
4733
+ return this.items[this.index]?.id ?? null;
4734
+ }
4735
+ /** Highlights the item with this ID. Returns false when there is none. */
4736
+ highlightId(id) {
4737
+ const i = this.items.findIndex((item) => item.id === id);
4738
+ if (i < 0) return false;
4739
+ this.highlight(i);
4740
+ return true;
4741
+ }
4742
+ /** Moves the highlight by a page: the number of items that fit in the list's height. Stops at the ends. */
4743
+ page(direction) {
4744
+ const row = this.el.querySelector(".mbe-menu-item");
4745
+ const perPage = row && row.offsetHeight > 0 ? Math.max(1, Math.floor(this.el.clientHeight / row.offsetHeight) - 1) : 8;
4746
+ this.highlight(Math.max(0, Math.min(this.items.length - 1, this.index + direction * perPage)));
4747
+ }
4377
4748
  highlight(i) {
4378
4749
  if (this.items.length === 0) return;
4379
4750
  this.index = (i + this.items.length) % this.items.length;
@@ -4382,9 +4753,14 @@ var Menu = class {
4382
4753
  row.setAttribute("aria-selected", String(k === this.index));
4383
4754
  });
4384
4755
  this.el.querySelector(`#${this.id}-${this.index}`)?.scrollIntoView?.({ block: "nearest" });
4756
+ this.onHighlight?.(this.index);
4385
4757
  }
4386
- move(delta) {
4387
- this.highlight(this.index + delta);
4758
+ /** The index of the highlighted item. */
4759
+ get activeIndex() {
4760
+ return this.items.length ? this.index : -1;
4761
+ }
4762
+ move(delta2) {
4763
+ this.highlight(this.index + delta2);
4388
4764
  }
4389
4765
  pick(i = this.index) {
4390
4766
  const item = this.items[i];
@@ -4399,6 +4775,18 @@ var Menu = class {
4399
4775
  this.popup.destroy();
4400
4776
  }
4401
4777
  };
4778
+ function setMarked(el, text, mark) {
4779
+ const at = mark ? text.toLowerCase().indexOf(mark.toLowerCase()) : -1;
4780
+ if (at < 0 || text.toLowerCase().length !== text.length) {
4781
+ el.textContent = text;
4782
+ return;
4783
+ }
4784
+ const doc = el.ownerDocument;
4785
+ const m = doc.createElement("mark");
4786
+ m.className = "mbe-menu-match";
4787
+ m.textContent = text.slice(at, at + mark.length);
4788
+ el.replaceChildren(text.slice(0, at), m, text.slice(at + mark.length));
4789
+ }
4402
4790
  function matches(item, query) {
4403
4791
  const q = query.trim().toLowerCase();
4404
4792
  if (!q) return true;
@@ -4423,18 +4811,630 @@ function defaultKeymap() {
4423
4811
  "Mod-Shift-7": ({ editor }) => editor.commands.toggleOrderedList() || true,
4424
4812
  "Mod-Shift-8": ({ editor }) => editor.commands.toggleBulletList() || true,
4425
4813
  "Mod-Shift-9": ({ editor }) => editor.commands.toggleTaskList() || true,
4814
+ "Mod-a": ({ editor }) => selectAll2(editor),
4426
4815
  "Mod-z": ({ editor }) => editor.commands.undo() || true,
4427
4816
  "Mod-Shift-z": ({ editor }) => editor.commands.redo() || true,
4428
4817
  "Mod-Enter": ({ editor }) => editor.submit(),
4429
4818
  "Ctrl-Enter": ({ editor }) => editor.submit(),
4430
- Tab: ({ editor }) => (editor.isActive("table") ? editor.run((s) => moveCell(s, 1)) : editor.commands.indent()) || true,
4431
- "Shift-Tab": ({ editor }) => (editor.isActive("table") ? editor.run((s) => moveCell(s, -1)) : editor.commands.outdent()) || true,
4819
+ Tab: ({ editor }) => tab(editor, 1),
4820
+ "Shift-Tab": ({ editor }) => tab(editor, -1),
4432
4821
  // The first Escape selects the block; Escape in a block selection leaves the editor.
4433
- Escape: ({ editor }) => editor.commands.selectBlocks() || editor.commands.blur()
4822
+ Escape: ({ editor }) => editor.commands.selectBlocks() || editor.commands.blur(),
4823
+ // Opens the autocomplete popup for the token at the caret.
4824
+ "Ctrl-Space": ({ editor }) => editor.suggestion.open()
4434
4825
  };
4826
+ if (isMac) keymap["Alt-Escape"] = ({ editor }) => editor.suggestion.open();
4435
4827
  if (!isMac) keymap["Ctrl-y"] = ({ editor }) => editor.commands.redo() || true;
4436
4828
  return { name: "defaultKeymap", keymap };
4437
4829
  }
4830
+ function tab(editor, delta2) {
4831
+ if (editor.isActive("table")) editor.run((s) => moveCell(s, delta2));
4832
+ else if (editor.isActive("codeBlock")) editor.run((s) => indentCode(s, delta2));
4833
+ else if (delta2 === 1) editor.commands.indent();
4834
+ else editor.commands.outdent();
4835
+ return true;
4836
+ }
4837
+ function selectAll2(editor) {
4838
+ const { doc, selection } = editor.state;
4839
+ const { anchor, focus } = selection;
4840
+ if (anchor.blockId === focus.blockId && sameCell(anchor.cell, focus.cell)) {
4841
+ const block3 = getBlock(doc, focus.blockId);
4842
+ const content = focus.cell || block3.type === "code" ? containerContent(block3, focus.cell) : null;
4843
+ if (content) {
4844
+ const end = inlineLength(content);
4845
+ if (Math.min(anchor.offset, focus.offset) !== 0 || Math.max(anchor.offset, focus.offset) !== end) {
4846
+ editor.setSelection({ anchor: { ...focus, offset: 0 }, focus: { ...focus, offset: end } });
4847
+ return true;
4848
+ }
4849
+ }
4850
+ }
4851
+ return editor.commands.selectAll();
4852
+ }
4853
+
4854
+ // src/suggest/anchor.ts
4855
+ function suggestionAnchor(trigger, caret2, rtl, visible) {
4856
+ const line = caret2 ?? trigger;
4857
+ if (!line) return null;
4858
+ if (trigger && visible && (trigger.bottom <= visible.top || trigger.top >= visible.bottom || trigger.right < visible.left || trigger.left > visible.right)) {
4859
+ return null;
4860
+ }
4861
+ const sameLine = trigger && caret2 && Math.abs(trigger.top - caret2.top) < Math.max(1, Math.min(trigger.bottom - trigger.top, caret2.bottom - caret2.top) / 2);
4862
+ const from = trigger && (sameLine || !caret2) ? trigger : line;
4863
+ const x = rtl ? from.right : from.left;
4864
+ return { rect: { left: x, right: x, top: line.top, bottom: line.bottom }, align: rtl ? "end" : "start" };
4865
+ }
4866
+ function visibleArea(el) {
4867
+ const view = el.ownerDocument.defaultView;
4868
+ let box = { left: 0, top: 0, right: view.innerWidth, bottom: view.innerHeight };
4869
+ const top = el.ownerDocument.documentElement;
4870
+ for (let node = el; node && node !== top && node !== el.ownerDocument.body; node = node.parentElement) {
4871
+ const style = view.getComputedStyle(node);
4872
+ if (style.overflowX === "visible" && style.overflowY === "visible") continue;
4873
+ const r = node.getBoundingClientRect();
4874
+ box = { left: Math.max(box.left, r.left), top: Math.max(box.top, r.top), right: Math.min(box.right, r.right), bottom: Math.min(box.bottom, r.bottom) };
4875
+ }
4876
+ return box;
4877
+ }
4878
+
4879
+ // src/suggest/match.ts
4880
+ function defaultMatcher({ allowSpaces = false, allowAnywhere = false, maxLength = 30 } = {}) {
4881
+ const invalid = allowSpaces ? /\s\s|\n/ : /\s/;
4882
+ return ({ text, caret: caret2, triggers }) => {
4883
+ const lineStart = text.lastIndexOf("\n", caret2 - 1) + 1;
4884
+ const longest = Math.max(0, ...triggers.map((t) => t.length));
4885
+ const lowest = Math.max(lineStart, caret2 - maxLength - longest);
4886
+ for (let i = caret2 - 1; i >= lowest; i--) {
4887
+ const trigger = longestAt(text, i, triggers, caret2);
4888
+ if (!trigger) continue;
4889
+ const query = text.slice(i + trigger.length, caret2);
4890
+ if (query.length > maxLength || invalid.test(query)) return null;
4891
+ const before = text[i - 1];
4892
+ if (!allowAnywhere && before !== void 0 && !/\s/.test(before)) continue;
4893
+ let to = caret2;
4894
+ if (!allowSpaces) while (to < text.length && !/\s/.test(text[to])) to++;
4895
+ return { from: i, to, query };
4896
+ }
4897
+ return null;
4898
+ };
4899
+ }
4900
+ var reJoining = /^[\p{M}\u200c\u200d\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/u;
4901
+ function matchToken(scan, { probe = "a", maxLength = 30 } = {}) {
4902
+ return ({ text, caret: caret2, triggers }) => {
4903
+ const next = text.codePointAt(caret2);
4904
+ if (next !== void 0 && reJoining.test(String.fromCodePoint(next))) return null;
4905
+ let scanned = text;
4906
+ const first = triggers[0];
4907
+ if (first) {
4908
+ for (const t of triggers) if (t !== first && t.length === first.length) scanned = scanned.split(t).join(first);
4909
+ }
4910
+ const probed = scanned.slice(0, caret2) + probe + scanned.slice(caret2);
4911
+ const lineStart = text.lastIndexOf("\n", caret2 - 1) + 1;
4912
+ let lineEnd = text.indexOf("\n", caret2);
4913
+ if (lineEnd < 0) lineEnd = text.length;
4914
+ const reach = maxLength + 16;
4915
+ const from = Math.max(lineStart, caret2 - reach);
4916
+ const to = Math.min(lineEnd + probe.length, caret2 + probe.length + reach);
4917
+ for (const token of scan(probed, from, to)) {
4918
+ if (token.from >= caret2 || token.to < caret2 + probe.length) continue;
4919
+ const trigger = longestAt(text, token.from, triggers, caret2);
4920
+ if (!trigger) return null;
4921
+ const query = text.slice(token.from + trigger.length, caret2);
4922
+ if (query.length > maxLength) return null;
4923
+ return { from: token.from, to: token.to - probe.length, query };
4924
+ }
4925
+ return null;
4926
+ };
4927
+ }
4928
+ function longestAt(text, i, triggers, limit = text.length) {
4929
+ let found = null;
4930
+ for (const t of triggers) {
4931
+ if (t && i + t.length <= limit && text.startsWith(t, i) && (!found || t.length > found.length)) found = t;
4932
+ }
4933
+ return found;
4934
+ }
4935
+ function excludedAt(content, offset) {
4936
+ let pos = 0;
4937
+ for (const span of content) {
4938
+ const end = pos + span.text.length;
4939
+ if (offset < end) return isExcluded(span);
4940
+ pos = end;
4941
+ }
4942
+ return false;
4943
+ }
4944
+
4945
+ // src/suggest/source.ts
4946
+ var LOADING_DELAY = 300;
4947
+ var SourceRunner = class {
4948
+ request = 0;
4949
+ controller = null;
4950
+ debounceTimer = null;
4951
+ loadingTimer = null;
4952
+ waiting = false;
4953
+ /** True from `run` until its result arrives or it is cancelled. */
4954
+ get pending() {
4955
+ return this.waiting;
4956
+ }
4957
+ /** Calls `fetch` after `debounce` ms and passes its result to `show`, unless a newer request or `cancel` came first. */
4958
+ run(fetch, handlers, debounce = 0) {
4959
+ this.cancel();
4960
+ const request = this.request;
4961
+ this.waiting = true;
4962
+ this.loadingTimer = setTimeout(() => {
4963
+ this.loadingTimer = null;
4964
+ if (request === this.request) handlers.loading();
4965
+ }, LOADING_DELAY);
4966
+ const done = (value) => {
4967
+ if (request !== this.request) return;
4968
+ this.settle();
4969
+ handlers.show(value);
4970
+ };
4971
+ const start = () => {
4972
+ this.debounceTimer = null;
4973
+ const controller = new AbortController();
4974
+ this.controller = controller;
4975
+ let result;
4976
+ try {
4977
+ result = fetch(controller.signal);
4978
+ } catch {
4979
+ done(null);
4980
+ return;
4981
+ }
4982
+ if (isPromise(result)) result.then(done, () => done(null));
4983
+ else done(result);
4984
+ };
4985
+ if (debounce > 0) this.debounceTimer = setTimeout(start, debounce);
4986
+ else start();
4987
+ }
4988
+ /** Drops the pending request: aborts its signal and clears its timers. */
4989
+ cancel() {
4990
+ this.request++;
4991
+ this.controller?.abort();
4992
+ this.settle();
4993
+ }
4994
+ settle() {
4995
+ this.waiting = false;
4996
+ this.controller = null;
4997
+ if (this.debounceTimer !== null) clearTimeout(this.debounceTimer);
4998
+ if (this.loadingTimer !== null) clearTimeout(this.loadingTimer);
4999
+ this.debounceTimer = this.loadingTimer = null;
5000
+ }
5001
+ };
5002
+ function isPromise(value) {
5003
+ return typeof value?.then === "function";
5004
+ }
5005
+
5006
+ // src/suggest/controller.ts
5007
+ var INTERACTION_DELAY = 75;
5008
+ var NO_SPACE_BEFORE = /[\s.,;:!?)\]}>'"’”»)」』】、。,.:;!?]/;
5009
+ var listboxCounter = 0;
5010
+ var SuggestionController = class {
5011
+ constructor(host, configs) {
5012
+ this.host = host;
5013
+ this.entries = configs.map((config) => {
5014
+ let menu = null;
5015
+ if (config.render !== false) {
5016
+ menu = new Menu(host.root, `mbe-suggestion-menu ${config.className ?? ""}`.trim(), "listbox");
5017
+ menu.el.setAttribute("aria-label", config.label ?? host.editor.labels.suggestions);
5018
+ menu.el.setAttribute("aria-expanded", "true");
5019
+ menu.onHighlight = (i) => {
5020
+ if (this.session?.entry.menu !== menu || this.active === i) return;
5021
+ this.active = i;
5022
+ this.host.syncActiveDescendant();
5023
+ this.report();
5024
+ };
5025
+ }
5026
+ return {
5027
+ config,
5028
+ matcher: config.match ?? defaultMatcher(config),
5029
+ triggers: typeof config.trigger === "string" ? [config.trigger] : config.trigger,
5030
+ menu,
5031
+ listboxId: menu?.el.id ?? `mbe-suggestion-${++listboxCounter}`,
5032
+ source: new SourceRunner()
5033
+ };
5034
+ });
5035
+ if (this.entries.length > 0) host.root.setAttribute("aria-autocomplete", "list");
5036
+ const view = host.root.ownerDocument.defaultView;
5037
+ if (view && this.entries.some((e) => e.menu)) {
5038
+ const schedule = () => this.schedule();
5039
+ const targets = [view];
5040
+ if (view.visualViewport) targets.push(view.visualViewport);
5041
+ for (const target of targets) {
5042
+ for (const type of target === view ? ["resize"] : ["resize", "scroll"]) {
5043
+ target.addEventListener(type, schedule);
5044
+ this.cleanup.push(() => target.removeEventListener(type, schedule));
5045
+ }
5046
+ }
5047
+ }
5048
+ }
5049
+ entries;
5050
+ session = null;
5051
+ /** The token Escape closed the popup for. It stays closed until the caret leaves it. */
5052
+ dismissed = null;
5053
+ /** The items shown, and the highlighted one. */
5054
+ items = [];
5055
+ active = -1;
5056
+ /** A line shown instead of items: the loading row or the empty label. */
5057
+ message = null;
5058
+ /** The side the popup is on. It stays there while open, unless it no longer fits. */
5059
+ side = "below";
5060
+ frame = null;
5061
+ /** The last request was made while composing. */
5062
+ requestedComposing = false;
5063
+ /** Until this time (ms), the popup takes no keys but Escape. */
5064
+ keysFrom = 0;
5065
+ /** What `suggestionChange` last reported, to emit only changes. */
5066
+ reported = "";
5067
+ cleanup = [];
5068
+ /** True while a suggestion tracks the token at the caret, shown or not. */
5069
+ get isActive() {
5070
+ return this.session !== null;
5071
+ }
5072
+ /** True while the popup shows items, a loading row or the empty label. Its keys work then. */
5073
+ get isOpen() {
5074
+ const session = this.session;
5075
+ if (!session || !this.shown) return false;
5076
+ return session.entry.menu ? session.entry.menu.isOpen : true;
5077
+ }
5078
+ /** The ID of the highlighted option while the popup is open. */
5079
+ get activeDescendant() {
5080
+ return this.isOpen && this.active >= 0 ? `${this.session.entry.listboxId}-${this.active}` : null;
5081
+ }
5082
+ /** The open suggestion, or null. */
5083
+ get state() {
5084
+ const session = this.session;
5085
+ if (!session) return null;
5086
+ const { entry, blockId, cell, from, to, query } = session;
5087
+ const at = (offset) => cell ? { blockId, offset, cell } : { blockId, offset };
5088
+ const listboxId = entry.listboxId;
5089
+ return {
5090
+ name: entry.config.name,
5091
+ query,
5092
+ range: { from: at(from), to: at(to) },
5093
+ items: this.items,
5094
+ active: this.active,
5095
+ loading: entry.source.pending,
5096
+ listboxId,
5097
+ optionId: (index) => `${listboxId}-${index}`,
5098
+ anchorRect: () => {
5099
+ if (this.session !== session) return null;
5100
+ const anchor = this.anchor();
5101
+ return anchor ? new DOMRect(anchor.rect.left, anchor.rect.top, 0, anchor.rect.bottom - anchor.rect.top) : null;
5102
+ }
5103
+ };
5104
+ }
5105
+ get shown() {
5106
+ return this.items.length > 0 || this.message !== null;
5107
+ }
5108
+ get editor() {
5109
+ return this.host.editor;
5110
+ }
5111
+ /**
5112
+ * Takes new configs for the same suggestions, by name, so callbacks
5113
+ * (`items`, `command`, `match`, `allow`) can change while the editor runs.
5114
+ */
5115
+ setConfigs(configs) {
5116
+ for (const config of configs) {
5117
+ const entry = this.entries.find((e) => e.config.name === config.name);
5118
+ if (!entry || entry.config === config) continue;
5119
+ if (config.match !== entry.config.match) entry.matcher = config.match ?? defaultMatcher(config);
5120
+ entry.config = config;
5121
+ }
5122
+ }
5123
+ /** After typing: opens the suggestion whose token is at the caret, if any. Returns true when one opened. */
5124
+ typed() {
5125
+ if (this.entries.length === 0 || !this.editor.isEditable) return false;
5126
+ const found = this.find(false);
5127
+ if (!found) return false;
5128
+ const dismissed = this.dismissed;
5129
+ if (dismissed && dismissed.blockId === found.blockId && sameCell(dismissed.cell, found.cell) && dismissed.from === found.from) return false;
5130
+ const session = this.session;
5131
+ if (session && session.entry === found.entry && session.blockId === found.blockId && sameCell(session.cell, found.cell) && session.from === found.from) {
5132
+ return false;
5133
+ }
5134
+ this.close();
5135
+ this.session = { ...found, explicit: false };
5136
+ return true;
5137
+ }
5138
+ /** Opens the popup for the token at the caret, as Ctrl+Space does. Returns false when there is none. */
5139
+ open(name) {
5140
+ if (!this.editor.isEditable) return false;
5141
+ const only = name === void 0 ? void 0 : this.entries.find((e) => e.config.name === name);
5142
+ if (name !== void 0 && !only) return false;
5143
+ const found = this.find(true, only);
5144
+ if (!found) return false;
5145
+ this.close();
5146
+ this.dismissed = null;
5147
+ this.session = { ...found, explicit: true };
5148
+ this.host.refresh();
5149
+ return true;
5150
+ }
5151
+ /** Follows the document and the caret: updates the query, or closes. */
5152
+ update(focused) {
5153
+ const dismissed = this.dismissed;
5154
+ if (dismissed) {
5155
+ const found2 = focused ? this.find(true) : null;
5156
+ if (!found2 || found2.blockId !== dismissed.blockId || !sameCell(found2.cell, dismissed.cell) || found2.from !== dismissed.from) {
5157
+ this.dismissed = null;
5158
+ }
5159
+ }
5160
+ const session = this.session;
5161
+ if (!session) return;
5162
+ const found = focused && this.editor.isEditable ? this.find(session.explicit, session.entry) : null;
5163
+ const same = found && found.blockId === session.blockId && sameCell(found.cell, session.cell) && (found.from === session.from || found.text !== session.text);
5164
+ if (!same) {
5165
+ this.close();
5166
+ return;
5167
+ }
5168
+ this.session = { ...session, ...found };
5169
+ this.refresh();
5170
+ this.report();
5171
+ }
5172
+ close() {
5173
+ const session = this.session;
5174
+ if (session) {
5175
+ session.entry.menu?.hide();
5176
+ if (session.entry.menu) session.entry.menu.busy = false;
5177
+ session.entry.source.cancel();
5178
+ }
5179
+ this.session = null;
5180
+ this.items = [];
5181
+ this.active = -1;
5182
+ this.message = null;
5183
+ this.requestedComposing = false;
5184
+ this.side = "below";
5185
+ this.keysFrom = 0;
5186
+ for (const name of ["aria-activedescendant", "aria-controls", "aria-haspopup"]) this.host.root.removeAttribute(name);
5187
+ this.report();
5188
+ }
5189
+ /** Moves the highlight by `delta` items, wrapping around. */
5190
+ move(delta2) {
5191
+ if (!this.session || this.items.length === 0) return;
5192
+ this.highlight(((this.active + delta2) % this.items.length + this.items.length) % this.items.length);
5193
+ }
5194
+ /** Picks the item at `index`, or the highlighted one. Returns false when there is none. */
5195
+ accept(index = this.active) {
5196
+ const item = this.items[index];
5197
+ if (!this.session || !item) return false;
5198
+ this.pick(item);
5199
+ return true;
5200
+ }
5201
+ /**
5202
+ * Handles a key while the popup is open. Returns true when the key was
5203
+ * taken; the caller then prevents its default. Only the popup's keys are
5204
+ * taken: arrows, Page Up and Down, Enter, Tab, Escape, and Ctrl+N and
5205
+ * Ctrl+P on macOS.
5206
+ */
5207
+ keydown(e) {
5208
+ if (!this.isOpen) return false;
5209
+ const plain2 = !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey;
5210
+ if (plain2 && e.key === "Escape") {
5211
+ this.dismiss();
5212
+ return true;
5213
+ }
5214
+ const emacs = isMac && e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey;
5215
+ const key = e.key;
5216
+ let action = null;
5217
+ if (plain2 && key === "ArrowDown") action = "down";
5218
+ else if (plain2 && key === "ArrowUp") action = "up";
5219
+ else if (emacs && key.toLowerCase() === "n") action = "down";
5220
+ else if (emacs && key.toLowerCase() === "p") action = "up";
5221
+ else if (plain2 && key === "PageDown") action = "pageDown";
5222
+ else if (plain2 && key === "PageUp") action = "pageUp";
5223
+ else if (plain2 && (key === "Enter" || key === "Tab")) action = "accept";
5224
+ if (!action || Date.now() < this.keysFrom) return false;
5225
+ if (this.items.length === 0) {
5226
+ if (key === "Enter") this.close();
5227
+ return false;
5228
+ }
5229
+ const menu = this.session.entry.menu;
5230
+ if (action === "down") this.move(1);
5231
+ else if (action === "up") this.move(-1);
5232
+ else if (action === "accept") this.accept();
5233
+ else if (menu) menu.page(action === "pageDown" ? 1 : -1);
5234
+ else this.highlight(Math.max(0, Math.min(this.items.length - 1, this.active + (action === "pageDown" ? 8 : -8))));
5235
+ return true;
5236
+ }
5237
+ /** Closes the popup and keeps it closed for this token (Escape). */
5238
+ dismiss() {
5239
+ const session = this.session;
5240
+ if (session) this.dismissed = { blockId: session.blockId, cell: session.cell, from: session.from };
5241
+ this.close();
5242
+ }
5243
+ /** Closes the popup and forgets dismissed tokens, as when the document is replaced. */
5244
+ reset() {
5245
+ this.dismissed = null;
5246
+ this.close();
5247
+ }
5248
+ /** Follows scrolling, resizing and the on-screen keyboard. */
5249
+ reposition() {
5250
+ if (this.session && this.shown) this.place();
5251
+ }
5252
+ destroy() {
5253
+ this.close();
5254
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
5255
+ for (const fn of this.cleanup) fn();
5256
+ for (const { menu } of this.entries) menu?.destroy();
5257
+ }
5258
+ schedule() {
5259
+ if (this.frame !== null || !this.shown) return;
5260
+ this.frame = requestAnimationFrame(() => {
5261
+ this.frame = null;
5262
+ this.reposition();
5263
+ });
5264
+ }
5265
+ highlight(index) {
5266
+ const menu = this.session?.entry.menu;
5267
+ if (menu) menu.highlight(index);
5268
+ else if (this.active !== index) {
5269
+ this.active = index;
5270
+ this.host.syncActiveDescendant();
5271
+ this.report();
5272
+ }
5273
+ }
5274
+ /** Emits `suggestionChange` when the state differs from the last one reported. */
5275
+ report() {
5276
+ const s = this.session;
5277
+ const key = s ? `${s.entry.config.name}
5278
+ ${s.blockId}
5279
+ ${s.cell?.row},${s.cell?.col}
5280
+ ${s.from}
5281
+ ${s.to}
5282
+ ${s.query}
5283
+ ${this.active}
5284
+ ${s.entry.source.pending}
5285
+ ${this.message}` : "";
5286
+ if (key === this.reported && !(s && this.itemsChanged)) return;
5287
+ this.reported = key;
5288
+ this.itemsChanged = false;
5289
+ this.host.changed(this.state);
5290
+ }
5291
+ itemsChanged = false;
5292
+ /**
5293
+ * The token at the caret that a suggestion accepts. When several do, the
5294
+ * one that starts closest to the caret wins; on a tie, the earlier one.
5295
+ */
5296
+ find(explicit, only) {
5297
+ const { doc, selection } = this.editor.state;
5298
+ if (!isCollapsed(selection)) return null;
5299
+ const pos = selection.focus;
5300
+ const block3 = doc.blocks.find((b) => b.id === pos.blockId);
5301
+ if (!block3 || isPlainTextBlock(block3)) return null;
5302
+ const content = containerContent(block3, pos.cell);
5303
+ if (!content) return null;
5304
+ const text = inlineText(content);
5305
+ const caret2 = pos.offset;
5306
+ let best = null;
5307
+ for (const entry of only ? [only] : this.entries) {
5308
+ const match = entry.matcher({ text, caret: caret2, content, triggers: entry.triggers });
5309
+ if (!match || best && match.from <= best.from) continue;
5310
+ if (match.from < 0 || match.from >= caret2 || match.to < caret2 || match.to > text.length) continue;
5311
+ if (!longestAt(text, match.from, entry.triggers, caret2)) continue;
5312
+ if (match.query.length > (entry.config.maxLength ?? 30)) continue;
5313
+ const excluded = excludedAt(content, match.from);
5314
+ const allow = entry.config.allow;
5315
+ const allowed = allow ? allow({ editor: this.editor, block: block3, cell: pos.cell, from: match.from, query: match.query, textBefore: text.slice(0, match.from), excluded, explicit }) : !excluded;
5316
+ if (!allowed) continue;
5317
+ best = { ...match, entry, blockId: block3.id, cell: pos.cell, text };
5318
+ }
5319
+ return best;
5320
+ }
5321
+ /** Asks for items when the query changed, and shows them when they arrive. */
5322
+ refresh() {
5323
+ const session = this.session;
5324
+ const { menu, source } = session.entry;
5325
+ const query = session.query;
5326
+ const composing = this.editor.isComposing;
5327
+ if (session.requested === query && !(this.requestedComposing && !composing)) {
5328
+ if (this.shown) this.place();
5329
+ return;
5330
+ }
5331
+ this.session = { ...session, requested: query };
5332
+ const current = this.session;
5333
+ const entry = current.entry;
5334
+ const live = () => this.session?.entry === entry && this.session.requested === query;
5335
+ let sync = true;
5336
+ const show = (result) => {
5337
+ if (!live()) return;
5338
+ const config = entry.config;
5339
+ if (menu) menu.busy = false;
5340
+ const items = (result ?? []).slice(0, config.limit ?? 50);
5341
+ if (items.length === 0 && composing && this.items.length > 0) return this.report();
5342
+ const empty = items.length === 0 && (!config.emptyLabel || query.length > 3);
5343
+ if (!empty && !sync && !this.isOpen) this.keysFrom = Date.now() + INTERACTION_DELAY;
5344
+ const activeId = this.items[this.active]?.id;
5345
+ const kept = activeId === void 0 ? -1 : items.findIndex((item) => item.id === activeId);
5346
+ const active = items.length === 0 ? -1 : Math.max(0, kept);
5347
+ this.items = items;
5348
+ this.active = active;
5349
+ this.message = items.length === 0 && !empty ? config.emptyLabel : null;
5350
+ this.itemsChanged = true;
5351
+ if (menu) {
5352
+ if (empty) menu.hide();
5353
+ else {
5354
+ menu.setSections(sections(items, query, (item) => this.pick(item)), config.emptyLabel);
5355
+ menu.highlight(active);
5356
+ }
5357
+ }
5358
+ if (empty) {
5359
+ this.host.root.removeAttribute("aria-haspopup");
5360
+ this.host.root.removeAttribute("aria-controls");
5361
+ this.host.syncActiveDescendant();
5362
+ } else {
5363
+ this.place();
5364
+ }
5365
+ this.report();
5366
+ };
5367
+ const loading = () => {
5368
+ if (!live() || this.shown) return this.report();
5369
+ this.message = this.editor.labels.loading;
5370
+ menu?.setMessage(this.message, "mbe-menu-loading");
5371
+ this.place();
5372
+ this.report();
5373
+ };
5374
+ this.requestedComposing = composing;
5375
+ source.run(
5376
+ (signal) => entry.config.items({ query, editor: this.editor, explicit: current.explicit, composing, signal }),
5377
+ { show, loading },
5378
+ entry.config.debounce ?? 0
5379
+ );
5380
+ sync = false;
5381
+ if (source.pending && menu?.isOpen) menu.busy = true;
5382
+ }
5383
+ /** The popup's anchor, or null while the trigger is out of view. */
5384
+ anchor() {
5385
+ const session = this.session;
5386
+ const at = (offset) => session.cell ? { blockId: session.blockId, offset, cell: session.cell } : { blockId: session.blockId, offset };
5387
+ const end = session.from + (longestAt(session.text, session.from, session.entry.triggers)?.length ?? 1);
5388
+ const trigger = this.editor.textRect(at(session.from), at(end));
5389
+ return suggestionAnchor(trigger?.rect ?? null, this.editor.caretRect(), trigger?.rtl ?? false, visibleArea(this.host.root));
5390
+ }
5391
+ /** Shows the popup under the caret's line, lined up with the trigger, or hides it while the trigger is out of view. */
5392
+ place() {
5393
+ const session = this.session;
5394
+ const { menu, listboxId } = session.entry;
5395
+ const root = this.host.root;
5396
+ const anchor = menu ? this.anchor() : null;
5397
+ if (menu && anchor) menu.popup.show(anchor.rect, this.side, 4, anchor.align);
5398
+ else menu?.hide();
5399
+ if (menu) this.side = menu.popup.side;
5400
+ if (this.isOpen) {
5401
+ root.setAttribute("aria-haspopup", "listbox");
5402
+ root.setAttribute("aria-controls", listboxId);
5403
+ } else {
5404
+ root.removeAttribute("aria-haspopup");
5405
+ root.removeAttribute("aria-controls");
5406
+ }
5407
+ this.host.syncActiveDescendant();
5408
+ }
5409
+ pick(item) {
5410
+ if (this.editor.isComposing) this.host.endComposition();
5411
+ const session = this.session;
5412
+ if (!session) return;
5413
+ const { entry, blockId, cell, from, to, query, text } = session;
5414
+ const at = (offset) => cell ? { blockId, offset, cell } : { blockId, offset };
5415
+ const range = { from: at(from), to: at(to) };
5416
+ this.close();
5417
+ if (entry.config.command) {
5418
+ entry.config.command({ editor: this.editor, range, item, query });
5419
+ return;
5420
+ }
5421
+ const next = text[to];
5422
+ const space = next !== void 0 && NO_SPACE_BEFORE.test(next) ? "" : " ";
5423
+ this.editor.commands.insertText(entry.triggers[0] + (item.value ?? item.id ?? item.label) + space, { range });
5424
+ }
5425
+ };
5426
+ function itemId(item, index) {
5427
+ return item.id ?? `${index}`;
5428
+ }
5429
+ function sections(items, query, pick) {
5430
+ const out = [];
5431
+ items.forEach((item, i) => {
5432
+ let last = out[out.length - 1];
5433
+ if (!last || item.section !== last.title) out.push(last = { title: item.section, items: [] });
5434
+ last.items.push({ id: itemId(item, i), label: item.label, detail: item.detail, icon: item.icon, mark: query, run: () => pick(item) });
5435
+ });
5436
+ return out;
5437
+ }
4438
5438
 
4439
5439
  // src/widgets.ts
4440
5440
  var WidgetImpl = class {
@@ -4506,10 +5506,10 @@ function matchesKey(binding, e) {
4506
5506
  // src/ui/toolbar.ts
4507
5507
  var mod = (key) => isMac ? `\u2318${key}` : `Ctrl+${key}`;
4508
5508
  var MARK_BUTTONS = [
4509
- { mark: "bold", label: "bold", text: "B", shortcut: mod("B") },
4510
- { mark: "italic", label: "italic", text: "I", shortcut: mod("I") },
4511
- { mark: "strike", label: "strike", text: "S", shortcut: isMac ? "\u2318\u21E7X" : "Ctrl+Shift+X" },
4512
- { mark: "code", label: "inlineCode", text: "</>", shortcut: mod("E") }
5509
+ { mark: "bold", name: "bold", shortcut: mod("B") },
5510
+ { mark: "italic", name: "italic", shortcut: mod("I") },
5511
+ { mark: "strike", name: "strike", shortcut: isMac ? "\u2318\u21E7X" : "Ctrl+Shift+X" },
5512
+ { mark: "code", name: "inlineCode", shortcut: mod("E") }
4513
5513
  ];
4514
5514
  var FormatToolbar = class {
4515
5515
  constructor(editor) {
@@ -4518,11 +5518,12 @@ var FormatToolbar = class {
4518
5518
  this.popup = new Popup(editor.root, "mbe-toolbar");
4519
5519
  const el = this.popup.el;
4520
5520
  el.setAttribute("role", "toolbar");
4521
- const button = (text, label, className, onClick) => {
5521
+ const button = (icon, label, className, onClick) => {
4522
5522
  const b = doc.createElement("button");
4523
5523
  b.type = "button";
4524
5524
  b.className = `mbe-tool ${className}`;
4525
- b.textContent = text;
5525
+ const content = iconNode(doc, editor.icon(icon));
5526
+ if (content) b.appendChild(content);
4526
5527
  b.title = label;
4527
5528
  b.setAttribute("aria-label", label);
4528
5529
  b.addEventListener("click", onClick);
@@ -4531,7 +5532,7 @@ var FormatToolbar = class {
4531
5532
  };
4532
5533
  const labels = editor.labels;
4533
5534
  for (const b of MARK_BUTTONS) {
4534
- const btn = button(b.text, `${labels[b.label]} (${b.shortcut})`, `mbe-tool-${b.mark}`, () => {
5535
+ const btn = button(b.name, `${labels[b.name]} (${b.shortcut})`, `mbe-tool-${b.mark}`, () => {
4535
5536
  editor.run((s) => toggleMark(s, b.mark));
4536
5537
  this.update();
4537
5538
  });
@@ -4539,7 +5540,7 @@ var FormatToolbar = class {
4539
5540
  this.markButtons.set(b.mark, btn);
4540
5541
  }
4541
5542
  el.appendChild(separator(doc));
4542
- this.linkButton = button(labels.link, `${labels.link} (${mod("K")})`, "mbe-tool-link", () => editor.openLinkPopover());
5543
+ this.linkButton = button("link", `${labels.link} (${mod("K")})`, "mbe-tool-link", () => editor.openLinkPopover());
4543
5544
  }
4544
5545
  popup;
4545
5546
  markButtons = /* @__PURE__ */ new Map();
@@ -4639,6 +5640,9 @@ var LinkPopover = class {
4639
5640
 
4640
5641
  // src/view/dom.ts
4641
5642
  var BLOCK_ATTR = "data-block-id";
5643
+ function codeViewName(language) {
5644
+ return `code:${language.trim().toLowerCase()}`;
5645
+ }
4642
5646
  var CONTENT_ATTR = "data-content";
4643
5647
  var FILL_ATTR = "data-mbe-fill";
4644
5648
  var ATOM_ATTR = "data-atom";
@@ -4675,12 +5679,12 @@ function blockClasses(block3, theme) {
4675
5679
  return void 0;
4676
5680
  }
4677
5681
  }
4678
- function safeHref(href) {
4679
- const trimmed = href.trim();
5682
+ var defaultResolveUrl = (url) => {
5683
+ const trimmed = url.trim();
4680
5684
  const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(trimmed);
4681
5685
  if (!scheme) return trimmed;
4682
5686
  return ["http", "https", "mailto", "tel"].includes(scheme[1].toLowerCase()) ? trimmed : null;
4683
- }
5687
+ };
4684
5688
  var REVEAL_BLOCK = "block";
4685
5689
  function tokenKey(cell, from) {
4686
5690
  return cell ? `${cell.row}:${cell.col}@${from}` : `@${from}`;
@@ -4704,10 +5708,12 @@ function renderBlock(block3, ctx, reveal) {
4704
5708
  case "heading":
4705
5709
  case "quote":
4706
5710
  root = el(block3.type === "paragraph" ? "p" : block3.type === "quote" ? "blockquote" : `h${block3.level}`);
5711
+ root.dir = "auto";
4707
5712
  fillContent(root, block3.content, ctx, block3, reveal);
4708
5713
  break;
4709
5714
  case "listItem": {
4710
5715
  root = el("div");
5716
+ root.dir = "auto";
4711
5717
  root.dataset.listType = block3.listType;
4712
5718
  root.dataset.indent = String(block3.indent);
4713
5719
  const marker = el("span", "mbe-marker");
@@ -4725,6 +5731,14 @@ function renderBlock(block3, ctx, reveal) {
4725
5731
  break;
4726
5732
  }
4727
5733
  case "code": {
5734
+ const view = reveal?.has(REVEAL_BLOCK) ? null : ctx.view?.(codeViewName(block3.language), inlineText(block3.content), "block");
5735
+ if (view) {
5736
+ root = view;
5737
+ root.classList.add("mbe-view-block");
5738
+ root.contentEditable = "false";
5739
+ root.dataset.language = block3.language;
5740
+ break;
5741
+ }
4728
5742
  root = el("div");
4729
5743
  root.dataset.language = block3.language;
4730
5744
  const bar = el("div", "mbe-code-bar");
@@ -4772,6 +5786,7 @@ function renderBlock(block3, ctx, reveal) {
4772
5786
  row.forEach((cell, c) => {
4773
5787
  const td = el(r === 0 ? "th" : "td");
4774
5788
  td.contentEditable = "true";
5789
+ td.dir = "auto";
4775
5790
  td.dataset.row = String(r);
4776
5791
  td.dataset.col = String(c);
4777
5792
  const align = block3.align[c];
@@ -4803,8 +5818,13 @@ function fillContent(target, inline3, ctx, block3, reveal, cell, decorated = tru
4803
5818
  target.appendChild(fill(doc));
4804
5819
  return;
4805
5820
  }
4806
- const decorations = decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
4807
- renderInline(inline3, target, ctx, decorations, reveal, cell);
5821
+ const decorations = block3.type === "code" ? ctx.decorateCode?.(block3) ?? [] : decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
5822
+ const only = inline3.length === 1 ? inline3[0] : null;
5823
+ if (only && decorations.length === 0 && only.marks.length === 0 && !only.link && !only.token && !only.image) {
5824
+ target.appendChild(doc.createTextNode(only.text));
5825
+ } else {
5826
+ renderInline(inline3, target, ctx, decorations, reveal, cell);
5827
+ }
4808
5828
  const last = inline3[inline3.length - 1];
4809
5829
  if (last && last.text.endsWith("\n")) target.appendChild(fill(doc));
4810
5830
  }
@@ -4813,18 +5833,73 @@ function fill(doc) {
4813
5833
  br.setAttribute(FILL_ATTR, "");
4814
5834
  return br;
4815
5835
  }
5836
+ var VOID_TAGS = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
5837
+ function htmlRuns(inline3) {
5838
+ const spans = [];
5839
+ let pos = 0;
5840
+ for (const span of inline3) {
5841
+ spans.push({ span, from: pos, to: pos + span.text.length });
5842
+ pos += span.text.length;
5843
+ }
5844
+ const isHtml = (span) => span.marks.includes("html");
5845
+ const runs = [];
5846
+ for (let i = 0; i < spans.length; i++) {
5847
+ const { span, from, to } = spans[i];
5848
+ if (!isHtml(span)) continue;
5849
+ const open = /^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*?(\/?)>$/.exec(span.text);
5850
+ let end = i;
5851
+ if (open && !open[2] && !VOID_TAGS.has(open[1].toLowerCase())) {
5852
+ const name = open[1].toLowerCase();
5853
+ let depth = 0;
5854
+ for (let j = i + 1; j < spans.length; j++) {
5855
+ const t = spans[j].span;
5856
+ if (t.link) break;
5857
+ if (!isHtml(t)) continue;
5858
+ const tag = /^<(\/?)([A-Za-z][A-Za-z0-9-]*)\b[^>]*?(\/?)>$/.exec(t.text);
5859
+ if (!tag || tag[2].toLowerCase() !== name || tag[3]) continue;
5860
+ if (!tag[1]) depth++;
5861
+ else if (depth > 0) depth--;
5862
+ else {
5863
+ end = j;
5864
+ break;
5865
+ }
5866
+ }
5867
+ }
5868
+ if (spans.slice(i, end + 1).some((s) => s.span.link)) continue;
5869
+ runs.push({ from, to: end === i ? to : spans[end].to });
5870
+ i = end;
5871
+ }
5872
+ return runs;
5873
+ }
4816
5874
  function renderInline(inline3, parent, ctx, decorations, reveal, cell) {
4817
5875
  const doc = ctx.doc;
4818
5876
  const views = ctx.views;
4819
5877
  const viewed = views ? (span, from) => !!span.token && views.has(span.token) && !reveal?.has(tokenKey(cell, from)) : void 0;
4820
- const pieces = splitByDecorations(inline3, decorations, viewed);
4821
- const render2 = (piece) => decorate(renderSpan(piece.span, ctx, piece.atomic), piece.decorations, doc);
5878
+ const runs = views?.has("html") && inline3.some((s) => s.marks.includes("html")) ? htmlRuns(inline3).filter((run) => !reveal?.has(tokenKey(cell, run.from))) : [];
5879
+ const inRun = (from) => runs.some((run) => from >= run.from && from < run.to);
5880
+ const atomic = viewed || runs.length > 0 ? (span, from) => !!viewed?.(span, from) || inRun(from) : void 0;
5881
+ const pieces = splitByDecorations(inline3, decorations, atomic);
5882
+ const render2 = (piece) => decorate(renderSpan(piece.span, ctx, piece.atomic && !inRun(offsets.get(piece) ?? -1)), piece.decorations, doc);
5883
+ const offsets = /* @__PURE__ */ new Map();
5884
+ let offset = 0;
5885
+ for (const piece of pieces) {
5886
+ offsets.set(piece, offset);
5887
+ offset += piece.span.text.length;
5888
+ }
4822
5889
  let i = 0;
4823
5890
  while (i < pieces.length) {
4824
5891
  const span = pieces[i].span;
5892
+ const run = runs.find((r) => r.from === offsets.get(pieces[i]));
5893
+ const view = run && ctx.view?.("html", serializeInline(sliceInline(inline3, run.from, run.to)), "inline");
5894
+ if (run && view) {
5895
+ const text = inlineText(sliceInline(inline3, run.from, run.to));
5896
+ parent.appendChild(atom(view, classes("mbe-view", "mbe-view-html", ctx.classes.token?.html), text));
5897
+ while (i < pieces.length && offsets.get(pieces[i]) < run.to) i++;
5898
+ continue;
5899
+ }
4825
5900
  if (span.link) {
4826
5901
  const a = doc.createElement("a");
4827
- const href = safeHref(span.link);
5902
+ const href = ctx.resolveUrl(span.link, "link");
4828
5903
  if (href !== null) a.setAttribute("href", href);
4829
5904
  a.dataset.href = span.link;
4830
5905
  a.className = classes("mbe-link", ctx.classes.link);
@@ -4863,7 +5938,10 @@ function renderSpan(span, ctx, viewed = false) {
4863
5938
  if (view) return wrapMarks(span, atom(view, classes("mbe-view", `mbe-view-${span.token}`, ctx.classes.token?.[span.token]), span.text), ctx);
4864
5939
  if (span.image) {
4865
5940
  const img = doc.createElement("img");
4866
- const src = safeHref(ctx.resolveImageSrc ? ctx.resolveImageSrc(span.image.src) : span.image.src);
5941
+ img.setAttribute("loading", "lazy");
5942
+ img.setAttribute("decoding", "async");
5943
+ if (ctx.referrerPolicy) img.setAttribute("referrerpolicy", ctx.referrerPolicy);
5944
+ const src = ctx.resolveUrl(span.image.src, "image");
4867
5945
  if (src !== null) img.src = src;
4868
5946
  img.alt = span.image.alt;
4869
5947
  if (span.image.title) img.title = span.image.title;
@@ -4900,10 +5978,20 @@ var BlockRenderer = class {
4900
5978
  rendered = /* @__PURE__ */ new Map();
4901
5979
  /** Last number written into each ordered item's marker, keyed by element. */
4902
5980
  numbers = /* @__PURE__ */ new WeakMap();
4903
- /** Maps an image `src` to the URL to display. Set before a full render. */
4904
- resolveImageSrc;
5981
+ /** The URL policy for links and images. Set before a full render. */
5982
+ resolveUrl = defaultResolveUrl;
5983
+ /** `referrerpolicy` for images. */
5984
+ referrerPolicy;
4905
5985
  /** Decorations for a text container. */
4906
5986
  decorate;
5987
+ /** Decorations for a code block's code. */
5988
+ decorateCode;
5989
+ /**
5990
+ * Called when views that returned a promise settle, with the blocks that
5991
+ * showed them. Those blocks must render again to show the finished view,
5992
+ * or their source if it failed.
5993
+ */
5994
+ onViewSettled;
4907
5995
  /** Widget elements to place after a block. */
4908
5996
  widgetsAfter;
4909
5997
  /** Views of extension syntaxes, by syntax name. */
@@ -4917,12 +6005,20 @@ var BlockRenderer = class {
4917
6005
  * Cloned on reuse: typing re-renders a block and every formula in it.
4918
6006
  */
4919
6007
  viewCache = /* @__PURE__ */ new Map();
6008
+ /** Views whose promise has not settled, by cache key, with the blocks showing them. */
6009
+ pendingViews = /* @__PURE__ */ new Map();
6010
+ /** Views whose promise rejected or resolved to false: their source shows. */
6011
+ failedViews = /* @__PURE__ */ new Set();
6012
+ /** The block being rendered, so a pending view knows which blocks to render again. */
6013
+ renderingBlock = "";
4920
6014
  context() {
4921
6015
  return {
4922
6016
  doc: this.root.ownerDocument,
4923
6017
  labels: this.labels,
4924
- resolveImageSrc: this.resolveImageSrc,
6018
+ resolveUrl: this.resolveUrl,
6019
+ referrerPolicy: this.referrerPolicy,
4925
6020
  decorate: this.decorate,
6021
+ decorateCode: this.decorateCode,
4926
6022
  views: this.views,
4927
6023
  view: this.views && ((syntax, source, kind) => this.renderView(syntax, source, kind)),
4928
6024
  classes: this.classes
@@ -4932,21 +6028,46 @@ var BlockRenderer = class {
4932
6028
  const view = this.views?.get(syntax);
4933
6029
  if (!view) return null;
4934
6030
  const key = `${kind}\0${syntax}\0${source}`;
6031
+ if (this.failedViews.has(key)) return null;
4935
6032
  let el = this.viewCache.get(key);
4936
6033
  if (el) {
4937
6034
  this.viewCache.delete(key);
4938
6035
  } else {
4939
6036
  el = this.root.ownerDocument.createElement(kind === "inline" ? "span" : "div");
6037
+ let result;
4940
6038
  try {
4941
- if (view(source, el, kind) === false) return null;
6039
+ result = view(source, el, kind);
4942
6040
  } catch {
4943
6041
  return null;
4944
6042
  }
6043
+ if (result === false) return null;
6044
+ if (result && typeof result.then === "function") this.awaitView(key, result);
4945
6045
  if (this.viewCache.size >= 500) this.viewCache.delete(this.viewCache.keys().next().value);
4946
6046
  }
6047
+ this.pendingViews.get(key)?.add(this.renderingBlock);
4947
6048
  this.viewCache.set(key, el);
4948
6049
  return el.cloneNode(true);
4949
6050
  }
6051
+ /**
6052
+ * A view that renders later (a diagram, a lazily loaded renderer) shows what
6053
+ * it filled in at once, and its blocks render again when it settles.
6054
+ */
6055
+ awaitView(key, result) {
6056
+ this.pendingViews.set(key, /* @__PURE__ */ new Set());
6057
+ const settle = (ok) => {
6058
+ const blocks = this.pendingViews.get(key);
6059
+ this.pendingViews.delete(key);
6060
+ if (!ok) {
6061
+ this.failedViews.add(key);
6062
+ this.viewCache.delete(key);
6063
+ }
6064
+ if (blocks && blocks.size > 0) this.onViewSettled?.([...blocks]);
6065
+ };
6066
+ result.then(
6067
+ (value) => settle(value !== false),
6068
+ () => settle(false)
6069
+ );
6070
+ }
4950
6071
  /**
4951
6072
  * `force` re-renders every block. `lazy` (with a full render) lets blocks
4952
6073
  * skip layout while off screen; use it only when loading a document.
@@ -4955,6 +6076,7 @@ var BlockRenderer = class {
4955
6076
  const ctx = this.context();
4956
6077
  const next = /* @__PURE__ */ new Map();
4957
6078
  for (const block3 of doc.blocks) {
6079
+ this.renderingBlock = block3.id;
4958
6080
  const prev = this.rendered.get(block3.id);
4959
6081
  const reveal = this.revealed.get(block3.id);
4960
6082
  const reuse = !force && prev && prev.block === block3 && prev.el.parentNode === this.root && sameReveal(prev.reveal, reveal);
@@ -5166,7 +6288,8 @@ var BlockHandle = class {
5166
6288
  this.el = doc.createElement("button");
5167
6289
  this.el.type = "button";
5168
6290
  this.el.className = "mbe-ui mbe-handle";
5169
- this.el.textContent = "\u22EE\u22EE";
6291
+ const icon = iconNode(doc, editor.icon("blockHandle"));
6292
+ if (icon) this.el.appendChild(icon);
5170
6293
  this.el.setAttribute("aria-label", editor.labels.blockHandle);
5171
6294
  this.el.setAttribute("aria-haspopup", "menu");
5172
6295
  this.el.tabIndex = -1;
@@ -5204,15 +6327,15 @@ var BlockHandle = class {
5204
6327
  const blockEl = this.editor.blockElement(blockId);
5205
6328
  if (!blockEl) return this.hide();
5206
6329
  const doc = this.editor.root.ownerDocument;
5207
- if (!this.el.isConnected) doc.body.appendChild(this.el);
5208
6330
  this.blockId = blockId;
5209
6331
  this.el.hidden = false;
6332
+ const offset = attach(this.el, this.editor.root);
5210
6333
  const rect = blockEl.getBoundingClientRect();
5211
6334
  const lineHeight = parseFloat(doc.defaultView.getComputedStyle(blockEl).lineHeight) || 24;
5212
6335
  const firstLine = Math.min(rect.height, lineHeight);
5213
6336
  const size = this.el.offsetHeight || 22;
5214
- this.el.style.left = `${Math.round(rect.left - (this.el.offsetWidth || 20) - 6)}px`;
5215
- this.el.style.top = `${Math.round(rect.top + firstLine / 2 - size / 2)}px`;
6337
+ this.el.style.left = `${Math.round(rect.left - (this.el.offsetWidth || 20) - 6 - offset.x)}px`;
6338
+ this.el.style.top = `${Math.round(rect.top + firstLine / 2 - size / 2 - offset.y)}px`;
5216
6339
  }
5217
6340
  hide() {
5218
6341
  this.cancelHide();
@@ -5248,10 +6371,16 @@ function revealedViews(state, views, active) {
5248
6371
  const keys = out.get(block3.id) ?? /* @__PURE__ */ new Set();
5249
6372
  if (block3.type === "raw") {
5250
6373
  if (views.has(block3.syntax)) keys.add(REVEAL_BLOCK);
6374
+ } else if (block3.type === "code") {
6375
+ if (views.has(codeViewName(block3.language))) keys.add(REVEAL_BLOCK);
5251
6376
  } else {
5252
- for (const { token, from } of tokensAt(containerContent(block3, pos.cell) ?? [], pos.offset)) {
6377
+ const content = containerContent(block3, pos.cell) ?? [];
6378
+ for (const { token, from } of tokensAt(content, pos.offset)) {
5253
6379
  if (views.has(token)) keys.add(tokenKey(pos.cell, from));
5254
6380
  }
6381
+ if (views.has("html") && content.some((s) => s.marks.includes("html"))) {
6382
+ for (const run of htmlRuns(content)) if (run.from <= pos.offset && pos.offset <= run.to) keys.add(tokenKey(pos.cell, run.from));
6383
+ }
5255
6384
  }
5256
6385
  if (keys.size > 0) out.set(block3.id, keys);
5257
6386
  }
@@ -5262,6 +6391,7 @@ function sameRevealed(a, b) {
5262
6391
  }
5263
6392
  function viewEntry(block3, forward) {
5264
6393
  const text = inlineText(block3.content);
6394
+ if (block3.type === "code") return { blockId: block3.id, offset: forward ? 0 : text.length };
5265
6395
  if (forward) {
5266
6396
  const firstBreak = text.indexOf("\n");
5267
6397
  return { blockId: block3.id, offset: firstBreak >= 0 && firstBreak < text.length - 1 ? firstBreak + 1 : 0 };
@@ -5270,6 +6400,47 @@ function viewEntry(block3, forward) {
5270
6400
  return { blockId: block3.id, offset: lastBreak > 0 ? lastBreak : text.length };
5271
6401
  }
5272
6402
 
6403
+ // src/view/scroll.ts
6404
+ var MARGIN = 8;
6405
+ function scrollRectIntoView(from, rect) {
6406
+ const doc = from.ownerDocument;
6407
+ const win = doc.defaultView;
6408
+ let top = rect.top;
6409
+ let bottom = rect.bottom;
6410
+ let left = rect.left;
6411
+ let right = rect.right;
6412
+ for (let el = from; el && el !== doc.body && el !== doc.documentElement; el = el.parentElement) {
6413
+ const style = win?.getComputedStyle(el);
6414
+ const scrollsY = el.scrollHeight > el.clientHeight && /auto|scroll|overlay/.test(style?.overflowY ?? "");
6415
+ const scrollsX = el.scrollWidth > el.clientWidth && /auto|scroll|overlay/.test(style?.overflowX ?? "");
6416
+ if (!scrollsY && !scrollsX) continue;
6417
+ const box = el.getBoundingClientRect();
6418
+ const viewTop = box.top + el.clientTop;
6419
+ const viewLeft = box.left + el.clientLeft;
6420
+ const dy2 = scrollsY ? delta(top, bottom, viewTop, viewTop + el.clientHeight) : 0;
6421
+ const dx2 = scrollsX ? delta(left, right, viewLeft, viewLeft + el.clientWidth) : 0;
6422
+ if (!dy2 && !dx2) continue;
6423
+ const beforeTop = el.scrollTop;
6424
+ const beforeLeft = el.scrollLeft;
6425
+ el.scrollTop += dy2;
6426
+ el.scrollLeft += dx2;
6427
+ top -= el.scrollTop - beforeTop;
6428
+ bottom -= el.scrollTop - beforeTop;
6429
+ left -= el.scrollLeft - beforeLeft;
6430
+ right -= el.scrollLeft - beforeLeft;
6431
+ }
6432
+ if (!win) return;
6433
+ const viewport = doc.documentElement;
6434
+ const dy = delta(top, bottom, 0, viewport.clientHeight);
6435
+ const dx = delta(left, right, 0, viewport.clientWidth);
6436
+ if (dy || dx) win.scrollBy(dx, dy);
6437
+ }
6438
+ function delta(start, end, viewStart, viewEnd) {
6439
+ if (start < viewStart + MARGIN) return start - viewStart - MARGIN;
6440
+ if (end > viewEnd - MARGIN) return Math.min(end - viewEnd + MARGIN, start - viewStart - MARGIN);
6441
+ return 0;
6442
+ }
6443
+
5273
6444
  // src/theme.ts
5274
6445
  function mergeClasses(maps) {
5275
6446
  const out = {};
@@ -5333,35 +6504,40 @@ var SLASH_ITEM_IDS = [
5333
6504
  "divider"
5334
6505
  ];
5335
6506
  var BLOCK_ITEMS = [
5336
- { id: "text", icon: "T", aliases: ["paragraph", "plain"], spec: { type: "paragraph" } },
5337
- { id: "heading1", icon: "H1", aliases: ["h1", "title"], spec: { type: "heading", level: 1 } },
5338
- { id: "heading2", icon: "H2", aliases: ["h2", "subtitle"], spec: { type: "heading", level: 2 } },
5339
- { id: "heading3", icon: "H3", aliases: ["h3"], spec: { type: "heading", level: 3 } },
5340
- { id: "bulletList", icon: "\u2022", aliases: ["ul", "unordered", "bullet"], spec: { type: "listItem", listType: "bullet" } },
5341
- { id: "numberedList", icon: "1.", aliases: ["ol", "ordered"], spec: { type: "listItem", listType: "ordered" } },
5342
- { id: "todoList", icon: "\u2610", aliases: ["task", "checkbox", "checklist"], spec: { type: "listItem", listType: "task" } },
5343
- { id: "quote", icon: "\u275D", aliases: ["blockquote", "citation"], spec: { type: "quote" } },
5344
- { id: "code", icon: "</>", aliases: ["pre", "snippet", "fence"], spec: { type: "code" } },
5345
- { id: "table", icon: "\u229E", aliases: ["grid"], spec: { type: "table" } },
5346
- { id: "divider", icon: "\u2014", aliases: ["hr", "separator", "line", "rule"], spec: { type: "divider" } }
6507
+ { id: "text", aliases: ["paragraph", "plain"], spec: { type: "paragraph" } },
6508
+ { id: "heading1", aliases: ["h1", "title"], spec: { type: "heading", level: 1 } },
6509
+ { id: "heading2", aliases: ["h2", "subtitle"], spec: { type: "heading", level: 2 } },
6510
+ { id: "heading3", aliases: ["h3"], spec: { type: "heading", level: 3 } },
6511
+ { id: "bulletList", aliases: ["ul", "unordered", "bullet"], spec: { type: "listItem", listType: "bullet" } },
6512
+ { id: "numberedList", aliases: ["ol", "ordered"], spec: { type: "listItem", listType: "ordered" } },
6513
+ { id: "todoList", aliases: ["task", "checkbox", "checklist"], spec: { type: "listItem", listType: "task" } },
6514
+ { id: "quote", aliases: ["blockquote", "citation"], spec: { type: "quote" } },
6515
+ { id: "code", aliases: ["pre", "snippet", "fence"], spec: { type: "code" } },
6516
+ { id: "table", aliases: ["grid"], spec: { type: "table" } },
6517
+ { id: "divider", aliases: ["hr", "separator", "line", "rule"], spec: { type: "divider" } }
5347
6518
  ];
5348
6519
  var TABLE_ITEMS = [
5349
- { id: "addRowAbove", icon: "\u2191", action: { kind: "addRowAbove" } },
5350
- { id: "addRowBelow", icon: "\u2193", action: { kind: "addRowBelow" } },
5351
- { id: "addColumnLeft", icon: "\u2190", action: { kind: "addColumnLeft" } },
5352
- { id: "addColumnRight", icon: "\u2192", action: { kind: "addColumnRight" } },
5353
- { id: "alignLeft", icon: "\u21E4", action: { kind: "align", align: "left" } },
5354
- { id: "alignCenter", icon: "\u2194", action: { kind: "align", align: "center" } },
5355
- { id: "alignRight", icon: "\u21E5", action: { kind: "align", align: "right" } },
5356
- { id: "deleteRow", icon: "\u2715", action: { kind: "deleteRow" } },
5357
- { id: "deleteColumn", icon: "\u2715", action: { kind: "deleteColumn" } }
6520
+ { id: "addRowAbove", action: { kind: "addRowAbove" } },
6521
+ { id: "addRowBelow", action: { kind: "addRowBelow" } },
6522
+ { id: "addColumnLeft", action: { kind: "addColumnLeft" } },
6523
+ { id: "addColumnRight", action: { kind: "addColumnRight" } },
6524
+ { id: "alignLeft", action: { kind: "align", align: "left" } },
6525
+ { id: "alignCenter", action: { kind: "align", align: "center" } },
6526
+ { id: "alignRight", action: { kind: "align", align: "right" } },
6527
+ { id: "deleteRow", action: { kind: "deleteRow" } },
6528
+ { id: "deleteColumn", action: { kind: "deleteColumn" } }
5358
6529
  ];
5359
6530
  var SLASH_CHARS = ["/", "\uFF0F"];
6531
+ var CARET_KEY = /^(Arrow(Up|Down|Left|Right)|Home|End|PageUp|PageDown)$/;
5360
6532
  var COMPOSITION_INPUT = /* @__PURE__ */ new Set(["insertCompositionText", "deleteCompositionText", "insertFromComposition", "deleteByComposition"]);
5361
6533
  var Editor = class {
6534
+ /** The editable element the editor renders into: `options.element`, or for `useEditor`, the element `<EditorContent>` mounts. */
5362
6535
  root;
6536
+ /** @internal The UI strings: the defaults with the `labels` option applied. */
5363
6537
  labels;
5364
6538
  commands;
6539
+ /** The autocomplete popup of `suggestion()` extensions and the slash menu. */
6540
+ suggestion;
5365
6541
  current;
5366
6542
  /** The Markdown the document was loaded from; unchanged blocks are saved as this text. */
5367
6543
  source;
@@ -5375,11 +6551,15 @@ var Editor = class {
5375
6551
  * block, the marks for composed text, and whether it has an undo step yet.
5376
6552
  */
5377
6553
  composition = null;
6554
+ /** When the last composition ended (Safari only): the next key may be the Enter that committed it. */
6555
+ compositionEndedAt = 0;
5378
6556
  /** Blocks the browser edited during a composition that ended, rendered again on the next frame. */
5379
6557
  unsettled = /* @__PURE__ */ new Set();
5380
6558
  settleFrame = null;
5381
6559
  readOnly;
5382
6560
  wasReadOnly = false;
6561
+ /** Task checkboxes stay usable while read-only. */
6562
+ taskToggle;
5383
6563
  options;
5384
6564
  /** The extensions in priority order, ending with the default keymap unless one was given. */
5385
6565
  extensions;
@@ -5398,10 +6578,18 @@ var Editor = class {
5398
6578
  focused = false;
5399
6579
  /** A mouse button is down in the editor. Rendered views keep their state until it is released, so a drag is not disturbed. */
5400
6580
  pointerDown = false;
5401
- /** Suggestion menus from extensions, then the slash menu. */
6581
+ /** The selection the formatting toolbar was closed for with Escape. It stays closed until the selection changes. */
6582
+ toolbarClosedFor = null;
6583
+ /** Handling a key press, typed text, a paste or a drop: changes then scroll the caret into view. */
6584
+ typing = 0;
6585
+ /**
6586
+ * A caret key the browser is handling: the block the caret was in, the
6587
+ * caret's x, and 1 or -1 for a plain ArrowDown or ArrowUp. The next
6588
+ * selection change checks where the caret went (see `onSelectionChange`).
6589
+ */
6590
+ caretKey = null;
6591
+ /** Suggestion menus from extensions, then the slash menu (see suggest/controller.ts). */
5402
6592
  suggestions;
5403
- /** The open suggestion: which one, where its trigger is, and the last query shown. */
5404
- suggest = null;
5405
6593
  blockMenu;
5406
6594
  toolbar;
5407
6595
  linkPopover;
@@ -5416,6 +6604,12 @@ var Editor = class {
5416
6604
  blockSel = null;
5417
6605
  /** Block elements that carry the selected class. */
5418
6606
  selectedEls = [];
6607
+ /** The ids `headingIds` gave the headings of `doc`, by block ID. */
6608
+ headingIdsFor = null;
6609
+ /** `redecorate()` was called during a composition; it runs when the composition settles. */
6610
+ redecoratePending = false;
6611
+ /** The frame that renders blocks again after their views settled. */
6612
+ viewFrame = 0;
5419
6613
  constructor(options) {
5420
6614
  const root = options.element;
5421
6615
  this.root = root;
@@ -5423,6 +6617,7 @@ var Editor = class {
5423
6617
  this.runtime = {};
5424
6618
  this.labels = { ...DEFAULT_LABELS, ...options.labels };
5425
6619
  this.readOnly = options.editable === false;
6620
+ this.taskToggle = options.taskToggle === true;
5426
6621
  const given = options.extensions ?? [];
5427
6622
  this.extensions = given.some((e) => e.name === "defaultKeymap") ? given : [...given, defaultKeymap()];
5428
6623
  this.bindings = this.extensions.flatMap(
@@ -5441,6 +6636,14 @@ var Editor = class {
5441
6636
  };
5442
6637
  const views = new Map(this.extensions.flatMap((e) => Object.entries(e.views ?? {})));
5443
6638
  if (views.size > 0) this.renderer.views = views;
6639
+ this.renderer.onViewSettled = (ids) => this.viewsSettled(ids);
6640
+ const codeDecorators = this.extensions.flatMap((e) => e.codeDecorations ? [e.codeDecorations] : []);
6641
+ if (codeDecorators.length > 0) {
6642
+ this.renderer.decorateCode = (block3) => {
6643
+ const ctx = { block: block3, text: inlineText(block3.content), language: block3.language };
6644
+ return codeDecorators.flatMap((fn) => fn(ctx));
6645
+ };
6646
+ }
5444
6647
  const decorators = this.extensions.flatMap((e) => e.decorations ? [e.decorations] : []);
5445
6648
  if (decorators.length > 0) {
5446
6649
  this.renderer.decorate = (block3, content, cell) => {
@@ -5456,33 +6659,52 @@ var Editor = class {
5456
6659
  root.translate = false;
5457
6660
  root.style.setProperty("--mbe-slash-hint", JSON.stringify(this.labels.slashHint));
5458
6661
  this.applyRuntime({ placeholder: options.placeholder, attributes: options.attributes });
5459
- this.runtime = { ...this.runtime, resolveImageSrc: options.resolveImageSrc };
5460
- this.renderer.resolveImageSrc = options.resolveImageSrc;
6662
+ this.runtime = { ...this.runtime, resolveUrl: options.resolveUrl, onLinkClick: options.onLinkClick };
6663
+ this.renderer.resolveUrl = options.resolveUrl ?? defaultResolveUrl;
6664
+ this.renderer.referrerPolicy = options.referrerPolicy;
5461
6665
  this.applyTheme(options.theme);
6666
+ setPopupContainer(root, options.popupContainer);
5462
6667
  const configs = this.extensions.flatMap((e) => e.suggestion ? [e.suggestion] : []);
5463
6668
  if (options.slashMenu !== false) configs.push(this.slashSuggestion());
5464
- this.suggestions = configs.map((config) => ({
5465
- config,
5466
- menu: new Menu(root, `mbe-suggestion-menu ${config.className ?? ""}`.trim(), "listbox")
5467
- }));
6669
+ this.suggestions = new SuggestionController(
6670
+ {
6671
+ editor: this,
6672
+ root,
6673
+ syncActiveDescendant: () => this.syncActiveDescendant(),
6674
+ refresh: () => this.updateUi(),
6675
+ endComposition: () => this.endComposition(),
6676
+ changed: (state) => this.emit("suggestionChange", { editor: this, state })
6677
+ },
6678
+ configs
6679
+ );
6680
+ const suggestions = this.suggestions;
6681
+ this.suggestion = {
6682
+ get state() {
6683
+ return suggestions.state;
6684
+ },
6685
+ open: (name) => !this.destroyed && (this.refreshSelection(), suggestions.open(name)),
6686
+ close: () => suggestions.dismiss(),
6687
+ move: (delta2) => suggestions.move(delta2),
6688
+ accept: (index) => !this.destroyed && suggestions.accept(index)
6689
+ };
5468
6690
  this.blockMenu = new Menu(root, "mbe-block-menu", "menu");
5469
6691
  this.blockMenu.onPicked = () => this.blockMenu.hide();
5470
6692
  this.linkPopover = new LinkPopover(this);
5471
6693
  this.toolbar = options.toolbar === false ? null : new FormatToolbar(this);
5472
6694
  this.handle = new BlockHandle(this);
5473
- this.listen(root, "beforeinput", (e) => this.onBeforeInput(e));
5474
- this.listen(root, "input", (e) => this.onInput(e));
6695
+ this.listen(root, "beforeinput", this.typed((e) => this.onBeforeInput(e)));
6696
+ this.listen(root, "input", this.typed((e) => this.onInput(e)));
5475
6697
  this.listen(root, "compositionstart", (e) => this.onCompositionStart(e));
5476
- this.listen(root, "compositionend", (e) => this.onCompositionEnd(e));
5477
- this.listen(root, "keydown", (e) => this.onKeyDown(e));
6698
+ this.listen(root, "compositionend", this.typed((e) => this.onCompositionEnd(e)));
6699
+ this.listen(root, "keydown", this.typed((e) => this.onKeyDown(e)));
5478
6700
  this.listen(root, "copy", (e) => this.onCopy(e, false));
5479
- this.listen(root, "cut", (e) => this.onCopy(e, true));
5480
- this.listen(root, "paste", (e) => this.onPaste(e));
6701
+ this.listen(root, "cut", this.typed((e) => this.onCopy(e, true)));
6702
+ this.listen(root, "paste", this.typed((e) => this.onPaste(e)));
5481
6703
  this.listen(root, "dragstart", (e) => e.preventDefault());
5482
6704
  this.listen(root, "dragover", (e) => {
5483
6705
  if (!this.readOnly) e.preventDefault();
5484
6706
  });
5485
- this.listen(root, "drop", (e) => this.onDrop(e));
6707
+ this.listen(root, "drop", this.typed((e) => this.onDrop(e)));
5486
6708
  this.listen(root, "mousedown", (e) => this.onMouseDown(e));
5487
6709
  this.listen(root, "click", (e) => this.onClick(e));
5488
6710
  this.listen(root, "change", (e) => this.onControlChange(e));
@@ -5510,11 +6732,13 @@ var Editor = class {
5510
6732
  * undo history; with `history: 'keep'` the replacement is one undo step.
5511
6733
  */
5512
6734
  setMarkdown(markdown, options = {}) {
6735
+ if (this.destroyed) return;
5513
6736
  if (options.history === "keep") this.history.record(this.current, "other");
5514
6737
  else this.history.clear();
5515
6738
  const loaded = loadMarkdown(markdown, this.markdown);
5516
6739
  this.source = loaded.source;
5517
6740
  this.blockSel = null;
6741
+ this.suggestions.reset();
5518
6742
  const next = createState(loaded.doc);
5519
6743
  this.relocateWidgets(this.current.doc, next.doc, true);
5520
6744
  this.current = next;
@@ -5537,7 +6761,11 @@ var Editor = class {
5537
6761
  return this.composing;
5538
6762
  }
5539
6763
  get isEditable() {
5540
- return !this.readOnly;
6764
+ return !this.readOnly && !this.destroyed;
6765
+ }
6766
+ /** True after `destroy()`. The editor then ignores every call that would change it; `getMarkdown()` still returns its last Markdown. */
6767
+ get isDestroyed() {
6768
+ return this.destroyed;
5541
6769
  }
5542
6770
  /** True if `name` applies at the selection: a mark on the selected text, or the type of the block with the caret. */
5543
6771
  isActive(name, attrs) {
@@ -5588,6 +6816,7 @@ var Editor = class {
5588
6816
  * a value that is not a selection at all is ignored and returns false.
5589
6817
  */
5590
6818
  setSelection(selection) {
6819
+ if (this.destroyed) return false;
5591
6820
  const sel = isSelection(selection) ? clampSelection(this.current.doc, selection) : selectionFromJSON(this.current.doc, selection);
5592
6821
  if (!sel) return false;
5593
6822
  this.dropBlockSelection();
@@ -5620,6 +6849,13 @@ var Editor = class {
5620
6849
  * block is deleted, it moves to the nearest remaining block.
5621
6850
  */
5622
6851
  addWidget(options) {
6852
+ if (this.destroyed) {
6853
+ const widget2 = new WidgetImpl(this.root.ownerDocument.createElement("div"), "", () => {
6854
+ }, () => {
6855
+ });
6856
+ widget2.remove();
6857
+ return widget2;
6858
+ }
5623
6859
  const blocks = this.current.doc.blocks;
5624
6860
  const at = options.at === "end" ? endOf(blocks[blocks.length - 1]) : options.at;
5625
6861
  const blockId = clampSelection(this.current.doc, { anchor: at, focus: at }).focus.blockId;
@@ -5656,6 +6892,7 @@ var Editor = class {
5656
6892
  }
5657
6893
  /** Focuses the editor at the current selection. */
5658
6894
  focus() {
6895
+ if (this.destroyed) return;
5659
6896
  const pos = this.current.selection.focus;
5660
6897
  const el = this.renderer.elementFor(pos.blockId);
5661
6898
  const host = pos.cell && el ? contentElement(el, pos.cell) : this.root;
@@ -5667,13 +6904,24 @@ var Editor = class {
5667
6904
  }
5668
6905
  // -------------------------------------------------------------------------
5669
6906
  // Options and events
5670
- /** Changes `placeholder`, `editable`, `attributes`, `resolveImageSrc` or `theme`. */
6907
+ /**
6908
+ * Changes `placeholder`, `editable`, `taskToggle`, `attributes`,
6909
+ * `resolveUrl`, `onLinkClick` or `theme`. `extensions` only updates the callbacks of
6910
+ * `suggestion()` extensions (`items`, `command`, `match`, `allow`), matched
6911
+ * by name; other changes to extensions need a new editor.
6912
+ */
5671
6913
  setOptions(options) {
6914
+ if (this.destroyed) return;
6915
+ if (options.extensions) this.suggestions.setConfigs(options.extensions.flatMap((e) => e.suggestion ? [e.suggestion] : []));
6916
+ const toggle = options.taskToggle !== void 0 && options.taskToggle !== this.taskToggle;
6917
+ if (toggle) this.taskToggle = options.taskToggle === true;
5672
6918
  if (options.editable !== void 0 && options.editable === this.readOnly) {
5673
6919
  this.readOnly = !options.editable;
5674
6920
  this.refreshRevealed();
5675
6921
  this.applyReadOnly();
5676
6922
  this.hideUi();
6923
+ } else if (toggle) {
6924
+ this.applyReadOnly();
5677
6925
  }
5678
6926
  this.applyRuntime(options);
5679
6927
  }
@@ -5700,11 +6948,12 @@ var Editor = class {
5700
6948
  for (const [name, value] of Object.entries(options.attributes ?? {})) root.setAttribute(name, value);
5701
6949
  this.runtime = { ...this.runtime, attributes: options.attributes };
5702
6950
  }
5703
- if ("resolveImageSrc" in options && options.resolveImageSrc !== this.runtime.resolveImageSrc) {
5704
- this.runtime = { ...this.runtime, resolveImageSrc: options.resolveImageSrc };
5705
- this.renderer.resolveImageSrc = options.resolveImageSrc;
6951
+ if ("resolveUrl" in options && options.resolveUrl !== this.runtime.resolveUrl) {
6952
+ this.runtime = { ...this.runtime, resolveUrl: options.resolveUrl };
6953
+ this.renderer.resolveUrl = options.resolveUrl ?? defaultResolveUrl;
5706
6954
  this.paint(true);
5707
6955
  }
6956
+ if ("onLinkClick" in options) this.runtime = { ...this.runtime, onLinkClick: options.onLinkClick };
5708
6957
  if ("theme" in options && this.applyTheme(options.theme)) this.paint(true);
5709
6958
  }
5710
6959
  /** Sets the theme. Returns true when blocks must re-render for new classes. */
@@ -5728,9 +6977,11 @@ var Editor = class {
5728
6977
  // Commands
5729
6978
  /** Applies a command (a pure function of the state), records history, re-renders, and emits events. */
5730
6979
  run(command, kind = "other") {
5731
- if (this.readOnly) return false;
6980
+ if (this.readOnly || this.destroyed) return false;
5732
6981
  let next = command(this.current);
5733
6982
  if (!next || next === this.current) return false;
6983
+ next = dropBrokenTokens(next, this.current, this.markdown.inline);
6984
+ next = clampListIndents(next, this.current);
5734
6985
  if (next.doc !== this.current.doc && sameBlocks(next.doc, this.current.doc)) next = { ...next, doc: this.current.doc };
5735
6986
  if (next.doc === this.current.doc && next.selection === this.current.selection && next.storedMarks === this.current.storedMarks) {
5736
6987
  return false;
@@ -5741,7 +6992,7 @@ var Editor = class {
5741
6992
  createCommands() {
5742
6993
  const run = (fn) => this.run(fn);
5743
6994
  const block3 = (spec) => run((s) => toggleBlockType(s, spec));
5744
- return {
6995
+ const commands = {
5745
6996
  toggleBold: () => run((s) => toggleMark(s, "bold")),
5746
6997
  toggleItalic: () => run((s) => toggleMark(s, "italic")),
5747
6998
  toggleStrike: () => run((s) => toggleMark(s, "strike")),
@@ -5802,8 +7053,19 @@ var Editor = class {
5802
7053
  const had = this.hasFocus();
5803
7054
  this.blur();
5804
7055
  return had;
7056
+ },
7057
+ scrollIntoView: () => {
7058
+ const rect = this.caretRect();
7059
+ if (!rect) return false;
7060
+ scrollRectIntoView(this.root, rect);
7061
+ return true;
5805
7062
  }
5806
7063
  };
7064
+ for (const name of Object.keys(commands)) {
7065
+ const fn = commands[name];
7066
+ commands[name] = (...args) => !this.destroyed && fn(...args);
7067
+ }
7068
+ return commands;
5807
7069
  }
5808
7070
  toggleMark(mark) {
5809
7071
  return this.run((s) => toggleMark(s, mark));
@@ -5836,21 +7098,56 @@ var Editor = class {
5836
7098
  const content = el ? contentElement(el, this.current.selection.focus.cell) : null;
5837
7099
  return (content ?? el)?.getBoundingClientRect() ?? null;
5838
7100
  }
7101
+ /** @internal The caret at the model's selection focus. Unlike `selectionRect`, works while the editor is not focused. */
7102
+ caretRect() {
7103
+ const pos = this.current.selection.focus;
7104
+ const point = this.toDom(pos);
7105
+ if (point) {
7106
+ const range = this.root.ownerDocument.createRange();
7107
+ range.setStart(point.node, point.offset);
7108
+ const rects = range.getClientRects();
7109
+ const rect = rects[rects.length - 1];
7110
+ if (rect && rect.height > 0) return rect;
7111
+ }
7112
+ const el = this.renderer.elementFor(pos.blockId);
7113
+ return ((el && contentElement(el, pos.cell)) ?? el)?.getBoundingClientRect() ?? null;
7114
+ }
7115
+ /** @internal The viewport rectangle of the text from `from` to `to` in one block or cell (its first line), and whether that text is right-to-left. */
7116
+ textRect(from, to) {
7117
+ const start = this.toDom(from);
7118
+ const end = this.toDom(to);
7119
+ if (!start || !end) return null;
7120
+ const range = this.root.ownerDocument.createRange();
7121
+ range.setStart(start.node, start.offset);
7122
+ range.setEnd(end.node, end.offset);
7123
+ const rect = range.getClientRects()[0];
7124
+ if (!rect) return null;
7125
+ const el = start.node.nodeType === 1 ? start.node : start.node.parentElement;
7126
+ const rtl = !!el && this.root.ownerDocument.defaultView.getComputedStyle(el).direction === "rtl";
7127
+ return { rect, rtl };
7128
+ }
7129
+ /** Scrolls the editor and the elements around it so the caret is visible. */
7130
+ scrollCaretIntoView() {
7131
+ const rect = this.caretRect();
7132
+ if (rect) scrollRectIntoView(this.root, rect);
7133
+ }
5839
7134
  /** @internal The rendered element of a block. */
5840
7135
  blockElement(id) {
5841
7136
  return this.renderer.elementFor(id);
5842
7137
  }
5843
7138
  destroy() {
7139
+ if (this.destroyed) return;
5844
7140
  this.destroyed = true;
5845
7141
  if (this.changeFrame !== null) cancelAnimationFrame(this.changeFrame);
5846
7142
  if (this.settleFrame !== null) cancelAnimationFrame(this.settleFrame);
5847
7143
  for (const fn of this.cleanup) fn();
5848
- for (const { menu } of this.suggestions) menu.destroy();
7144
+ this.suggestions.destroy();
5849
7145
  for (const widget of [...this.widgets]) widget.remove();
5850
7146
  this.blockMenu.destroy();
5851
7147
  this.toolbar?.destroy();
5852
7148
  this.linkPopover.destroy();
5853
7149
  this.handle.destroy();
7150
+ setPopupContainer(this.root, void 0);
5854
7151
  for (const name of Object.keys(this.runtime.attributes ?? {})) this.root.removeAttribute(name);
5855
7152
  for (const name of this.tokenNames) this.root.style.removeProperty(name);
5856
7153
  this.root.style.colorScheme = "";
@@ -5867,6 +7164,7 @@ var Editor = class {
5867
7164
  }
5868
7165
  commit(next) {
5869
7166
  const docChanged = next.doc !== this.state.doc;
7167
+ const moved = next.selection !== this.state.selection;
5870
7168
  const hadFocus = this.hasFocus();
5871
7169
  if (docChanged) this.relocateWidgets(this.current.doc, next.doc, false);
5872
7170
  this.current = next;
@@ -5877,6 +7175,7 @@ var Editor = class {
5877
7175
  }
5878
7176
  this.paint(false, false, hadFocus);
5879
7177
  this.afterRender();
7178
+ if (moved && hadFocus && this.typing > 0) this.scrollCaretIntoView();
5880
7179
  if (docChanged) this.scheduleChange();
5881
7180
  this.emit("selectionChange", { editor: this });
5882
7181
  }
@@ -5906,6 +7205,7 @@ var Editor = class {
5906
7205
  * this). Returns false, doing nothing, when no one listens for submit.
5907
7206
  */
5908
7207
  submit() {
7208
+ if (this.destroyed) return false;
5909
7209
  if (!this.options.onSubmit && !this.listeners.get("submit")?.size) return false;
5910
7210
  this.flushChange();
5911
7211
  this.options.onSubmit?.(this.getMarkdown(), this);
@@ -5922,15 +7222,37 @@ var Editor = class {
5922
7222
  if (this.root.contentEditable !== editable) this.root.contentEditable = editable;
5923
7223
  if (!this.readOnly && !this.wasReadOnly) return;
5924
7224
  this.wasReadOnly = this.readOnly;
7225
+ const ticking = this.ticking;
5925
7226
  this.root.classList.toggle("mbe-readonly", this.readOnly);
7227
+ this.root.classList.toggle("mbe-tasks", ticking);
5926
7228
  this.root.setAttribute("aria-readonly", String(this.readOnly));
5927
7229
  this.root.querySelectorAll("[data-row]").forEach((cell) => {
5928
7230
  cell.contentEditable = this.readOnly ? "false" : "true";
5929
7231
  });
5930
7232
  this.root.querySelectorAll("input").forEach((input) => {
5931
- input.disabled = this.readOnly;
7233
+ const box = input.classList.contains("mbe-checkbox");
7234
+ input.disabled = this.readOnly && !(box && ticking);
7235
+ if (!box) return;
7236
+ input.tabIndex = ticking ? 0 : -1;
7237
+ if (ticking) input.setAttribute("aria-label", taskName(input, this.labels.task));
7238
+ else input.removeAttribute("aria-label");
5932
7239
  });
5933
7240
  }
7241
+ /** True while read-only with task toggling on: only task checkboxes respond. */
7242
+ get ticking() {
7243
+ return this.readOnly && this.taskToggle;
7244
+ }
7245
+ /** Toggles a task item from its checkbox, while editing or while read-only with `taskToggle`. */
7246
+ toggleTaskAt(box) {
7247
+ const blockEl = box.closest("[data-block-id]");
7248
+ if (!blockEl) return;
7249
+ const id = blockEl.dataset.blockId;
7250
+ const focused = box === this.root.ownerDocument.activeElement;
7251
+ if (!this.readOnly) this.run((s) => toggleTask(s, id));
7252
+ else if (this.ticking && this.current.doc.blocks.some((b) => b.id === id)) this.apply(toggleTask(this.current, id), "other");
7253
+ else return;
7254
+ if (focused) this.root.querySelector(`[data-block-id="${id}"] .mbe-checkbox`)?.focus({ preventScroll: true });
7255
+ }
5934
7256
  /** Hints for empty blocks, and the UI that follows the selection. */
5935
7257
  afterRender() {
5936
7258
  for (const block3 of this.state.doc.blocks) {
@@ -5983,6 +7305,8 @@ var Editor = class {
5983
7305
  if (!this.hasFocus()) this.updateUi();
5984
7306
  return;
5985
7307
  }
7308
+ const key = this.caretKey;
7309
+ this.caretKey = null;
5986
7310
  if (this.blockSel) {
5987
7311
  this.updateUi();
5988
7312
  return;
@@ -5992,11 +7316,52 @@ var Editor = class {
5992
7316
  this.updateUi();
5993
7317
  return;
5994
7318
  }
5995
- this.current = { ...this.state, selection, storedMarks: null };
5996
- this.history.breakGroup();
5997
- if (!this.pointerDown) this.refreshRevealed();
5998
- this.updateUi();
5999
- this.emit("selectionChange", { editor: this });
7319
+ const skipped = key?.vertical ? this.skippedBlock(key.from, key.vertical, key.x, selection.focus) : null;
7320
+ if (skipped) {
7321
+ this.setSelection({ anchor: skipped, focus: skipped });
7322
+ } else {
7323
+ this.current = { ...this.state, selection, storedMarks: null };
7324
+ this.history.breakGroup();
7325
+ if (!this.pointerDown) this.refreshRevealed();
7326
+ this.updateUi();
7327
+ this.emit("selectionChange", { editor: this });
7328
+ }
7329
+ if (key) this.scrollCaretIntoView();
7330
+ }
7331
+ /**
7332
+ * After the browser moved the caret from block `from` with ArrowDown
7333
+ * (`dir` 1) or ArrowUp to `to`: the position in the first block it passed
7334
+ * over that holds a caret, at `x`. Firefox passes over list items (they are
7335
+ * flex boxes), WebKit over code blocks and tables. Null when no block was
7336
+ * passed over.
7337
+ */
7338
+ skippedBlock(from, dir, x, to) {
7339
+ const blocks = this.state.doc.blocks;
7340
+ const end = blockIndex(this.state.doc, to.blockId);
7341
+ for (let i = from + dir; (end - i) * dir > 0; i += dir) {
7342
+ const block3 = blocks[i];
7343
+ if (block3.type !== "divider") return this.blockEntry(block3, dir === 1, x);
7344
+ }
7345
+ return null;
7346
+ }
7347
+ /** Where the caret goes moving into `block` from above (`forward`) or below: its first or last line, at `x`. */
7348
+ blockEntry(block3, forward, x) {
7349
+ const el = this.renderer.elementFor(block3.id);
7350
+ const viewed = this.viewBlock(block3);
7351
+ if (viewed) return viewEntry(viewed, forward);
7352
+ if (el) {
7353
+ const range = el.ownerDocument.createRange();
7354
+ range.selectNodeContents(contentElement(el) ?? el);
7355
+ const lines = Array.from(range.getClientRects()).filter((r) => r.height > 0);
7356
+ const line = forward ? lines[0] : lines[lines.length - 1];
7357
+ const pos = line ? this.positionAtPoint(x, line.top + line.height / 2) : null;
7358
+ if (pos?.blockId === block3.id) return pos;
7359
+ }
7360
+ if (block3.type === "table") {
7361
+ const row = forward ? 0 : block3.rows.length - 1;
7362
+ return { blockId: block3.id, offset: forward ? 0 : inlineLength(block3.rows[row][0]), cell: { row, col: 0 } };
7363
+ }
7364
+ return forward ? startOf(block3) : endOf(block3);
6000
7365
  }
6001
7366
  /**
6002
7367
  * Renders the document, then puts the browser selection back. Only blocks
@@ -6008,10 +7373,70 @@ var Editor = class {
6008
7373
  const views = this.renderer.views;
6009
7374
  if (views && !this.pointerDown && !this.composing) this.renderer.revealed = revealedViews(this.state, views, !this.readOnly && hadFocus);
6010
7375
  this.renderer.render(this.state.doc, force, lazy);
7376
+ this.applyHeadingIds();
6011
7377
  this.applyReadOnly();
6012
7378
  this.paintBlockSelection();
6013
7379
  if (!this.composing) this.syncDomSelection(hadFocus);
6014
7380
  }
7381
+ /** Heading ids from the `headingIds` option, computed again only when the document changes. */
7382
+ applyHeadingIds() {
7383
+ const headingIds = this.options.headingIds;
7384
+ if (!headingIds) return;
7385
+ const doc = this.state.doc;
7386
+ if (this.headingIdsFor?.doc !== doc) {
7387
+ const headings = doc.blocks.filter((b) => b.type === "heading");
7388
+ const ids = headingIds(headings.map((h) => ({ text: inlineText(h.content), level: h.level })));
7389
+ this.headingIdsFor = { doc, ids: new Map(headings.map((h, i) => [h.id, ids[i]])) };
7390
+ }
7391
+ for (const [blockId, id] of this.headingIdsFor.ids) {
7392
+ const el = this.renderer.elementFor(blockId);
7393
+ if (!el) continue;
7394
+ if (id) {
7395
+ if (el.id !== id) el.id = id;
7396
+ } else if (el.id) {
7397
+ el.removeAttribute("id");
7398
+ }
7399
+ }
7400
+ }
7401
+ /**
7402
+ * Computes decorations again for every block and renders the blocks whose
7403
+ * decorations depend on something outside the document changed, such as
7404
+ * which mentioned people exist or a highlighter's language that finished
7405
+ * loading. Waits for an input method to finish composing.
7406
+ */
7407
+ redecorate() {
7408
+ if (this.destroyed) return;
7409
+ if (this.composing || this.composition) {
7410
+ this.redecoratePending = true;
7411
+ return;
7412
+ }
7413
+ this.redecoratePending = false;
7414
+ this.paint(true);
7415
+ this.afterRender();
7416
+ }
7417
+ /**
7418
+ * Views that returned a promise settled: their blocks render again on the
7419
+ * next frame, or when a composition settles, since rendering would end it.
7420
+ */
7421
+ viewsSettled(ids) {
7422
+ if (this.destroyed) return;
7423
+ if (this.composing || this.composition) {
7424
+ for (const id of ids) this.unsettled.add(id);
7425
+ return;
7426
+ }
7427
+ for (const id of ids) this.renderer.invalidate(id);
7428
+ this.viewFrame ||= requestAnimationFrame(() => {
7429
+ this.viewFrame = 0;
7430
+ if (this.destroyed || this.composing || this.composition) return;
7431
+ this.paint();
7432
+ this.afterRender();
7433
+ });
7434
+ }
7435
+ /** A block rendered by a view (a formula block, a diagram), or null. */
7436
+ viewBlock(block3) {
7437
+ if (!block3 || block3.type !== "raw" && block3.type !== "code") return null;
7438
+ return this.renderer.elementFor(block3.id)?.classList.contains("mbe-view-block") ? block3 : null;
7439
+ }
6015
7440
  /** Re-renders if the views that show their source changed: after the selection, focus or editability changes. */
6016
7441
  refreshRevealed() {
6017
7442
  const views = this.renderer.views;
@@ -6026,10 +7451,12 @@ var Editor = class {
6026
7451
  }
6027
7452
  /**
6028
7453
  * When an arrow key at the edge of a block would move past a rendered raw
6029
- * block next to it (the browser skips non-editable blocks), the position in
6030
- * that block's source to move to instead.
7454
+ * block or a table next to it, the position inside that block to move to
7455
+ * instead: the browser skips non-editable blocks, and sometimes a table
7456
+ * (its cells are separate editing hosts). A table is entered in its first
7457
+ * column.
6031
7458
  */
6032
- viewBlockPast(key) {
7459
+ blockPast(key) {
6033
7460
  const sel = this.state.selection;
6034
7461
  if (!isCollapsed(sel) || sel.focus.cell) return null;
6035
7462
  const pos = sel.focus;
@@ -6037,22 +7464,78 @@ var Editor = class {
6037
7464
  const index = blockIndex(this.state.doc, pos.blockId);
6038
7465
  const forward = key === "ArrowDown" || key === "ArrowRight";
6039
7466
  const next = blocks[index + (forward ? 1 : -1)];
6040
- if (next?.type !== "raw" || !this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block")) return null;
7467
+ const view = this.viewBlock(next);
7468
+ if (!next || !view && next.type !== "table") return null;
6041
7469
  const current = blocks[index];
6042
7470
  if (!isTextBlock(current)) return null;
6043
7471
  if (key === "ArrowRight" && pos.offset !== endOf(current).offset) return null;
6044
7472
  if (key === "ArrowLeft" && pos.offset !== 0) return null;
6045
7473
  if (key === "ArrowDown" || key === "ArrowUp") {
6046
- const caret2 = this.selectionRect();
6047
- const box = contentElement(this.renderer.elementFor(current.id))?.getBoundingClientRect();
6048
- if (caret2 && box && caret2.height > 0 && (forward ? box.bottom - caret2.bottom : caret2.top - box.top) > caret2.height / 2) return null;
7474
+ const content = contentElement(this.renderer.elementFor(current.id));
7475
+ if (content && !this.onEdgeLine(content, forward)) return null;
7476
+ }
7477
+ if (next.type === "table") {
7478
+ const row = forward ? 0 : next.rows.length - 1;
7479
+ return { blockId: next.id, offset: forward ? 0 : inlineLength(next.rows[row][0]), cell: { row, col: 0 } };
6049
7480
  }
6050
- return viewEntry(next, forward);
7481
+ return viewEntry(view, forward);
7482
+ }
7483
+ /**
7484
+ * ArrowUp or ArrowDown on the first or last line of a table cell: the
7485
+ * position in the cell above or below (same column), or past the table in
7486
+ * the next block that holds a caret. Null when the caret is not on that
7487
+ * line, or when the table ends the document that way (`exitBlock` adds a
7488
+ * paragraph there).
7489
+ */
7490
+ tableCellPast(dir) {
7491
+ const sel = this.state.selection;
7492
+ const pos = sel.focus;
7493
+ if (!isCollapsed(sel) || !pos.cell) return null;
7494
+ const blocks = this.state.doc.blocks;
7495
+ const index = blockIndex(this.state.doc, pos.blockId);
7496
+ const table2 = blocks[index];
7497
+ if (table2?.type !== "table") return null;
7498
+ const content = contentElement(this.renderer.elementFor(table2.id), pos.cell);
7499
+ if (content && !this.onEdgeLine(content, dir === 1)) return null;
7500
+ const { row, col } = pos.cell;
7501
+ const target = table2.rows[row + dir];
7502
+ if (target) {
7503
+ const offset = Math.min(pos.offset, inlineLength(target[col]));
7504
+ return { blockId: table2.id, offset, cell: { row: row + dir, col } };
7505
+ }
7506
+ for (let i = index + dir; i >= 0 && i < blocks.length; i += dir) {
7507
+ const next = blocks[i];
7508
+ if (next.type === "divider") continue;
7509
+ if (next.type === "table") {
7510
+ const r = dir === 1 ? 0 : next.rows.length - 1;
7511
+ const c = Math.min(col, next.align.length - 1);
7512
+ return { blockId: next.id, offset: dir === 1 ? 0 : inlineLength(next.rows[r][c]), cell: { row: r, col: c } };
7513
+ }
7514
+ const viewed = this.viewBlock(next);
7515
+ if (viewed) return viewEntry(viewed, dir === 1);
7516
+ return dir === 1 ? startOf(next) : endOf(next);
7517
+ }
7518
+ return null;
7519
+ }
7520
+ /**
7521
+ * Whether the caret is on the last (`forward`) or first line of the text in
7522
+ * `content`. Lines are measured from the text, not the element's box, which
7523
+ * has padding (a table cell) and may be taller than its text.
7524
+ */
7525
+ onEdgeLine(content, forward) {
7526
+ const caret2 = this.selectionRect();
7527
+ if (!caret2 || caret2.height === 0) return true;
7528
+ const range = content.ownerDocument.createRange();
7529
+ range.selectNodeContents(content);
7530
+ const lines = Array.from(range.getClientRects()).filter((r) => r.height > 0);
7531
+ if (lines.length === 0) return true;
7532
+ const half = caret2.height / 2;
7533
+ return forward ? Math.max(...lines.map((r) => r.bottom)) - caret2.bottom <= half : caret2.top - Math.min(...lines.map((r) => r.top)) <= half;
6051
7534
  }
6052
7535
  /** A click on a rendered view puts the caret in its source: at the end of a token, or of a block's formula. */
6053
7536
  revealView(view) {
6054
7537
  const block3 = view.hasAttribute(BLOCK_ATTR) ? getBlock(this.state.doc, view.getAttribute(BLOCK_ATTR)) : null;
6055
- const pos = block3 ? block3.type === "raw" ? viewEntry(block3, false) : null : domToPosition(this.root, view.parentNode, childIndex(view) + 1);
7538
+ const pos = block3 ? block3.type === "raw" || block3.type === "code" ? viewEntry(block3, false) : null : domToPosition(this.root, view.parentNode, childIndex(view) + 1);
6056
7539
  if (!pos) return;
6057
7540
  this.root.focus({ preventScroll: true });
6058
7541
  this.setSelection({ anchor: pos, focus: pos });
@@ -6108,11 +7591,7 @@ var Editor = class {
6108
7591
  return;
6109
7592
  }
6110
7593
  case "insertParagraph": {
6111
- const menu = this.openMenu();
6112
- if (menu && menu !== this.blockMenu && menu.count > 0) {
6113
- menu.pick();
6114
- return;
6115
- }
7594
+ if (this.suggestions.isOpen && this.suggestions.accept()) return;
6116
7595
  this.run(splitBlock);
6117
7596
  return;
6118
7597
  }
@@ -6185,7 +7664,7 @@ var Editor = class {
6185
7664
  if (text.length === 1 && "*_`~".includes(text)) this.run((s) => applyInlineInputRules(s));
6186
7665
  if (this.markdown.inline.length > 0) this.run((s) => applyTokenInputRules(s, this.markdown.inline) ?? s);
6187
7666
  if (text === " " && this.markdown.autolinks) this.run((s) => applyAutolinkInputRule(s) ?? s);
6188
- if ([...text].length === 1) this.maybeOpenSuggestion(text);
7667
+ if (!text.includes("\n")) this.typedForSuggestion();
6189
7668
  }
6190
7669
  onCompositionStart(e) {
6191
7670
  if (this.fromControl(e)) return;
@@ -6205,6 +7684,7 @@ var Editor = class {
6205
7684
  }
6206
7685
  this.syncComposition();
6207
7686
  this.composing = false;
7687
+ if (isSafari) this.compositionEndedAt = Date.now();
6208
7688
  this.unsettled.add(this.composition.blockId);
6209
7689
  if (this.settleFrame === null) {
6210
7690
  const settle = () => {
@@ -6221,19 +7701,17 @@ var Editor = class {
6221
7701
  this.composition = null;
6222
7702
  for (const id of this.unsettled) this.renderer.invalidate(id);
6223
7703
  this.unsettled.clear();
6224
- this.paint();
7704
+ this.paint(this.redecoratePending);
7705
+ this.redecoratePending = false;
6225
7706
  this.afterRender();
6226
- if (!composed) return;
6227
- const pos = this.state.selection.focus;
6228
- if (!isCollapsed(this.state.selection) || !this.state.doc.blocks.some((b) => b.id === pos.blockId)) return;
6229
- const content = containerContent(getBlock(this.state.doc, pos.blockId), pos.cell);
6230
- const ch = content ? inlineText(content)[pos.offset - 1] : void 0;
6231
- if (ch) this.maybeOpenSuggestion(ch);
7707
+ if (composed) this.typedForSuggestion();
6232
7708
  }
6233
7709
  onInput(e) {
6234
7710
  if (this.fromControl(e)) return;
6235
7711
  if (this.composing || this.composition && COMPOSITION_INPUT.has(e.inputType)) {
7712
+ const before2 = this.composedLength();
6236
7713
  this.syncComposition();
7714
+ if (this.composing && this.composedLength() > before2) this.typedForSuggestion();
6237
7715
  return;
6238
7716
  }
6239
7717
  if (e.isComposing) return;
@@ -6241,6 +7719,27 @@ var Editor = class {
6241
7719
  this.reconcileFromDom("typing");
6242
7720
  if (e.inputType === "insertText" && e.data && this.state !== before) this.afterTyping(e.data);
6243
7721
  }
7722
+ /** The length of the composed block's or cell's text. */
7723
+ composedLength() {
7724
+ const pos = this.state.selection.focus;
7725
+ const block3 = this.state.doc.blocks.find((b) => b.id === this.composition?.blockId);
7726
+ const content = block3 && containerContent(block3, block3.id === pos.blockId ? pos.cell : void 0);
7727
+ return content ? inlineLength(content) : 0;
7728
+ }
7729
+ /**
7730
+ * Ends the composition on purpose: reads the composed text into the model
7731
+ * and renders the block from it, which ends the browser's composition.
7732
+ * Picking a suggestion item while composing does this first.
7733
+ */
7734
+ endComposition() {
7735
+ if (!this.composing || !this.composition) return;
7736
+ this.syncComposition();
7737
+ this.composing = false;
7738
+ this.unsettled.add(this.composition.blockId);
7739
+ if (this.settleFrame !== null) cancelAnimationFrame(this.settleFrame);
7740
+ this.settleFrame = null;
7741
+ this.settleComposition();
7742
+ }
6244
7743
  /**
6245
7744
  * Reads the composed text into the model while composing. The browser's
6246
7745
  * DOM for the block already shows it, so the block is not re-rendered.
@@ -6288,8 +7787,8 @@ var Editor = class {
6288
7787
  if (blockId !== void 0 && block3.id !== blockId) continue;
6289
7788
  const el = this.renderer.elementFor(block3.id);
6290
7789
  if (!el || !el.isConnected) continue;
6291
- const containers = block3.type === "table" ? block3.rows.flatMap((row, r) => row.map((_, c) => ({ cell: { row: r, col: c } }))) : block3.type === "divider" ? [] : [{}];
6292
- for (const { cell } of containers) {
7790
+ const containers2 = block3.type === "table" ? block3.rows.flatMap((row, r) => row.map((_, c) => ({ cell: { row: r, col: c } }))) : block3.type === "divider" ? [] : [{}];
7791
+ for (const { cell } of containers2) {
6293
7792
  const contentEl = contentElement(el, cell);
6294
7793
  const content = containerContent(getBlock(state.doc, block3.id), cell);
6295
7794
  if (!contentEl || !content) continue;
@@ -6314,6 +7813,7 @@ var Editor = class {
6314
7813
  return changed ? state : null;
6315
7814
  }
6316
7815
  onKeyDown(e) {
7816
+ this.caretKey = null;
6317
7817
  if (this.fromControl(e)) return;
6318
7818
  if (e.isComposing || e.keyCode === 229) return;
6319
7819
  const mod2 = isMac ? e.metaKey : e.ctrlKey;
@@ -6323,17 +7823,28 @@ var Editor = class {
6323
7823
  this.refreshSelection();
6324
7824
  fn();
6325
7825
  };
6326
- const menu = this.openMenu();
7826
+ const justComposed = Date.now() - this.compositionEndedAt < 100;
7827
+ this.compositionEndedAt = 0;
7828
+ if (this.suggestions.isOpen && !justComposed) {
7829
+ this.refreshSelection();
7830
+ if (this.suggestions.keydown(e)) {
7831
+ e.preventDefault();
7832
+ return;
7833
+ }
7834
+ }
7835
+ const menu = this.blockMenu.isOpen ? this.blockMenu : null;
6327
7836
  if (menu) {
6328
7837
  if (e.key === "ArrowDown" || e.key === "Tab" && !e.shiftKey) return handled(() => this.moveMenu(menu, 1));
6329
7838
  if (e.key === "ArrowUp" || e.key === "Tab" && e.shiftKey) return handled(() => this.moveMenu(menu, -1));
6330
- if (e.key === "Enter") {
6331
- if (menu.count > 0) return handled(() => menu.pick());
6332
- if (menu !== this.blockMenu) this.closeSuggestion();
6333
- }
6334
- if (e.key === "Escape") return handled(() => menu !== this.blockMenu ? this.closeSuggestion() : this.closeBlockMenu());
7839
+ if (e.key === "Enter" && menu.count > 0) return handled(() => menu.pick());
7840
+ if (e.key === "Escape") return handled(() => this.closeBlockMenu());
7841
+ }
7842
+ if (e.key === "Escape" && this.toolbar?.isOpen) {
7843
+ return handled(() => {
7844
+ this.toolbarClosedFor = this.state.selection;
7845
+ this.toolbar.hide();
7846
+ });
6335
7847
  }
6336
- if (e.key === "Escape" && this.toolbar?.isOpen) return handled(() => this.toolbar.hide());
6337
7848
  if (this.readOnly) return;
6338
7849
  if (this.blockSel && this.onBlockKey(e)) {
6339
7850
  e.preventDefault();
@@ -6349,6 +7860,15 @@ var Editor = class {
6349
7860
  return;
6350
7861
  }
6351
7862
  }
7863
+ if (e.key === "Backspace" && !e.ctrlKey && !e.metaKey && !e.altKey) {
7864
+ this.refreshSelection();
7865
+ const { selection } = this.state;
7866
+ if (isCollapsed(selection) && selection.focus.offset === 0) {
7867
+ e.preventDefault();
7868
+ this.run(deleteBackward);
7869
+ return;
7870
+ }
7871
+ }
6352
7872
  if (mod2 && !e.altKey) {
6353
7873
  if (e.key === "/" && !e.shiftKey && this.hasBlockMenu(this.state.selection.focus.blockId)) {
6354
7874
  return handled(() => this.openBlockMenu(this.state.selection.focus.blockId));
@@ -6360,25 +7880,83 @@ var Editor = class {
6360
7880
  }
6361
7881
  if (e.key.startsWith("Arrow") && !mod2 && !e.shiftKey && !e.altKey) {
6362
7882
  this.refreshSelection();
6363
- const into = this.renderer.views ? this.viewBlockPast(e.key) : null;
7883
+ const into = this.blockPast(e.key);
6364
7884
  if (into) {
6365
7885
  e.preventDefault();
6366
7886
  this.setSelection({ anchor: into, focus: into });
6367
7887
  return;
6368
7888
  }
6369
7889
  const vertical = e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
7890
+ const cell = vertical ? this.tableCellPast(vertical) : null;
7891
+ if (cell) {
7892
+ e.preventDefault();
7893
+ this.setSelection({ anchor: cell, focus: cell });
7894
+ return;
7895
+ }
6370
7896
  const next = vertical ? exitBlock(this.state, vertical) : this.state;
6371
7897
  if (next !== this.state) {
6372
7898
  e.preventDefault();
6373
7899
  this.run(() => next);
7900
+ return;
6374
7901
  }
6375
7902
  }
7903
+ if (CARET_KEY.test(e.key)) {
7904
+ this.refreshSelection();
7905
+ const plain2 = !mod2 && !e.shiftKey && !e.altKey;
7906
+ const vertical = !plain2 ? 0 : e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
7907
+ const from = blockIndex(this.state.doc, this.state.selection.focus.blockId);
7908
+ const key2 = { from, x: this.selectionRect()?.left ?? 0, vertical };
7909
+ this.caretKey = key2;
7910
+ if (vertical) this.unlessCaretMoves(key2);
7911
+ }
7912
+ }
7913
+ /**
7914
+ * WebKit skips code blocks and tables with ArrowDown and ArrowUp. When no
7915
+ * editable text follows them (a rendered footnote or formula is not), it
7916
+ * does not move the caret at all. If the browser left the caret on the edge
7917
+ * line of its block, move it into the next block that holds a caret.
7918
+ */
7919
+ unlessCaretMoves(key) {
7920
+ const before = this.state.selection.focus;
7921
+ if (before.cell || !isCollapsed(this.state.selection)) return;
7922
+ const content = contentElement(this.renderer.elementFor(before.blockId) ?? this.root);
7923
+ if (!content || !this.onEdgeLine(content, key.vertical === 1)) return;
7924
+ setTimeout(() => {
7925
+ if (this.destroyed || this.caretKey !== key) return;
7926
+ const now = this.readDomSelection();
7927
+ if (!now || !samePosition(now.focus, before)) return;
7928
+ const blocks = this.state.doc.blocks;
7929
+ for (let i = key.from + key.vertical; i >= 0 && i < blocks.length; i += key.vertical) {
7930
+ const block3 = blocks[i];
7931
+ if (block3.type === "divider") continue;
7932
+ this.caretKey = null;
7933
+ const row = key.vertical === 1 ? 0 : block3.type === "table" ? block3.rows.length - 1 : 0;
7934
+ const pos = block3.type === "table" ? { blockId: block3.id, offset: key.vertical === 1 ? 0 : inlineLength(block3.rows[row][0]), cell: { row, col: 0 } } : this.blockEntry(block3, key.vertical === 1, key.x);
7935
+ this.setSelection({ anchor: pos, focus: pos });
7936
+ this.scrollCaretIntoView();
7937
+ return;
7938
+ }
7939
+ });
7940
+ }
7941
+ /** Selects all the text of the block (or table cell) holding `target`. False if it holds none. */
7942
+ selectBlockText(target) {
7943
+ const blockEl = target.closest?.(`[${BLOCK_ATTR}]`);
7944
+ if (!blockEl || !this.root.contains(blockEl)) return false;
7945
+ const block3 = getBlock(this.state.doc, blockEl.getAttribute(BLOCK_ATTR));
7946
+ const cellEl = target.closest("[data-row]");
7947
+ const cell = block3.type === "table" && cellEl ? { row: Number(cellEl.dataset.row), col: Number(cellEl.dataset.col) } : void 0;
7948
+ const content = containerContent(block3, cell);
7949
+ if (!content || blockEl.classList.contains("mbe-view-block")) return false;
7950
+ const at = (offset) => cell ? { blockId: block3.id, offset, cell } : { blockId: block3.id, offset };
7951
+ this.setSelection({ anchor: at(0), focus: at(inlineLength(content)) });
7952
+ return true;
6376
7953
  }
6377
- moveMenu(menu, delta) {
6378
- menu.move(delta);
7954
+ moveMenu(menu, delta2) {
7955
+ menu.move(delta2);
6379
7956
  this.syncActiveDescendant();
6380
7957
  }
6381
7958
  onMouseDown(e) {
7959
+ this.caretKey = null;
6382
7960
  const target = e.target;
6383
7961
  this.dropBlockSelection();
6384
7962
  if (target === this.root && e.button === 0 && !this.readOnly && this.clickBelowLastBlock(e)) return;
@@ -6388,11 +7966,14 @@ var Editor = class {
6388
7966
  this.revealView(view);
6389
7967
  return;
6390
7968
  }
7969
+ if (e.button === 0 && e.detail === 3 && !this.readOnly && this.selectBlockText(target)) {
7970
+ e.preventDefault();
7971
+ return;
7972
+ }
6391
7973
  if (e.button === 0) this.pointerDown = true;
6392
7974
  if (target.classList?.contains("mbe-checkbox")) {
6393
7975
  e.preventDefault();
6394
- const blockEl = target.closest("[data-block-id]");
6395
- if (blockEl && !this.readOnly) this.run((s) => toggleTask(s, blockEl.dataset.blockId));
7976
+ if (e.button === 0) this.toggleTaskAt(target);
6396
7977
  }
6397
7978
  }
6398
7979
  /**
@@ -6416,14 +7997,16 @@ var Editor = class {
6416
7997
  const target = e.target;
6417
7998
  if (target.classList?.contains("mbe-checkbox")) {
6418
7999
  e.preventDefault();
8000
+ if (e.detail === 0) this.toggleTaskAt(target);
6419
8001
  return;
6420
8002
  }
6421
8003
  const link = target.closest?.("a.mbe-link");
6422
8004
  if (!link) return;
6423
8005
  e.preventDefault();
6424
8006
  if (this.readOnly || (isMac ? e.metaKey : e.ctrlKey)) {
6425
- const href = safeHref(link.dataset.href ?? "");
6426
- if (href) this.root.ownerDocument.defaultView?.open(href, "_blank", "noopener,noreferrer");
8007
+ const href = link.getAttribute("href");
8008
+ if (!href || this.runtime.onLinkClick?.({ editor: this, href, event: e })) return;
8009
+ this.root.ownerDocument.defaultView?.open(href, "_blank", "noopener,noreferrer");
6427
8010
  }
6428
8011
  }
6429
8012
  /** The code block language input. */
@@ -6459,7 +8042,7 @@ var Editor = class {
6459
8042
  }
6460
8043
  onScroll() {
6461
8044
  this.handle.hide();
6462
- if (this.suggest || this.toolbar?.isOpen || this.blockMenu.isOpen) this.updateUi();
8045
+ if (this.suggestions.isActive || this.toolbar?.isOpen || this.blockMenu.isOpen) this.updateUi();
6463
8046
  }
6464
8047
  // -------------------------------------------------------------------------
6465
8048
  // Clipboard
@@ -6555,105 +8138,21 @@ var Editor = class {
6555
8138
  return domToPosition(this.root, node, offset);
6556
8139
  }
6557
8140
  // -------------------------------------------------------------------------
6558
- // Suggestion menus (see extensions/suggestion.ts)
6559
- /** Opens the suggestion menu whose trigger was just typed, if any. */
6560
- maybeOpenSuggestion(ch) {
6561
- const index = this.suggestions.findIndex(({ config: config2 }) => triggers(config2).includes(ch));
6562
- if (index < 0) return;
6563
- const config = this.suggestions[index].config;
6564
- const pos = this.current.selection.focus;
6565
- const block3 = getBlock(this.current.doc, pos.blockId);
6566
- if (!isTextBlock(block3) || isPlainTextBlock(block3) || pos.cell || !isCollapsed(this.current.selection)) return;
6567
- const before = inlineText(block3.content)[pos.offset - 2];
6568
- if (!config.allowAnywhere && before !== void 0 && !/\s/.test(before)) return;
6569
- this.closeSuggestion();
6570
- this.suggest = { index, blockId: block3.id, from: pos.offset - 1, request: 0 };
6571
- this.updateUi();
6572
- }
6573
- closeSuggestion() {
6574
- if (this.suggest) this.suggestions[this.suggest.index].menu.hide();
6575
- this.suggest = null;
6576
- this.root.removeAttribute("aria-activedescendant");
6577
- this.root.removeAttribute("aria-controls");
6578
- }
6579
- /** The text typed after the trigger, or null when the suggestion should close. */
6580
- suggestionQuery() {
6581
- const active = this.suggest;
6582
- if (!active || !isCollapsed(this.current.selection)) return null;
6583
- const { config } = this.suggestions[active.index];
6584
- const pos = this.current.selection.focus;
6585
- if (pos.blockId !== active.blockId || pos.cell || pos.offset <= active.from) return null;
6586
- const block3 = this.current.doc.blocks.find((b) => b.id === active.blockId);
6587
- if (!block3 || !isTextBlock(block3)) return null;
6588
- const text = inlineText(block3.content);
6589
- if (!triggers(config).includes(text[active.from] ?? "")) return null;
6590
- const query = text.slice(active.from + 1, pos.offset);
6591
- if (query.includes("\n") || query.length > (config.maxLength ?? 30)) return null;
6592
- if (config.allowSpaces ? /\s\s/.test(query) : /\s/.test(query)) return null;
6593
- return query;
6594
- }
6595
- /** Asks for items when the query changed, and shows them when they arrive. */
6596
- refreshSuggestion(query) {
6597
- const active = this.suggest;
6598
- const { config, menu } = this.suggestions[active.index];
6599
- if (active.query === query) {
6600
- if (menu.isOpen) this.placeSuggestion(menu);
6601
- return;
6602
- }
6603
- active.query = query;
6604
- const request = ++active.request;
6605
- const result = config.items({ query, editor: this });
6606
- const show = (items) => {
6607
- if (this.suggest !== active || active.request !== request || this.destroyed) return;
6608
- if (items.length === 0 && (!config.emptyLabel || query.length > 3)) {
6609
- menu.hide();
6610
- this.syncActiveDescendant();
6611
- return;
6612
- }
6613
- menu.setSections(
6614
- [
6615
- {
6616
- items: items.map((item, i) => ({
6617
- id: item.id ?? `${i}`,
6618
- label: item.label,
6619
- icon: item.icon,
6620
- run: () => this.pickSuggestion(item)
6621
- }))
6622
- }
6623
- ],
6624
- config.emptyLabel
6625
- );
6626
- this.placeSuggestion(menu);
6627
- };
6628
- if (isPromise(result)) result.then(show, () => void 0);
6629
- else show(result);
6630
- }
6631
- placeSuggestion(menu) {
6632
- const rect = this.selectionRect();
6633
- if (rect) menu.popup.show(rect, "below");
6634
- this.root.setAttribute("aria-controls", menu.el.id);
6635
- this.syncActiveDescendant();
6636
- }
6637
- pickSuggestion(item) {
6638
- const active = this.suggest;
6639
- if (!active) return;
6640
- const { config } = this.suggestions[active.index];
6641
- const query = active.query ?? "";
6642
- const range = {
6643
- from: { blockId: active.blockId, offset: active.from },
6644
- to: { blockId: active.blockId, offset: active.from + 1 + query.length }
6645
- };
6646
- this.closeSuggestion();
6647
- config.command({ editor: this, range, item, query });
8141
+ // Suggestion menus (see suggest/controller.ts)
8142
+ /** After typing: opens the suggestion whose token is at the caret, if any. */
8143
+ typedForSuggestion() {
8144
+ if (this.suggestions.typed()) this.updateUi();
6648
8145
  }
6649
8146
  /** The slash menu, as a suggestion. */
6650
8147
  slashSuggestion() {
6651
8148
  const ids = this.options.slashMenu || SLASH_ITEM_IDS;
6652
- const items = ids.map((id) => BLOCK_ITEMS.find((b) => b.id === id)).filter((b) => !!b).map((b) => ({ id: b.id, label: this.labels[b.id], icon: b.icon, aliases: b.aliases, spec: b.spec }));
8149
+ const items = ids.map((id) => BLOCK_ITEMS.find((b) => b.id === id)).filter((b) => !!b).map((b) => ({ id: b.id, label: this.labels[b.id], icon: this.icon(b.id), aliases: b.aliases, spec: b.spec }));
6653
8150
  return {
6654
- char: SLASH_CHARS,
8151
+ name: "slash",
8152
+ trigger: SLASH_CHARS,
6655
8153
  allowSpaces: true,
6656
8154
  emptyLabel: this.labels.noResults,
8155
+ label: this.labels.commands,
6657
8156
  className: "mbe-slash-menu",
6658
8157
  items: ({ query }) => items.filter((item) => matches(item, query)),
6659
8158
  command: ({ range, item }) => {
@@ -6688,7 +8187,7 @@ var Editor = class {
6688
8187
  this.blockSel = { anchor, head };
6689
8188
  this.current = { ...this.current, selection: spanBlocks(this.current.doc.blocks, this.blockRange()), storedMarks: null };
6690
8189
  this.history.breakGroup();
6691
- this.closeSuggestion();
8190
+ this.suggestions.close();
6692
8191
  this.toolbar?.hide();
6693
8192
  this.blockMenu.hide();
6694
8193
  this.refreshRevealed();
@@ -6803,29 +8302,34 @@ var Editor = class {
6803
8302
  }
6804
8303
  // -------------------------------------------------------------------------
6805
8304
  // Block menu
8305
+ /** @internal The icon for a UI control: the `icons` option's entry, or the built-in Lucide icon. */
8306
+ icon(name) {
8307
+ return this.options.icons?.[name] ?? builtinIcon(this.root.ownerDocument, name);
8308
+ }
6806
8309
  blockMenuSections(blockId) {
6807
8310
  const block3 = getBlock(this.state.doc, blockId);
6808
- const sections = [];
8311
+ const sections2 = [];
6809
8312
  if (block3.type === "table" && this.state.selection.focus.blockId === blockId && this.state.selection.focus.cell) {
6810
- sections.push({
8313
+ sections2.push({
6811
8314
  title: this.labels.tableSection,
6812
- items: TABLE_ITEMS.map(({ id, icon, action }) => ({
8315
+ items: TABLE_ITEMS.map(({ id, action }) => ({
6813
8316
  id,
6814
8317
  label: this.labels[id],
6815
- icon,
8318
+ icon: this.icon(id),
6816
8319
  run: () => this.run((s) => tableAction(s, action))
6817
8320
  }))
6818
8321
  });
6819
8322
  }
6820
- sections.push({
8323
+ sections2.push({
6821
8324
  items: [
6822
- { id: "duplicate", label: this.labels.duplicate, icon: "\u29C9", run: () => this.run((s) => duplicateBlock(s, blockId)) },
6823
- { id: "delete", label: this.labels.delete, icon: "\u{1F5D1}", danger: true, run: () => this.run((s) => deleteBlock(s, blockId)) }
8325
+ { id: "duplicate", label: this.labels.duplicate, icon: this.icon("duplicate"), run: () => this.run((s) => duplicateBlock(s, blockId)) },
8326
+ { id: "delete", label: this.labels.delete, icon: this.icon("delete"), danger: true, run: () => this.run((s) => deleteBlock(s, blockId)) }
6824
8327
  ]
6825
8328
  });
6826
- return sections;
8329
+ return sections2;
6827
8330
  }
6828
8331
  /**
8332
+ * @internal
6829
8333
  * Only large blocks get the handle and block menu: tables and code blocks.
6830
8334
  * Other blocks change type through the slash menu or Markdown shortcuts.
6831
8335
  */
@@ -6833,10 +8337,11 @@ var Editor = class {
6833
8337
  const block3 = this.state.doc.blocks.find((b) => b.id === blockId);
6834
8338
  return block3?.type === "table" || block3?.type === "code";
6835
8339
  }
8340
+ /** @internal Opens the block menu of a table or code block, as the block handle and Mod+/ do. */
6836
8341
  openBlockMenu(blockId, anchor) {
6837
8342
  if (this.readOnly || !this.hasBlockMenu(blockId)) return;
6838
8343
  this.dropBlockSelection();
6839
- this.closeSuggestion();
8344
+ this.suggestions.close();
6840
8345
  this.toolbar?.hide();
6841
8346
  if (this.state.selection.focus.blockId !== blockId) {
6842
8347
  const block3 = getBlock(this.state.doc, blockId);
@@ -6855,6 +8360,7 @@ var Editor = class {
6855
8360
  }
6856
8361
  // -------------------------------------------------------------------------
6857
8362
  // Toolbar and link popover (see ui/toolbar.ts)
8363
+ /** @internal Opens the link popover for the selection, as Mod+K does. */
6858
8364
  openLinkPopover() {
6859
8365
  if (this.readOnly) return;
6860
8366
  const block3 = getBlock(this.state.doc, this.state.selection.focus.blockId);
@@ -6885,15 +8391,12 @@ var Editor = class {
6885
8391
  nextHint?.classList.add("mbe-show-hint");
6886
8392
  this.hintEl = nextHint;
6887
8393
  }
6888
- const query = focused ? this.suggestionQuery() : null;
6889
- if (query === null) {
6890
- if (this.suggest) this.closeSuggestion();
6891
- } else {
6892
- this.refreshSuggestion(query);
6893
- }
8394
+ this.suggestions.update(focused);
6894
8395
  if (this.toolbar) {
6895
8396
  const block3 = this.state.doc.blocks.find((b) => b.id === pos.blockId);
6896
- const show = focused && !this.readOnly && !this.composing && !isCollapsed(this.state.selection) && !this.blockSel && !this.suggest && !this.blockMenu.isOpen && !!block3 && !isPlainTextBlock(block3) && block3.type !== "divider";
8397
+ const closed = this.toolbarClosedFor;
8398
+ if (closed && !(samePosition(closed.anchor, this.state.selection.anchor) && samePosition(closed.focus, pos))) this.toolbarClosedFor = null;
8399
+ const show = !this.toolbarClosedFor && focused && !this.readOnly && !this.composing && !isCollapsed(this.state.selection) && !this.blockSel && !this.suggestions.isActive && !this.blockMenu.isOpen && !!block3 && !isPlainTextBlock(block3) && block3.type !== "divider";
6897
8400
  if (show) this.toolbar.show();
6898
8401
  else this.toolbar.hide();
6899
8402
  }
@@ -6904,24 +8407,31 @@ var Editor = class {
6904
8407
  if (!focused && this.blockMenu.isOpen && !this.root.ownerDocument.activeElement?.closest?.(".mbe-ui")) this.blockMenu.hide();
6905
8408
  this.syncActiveDescendant();
6906
8409
  }
6907
- openMenu() {
6908
- const suggestion2 = this.suggest ? this.suggestions[this.suggest.index].menu : null;
6909
- return suggestion2?.isOpen ? suggestion2 : this.blockMenu.isOpen ? this.blockMenu : null;
6910
- }
6911
8410
  syncActiveDescendant() {
6912
- const id = this.openMenu()?.activeDescendant;
8411
+ const id = this.suggestions.activeDescendant ?? (this.blockMenu.isOpen ? this.blockMenu.activeDescendant : null);
6913
8412
  if (id) this.root.setAttribute("aria-activedescendant", id);
6914
8413
  else this.root.removeAttribute("aria-activedescendant");
6915
8414
  }
6916
8415
  hideUi() {
6917
8416
  this.dropBlockSelection();
6918
- this.closeSuggestion();
8417
+ this.suggestions.close();
6919
8418
  this.blockMenu.hide();
6920
8419
  this.toolbar?.hide();
6921
8420
  this.handle.hide();
6922
8421
  this.hintEl?.classList.remove("mbe-show-hint");
6923
8422
  this.hintEl = null;
6924
8423
  }
8424
+ /** Wraps an input event handler so the changes it makes keep the caret in view. */
8425
+ typed(fn) {
8426
+ return (e) => {
8427
+ this.typing++;
8428
+ try {
8429
+ fn(e);
8430
+ } finally {
8431
+ this.typing--;
8432
+ }
8433
+ };
8434
+ }
6925
8435
  listen(target, type, fn, capture = false) {
6926
8436
  target.addEventListener(type, fn, capture);
6927
8437
  this.cleanup.push(() => target.removeEventListener(type, fn, capture));
@@ -6971,11 +8481,9 @@ function selectionFromJSON(doc, value) {
6971
8481
  if (!anchor || !focus) return null;
6972
8482
  return clampSelection(doc, { anchor, focus });
6973
8483
  }
6974
- function triggers(config) {
6975
- return typeof config.char === "string" ? [config.char] : config.char;
6976
- }
6977
- function isPromise(value) {
6978
- return typeof value?.then === "function";
8484
+ function taskName(box, fallback) {
8485
+ const text = box.closest("[data-block-id]")?.querySelector(".mbe-content")?.textContent?.trim();
8486
+ return text || fallback;
6979
8487
  }
6980
8488
 
6981
8489
  // src/extensions/math.ts
@@ -7051,7 +8559,10 @@ function math(options = {}) {
7051
8559
  math(source, element, kind) {
7052
8560
  const tex = mathSource(source, kind);
7053
8561
  if (!tex.trim()) return false;
7054
- render2(tex, element, { displayMode: kind === "block" });
8562
+ const result = render2(tex, element, { displayMode: kind === "block" });
8563
+ if (!result) return;
8564
+ if (!element.hasChildNodes()) element.textContent = source;
8565
+ return result;
7055
8566
  }
7056
8567
  }
7057
8568
  };
@@ -7082,8 +8593,46 @@ var block2 = {
7082
8593
  };
7083
8594
  }
7084
8595
  };
7085
- function footnotes() {
7086
- return { name: "footnotes", markdown: { inline: [inline2], block: [block2] } };
8596
+ var labelOf = (source) => /^\[\^((?:[^\]\\]|\\.)+)\]/.exec(source)?.[1]?.replace(/\\(.)/g, "$1") ?? "";
8597
+ var renderReference = (source, element) => {
8598
+ const label = labelOf(source);
8599
+ const sup = element.ownerDocument.createElement("sup");
8600
+ sup.className = "mbe-footnote-ref";
8601
+ sup.dataset.label = label;
8602
+ sup.textContent = label;
8603
+ element.appendChild(sup);
8604
+ };
8605
+ var renderDefinition = (source, element) => {
8606
+ const label = labelOf(source);
8607
+ const doc = element.ownerDocument;
8608
+ element.classList.add("mbe-footnote");
8609
+ element.dataset.label = label;
8610
+ const sup = doc.createElement("sup");
8611
+ sup.className = "mbe-footnote-label";
8612
+ sup.textContent = label;
8613
+ const text = doc.createElement("span");
8614
+ text.textContent = source.replace(/^\[\^(?:[^\]\\]|\\.)+\]:[ \t]*/, "").split("\n").map((line) => line.trim()).filter(Boolean).join(" ");
8615
+ element.append(sup, text);
8616
+ };
8617
+ function footnotes(options = {}) {
8618
+ if (options.render === false) return { name: "footnotes", markdown: { inline: [inline2], block: [block2] } };
8619
+ return {
8620
+ name: "footnotes",
8621
+ markdown: { inline: [inline2], block: [block2] },
8622
+ views: { footnote: (source, element, kind) => (kind === "inline" ? renderReference : renderDefinition)(source, element, kind) },
8623
+ onCreate: ({ editor }) => {
8624
+ const onClick = (e) => {
8625
+ const ref = e.target.closest?.(".mbe-footnote-ref");
8626
+ if (!ref || editor.isEditable) return;
8627
+ const definition = [...editor.root.querySelectorAll(".mbe-footnote")].find((d) => d.dataset.label === ref.dataset.label);
8628
+ if (!definition) return;
8629
+ e.preventDefault();
8630
+ definition.scrollIntoView({ block: "center", behavior: "smooth" });
8631
+ };
8632
+ editor.root.addEventListener("click", onClick);
8633
+ return () => editor.root.removeEventListener("click", onClick);
8634
+ }
8635
+ };
7087
8636
  }
7088
8637
 
7089
8638
  // src/extensions/textDecorator.ts
@@ -7170,7 +8719,11 @@ function decorate2(scan, cls, attributes) {
7170
8719
  for (const r of scan(text, pos, end)) {
7171
8720
  const from = Math.max(r.from, pos);
7172
8721
  const to = Math.min(r.to, end);
7173
- if (to > from) out.push(attributes ? { from, to, class: cls, attributes } : { from, to, class: cls });
8722
+ if (to <= from) continue;
8723
+ const match = text.slice(from, to);
8724
+ const className = typeof cls === "function" ? cls(match) : cls;
8725
+ const attrs = typeof attributes === "function" ? attributes(match) : attributes;
8726
+ out.push(attrs ? { from, to, class: className, attributes: attrs } : { from, to, class: className });
7174
8727
  }
7175
8728
  }
7176
8729
  pos = end;
@@ -7185,8 +8738,7 @@ function build(name, char, scan, defaultClass, options) {
7185
8738
  return {
7186
8739
  name,
7187
8740
  markdown: { inline: [escapeSyntax(char)] },
7188
- decorations: decorate2(options.scan ?? scan, options.class ?? defaultClass, options.attributes),
7189
- suggestion: options.suggestion && { ...options.suggestion, char }
8741
+ decorations: decorate2(options.scan ?? scan, options.class ?? defaultClass, options.attributes)
7190
8742
  };
7191
8743
  }
7192
8744
  function tags(options = {}) {
@@ -7198,7 +8750,7 @@ function mentions(options = {}) {
7198
8750
 
7199
8751
  // src/extensions/suggestion.ts
7200
8752
  function suggestion(config) {
7201
- return { name: config.name ?? "suggestion", suggestion: config };
8753
+ return { name: config.name, suggestion: config };
7202
8754
  }
7203
8755
 
7204
8756
  // src/extensions/fileHandler.ts
@@ -7246,6 +8798,7 @@ export {
7246
8798
  createId,
7247
8799
  createState,
7248
8800
  defaultKeymap,
8801
+ defaultResolveUrl,
7249
8802
  deleteInline,
7250
8803
  divider,
7251
8804
  docToHtml,
@@ -7268,6 +8821,7 @@ export {
7268
8821
  listItem,
7269
8822
  loadMarkdown,
7270
8823
  marksAt,
8824
+ matchToken,
7271
8825
  math,
7272
8826
  mentions,
7273
8827
  normalizeInline,
@@ -7301,4 +8855,17 @@ export {
7301
8855
  withContainerContent,
7302
8856
  withContent
7303
8857
  };
8858
+ /*! Icons from Lucide (lucide-static 1.55.0), https://lucide.dev
8859
+ * ISC License. Copyright (c) 2026 Lucide Icons and Contributors.
8860
+ * Permission to use, copy, modify, and/or distribute this software for any
8861
+ * purpose with or without fee is hereby granted, provided that the above
8862
+ * copyright notice and this permission notice appear in all copies.
8863
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8864
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
8865
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
8866
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
8867
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
8868
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
8869
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
8870
+ */
7304
8871
  //# sourceMappingURL=index.js.map