@usememos/editor 26.10.1 → 26.10.2

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 */;
@@ -3826,7 +4035,7 @@ function tokenize(spans, ctx, italic, bare) {
3826
4035
  while (keep < stack.length && marks.includes(stack[keep].mark)) keep++;
3827
4036
  closeTo(keep);
3828
4037
  };
3829
- const emitSpan = (span, base, index, limit) => {
4038
+ const emitSpan = (span, base, index, limit, inLink = false) => {
3830
4039
  const target = emphasisMarks(span);
3831
4040
  closeExcept(target, base);
3832
4041
  openMarks(target, index, limit);
@@ -3837,7 +4046,7 @@ function tokenize(spans, ctx, italic, bare) {
3837
4046
  } else if (span.marks.includes("code")) {
3838
4047
  tokens.push({ kind: "raw", text: codeSpan(span.text) });
3839
4048
  } else {
3840
- tokens.push({ kind: "text", text: span.text, encodeFirst: false, encodeLast: false });
4049
+ tokens.push({ kind: "text", text: span.text, encodeFirst: false, encodeLast: false, inLink });
3841
4050
  }
3842
4051
  };
3843
4052
  let i = 0;
@@ -3859,7 +4068,7 @@ function tokenize(spans, ctx, italic, bare) {
3859
4068
  } else {
3860
4069
  tokens.push({ kind: "raw", text: "[" });
3861
4070
  const base = stack.length;
3862
- for (let k = i; k < j; k++) emitSpan(spans[k], base, k, j);
4071
+ for (let k = i; k < j; k++) emitSpan(spans[k], base, k, j, true);
3863
4072
  closeTo(base);
3864
4073
  tokens.push({ kind: "raw", text: `](${linkDestination(span.link)})` });
3865
4074
  }
@@ -3980,7 +4189,8 @@ function escapeText(tok, ctx, edges) {
3980
4189
  endsLine,
3981
4190
  blockSyntax: ctx.lineStart && startsLine,
3982
4191
  escape: ctx.options.escape,
3983
- inline: ctx.options.inline
4192
+ inline: ctx.options.inline,
4193
+ autolinks: ctx.options.autolinks && !tok.inLink
3984
4194
  });
3985
4195
  });
3986
4196
  return out;
@@ -3993,6 +4203,7 @@ function escapeLine(line, o) {
3993
4203
  if (o.encodeFirst || o.startsLine && (line[0] === " " || line[0] === " ")) encodeAt.add(0);
3994
4204
  if (o.encodeLast || o.endsLine && (line[lastIndex] === " " || line[lastIndex] === " ")) encodeAt.add(lastIndex);
3995
4205
  const blockEscape = o.blockSyntax && !encodeAt.has(0) ? blockSyntaxEscapeIndex(line) : -1;
4206
+ const urlEscapes = o.autolinks ? literalEscapes(line, o.before) : null;
3996
4207
  let out = "";
3997
4208
  for (let i = 0; i < line.length; i++) {
3998
4209
  if (encodeAt.has(i)) {
@@ -4004,7 +4215,7 @@ function escapeLine(line, o) {
4004
4215
  const ch = line[i];
4005
4216
  const prev = i > 0 ? encodeAt.has(i - 1) ? ";" : line[i - 1] : o.before;
4006
4217
  const next = i < line.length - 1 ? encodeAt.has(i + 1) ? "&" : line[i + 1] : o.after;
4007
- if (i === blockEscape) {
4218
+ if (i === blockEscape || urlEscapes?.has(i)) {
4008
4219
  out += bs(ch);
4009
4220
  continue;
4010
4221
  }
@@ -4039,6 +4250,18 @@ function escapeLine(line, o) {
4039
4250
  }
4040
4251
  return out;
4041
4252
  }
4253
+ function literalEscapes(line, before) {
4254
+ const emails = emailLiterals(line);
4255
+ if (!emails.length && !/www\.|:\/\//i.test(line)) return null;
4256
+ const out = /* @__PURE__ */ new Set();
4257
+ for (const c of line.matchAll(/www\.|(?:https?|ftp):\/\//gi)) {
4258
+ const at = c.index;
4259
+ if (!isLiteralBoundary(at > 0 ? line[at - 1] : before) || !urlLiteralAt(line, at)) continue;
4260
+ out.add(at + c[0].indexOf(c[0].startsWith("w") || c[0].startsWith("W") ? "." : ":"));
4261
+ }
4262
+ for (const { from } of emails) out.add(line.indexOf("@", from));
4263
+ return out;
4264
+ }
4042
4265
  function blockSyntaxEscapeIndex(line) {
4043
4266
  if (/^#{1,6}(?:[ \t]|$)/.test(line) || line[0] === ">") return 0;
4044
4267
  if (/^[-+](?:[ \t]|$)/.test(line) || /^-+[ \t]*$/.test(line) || /^(?:-[ \t]*){3,}$/.test(line)) return 0;
@@ -4148,6 +4371,7 @@ function joins(a, b) {
4148
4371
  }
4149
4372
  function saveWithSource(blocks, source, options) {
4150
4373
  const text = source.text;
4374
+ let firstBlocks;
4151
4375
  const chunks = [];
4152
4376
  for (let i = 0; i < blocks.length; ) {
4153
4377
  const block3 = blocks[i];
@@ -4157,6 +4381,13 @@ function saveWithSource(blocks, source, options) {
4157
4381
  i += group.blocks.length;
4158
4382
  continue;
4159
4383
  }
4384
+ firstBlocks ??= new Map(source.groups.map((g) => [g.blocks[0].id, g]));
4385
+ const ticked = tickedGroup(blocks, i, firstBlocks, source, options);
4386
+ if (ticked) {
4387
+ chunks.push(ticked);
4388
+ i += ticked.blocks.length;
4389
+ continue;
4390
+ }
4160
4391
  const last2 = chunks[chunks.length - 1];
4161
4392
  if (last2 && !last2.group) last2.blocks.push(block3);
4162
4393
  else chunks.push({ group: null, blocks: [block3] });
@@ -4203,7 +4434,7 @@ function saveWithSource(blocks, source, options) {
4203
4434
  let out = "";
4204
4435
  let prev;
4205
4436
  for (const chunk of chunks) {
4206
- const body = chunk.group ? text.slice(chunk.group.from, chunk.group.to) : serializeBlocks(chunk.blocks, options);
4437
+ const body = chunk.group ? chunk.text ?? text.slice(chunk.group.from, chunk.group.to) : serializeBlocks(chunk.blocks, options);
4207
4438
  if (body === "" && !chunk.group) continue;
4208
4439
  const g = chunk.group;
4209
4440
  const p = prev?.group;
@@ -4232,6 +4463,38 @@ function saveWithSource(blocks, source, options) {
4232
4463
  }
4233
4464
  return out + ending;
4234
4465
  }
4466
+ var reTaskLine = /^([ \t]*(?:[-+*]|\d{1,9}[.)])[ \t]+\[)([ xX])(?=\][ \t]|\]$)/gm;
4467
+ function tickedGroup(blocks, i, firstBlocks, source, options) {
4468
+ const loaded = firstBlocks.get(blocks[i].id);
4469
+ if (!loaded || loaded.open) return null;
4470
+ const current = blocks.slice(i, i + loaded.blocks.length);
4471
+ if (current.length !== loaded.blocks.length) return null;
4472
+ let changed = false;
4473
+ for (let k = 0; k < current.length; k++) {
4474
+ const a = loaded.blocks[k];
4475
+ const b = current[k];
4476
+ if (a === b) continue;
4477
+ if (!onlyChecked(a, b)) return null;
4478
+ changed = true;
4479
+ }
4480
+ if (!changed) return null;
4481
+ const tasks = current.filter((b) => b.type === "listItem" && b.listType === "task");
4482
+ const original = source.text.slice(loaded.from, loaded.to);
4483
+ let n = 0;
4484
+ const patched = original.replace(reTaskLine, (match, head, box) => {
4485
+ const block3 = tasks[n++];
4486
+ if (!block3 || block3.type !== "listItem") return match;
4487
+ const checked = box !== " ";
4488
+ return checked === block3.checked ? match : head + (block3.checked ? "x" : " ");
4489
+ });
4490
+ if (n !== tasks.length) return null;
4491
+ const reread = loadMarkdown(patched, options).doc.blocks;
4492
+ if (serializeBlocks(reread, options) !== serializeBlocks(current, options)) return null;
4493
+ return { group: loaded, blocks: current, text: patched };
4494
+ }
4495
+ function onlyChecked(a, b) {
4496
+ 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;
4497
+ }
4235
4498
  function squash(s) {
4236
4499
  return s.replace(/\s+/g, " ").trim();
4237
4500
  }
@@ -4254,9 +4517,31 @@ var THEME_VARS = [
4254
4517
  "--mbe-hover",
4255
4518
  "--mbe-accent",
4256
4519
  "--mbe-danger",
4257
- "--mbe-radius"
4520
+ "--mbe-radius",
4521
+ "--mbe-popup-z"
4258
4522
  ];
4523
+ var containers = /* @__PURE__ */ new WeakMap();
4524
+ function setPopupContainer(owner, container) {
4525
+ if (container) containers.set(owner, container);
4526
+ else containers.delete(owner);
4527
+ }
4528
+ function popupContainer(owner) {
4529
+ return containers.get(owner) ?? owner.closest('dialog[open], [aria-modal="true"]') ?? owner.ownerDocument.body;
4530
+ }
4531
+ function attach(el, owner) {
4532
+ const container = popupContainer(owner);
4533
+ if (el.parentElement !== container) container.appendChild(el);
4534
+ el.style.left = "0px";
4535
+ el.style.top = "0px";
4536
+ const rect = el.getBoundingClientRect();
4537
+ return { x: rect.left, y: rect.top };
4538
+ }
4539
+ function visibleViewport(view) {
4540
+ const vv = view.visualViewport;
4541
+ return vv ? { left: vv.offsetLeft, top: vv.offsetTop, width: vv.width, height: vv.height } : { left: 0, top: 0, width: view.innerWidth, height: view.innerHeight };
4542
+ }
4259
4543
  var isMac = typeof navigator !== "undefined" && /Mac|iP(hone|ad|od)/.test(navigator.platform);
4544
+ var isSafari = typeof navigator !== "undefined" && /AppleWebKit/.test(navigator.userAgent) && !/Chrome|Chromium|CriOS|Edg|Android/.test(navigator.userAgent);
4260
4545
  var isTouch = () => typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
4261
4546
  var Popup = class {
4262
4547
  constructor(owner, className) {
@@ -4271,24 +4556,50 @@ var Popup = class {
4271
4556
  }
4272
4557
  el;
4273
4558
  open = false;
4559
+ placed = "below";
4274
4560
  get isOpen() {
4275
4561
  return this.open;
4276
4562
  }
4277
- /** Shows the popup next to `rect` (viewport coordinates), flipping to stay on screen. */
4278
- show(rect, placement = "below", gap = 6) {
4563
+ /** The side of the anchor the popup was last shown on. */
4564
+ get side() {
4565
+ return this.placed;
4566
+ }
4567
+ /**
4568
+ * Shows the popup next to `rect` (viewport coordinates), flipping to stay
4569
+ * on screen. With `align: 'end'`, its right edge lines up with `rect.right`
4570
+ * (for right-to-left text).
4571
+ */
4572
+ show(rect, placement = "below", gap = 6, align = "start") {
4279
4573
  const doc = this.owner.ownerDocument;
4280
- if (!this.el.isConnected) doc.body.appendChild(this.el);
4281
4574
  if (!this.open) this.copyTheme();
4282
4575
  this.el.hidden = false;
4283
4576
  this.open = true;
4577
+ const offset = attach(this.el, this.owner);
4284
4578
  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`;
4579
+ const vp = visibleViewport(view);
4580
+ const scrolled = this.el.scrollTop;
4581
+ this.el.style.maxHeight = "";
4582
+ const w = this.el.offsetWidth;
4583
+ let h = this.el.offsetHeight;
4584
+ const below = vp.top + vp.height - 8 - (rect.bottom + gap);
4585
+ const above = rect.top - gap - 8 - vp.top;
4586
+ let side = placement;
4587
+ if (side === "below" && h > below && above > below) side = "above";
4588
+ else if (side === "above" && h > above && below > above) side = "below";
4589
+ const room = side === "below" ? below : above;
4590
+ if (h > room) {
4591
+ const cs = view.getComputedStyle(this.el);
4592
+ const extra = cs.boxSizing === "border-box" ? 0 : ["paddingTop", "paddingBottom", "borderTopWidth", "borderBottomWidth"].reduce((n, k) => n + parseFloat(cs[k]), 0);
4593
+ this.el.style.maxHeight = `${Math.max(Math.floor(room - extra), 80)}px`;
4594
+ h = this.el.offsetHeight;
4595
+ this.el.scrollTop = scrolled;
4596
+ }
4597
+ this.placed = side;
4598
+ const top = side === "below" ? rect.bottom + gap : rect.top - h - gap;
4599
+ const start = align === "end" ? (rect.right ?? rect.left) - w : rect.left;
4600
+ const left = Math.max(vp.left + 8, Math.min(start, vp.left + vp.width - w - 8));
4601
+ this.el.style.left = `${Math.round(left - offset.x)}px`;
4602
+ this.el.style.top = `${Math.round(top - offset.y)}px`;
4292
4603
  }
4293
4604
  hide() {
4294
4605
  if (!this.open) return;
@@ -4315,6 +4626,8 @@ var Menu = class {
4315
4626
  id = `mbe-menu-${++menuCounter}`;
4316
4627
  /** Called after an item runs. */
4317
4628
  onPicked = null;
4629
+ /** Called when the highlight moves, by key, by mouse or because the items changed. */
4630
+ onHighlight = null;
4318
4631
  constructor(owner, className, role = "listbox") {
4319
4632
  this.popup = new Popup(owner, `mbe-menu ${className}`);
4320
4633
  this.popup.el.setAttribute("role", role);
@@ -4329,12 +4642,12 @@ var Menu = class {
4329
4642
  get activeDescendant() {
4330
4643
  return this.items.length ? `${this.id}-${this.index}` : null;
4331
4644
  }
4332
- setSections(sections, emptyLabel) {
4645
+ setSections(sections2, emptyLabel) {
4333
4646
  const doc = this.el.ownerDocument;
4334
4647
  this.el.replaceChildren();
4335
4648
  this.items = [];
4336
4649
  this.index = 0;
4337
- for (const section of sections) {
4650
+ for (const section of sections2) {
4338
4651
  if (section.items.length === 0) continue;
4339
4652
  if (section.title) {
4340
4653
  const title = doc.createElement("div");
@@ -4353,11 +4666,18 @@ var Menu = class {
4353
4666
  if (item.danger) row.classList.add("mbe-danger");
4354
4667
  const icon = doc.createElement("span");
4355
4668
  icon.className = "mbe-menu-icon";
4356
- icon.textContent = item.icon ?? "";
4669
+ const content = iconNode(doc, item.icon);
4670
+ if (content) icon.appendChild(content);
4357
4671
  const label = doc.createElement("span");
4358
4672
  label.className = "mbe-menu-label";
4359
- label.textContent = item.label;
4673
+ setMarked(label, item.label, item.mark);
4360
4674
  row.append(icon, label);
4675
+ if (item.detail) {
4676
+ const detail = doc.createElement("span");
4677
+ detail.className = "mbe-menu-detail";
4678
+ detail.textContent = item.detail;
4679
+ row.appendChild(detail);
4680
+ }
4361
4681
  row.addEventListener("mousemove", () => this.highlight(i));
4362
4682
  row.addEventListener("click", () => this.pick(i));
4363
4683
  this.el.appendChild(row);
@@ -4371,9 +4691,41 @@ var Menu = class {
4371
4691
  }
4372
4692
  this.highlight(0);
4373
4693
  }
4694
+ /** Replaces the items with a line of text that is not an option, such as "Loading…". */
4695
+ setMessage(text, className) {
4696
+ const doc = this.el.ownerDocument;
4697
+ const line = doc.createElement("div");
4698
+ line.className = className;
4699
+ line.textContent = text;
4700
+ this.el.replaceChildren(line);
4701
+ this.items = [];
4702
+ this.index = 0;
4703
+ }
4704
+ /** Marks the list as waiting for newer items (`aria-busy`). */
4705
+ set busy(busy) {
4706
+ if (busy) this.el.setAttribute("aria-busy", "true");
4707
+ else this.el.removeAttribute("aria-busy");
4708
+ }
4374
4709
  get count() {
4375
4710
  return this.items.length;
4376
4711
  }
4712
+ /** The ID of the highlighted item. */
4713
+ get activeId() {
4714
+ return this.items[this.index]?.id ?? null;
4715
+ }
4716
+ /** Highlights the item with this ID. Returns false when there is none. */
4717
+ highlightId(id) {
4718
+ const i = this.items.findIndex((item) => item.id === id);
4719
+ if (i < 0) return false;
4720
+ this.highlight(i);
4721
+ return true;
4722
+ }
4723
+ /** Moves the highlight by a page: the number of items that fit in the list's height. Stops at the ends. */
4724
+ page(direction) {
4725
+ const row = this.el.querySelector(".mbe-menu-item");
4726
+ const perPage = row && row.offsetHeight > 0 ? Math.max(1, Math.floor(this.el.clientHeight / row.offsetHeight) - 1) : 8;
4727
+ this.highlight(Math.max(0, Math.min(this.items.length - 1, this.index + direction * perPage)));
4728
+ }
4377
4729
  highlight(i) {
4378
4730
  if (this.items.length === 0) return;
4379
4731
  this.index = (i + this.items.length) % this.items.length;
@@ -4382,9 +4734,14 @@ var Menu = class {
4382
4734
  row.setAttribute("aria-selected", String(k === this.index));
4383
4735
  });
4384
4736
  this.el.querySelector(`#${this.id}-${this.index}`)?.scrollIntoView?.({ block: "nearest" });
4737
+ this.onHighlight?.(this.index);
4385
4738
  }
4386
- move(delta) {
4387
- this.highlight(this.index + delta);
4739
+ /** The index of the highlighted item. */
4740
+ get activeIndex() {
4741
+ return this.items.length ? this.index : -1;
4742
+ }
4743
+ move(delta2) {
4744
+ this.highlight(this.index + delta2);
4388
4745
  }
4389
4746
  pick(i = this.index) {
4390
4747
  const item = this.items[i];
@@ -4399,6 +4756,18 @@ var Menu = class {
4399
4756
  this.popup.destroy();
4400
4757
  }
4401
4758
  };
4759
+ function setMarked(el, text, mark) {
4760
+ const at = mark ? text.toLowerCase().indexOf(mark.toLowerCase()) : -1;
4761
+ if (at < 0 || text.toLowerCase().length !== text.length) {
4762
+ el.textContent = text;
4763
+ return;
4764
+ }
4765
+ const doc = el.ownerDocument;
4766
+ const m = doc.createElement("mark");
4767
+ m.className = "mbe-menu-match";
4768
+ m.textContent = text.slice(at, at + mark.length);
4769
+ el.replaceChildren(text.slice(0, at), m, text.slice(at + mark.length));
4770
+ }
4402
4771
  function matches(item, query) {
4403
4772
  const q = query.trim().toLowerCase();
4404
4773
  if (!q) return true;
@@ -4423,18 +4792,630 @@ function defaultKeymap() {
4423
4792
  "Mod-Shift-7": ({ editor }) => editor.commands.toggleOrderedList() || true,
4424
4793
  "Mod-Shift-8": ({ editor }) => editor.commands.toggleBulletList() || true,
4425
4794
  "Mod-Shift-9": ({ editor }) => editor.commands.toggleTaskList() || true,
4795
+ "Mod-a": ({ editor }) => selectAll2(editor),
4426
4796
  "Mod-z": ({ editor }) => editor.commands.undo() || true,
4427
4797
  "Mod-Shift-z": ({ editor }) => editor.commands.redo() || true,
4428
4798
  "Mod-Enter": ({ editor }) => editor.submit(),
4429
4799
  "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,
4800
+ Tab: ({ editor }) => tab(editor, 1),
4801
+ "Shift-Tab": ({ editor }) => tab(editor, -1),
4432
4802
  // The first Escape selects the block; Escape in a block selection leaves the editor.
4433
- Escape: ({ editor }) => editor.commands.selectBlocks() || editor.commands.blur()
4803
+ Escape: ({ editor }) => editor.commands.selectBlocks() || editor.commands.blur(),
4804
+ // Opens the autocomplete popup for the token at the caret.
4805
+ "Ctrl-Space": ({ editor }) => editor.suggestion.open()
4434
4806
  };
4807
+ if (isMac) keymap["Alt-Escape"] = ({ editor }) => editor.suggestion.open();
4435
4808
  if (!isMac) keymap["Ctrl-y"] = ({ editor }) => editor.commands.redo() || true;
4436
4809
  return { name: "defaultKeymap", keymap };
4437
4810
  }
4811
+ function tab(editor, delta2) {
4812
+ if (editor.isActive("table")) editor.run((s) => moveCell(s, delta2));
4813
+ else if (editor.isActive("codeBlock")) editor.run((s) => indentCode(s, delta2));
4814
+ else if (delta2 === 1) editor.commands.indent();
4815
+ else editor.commands.outdent();
4816
+ return true;
4817
+ }
4818
+ function selectAll2(editor) {
4819
+ const { doc, selection } = editor.state;
4820
+ const { anchor, focus } = selection;
4821
+ if (anchor.blockId === focus.blockId && sameCell(anchor.cell, focus.cell)) {
4822
+ const block3 = getBlock(doc, focus.blockId);
4823
+ const content = focus.cell || block3.type === "code" ? containerContent(block3, focus.cell) : null;
4824
+ if (content) {
4825
+ const end = inlineLength(content);
4826
+ if (Math.min(anchor.offset, focus.offset) !== 0 || Math.max(anchor.offset, focus.offset) !== end) {
4827
+ editor.setSelection({ anchor: { ...focus, offset: 0 }, focus: { ...focus, offset: end } });
4828
+ return true;
4829
+ }
4830
+ }
4831
+ }
4832
+ return editor.commands.selectAll();
4833
+ }
4834
+
4835
+ // src/suggest/anchor.ts
4836
+ function suggestionAnchor(trigger, caret2, rtl, visible) {
4837
+ const line = caret2 ?? trigger;
4838
+ if (!line) return null;
4839
+ if (trigger && visible && (trigger.bottom <= visible.top || trigger.top >= visible.bottom || trigger.right < visible.left || trigger.left > visible.right)) {
4840
+ return null;
4841
+ }
4842
+ const sameLine = trigger && caret2 && Math.abs(trigger.top - caret2.top) < Math.max(1, Math.min(trigger.bottom - trigger.top, caret2.bottom - caret2.top) / 2);
4843
+ const from = trigger && (sameLine || !caret2) ? trigger : line;
4844
+ const x = rtl ? from.right : from.left;
4845
+ return { rect: { left: x, right: x, top: line.top, bottom: line.bottom }, align: rtl ? "end" : "start" };
4846
+ }
4847
+ function visibleArea(el) {
4848
+ const view = el.ownerDocument.defaultView;
4849
+ let box = { left: 0, top: 0, right: view.innerWidth, bottom: view.innerHeight };
4850
+ const top = el.ownerDocument.documentElement;
4851
+ for (let node = el; node && node !== top && node !== el.ownerDocument.body; node = node.parentElement) {
4852
+ const style = view.getComputedStyle(node);
4853
+ if (style.overflowX === "visible" && style.overflowY === "visible") continue;
4854
+ const r = node.getBoundingClientRect();
4855
+ 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) };
4856
+ }
4857
+ return box;
4858
+ }
4859
+
4860
+ // src/suggest/match.ts
4861
+ function defaultMatcher({ allowSpaces = false, allowAnywhere = false, maxLength = 30 } = {}) {
4862
+ const invalid = allowSpaces ? /\s\s|\n/ : /\s/;
4863
+ return ({ text, caret: caret2, triggers }) => {
4864
+ const lineStart = text.lastIndexOf("\n", caret2 - 1) + 1;
4865
+ const longest = Math.max(0, ...triggers.map((t) => t.length));
4866
+ const lowest = Math.max(lineStart, caret2 - maxLength - longest);
4867
+ for (let i = caret2 - 1; i >= lowest; i--) {
4868
+ const trigger = longestAt(text, i, triggers, caret2);
4869
+ if (!trigger) continue;
4870
+ const query = text.slice(i + trigger.length, caret2);
4871
+ if (query.length > maxLength || invalid.test(query)) return null;
4872
+ const before = text[i - 1];
4873
+ if (!allowAnywhere && before !== void 0 && !/\s/.test(before)) continue;
4874
+ let to = caret2;
4875
+ if (!allowSpaces) while (to < text.length && !/\s/.test(text[to])) to++;
4876
+ return { from: i, to, query };
4877
+ }
4878
+ return null;
4879
+ };
4880
+ }
4881
+ var reJoining = /^[\p{M}\u200c\u200d\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/u;
4882
+ function matchToken(scan, { probe = "a", maxLength = 30 } = {}) {
4883
+ return ({ text, caret: caret2, triggers }) => {
4884
+ const next = text.codePointAt(caret2);
4885
+ if (next !== void 0 && reJoining.test(String.fromCodePoint(next))) return null;
4886
+ let scanned = text;
4887
+ const first = triggers[0];
4888
+ if (first) {
4889
+ for (const t of triggers) if (t !== first && t.length === first.length) scanned = scanned.split(t).join(first);
4890
+ }
4891
+ const probed = scanned.slice(0, caret2) + probe + scanned.slice(caret2);
4892
+ const lineStart = text.lastIndexOf("\n", caret2 - 1) + 1;
4893
+ let lineEnd = text.indexOf("\n", caret2);
4894
+ if (lineEnd < 0) lineEnd = text.length;
4895
+ const reach = maxLength + 16;
4896
+ const from = Math.max(lineStart, caret2 - reach);
4897
+ const to = Math.min(lineEnd + probe.length, caret2 + probe.length + reach);
4898
+ for (const token of scan(probed, from, to)) {
4899
+ if (token.from >= caret2 || token.to < caret2 + probe.length) continue;
4900
+ const trigger = longestAt(text, token.from, triggers, caret2);
4901
+ if (!trigger) return null;
4902
+ const query = text.slice(token.from + trigger.length, caret2);
4903
+ if (query.length > maxLength) return null;
4904
+ return { from: token.from, to: token.to - probe.length, query };
4905
+ }
4906
+ return null;
4907
+ };
4908
+ }
4909
+ function longestAt(text, i, triggers, limit = text.length) {
4910
+ let found = null;
4911
+ for (const t of triggers) {
4912
+ if (t && i + t.length <= limit && text.startsWith(t, i) && (!found || t.length > found.length)) found = t;
4913
+ }
4914
+ return found;
4915
+ }
4916
+ function excludedAt(content, offset) {
4917
+ let pos = 0;
4918
+ for (const span of content) {
4919
+ const end = pos + span.text.length;
4920
+ if (offset < end) return isExcluded(span);
4921
+ pos = end;
4922
+ }
4923
+ return false;
4924
+ }
4925
+
4926
+ // src/suggest/source.ts
4927
+ var LOADING_DELAY = 300;
4928
+ var SourceRunner = class {
4929
+ request = 0;
4930
+ controller = null;
4931
+ debounceTimer = null;
4932
+ loadingTimer = null;
4933
+ waiting = false;
4934
+ /** True from `run` until its result arrives or it is cancelled. */
4935
+ get pending() {
4936
+ return this.waiting;
4937
+ }
4938
+ /** Calls `fetch` after `debounce` ms and passes its result to `show`, unless a newer request or `cancel` came first. */
4939
+ run(fetch, handlers, debounce = 0) {
4940
+ this.cancel();
4941
+ const request = this.request;
4942
+ this.waiting = true;
4943
+ this.loadingTimer = setTimeout(() => {
4944
+ this.loadingTimer = null;
4945
+ if (request === this.request) handlers.loading();
4946
+ }, LOADING_DELAY);
4947
+ const done = (value) => {
4948
+ if (request !== this.request) return;
4949
+ this.settle();
4950
+ handlers.show(value);
4951
+ };
4952
+ const start = () => {
4953
+ this.debounceTimer = null;
4954
+ const controller = new AbortController();
4955
+ this.controller = controller;
4956
+ let result;
4957
+ try {
4958
+ result = fetch(controller.signal);
4959
+ } catch {
4960
+ done(null);
4961
+ return;
4962
+ }
4963
+ if (isPromise(result)) result.then(done, () => done(null));
4964
+ else done(result);
4965
+ };
4966
+ if (debounce > 0) this.debounceTimer = setTimeout(start, debounce);
4967
+ else start();
4968
+ }
4969
+ /** Drops the pending request: aborts its signal and clears its timers. */
4970
+ cancel() {
4971
+ this.request++;
4972
+ this.controller?.abort();
4973
+ this.settle();
4974
+ }
4975
+ settle() {
4976
+ this.waiting = false;
4977
+ this.controller = null;
4978
+ if (this.debounceTimer !== null) clearTimeout(this.debounceTimer);
4979
+ if (this.loadingTimer !== null) clearTimeout(this.loadingTimer);
4980
+ this.debounceTimer = this.loadingTimer = null;
4981
+ }
4982
+ };
4983
+ function isPromise(value) {
4984
+ return typeof value?.then === "function";
4985
+ }
4986
+
4987
+ // src/suggest/controller.ts
4988
+ var INTERACTION_DELAY = 75;
4989
+ var NO_SPACE_BEFORE = /[\s.,;:!?)\]}>'"’”»)」』】、。,.:;!?]/;
4990
+ var listboxCounter = 0;
4991
+ var SuggestionController = class {
4992
+ constructor(host, configs) {
4993
+ this.host = host;
4994
+ this.entries = configs.map((config) => {
4995
+ let menu = null;
4996
+ if (config.render !== false) {
4997
+ menu = new Menu(host.root, `mbe-suggestion-menu ${config.className ?? ""}`.trim(), "listbox");
4998
+ menu.el.setAttribute("aria-label", config.label ?? host.editor.labels.suggestions);
4999
+ menu.el.setAttribute("aria-expanded", "true");
5000
+ menu.onHighlight = (i) => {
5001
+ if (this.session?.entry.menu !== menu || this.active === i) return;
5002
+ this.active = i;
5003
+ this.host.syncActiveDescendant();
5004
+ this.report();
5005
+ };
5006
+ }
5007
+ return {
5008
+ config,
5009
+ matcher: config.match ?? defaultMatcher(config),
5010
+ triggers: typeof config.trigger === "string" ? [config.trigger] : config.trigger,
5011
+ menu,
5012
+ listboxId: menu?.el.id ?? `mbe-suggestion-${++listboxCounter}`,
5013
+ source: new SourceRunner()
5014
+ };
5015
+ });
5016
+ if (this.entries.length > 0) host.root.setAttribute("aria-autocomplete", "list");
5017
+ const view = host.root.ownerDocument.defaultView;
5018
+ if (view && this.entries.some((e) => e.menu)) {
5019
+ const schedule = () => this.schedule();
5020
+ const targets = [view];
5021
+ if (view.visualViewport) targets.push(view.visualViewport);
5022
+ for (const target of targets) {
5023
+ for (const type of target === view ? ["resize"] : ["resize", "scroll"]) {
5024
+ target.addEventListener(type, schedule);
5025
+ this.cleanup.push(() => target.removeEventListener(type, schedule));
5026
+ }
5027
+ }
5028
+ }
5029
+ }
5030
+ entries;
5031
+ session = null;
5032
+ /** The token Escape closed the popup for. It stays closed until the caret leaves it. */
5033
+ dismissed = null;
5034
+ /** The items shown, and the highlighted one. */
5035
+ items = [];
5036
+ active = -1;
5037
+ /** A line shown instead of items: the loading row or the empty label. */
5038
+ message = null;
5039
+ /** The side the popup is on. It stays there while open, unless it no longer fits. */
5040
+ side = "below";
5041
+ frame = null;
5042
+ /** The last request was made while composing. */
5043
+ requestedComposing = false;
5044
+ /** Until this time (ms), the popup takes no keys but Escape. */
5045
+ keysFrom = 0;
5046
+ /** What `suggestionChange` last reported, to emit only changes. */
5047
+ reported = "";
5048
+ cleanup = [];
5049
+ /** True while a suggestion tracks the token at the caret, shown or not. */
5050
+ get isActive() {
5051
+ return this.session !== null;
5052
+ }
5053
+ /** True while the popup shows items, a loading row or the empty label. Its keys work then. */
5054
+ get isOpen() {
5055
+ const session = this.session;
5056
+ if (!session || !this.shown) return false;
5057
+ return session.entry.menu ? session.entry.menu.isOpen : true;
5058
+ }
5059
+ /** The ID of the highlighted option while the popup is open. */
5060
+ get activeDescendant() {
5061
+ return this.isOpen && this.active >= 0 ? `${this.session.entry.listboxId}-${this.active}` : null;
5062
+ }
5063
+ /** The open suggestion, or null. */
5064
+ get state() {
5065
+ const session = this.session;
5066
+ if (!session) return null;
5067
+ const { entry, blockId, cell, from, to, query } = session;
5068
+ const at = (offset) => cell ? { blockId, offset, cell } : { blockId, offset };
5069
+ const listboxId = entry.listboxId;
5070
+ return {
5071
+ name: entry.config.name,
5072
+ query,
5073
+ range: { from: at(from), to: at(to) },
5074
+ items: this.items,
5075
+ active: this.active,
5076
+ loading: entry.source.pending,
5077
+ listboxId,
5078
+ optionId: (index) => `${listboxId}-${index}`,
5079
+ anchorRect: () => {
5080
+ if (this.session !== session) return null;
5081
+ const anchor = this.anchor();
5082
+ return anchor ? new DOMRect(anchor.rect.left, anchor.rect.top, 0, anchor.rect.bottom - anchor.rect.top) : null;
5083
+ }
5084
+ };
5085
+ }
5086
+ get shown() {
5087
+ return this.items.length > 0 || this.message !== null;
5088
+ }
5089
+ get editor() {
5090
+ return this.host.editor;
5091
+ }
5092
+ /**
5093
+ * Takes new configs for the same suggestions, by name, so callbacks
5094
+ * (`items`, `command`, `match`, `allow`) can change while the editor runs.
5095
+ */
5096
+ setConfigs(configs) {
5097
+ for (const config of configs) {
5098
+ const entry = this.entries.find((e) => e.config.name === config.name);
5099
+ if (!entry || entry.config === config) continue;
5100
+ if (config.match !== entry.config.match) entry.matcher = config.match ?? defaultMatcher(config);
5101
+ entry.config = config;
5102
+ }
5103
+ }
5104
+ /** After typing: opens the suggestion whose token is at the caret, if any. Returns true when one opened. */
5105
+ typed() {
5106
+ if (this.entries.length === 0 || !this.editor.isEditable) return false;
5107
+ const found = this.find(false);
5108
+ if (!found) return false;
5109
+ const dismissed = this.dismissed;
5110
+ if (dismissed && dismissed.blockId === found.blockId && sameCell(dismissed.cell, found.cell) && dismissed.from === found.from) return false;
5111
+ const session = this.session;
5112
+ if (session && session.entry === found.entry && session.blockId === found.blockId && sameCell(session.cell, found.cell) && session.from === found.from) {
5113
+ return false;
5114
+ }
5115
+ this.close();
5116
+ this.session = { ...found, explicit: false };
5117
+ return true;
5118
+ }
5119
+ /** Opens the popup for the token at the caret, as Ctrl+Space does. Returns false when there is none. */
5120
+ open(name) {
5121
+ if (!this.editor.isEditable) return false;
5122
+ const only = name === void 0 ? void 0 : this.entries.find((e) => e.config.name === name);
5123
+ if (name !== void 0 && !only) return false;
5124
+ const found = this.find(true, only);
5125
+ if (!found) return false;
5126
+ this.close();
5127
+ this.dismissed = null;
5128
+ this.session = { ...found, explicit: true };
5129
+ this.host.refresh();
5130
+ return true;
5131
+ }
5132
+ /** Follows the document and the caret: updates the query, or closes. */
5133
+ update(focused) {
5134
+ const dismissed = this.dismissed;
5135
+ if (dismissed) {
5136
+ const found2 = focused ? this.find(true) : null;
5137
+ if (!found2 || found2.blockId !== dismissed.blockId || !sameCell(found2.cell, dismissed.cell) || found2.from !== dismissed.from) {
5138
+ this.dismissed = null;
5139
+ }
5140
+ }
5141
+ const session = this.session;
5142
+ if (!session) return;
5143
+ const found = focused && this.editor.isEditable ? this.find(session.explicit, session.entry) : null;
5144
+ const same = found && found.blockId === session.blockId && sameCell(found.cell, session.cell) && (found.from === session.from || found.text !== session.text);
5145
+ if (!same) {
5146
+ this.close();
5147
+ return;
5148
+ }
5149
+ this.session = { ...session, ...found };
5150
+ this.refresh();
5151
+ this.report();
5152
+ }
5153
+ close() {
5154
+ const session = this.session;
5155
+ if (session) {
5156
+ session.entry.menu?.hide();
5157
+ if (session.entry.menu) session.entry.menu.busy = false;
5158
+ session.entry.source.cancel();
5159
+ }
5160
+ this.session = null;
5161
+ this.items = [];
5162
+ this.active = -1;
5163
+ this.message = null;
5164
+ this.requestedComposing = false;
5165
+ this.side = "below";
5166
+ this.keysFrom = 0;
5167
+ for (const name of ["aria-activedescendant", "aria-controls", "aria-haspopup"]) this.host.root.removeAttribute(name);
5168
+ this.report();
5169
+ }
5170
+ /** Moves the highlight by `delta` items, wrapping around. */
5171
+ move(delta2) {
5172
+ if (!this.session || this.items.length === 0) return;
5173
+ this.highlight(((this.active + delta2) % this.items.length + this.items.length) % this.items.length);
5174
+ }
5175
+ /** Picks the item at `index`, or the highlighted one. Returns false when there is none. */
5176
+ accept(index = this.active) {
5177
+ const item = this.items[index];
5178
+ if (!this.session || !item) return false;
5179
+ this.pick(item);
5180
+ return true;
5181
+ }
5182
+ /**
5183
+ * Handles a key while the popup is open. Returns true when the key was
5184
+ * taken; the caller then prevents its default. Only the popup's keys are
5185
+ * taken: arrows, Page Up and Down, Enter, Tab, Escape, and Ctrl+N and
5186
+ * Ctrl+P on macOS.
5187
+ */
5188
+ keydown(e) {
5189
+ if (!this.isOpen) return false;
5190
+ const plain2 = !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey;
5191
+ if (plain2 && e.key === "Escape") {
5192
+ this.dismiss();
5193
+ return true;
5194
+ }
5195
+ const emacs = isMac && e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey;
5196
+ const key = e.key;
5197
+ let action = null;
5198
+ if (plain2 && key === "ArrowDown") action = "down";
5199
+ else if (plain2 && key === "ArrowUp") action = "up";
5200
+ else if (emacs && key.toLowerCase() === "n") action = "down";
5201
+ else if (emacs && key.toLowerCase() === "p") action = "up";
5202
+ else if (plain2 && key === "PageDown") action = "pageDown";
5203
+ else if (plain2 && key === "PageUp") action = "pageUp";
5204
+ else if (plain2 && (key === "Enter" || key === "Tab")) action = "accept";
5205
+ if (!action || Date.now() < this.keysFrom) return false;
5206
+ if (this.items.length === 0) {
5207
+ if (key === "Enter") this.close();
5208
+ return false;
5209
+ }
5210
+ const menu = this.session.entry.menu;
5211
+ if (action === "down") this.move(1);
5212
+ else if (action === "up") this.move(-1);
5213
+ else if (action === "accept") this.accept();
5214
+ else if (menu) menu.page(action === "pageDown" ? 1 : -1);
5215
+ else this.highlight(Math.max(0, Math.min(this.items.length - 1, this.active + (action === "pageDown" ? 8 : -8))));
5216
+ return true;
5217
+ }
5218
+ /** Closes the popup and keeps it closed for this token (Escape). */
5219
+ dismiss() {
5220
+ const session = this.session;
5221
+ if (session) this.dismissed = { blockId: session.blockId, cell: session.cell, from: session.from };
5222
+ this.close();
5223
+ }
5224
+ /** Closes the popup and forgets dismissed tokens, as when the document is replaced. */
5225
+ reset() {
5226
+ this.dismissed = null;
5227
+ this.close();
5228
+ }
5229
+ /** Follows scrolling, resizing and the on-screen keyboard. */
5230
+ reposition() {
5231
+ if (this.session && this.shown) this.place();
5232
+ }
5233
+ destroy() {
5234
+ this.close();
5235
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
5236
+ for (const fn of this.cleanup) fn();
5237
+ for (const { menu } of this.entries) menu?.destroy();
5238
+ }
5239
+ schedule() {
5240
+ if (this.frame !== null || !this.shown) return;
5241
+ this.frame = requestAnimationFrame(() => {
5242
+ this.frame = null;
5243
+ this.reposition();
5244
+ });
5245
+ }
5246
+ highlight(index) {
5247
+ const menu = this.session?.entry.menu;
5248
+ if (menu) menu.highlight(index);
5249
+ else if (this.active !== index) {
5250
+ this.active = index;
5251
+ this.host.syncActiveDescendant();
5252
+ this.report();
5253
+ }
5254
+ }
5255
+ /** Emits `suggestionChange` when the state differs from the last one reported. */
5256
+ report() {
5257
+ const s = this.session;
5258
+ const key = s ? `${s.entry.config.name}
5259
+ ${s.blockId}
5260
+ ${s.cell?.row},${s.cell?.col}
5261
+ ${s.from}
5262
+ ${s.to}
5263
+ ${s.query}
5264
+ ${this.active}
5265
+ ${s.entry.source.pending}
5266
+ ${this.message}` : "";
5267
+ if (key === this.reported && !(s && this.itemsChanged)) return;
5268
+ this.reported = key;
5269
+ this.itemsChanged = false;
5270
+ this.host.changed(this.state);
5271
+ }
5272
+ itemsChanged = false;
5273
+ /**
5274
+ * The token at the caret that a suggestion accepts. When several do, the
5275
+ * one that starts closest to the caret wins; on a tie, the earlier one.
5276
+ */
5277
+ find(explicit, only) {
5278
+ const { doc, selection } = this.editor.state;
5279
+ if (!isCollapsed(selection)) return null;
5280
+ const pos = selection.focus;
5281
+ const block3 = doc.blocks.find((b) => b.id === pos.blockId);
5282
+ if (!block3 || isPlainTextBlock(block3)) return null;
5283
+ const content = containerContent(block3, pos.cell);
5284
+ if (!content) return null;
5285
+ const text = inlineText(content);
5286
+ const caret2 = pos.offset;
5287
+ let best = null;
5288
+ for (const entry of only ? [only] : this.entries) {
5289
+ const match = entry.matcher({ text, caret: caret2, content, triggers: entry.triggers });
5290
+ if (!match || best && match.from <= best.from) continue;
5291
+ if (match.from < 0 || match.from >= caret2 || match.to < caret2 || match.to > text.length) continue;
5292
+ if (!longestAt(text, match.from, entry.triggers, caret2)) continue;
5293
+ if (match.query.length > (entry.config.maxLength ?? 30)) continue;
5294
+ const excluded = excludedAt(content, match.from);
5295
+ const allow = entry.config.allow;
5296
+ 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;
5297
+ if (!allowed) continue;
5298
+ best = { ...match, entry, blockId: block3.id, cell: pos.cell, text };
5299
+ }
5300
+ return best;
5301
+ }
5302
+ /** Asks for items when the query changed, and shows them when they arrive. */
5303
+ refresh() {
5304
+ const session = this.session;
5305
+ const { menu, source } = session.entry;
5306
+ const query = session.query;
5307
+ const composing = this.editor.isComposing;
5308
+ if (session.requested === query && !(this.requestedComposing && !composing)) {
5309
+ if (this.shown) this.place();
5310
+ return;
5311
+ }
5312
+ this.session = { ...session, requested: query };
5313
+ const current = this.session;
5314
+ const entry = current.entry;
5315
+ const live = () => this.session?.entry === entry && this.session.requested === query;
5316
+ let sync = true;
5317
+ const show = (result) => {
5318
+ if (!live()) return;
5319
+ const config = entry.config;
5320
+ if (menu) menu.busy = false;
5321
+ const items = (result ?? []).slice(0, config.limit ?? 50);
5322
+ if (items.length === 0 && composing && this.items.length > 0) return this.report();
5323
+ const empty = items.length === 0 && (!config.emptyLabel || query.length > 3);
5324
+ if (!empty && !sync && !this.isOpen) this.keysFrom = Date.now() + INTERACTION_DELAY;
5325
+ const activeId = this.items[this.active]?.id;
5326
+ const kept = activeId === void 0 ? -1 : items.findIndex((item) => item.id === activeId);
5327
+ const active = items.length === 0 ? -1 : Math.max(0, kept);
5328
+ this.items = items;
5329
+ this.active = active;
5330
+ this.message = items.length === 0 && !empty ? config.emptyLabel : null;
5331
+ this.itemsChanged = true;
5332
+ if (menu) {
5333
+ if (empty) menu.hide();
5334
+ else {
5335
+ menu.setSections(sections(items, query, (item) => this.pick(item)), config.emptyLabel);
5336
+ menu.highlight(active);
5337
+ }
5338
+ }
5339
+ if (empty) {
5340
+ this.host.root.removeAttribute("aria-haspopup");
5341
+ this.host.root.removeAttribute("aria-controls");
5342
+ this.host.syncActiveDescendant();
5343
+ } else {
5344
+ this.place();
5345
+ }
5346
+ this.report();
5347
+ };
5348
+ const loading = () => {
5349
+ if (!live() || this.shown) return this.report();
5350
+ this.message = this.editor.labels.loading;
5351
+ menu?.setMessage(this.message, "mbe-menu-loading");
5352
+ this.place();
5353
+ this.report();
5354
+ };
5355
+ this.requestedComposing = composing;
5356
+ source.run(
5357
+ (signal) => entry.config.items({ query, editor: this.editor, explicit: current.explicit, composing, signal }),
5358
+ { show, loading },
5359
+ entry.config.debounce ?? 0
5360
+ );
5361
+ sync = false;
5362
+ if (source.pending && menu?.isOpen) menu.busy = true;
5363
+ }
5364
+ /** The popup's anchor, or null while the trigger is out of view. */
5365
+ anchor() {
5366
+ const session = this.session;
5367
+ const at = (offset) => session.cell ? { blockId: session.blockId, offset, cell: session.cell } : { blockId: session.blockId, offset };
5368
+ const end = session.from + (longestAt(session.text, session.from, session.entry.triggers)?.length ?? 1);
5369
+ const trigger = this.editor.textRect(at(session.from), at(end));
5370
+ return suggestionAnchor(trigger?.rect ?? null, this.editor.caretRect(), trigger?.rtl ?? false, visibleArea(this.host.root));
5371
+ }
5372
+ /** Shows the popup under the caret's line, lined up with the trigger, or hides it while the trigger is out of view. */
5373
+ place() {
5374
+ const session = this.session;
5375
+ const { menu, listboxId } = session.entry;
5376
+ const root = this.host.root;
5377
+ const anchor = menu ? this.anchor() : null;
5378
+ if (menu && anchor) menu.popup.show(anchor.rect, this.side, 4, anchor.align);
5379
+ else menu?.hide();
5380
+ if (menu) this.side = menu.popup.side;
5381
+ if (this.isOpen) {
5382
+ root.setAttribute("aria-haspopup", "listbox");
5383
+ root.setAttribute("aria-controls", listboxId);
5384
+ } else {
5385
+ root.removeAttribute("aria-haspopup");
5386
+ root.removeAttribute("aria-controls");
5387
+ }
5388
+ this.host.syncActiveDescendant();
5389
+ }
5390
+ pick(item) {
5391
+ if (this.editor.isComposing) this.host.endComposition();
5392
+ const session = this.session;
5393
+ if (!session) return;
5394
+ const { entry, blockId, cell, from, to, query, text } = session;
5395
+ const at = (offset) => cell ? { blockId, offset, cell } : { blockId, offset };
5396
+ const range = { from: at(from), to: at(to) };
5397
+ this.close();
5398
+ if (entry.config.command) {
5399
+ entry.config.command({ editor: this.editor, range, item, query });
5400
+ return;
5401
+ }
5402
+ const next = text[to];
5403
+ const space = next !== void 0 && NO_SPACE_BEFORE.test(next) ? "" : " ";
5404
+ this.editor.commands.insertText(entry.triggers[0] + (item.value ?? item.id ?? item.label) + space, { range });
5405
+ }
5406
+ };
5407
+ function itemId(item, index) {
5408
+ return item.id ?? `${index}`;
5409
+ }
5410
+ function sections(items, query, pick) {
5411
+ const out = [];
5412
+ items.forEach((item, i) => {
5413
+ let last = out[out.length - 1];
5414
+ if (!last || item.section !== last.title) out.push(last = { title: item.section, items: [] });
5415
+ last.items.push({ id: itemId(item, i), label: item.label, detail: item.detail, icon: item.icon, mark: query, run: () => pick(item) });
5416
+ });
5417
+ return out;
5418
+ }
4438
5419
 
4439
5420
  // src/widgets.ts
4440
5421
  var WidgetImpl = class {
@@ -4506,10 +5487,10 @@ function matchesKey(binding, e) {
4506
5487
  // src/ui/toolbar.ts
4507
5488
  var mod = (key) => isMac ? `\u2318${key}` : `Ctrl+${key}`;
4508
5489
  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") }
5490
+ { mark: "bold", name: "bold", shortcut: mod("B") },
5491
+ { mark: "italic", name: "italic", shortcut: mod("I") },
5492
+ { mark: "strike", name: "strike", shortcut: isMac ? "\u2318\u21E7X" : "Ctrl+Shift+X" },
5493
+ { mark: "code", name: "inlineCode", shortcut: mod("E") }
4513
5494
  ];
4514
5495
  var FormatToolbar = class {
4515
5496
  constructor(editor) {
@@ -4518,11 +5499,12 @@ var FormatToolbar = class {
4518
5499
  this.popup = new Popup(editor.root, "mbe-toolbar");
4519
5500
  const el = this.popup.el;
4520
5501
  el.setAttribute("role", "toolbar");
4521
- const button = (text, label, className, onClick) => {
5502
+ const button = (icon, label, className, onClick) => {
4522
5503
  const b = doc.createElement("button");
4523
5504
  b.type = "button";
4524
5505
  b.className = `mbe-tool ${className}`;
4525
- b.textContent = text;
5506
+ const content = iconNode(doc, editor.icon(icon));
5507
+ if (content) b.appendChild(content);
4526
5508
  b.title = label;
4527
5509
  b.setAttribute("aria-label", label);
4528
5510
  b.addEventListener("click", onClick);
@@ -4531,7 +5513,7 @@ var FormatToolbar = class {
4531
5513
  };
4532
5514
  const labels = editor.labels;
4533
5515
  for (const b of MARK_BUTTONS) {
4534
- const btn = button(b.text, `${labels[b.label]} (${b.shortcut})`, `mbe-tool-${b.mark}`, () => {
5516
+ const btn = button(b.name, `${labels[b.name]} (${b.shortcut})`, `mbe-tool-${b.mark}`, () => {
4535
5517
  editor.run((s) => toggleMark(s, b.mark));
4536
5518
  this.update();
4537
5519
  });
@@ -4539,7 +5521,7 @@ var FormatToolbar = class {
4539
5521
  this.markButtons.set(b.mark, btn);
4540
5522
  }
4541
5523
  el.appendChild(separator(doc));
4542
- this.linkButton = button(labels.link, `${labels.link} (${mod("K")})`, "mbe-tool-link", () => editor.openLinkPopover());
5524
+ this.linkButton = button("link", `${labels.link} (${mod("K")})`, "mbe-tool-link", () => editor.openLinkPopover());
4543
5525
  }
4544
5526
  popup;
4545
5527
  markButtons = /* @__PURE__ */ new Map();
@@ -4704,10 +5686,12 @@ function renderBlock(block3, ctx, reveal) {
4704
5686
  case "heading":
4705
5687
  case "quote":
4706
5688
  root = el(block3.type === "paragraph" ? "p" : block3.type === "quote" ? "blockquote" : `h${block3.level}`);
5689
+ root.dir = "auto";
4707
5690
  fillContent(root, block3.content, ctx, block3, reveal);
4708
5691
  break;
4709
5692
  case "listItem": {
4710
5693
  root = el("div");
5694
+ root.dir = "auto";
4711
5695
  root.dataset.listType = block3.listType;
4712
5696
  root.dataset.indent = String(block3.indent);
4713
5697
  const marker = el("span", "mbe-marker");
@@ -4772,6 +5756,7 @@ function renderBlock(block3, ctx, reveal) {
4772
5756
  row.forEach((cell, c) => {
4773
5757
  const td = el(r === 0 ? "th" : "td");
4774
5758
  td.contentEditable = "true";
5759
+ td.dir = "auto";
4775
5760
  td.dataset.row = String(r);
4776
5761
  td.dataset.col = String(c);
4777
5762
  const align = block3.align[c];
@@ -4804,7 +5789,12 @@ function fillContent(target, inline3, ctx, block3, reveal, cell, decorated = tru
4804
5789
  return;
4805
5790
  }
4806
5791
  const decorations = decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
4807
- renderInline(inline3, target, ctx, decorations, reveal, cell);
5792
+ const only = inline3.length === 1 ? inline3[0] : null;
5793
+ if (only && decorations.length === 0 && only.marks.length === 0 && !only.link && !only.token && !only.image) {
5794
+ target.appendChild(doc.createTextNode(only.text));
5795
+ } else {
5796
+ renderInline(inline3, target, ctx, decorations, reveal, cell);
5797
+ }
4808
5798
  const last = inline3[inline3.length - 1];
4809
5799
  if (last && last.text.endsWith("\n")) target.appendChild(fill(doc));
4810
5800
  }
@@ -5166,7 +6156,8 @@ var BlockHandle = class {
5166
6156
  this.el = doc.createElement("button");
5167
6157
  this.el.type = "button";
5168
6158
  this.el.className = "mbe-ui mbe-handle";
5169
- this.el.textContent = "\u22EE\u22EE";
6159
+ const icon = iconNode(doc, editor.icon("blockHandle"));
6160
+ if (icon) this.el.appendChild(icon);
5170
6161
  this.el.setAttribute("aria-label", editor.labels.blockHandle);
5171
6162
  this.el.setAttribute("aria-haspopup", "menu");
5172
6163
  this.el.tabIndex = -1;
@@ -5204,15 +6195,15 @@ var BlockHandle = class {
5204
6195
  const blockEl = this.editor.blockElement(blockId);
5205
6196
  if (!blockEl) return this.hide();
5206
6197
  const doc = this.editor.root.ownerDocument;
5207
- if (!this.el.isConnected) doc.body.appendChild(this.el);
5208
6198
  this.blockId = blockId;
5209
6199
  this.el.hidden = false;
6200
+ const offset = attach(this.el, this.editor.root);
5210
6201
  const rect = blockEl.getBoundingClientRect();
5211
6202
  const lineHeight = parseFloat(doc.defaultView.getComputedStyle(blockEl).lineHeight) || 24;
5212
6203
  const firstLine = Math.min(rect.height, lineHeight);
5213
6204
  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`;
6205
+ this.el.style.left = `${Math.round(rect.left - (this.el.offsetWidth || 20) - 6 - offset.x)}px`;
6206
+ this.el.style.top = `${Math.round(rect.top + firstLine / 2 - size / 2 - offset.y)}px`;
5216
6207
  }
5217
6208
  hide() {
5218
6209
  this.cancelHide();
@@ -5270,6 +6261,47 @@ function viewEntry(block3, forward) {
5270
6261
  return { blockId: block3.id, offset: lastBreak > 0 ? lastBreak : text.length };
5271
6262
  }
5272
6263
 
6264
+ // src/view/scroll.ts
6265
+ var MARGIN = 8;
6266
+ function scrollRectIntoView(from, rect) {
6267
+ const doc = from.ownerDocument;
6268
+ const win = doc.defaultView;
6269
+ let top = rect.top;
6270
+ let bottom = rect.bottom;
6271
+ let left = rect.left;
6272
+ let right = rect.right;
6273
+ for (let el = from; el && el !== doc.body && el !== doc.documentElement; el = el.parentElement) {
6274
+ const style = win?.getComputedStyle(el);
6275
+ const scrollsY = el.scrollHeight > el.clientHeight && /auto|scroll|overlay/.test(style?.overflowY ?? "");
6276
+ const scrollsX = el.scrollWidth > el.clientWidth && /auto|scroll|overlay/.test(style?.overflowX ?? "");
6277
+ if (!scrollsY && !scrollsX) continue;
6278
+ const box = el.getBoundingClientRect();
6279
+ const viewTop = box.top + el.clientTop;
6280
+ const viewLeft = box.left + el.clientLeft;
6281
+ const dy2 = scrollsY ? delta(top, bottom, viewTop, viewTop + el.clientHeight) : 0;
6282
+ const dx2 = scrollsX ? delta(left, right, viewLeft, viewLeft + el.clientWidth) : 0;
6283
+ if (!dy2 && !dx2) continue;
6284
+ const beforeTop = el.scrollTop;
6285
+ const beforeLeft = el.scrollLeft;
6286
+ el.scrollTop += dy2;
6287
+ el.scrollLeft += dx2;
6288
+ top -= el.scrollTop - beforeTop;
6289
+ bottom -= el.scrollTop - beforeTop;
6290
+ left -= el.scrollLeft - beforeLeft;
6291
+ right -= el.scrollLeft - beforeLeft;
6292
+ }
6293
+ if (!win) return;
6294
+ const viewport = doc.documentElement;
6295
+ const dy = delta(top, bottom, 0, viewport.clientHeight);
6296
+ const dx = delta(left, right, 0, viewport.clientWidth);
6297
+ if (dy || dx) win.scrollBy(dx, dy);
6298
+ }
6299
+ function delta(start, end, viewStart, viewEnd) {
6300
+ if (start < viewStart + MARGIN) return start - viewStart - MARGIN;
6301
+ if (end > viewEnd - MARGIN) return Math.min(end - viewEnd + MARGIN, start - viewStart - MARGIN);
6302
+ return 0;
6303
+ }
6304
+
5273
6305
  // src/theme.ts
5274
6306
  function mergeClasses(maps) {
5275
6307
  const out = {};
@@ -5333,35 +6365,40 @@ var SLASH_ITEM_IDS = [
5333
6365
  "divider"
5334
6366
  ];
5335
6367
  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" } }
6368
+ { id: "text", aliases: ["paragraph", "plain"], spec: { type: "paragraph" } },
6369
+ { id: "heading1", aliases: ["h1", "title"], spec: { type: "heading", level: 1 } },
6370
+ { id: "heading2", aliases: ["h2", "subtitle"], spec: { type: "heading", level: 2 } },
6371
+ { id: "heading3", aliases: ["h3"], spec: { type: "heading", level: 3 } },
6372
+ { id: "bulletList", aliases: ["ul", "unordered", "bullet"], spec: { type: "listItem", listType: "bullet" } },
6373
+ { id: "numberedList", aliases: ["ol", "ordered"], spec: { type: "listItem", listType: "ordered" } },
6374
+ { id: "todoList", aliases: ["task", "checkbox", "checklist"], spec: { type: "listItem", listType: "task" } },
6375
+ { id: "quote", aliases: ["blockquote", "citation"], spec: { type: "quote" } },
6376
+ { id: "code", aliases: ["pre", "snippet", "fence"], spec: { type: "code" } },
6377
+ { id: "table", aliases: ["grid"], spec: { type: "table" } },
6378
+ { id: "divider", aliases: ["hr", "separator", "line", "rule"], spec: { type: "divider" } }
5347
6379
  ];
5348
6380
  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" } }
6381
+ { id: "addRowAbove", action: { kind: "addRowAbove" } },
6382
+ { id: "addRowBelow", action: { kind: "addRowBelow" } },
6383
+ { id: "addColumnLeft", action: { kind: "addColumnLeft" } },
6384
+ { id: "addColumnRight", action: { kind: "addColumnRight" } },
6385
+ { id: "alignLeft", action: { kind: "align", align: "left" } },
6386
+ { id: "alignCenter", action: { kind: "align", align: "center" } },
6387
+ { id: "alignRight", action: { kind: "align", align: "right" } },
6388
+ { id: "deleteRow", action: { kind: "deleteRow" } },
6389
+ { id: "deleteColumn", action: { kind: "deleteColumn" } }
5358
6390
  ];
5359
6391
  var SLASH_CHARS = ["/", "\uFF0F"];
6392
+ var CARET_KEY = /^(Arrow(Up|Down|Left|Right)|Home|End|PageUp|PageDown)$/;
5360
6393
  var COMPOSITION_INPUT = /* @__PURE__ */ new Set(["insertCompositionText", "deleteCompositionText", "insertFromComposition", "deleteByComposition"]);
5361
6394
  var Editor = class {
6395
+ /** The editable element the editor renders into: `options.element`, or for `useEditor`, the element `<EditorContent>` mounts. */
5362
6396
  root;
6397
+ /** @internal The UI strings: the defaults with the `labels` option applied. */
5363
6398
  labels;
5364
6399
  commands;
6400
+ /** The autocomplete popup of `suggestion()` extensions and the slash menu. */
6401
+ suggestion;
5365
6402
  current;
5366
6403
  /** The Markdown the document was loaded from; unchanged blocks are saved as this text. */
5367
6404
  source;
@@ -5375,11 +6412,15 @@ var Editor = class {
5375
6412
  * block, the marks for composed text, and whether it has an undo step yet.
5376
6413
  */
5377
6414
  composition = null;
6415
+ /** When the last composition ended (Safari only): the next key may be the Enter that committed it. */
6416
+ compositionEndedAt = 0;
5378
6417
  /** Blocks the browser edited during a composition that ended, rendered again on the next frame. */
5379
6418
  unsettled = /* @__PURE__ */ new Set();
5380
6419
  settleFrame = null;
5381
6420
  readOnly;
5382
6421
  wasReadOnly = false;
6422
+ /** Task checkboxes stay usable while read-only. */
6423
+ taskToggle;
5383
6424
  options;
5384
6425
  /** The extensions in priority order, ending with the default keymap unless one was given. */
5385
6426
  extensions;
@@ -5398,10 +6439,18 @@ var Editor = class {
5398
6439
  focused = false;
5399
6440
  /** A mouse button is down in the editor. Rendered views keep their state until it is released, so a drag is not disturbed. */
5400
6441
  pointerDown = false;
5401
- /** Suggestion menus from extensions, then the slash menu. */
6442
+ /** The selection the formatting toolbar was closed for with Escape. It stays closed until the selection changes. */
6443
+ toolbarClosedFor = null;
6444
+ /** Handling a key press, typed text, a paste or a drop: changes then scroll the caret into view. */
6445
+ typing = 0;
6446
+ /**
6447
+ * A caret key the browser is handling: the block the caret was in, the
6448
+ * caret's x, and 1 or -1 for a plain ArrowDown or ArrowUp. The next
6449
+ * selection change checks where the caret went (see `onSelectionChange`).
6450
+ */
6451
+ caretKey = null;
6452
+ /** Suggestion menus from extensions, then the slash menu (see suggest/controller.ts). */
5402
6453
  suggestions;
5403
- /** The open suggestion: which one, where its trigger is, and the last query shown. */
5404
- suggest = null;
5405
6454
  blockMenu;
5406
6455
  toolbar;
5407
6456
  linkPopover;
@@ -5423,6 +6472,7 @@ var Editor = class {
5423
6472
  this.runtime = {};
5424
6473
  this.labels = { ...DEFAULT_LABELS, ...options.labels };
5425
6474
  this.readOnly = options.editable === false;
6475
+ this.taskToggle = options.taskToggle === true;
5426
6476
  const given = options.extensions ?? [];
5427
6477
  this.extensions = given.some((e) => e.name === "defaultKeymap") ? given : [...given, defaultKeymap()];
5428
6478
  this.bindings = this.extensions.flatMap(
@@ -5459,30 +6509,48 @@ var Editor = class {
5459
6509
  this.runtime = { ...this.runtime, resolveImageSrc: options.resolveImageSrc };
5460
6510
  this.renderer.resolveImageSrc = options.resolveImageSrc;
5461
6511
  this.applyTheme(options.theme);
6512
+ setPopupContainer(root, options.popupContainer);
5462
6513
  const configs = this.extensions.flatMap((e) => e.suggestion ? [e.suggestion] : []);
5463
6514
  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
- }));
6515
+ this.suggestions = new SuggestionController(
6516
+ {
6517
+ editor: this,
6518
+ root,
6519
+ syncActiveDescendant: () => this.syncActiveDescendant(),
6520
+ refresh: () => this.updateUi(),
6521
+ endComposition: () => this.endComposition(),
6522
+ changed: (state) => this.emit("suggestionChange", { editor: this, state })
6523
+ },
6524
+ configs
6525
+ );
6526
+ const suggestions = this.suggestions;
6527
+ this.suggestion = {
6528
+ get state() {
6529
+ return suggestions.state;
6530
+ },
6531
+ open: (name) => !this.destroyed && (this.refreshSelection(), suggestions.open(name)),
6532
+ close: () => suggestions.dismiss(),
6533
+ move: (delta2) => suggestions.move(delta2),
6534
+ accept: (index) => !this.destroyed && suggestions.accept(index)
6535
+ };
5468
6536
  this.blockMenu = new Menu(root, "mbe-block-menu", "menu");
5469
6537
  this.blockMenu.onPicked = () => this.blockMenu.hide();
5470
6538
  this.linkPopover = new LinkPopover(this);
5471
6539
  this.toolbar = options.toolbar === false ? null : new FormatToolbar(this);
5472
6540
  this.handle = new BlockHandle(this);
5473
- this.listen(root, "beforeinput", (e) => this.onBeforeInput(e));
5474
- this.listen(root, "input", (e) => this.onInput(e));
6541
+ this.listen(root, "beforeinput", this.typed((e) => this.onBeforeInput(e)));
6542
+ this.listen(root, "input", this.typed((e) => this.onInput(e)));
5475
6543
  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));
6544
+ this.listen(root, "compositionend", this.typed((e) => this.onCompositionEnd(e)));
6545
+ this.listen(root, "keydown", this.typed((e) => this.onKeyDown(e)));
5478
6546
  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));
6547
+ this.listen(root, "cut", this.typed((e) => this.onCopy(e, true)));
6548
+ this.listen(root, "paste", this.typed((e) => this.onPaste(e)));
5481
6549
  this.listen(root, "dragstart", (e) => e.preventDefault());
5482
6550
  this.listen(root, "dragover", (e) => {
5483
6551
  if (!this.readOnly) e.preventDefault();
5484
6552
  });
5485
- this.listen(root, "drop", (e) => this.onDrop(e));
6553
+ this.listen(root, "drop", this.typed((e) => this.onDrop(e)));
5486
6554
  this.listen(root, "mousedown", (e) => this.onMouseDown(e));
5487
6555
  this.listen(root, "click", (e) => this.onClick(e));
5488
6556
  this.listen(root, "change", (e) => this.onControlChange(e));
@@ -5510,11 +6578,13 @@ var Editor = class {
5510
6578
  * undo history; with `history: 'keep'` the replacement is one undo step.
5511
6579
  */
5512
6580
  setMarkdown(markdown, options = {}) {
6581
+ if (this.destroyed) return;
5513
6582
  if (options.history === "keep") this.history.record(this.current, "other");
5514
6583
  else this.history.clear();
5515
6584
  const loaded = loadMarkdown(markdown, this.markdown);
5516
6585
  this.source = loaded.source;
5517
6586
  this.blockSel = null;
6587
+ this.suggestions.reset();
5518
6588
  const next = createState(loaded.doc);
5519
6589
  this.relocateWidgets(this.current.doc, next.doc, true);
5520
6590
  this.current = next;
@@ -5537,7 +6607,11 @@ var Editor = class {
5537
6607
  return this.composing;
5538
6608
  }
5539
6609
  get isEditable() {
5540
- return !this.readOnly;
6610
+ return !this.readOnly && !this.destroyed;
6611
+ }
6612
+ /** True after `destroy()`. The editor then ignores every call that would change it; `getMarkdown()` still returns its last Markdown. */
6613
+ get isDestroyed() {
6614
+ return this.destroyed;
5541
6615
  }
5542
6616
  /** True if `name` applies at the selection: a mark on the selected text, or the type of the block with the caret. */
5543
6617
  isActive(name, attrs) {
@@ -5588,6 +6662,7 @@ var Editor = class {
5588
6662
  * a value that is not a selection at all is ignored and returns false.
5589
6663
  */
5590
6664
  setSelection(selection) {
6665
+ if (this.destroyed) return false;
5591
6666
  const sel = isSelection(selection) ? clampSelection(this.current.doc, selection) : selectionFromJSON(this.current.doc, selection);
5592
6667
  if (!sel) return false;
5593
6668
  this.dropBlockSelection();
@@ -5620,6 +6695,13 @@ var Editor = class {
5620
6695
  * block is deleted, it moves to the nearest remaining block.
5621
6696
  */
5622
6697
  addWidget(options) {
6698
+ if (this.destroyed) {
6699
+ const widget2 = new WidgetImpl(this.root.ownerDocument.createElement("div"), "", () => {
6700
+ }, () => {
6701
+ });
6702
+ widget2.remove();
6703
+ return widget2;
6704
+ }
5623
6705
  const blocks = this.current.doc.blocks;
5624
6706
  const at = options.at === "end" ? endOf(blocks[blocks.length - 1]) : options.at;
5625
6707
  const blockId = clampSelection(this.current.doc, { anchor: at, focus: at }).focus.blockId;
@@ -5656,6 +6738,7 @@ var Editor = class {
5656
6738
  }
5657
6739
  /** Focuses the editor at the current selection. */
5658
6740
  focus() {
6741
+ if (this.destroyed) return;
5659
6742
  const pos = this.current.selection.focus;
5660
6743
  const el = this.renderer.elementFor(pos.blockId);
5661
6744
  const host = pos.cell && el ? contentElement(el, pos.cell) : this.root;
@@ -5667,13 +6750,24 @@ var Editor = class {
5667
6750
  }
5668
6751
  // -------------------------------------------------------------------------
5669
6752
  // Options and events
5670
- /** Changes `placeholder`, `editable`, `attributes`, `resolveImageSrc` or `theme`. */
6753
+ /**
6754
+ * Changes `placeholder`, `editable`, `taskToggle`, `attributes`,
6755
+ * `resolveImageSrc` or `theme`. `extensions` only updates the callbacks of
6756
+ * `suggestion()` extensions (`items`, `command`, `match`, `allow`), matched
6757
+ * by name; other changes to extensions need a new editor.
6758
+ */
5671
6759
  setOptions(options) {
6760
+ if (this.destroyed) return;
6761
+ if (options.extensions) this.suggestions.setConfigs(options.extensions.flatMap((e) => e.suggestion ? [e.suggestion] : []));
6762
+ const toggle = options.taskToggle !== void 0 && options.taskToggle !== this.taskToggle;
6763
+ if (toggle) this.taskToggle = options.taskToggle === true;
5672
6764
  if (options.editable !== void 0 && options.editable === this.readOnly) {
5673
6765
  this.readOnly = !options.editable;
5674
6766
  this.refreshRevealed();
5675
6767
  this.applyReadOnly();
5676
6768
  this.hideUi();
6769
+ } else if (toggle) {
6770
+ this.applyReadOnly();
5677
6771
  }
5678
6772
  this.applyRuntime(options);
5679
6773
  }
@@ -5728,9 +6822,11 @@ var Editor = class {
5728
6822
  // Commands
5729
6823
  /** Applies a command (a pure function of the state), records history, re-renders, and emits events. */
5730
6824
  run(command, kind = "other") {
5731
- if (this.readOnly) return false;
6825
+ if (this.readOnly || this.destroyed) return false;
5732
6826
  let next = command(this.current);
5733
6827
  if (!next || next === this.current) return false;
6828
+ next = dropBrokenTokens(next, this.current, this.markdown.inline);
6829
+ next = clampListIndents(next, this.current);
5734
6830
  if (next.doc !== this.current.doc && sameBlocks(next.doc, this.current.doc)) next = { ...next, doc: this.current.doc };
5735
6831
  if (next.doc === this.current.doc && next.selection === this.current.selection && next.storedMarks === this.current.storedMarks) {
5736
6832
  return false;
@@ -5741,7 +6837,7 @@ var Editor = class {
5741
6837
  createCommands() {
5742
6838
  const run = (fn) => this.run(fn);
5743
6839
  const block3 = (spec) => run((s) => toggleBlockType(s, spec));
5744
- return {
6840
+ const commands = {
5745
6841
  toggleBold: () => run((s) => toggleMark(s, "bold")),
5746
6842
  toggleItalic: () => run((s) => toggleMark(s, "italic")),
5747
6843
  toggleStrike: () => run((s) => toggleMark(s, "strike")),
@@ -5802,8 +6898,19 @@ var Editor = class {
5802
6898
  const had = this.hasFocus();
5803
6899
  this.blur();
5804
6900
  return had;
6901
+ },
6902
+ scrollIntoView: () => {
6903
+ const rect = this.caretRect();
6904
+ if (!rect) return false;
6905
+ scrollRectIntoView(this.root, rect);
6906
+ return true;
5805
6907
  }
5806
6908
  };
6909
+ for (const name of Object.keys(commands)) {
6910
+ const fn = commands[name];
6911
+ commands[name] = (...args) => !this.destroyed && fn(...args);
6912
+ }
6913
+ return commands;
5807
6914
  }
5808
6915
  toggleMark(mark) {
5809
6916
  return this.run((s) => toggleMark(s, mark));
@@ -5836,21 +6943,56 @@ var Editor = class {
5836
6943
  const content = el ? contentElement(el, this.current.selection.focus.cell) : null;
5837
6944
  return (content ?? el)?.getBoundingClientRect() ?? null;
5838
6945
  }
6946
+ /** @internal The caret at the model's selection focus. Unlike `selectionRect`, works while the editor is not focused. */
6947
+ caretRect() {
6948
+ const pos = this.current.selection.focus;
6949
+ const point = this.toDom(pos);
6950
+ if (point) {
6951
+ const range = this.root.ownerDocument.createRange();
6952
+ range.setStart(point.node, point.offset);
6953
+ const rects = range.getClientRects();
6954
+ const rect = rects[rects.length - 1];
6955
+ if (rect && rect.height > 0) return rect;
6956
+ }
6957
+ const el = this.renderer.elementFor(pos.blockId);
6958
+ return ((el && contentElement(el, pos.cell)) ?? el)?.getBoundingClientRect() ?? null;
6959
+ }
6960
+ /** @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. */
6961
+ textRect(from, to) {
6962
+ const start = this.toDom(from);
6963
+ const end = this.toDom(to);
6964
+ if (!start || !end) return null;
6965
+ const range = this.root.ownerDocument.createRange();
6966
+ range.setStart(start.node, start.offset);
6967
+ range.setEnd(end.node, end.offset);
6968
+ const rect = range.getClientRects()[0];
6969
+ if (!rect) return null;
6970
+ const el = start.node.nodeType === 1 ? start.node : start.node.parentElement;
6971
+ const rtl = !!el && this.root.ownerDocument.defaultView.getComputedStyle(el).direction === "rtl";
6972
+ return { rect, rtl };
6973
+ }
6974
+ /** Scrolls the editor and the elements around it so the caret is visible. */
6975
+ scrollCaretIntoView() {
6976
+ const rect = this.caretRect();
6977
+ if (rect) scrollRectIntoView(this.root, rect);
6978
+ }
5839
6979
  /** @internal The rendered element of a block. */
5840
6980
  blockElement(id) {
5841
6981
  return this.renderer.elementFor(id);
5842
6982
  }
5843
6983
  destroy() {
6984
+ if (this.destroyed) return;
5844
6985
  this.destroyed = true;
5845
6986
  if (this.changeFrame !== null) cancelAnimationFrame(this.changeFrame);
5846
6987
  if (this.settleFrame !== null) cancelAnimationFrame(this.settleFrame);
5847
6988
  for (const fn of this.cleanup) fn();
5848
- for (const { menu } of this.suggestions) menu.destroy();
6989
+ this.suggestions.destroy();
5849
6990
  for (const widget of [...this.widgets]) widget.remove();
5850
6991
  this.blockMenu.destroy();
5851
6992
  this.toolbar?.destroy();
5852
6993
  this.linkPopover.destroy();
5853
6994
  this.handle.destroy();
6995
+ setPopupContainer(this.root, void 0);
5854
6996
  for (const name of Object.keys(this.runtime.attributes ?? {})) this.root.removeAttribute(name);
5855
6997
  for (const name of this.tokenNames) this.root.style.removeProperty(name);
5856
6998
  this.root.style.colorScheme = "";
@@ -5867,6 +7009,7 @@ var Editor = class {
5867
7009
  }
5868
7010
  commit(next) {
5869
7011
  const docChanged = next.doc !== this.state.doc;
7012
+ const moved = next.selection !== this.state.selection;
5870
7013
  const hadFocus = this.hasFocus();
5871
7014
  if (docChanged) this.relocateWidgets(this.current.doc, next.doc, false);
5872
7015
  this.current = next;
@@ -5877,6 +7020,7 @@ var Editor = class {
5877
7020
  }
5878
7021
  this.paint(false, false, hadFocus);
5879
7022
  this.afterRender();
7023
+ if (moved && hadFocus && this.typing > 0) this.scrollCaretIntoView();
5880
7024
  if (docChanged) this.scheduleChange();
5881
7025
  this.emit("selectionChange", { editor: this });
5882
7026
  }
@@ -5906,6 +7050,7 @@ var Editor = class {
5906
7050
  * this). Returns false, doing nothing, when no one listens for submit.
5907
7051
  */
5908
7052
  submit() {
7053
+ if (this.destroyed) return false;
5909
7054
  if (!this.options.onSubmit && !this.listeners.get("submit")?.size) return false;
5910
7055
  this.flushChange();
5911
7056
  this.options.onSubmit?.(this.getMarkdown(), this);
@@ -5922,15 +7067,37 @@ var Editor = class {
5922
7067
  if (this.root.contentEditable !== editable) this.root.contentEditable = editable;
5923
7068
  if (!this.readOnly && !this.wasReadOnly) return;
5924
7069
  this.wasReadOnly = this.readOnly;
7070
+ const ticking = this.ticking;
5925
7071
  this.root.classList.toggle("mbe-readonly", this.readOnly);
7072
+ this.root.classList.toggle("mbe-tasks", ticking);
5926
7073
  this.root.setAttribute("aria-readonly", String(this.readOnly));
5927
7074
  this.root.querySelectorAll("[data-row]").forEach((cell) => {
5928
7075
  cell.contentEditable = this.readOnly ? "false" : "true";
5929
7076
  });
5930
7077
  this.root.querySelectorAll("input").forEach((input) => {
5931
- input.disabled = this.readOnly;
7078
+ const box = input.classList.contains("mbe-checkbox");
7079
+ input.disabled = this.readOnly && !(box && ticking);
7080
+ if (!box) return;
7081
+ input.tabIndex = ticking ? 0 : -1;
7082
+ if (ticking) input.setAttribute("aria-label", taskName(input, this.labels.task));
7083
+ else input.removeAttribute("aria-label");
5932
7084
  });
5933
7085
  }
7086
+ /** True while read-only with task toggling on: only task checkboxes respond. */
7087
+ get ticking() {
7088
+ return this.readOnly && this.taskToggle;
7089
+ }
7090
+ /** Toggles a task item from its checkbox, while editing or while read-only with `taskToggle`. */
7091
+ toggleTaskAt(box) {
7092
+ const blockEl = box.closest("[data-block-id]");
7093
+ if (!blockEl) return;
7094
+ const id = blockEl.dataset.blockId;
7095
+ const focused = box === this.root.ownerDocument.activeElement;
7096
+ if (!this.readOnly) this.run((s) => toggleTask(s, id));
7097
+ else if (this.ticking && this.current.doc.blocks.some((b) => b.id === id)) this.apply(toggleTask(this.current, id), "other");
7098
+ else return;
7099
+ if (focused) this.root.querySelector(`[data-block-id="${id}"] .mbe-checkbox`)?.focus({ preventScroll: true });
7100
+ }
5934
7101
  /** Hints for empty blocks, and the UI that follows the selection. */
5935
7102
  afterRender() {
5936
7103
  for (const block3 of this.state.doc.blocks) {
@@ -5983,6 +7150,8 @@ var Editor = class {
5983
7150
  if (!this.hasFocus()) this.updateUi();
5984
7151
  return;
5985
7152
  }
7153
+ const key = this.caretKey;
7154
+ this.caretKey = null;
5986
7155
  if (this.blockSel) {
5987
7156
  this.updateUi();
5988
7157
  return;
@@ -5992,11 +7161,51 @@ var Editor = class {
5992
7161
  this.updateUi();
5993
7162
  return;
5994
7163
  }
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 });
7164
+ const skipped = key?.vertical ? this.skippedBlock(key.from, key.vertical, key.x, selection.focus) : null;
7165
+ if (skipped) {
7166
+ this.setSelection({ anchor: skipped, focus: skipped });
7167
+ } else {
7168
+ this.current = { ...this.state, selection, storedMarks: null };
7169
+ this.history.breakGroup();
7170
+ if (!this.pointerDown) this.refreshRevealed();
7171
+ this.updateUi();
7172
+ this.emit("selectionChange", { editor: this });
7173
+ }
7174
+ if (key) this.scrollCaretIntoView();
7175
+ }
7176
+ /**
7177
+ * After the browser moved the caret from block `from` with ArrowDown
7178
+ * (`dir` 1) or ArrowUp to `to`: the position in the first block it passed
7179
+ * over that holds a caret, at `x`. Firefox passes over list items (they are
7180
+ * flex boxes), WebKit over code blocks and tables. Null when no block was
7181
+ * passed over.
7182
+ */
7183
+ skippedBlock(from, dir, x, to) {
7184
+ const blocks = this.state.doc.blocks;
7185
+ const end = blockIndex(this.state.doc, to.blockId);
7186
+ for (let i = from + dir; (end - i) * dir > 0; i += dir) {
7187
+ const block3 = blocks[i];
7188
+ if (block3.type !== "divider") return this.blockEntry(block3, dir === 1, x);
7189
+ }
7190
+ return null;
7191
+ }
7192
+ /** Where the caret goes moving into `block` from above (`forward`) or below: its first or last line, at `x`. */
7193
+ blockEntry(block3, forward, x) {
7194
+ const el = this.renderer.elementFor(block3.id);
7195
+ if (block3.type === "raw" && el?.classList.contains("mbe-view-block")) return viewEntry(block3, forward);
7196
+ if (el) {
7197
+ const range = el.ownerDocument.createRange();
7198
+ range.selectNodeContents(contentElement(el) ?? el);
7199
+ const lines = Array.from(range.getClientRects()).filter((r) => r.height > 0);
7200
+ const line = forward ? lines[0] : lines[lines.length - 1];
7201
+ const pos = line ? this.positionAtPoint(x, line.top + line.height / 2) : null;
7202
+ if (pos?.blockId === block3.id) return pos;
7203
+ }
7204
+ if (block3.type === "table") {
7205
+ const row = forward ? 0 : block3.rows.length - 1;
7206
+ return { blockId: block3.id, offset: forward ? 0 : inlineLength(block3.rows[row][0]), cell: { row, col: 0 } };
7207
+ }
7208
+ return forward ? startOf(block3) : endOf(block3);
6000
7209
  }
6001
7210
  /**
6002
7211
  * Renders the document, then puts the browser selection back. Only blocks
@@ -6026,10 +7235,12 @@ var Editor = class {
6026
7235
  }
6027
7236
  /**
6028
7237
  * 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.
7238
+ * block or a table next to it, the position inside that block to move to
7239
+ * instead: the browser skips non-editable blocks, and sometimes a table
7240
+ * (its cells are separate editing hosts). A table is entered in its first
7241
+ * column.
6031
7242
  */
6032
- viewBlockPast(key) {
7243
+ blockPast(key) {
6033
7244
  const sel = this.state.selection;
6034
7245
  if (!isCollapsed(sel) || sel.focus.cell) return null;
6035
7246
  const pos = sel.focus;
@@ -6037,18 +7248,73 @@ var Editor = class {
6037
7248
  const index = blockIndex(this.state.doc, pos.blockId);
6038
7249
  const forward = key === "ArrowDown" || key === "ArrowRight";
6039
7250
  const next = blocks[index + (forward ? 1 : -1)];
6040
- if (next?.type !== "raw" || !this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block")) return null;
7251
+ const view = next?.type === "raw" && this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block");
7252
+ if (!next || !view && next.type !== "table") return null;
6041
7253
  const current = blocks[index];
6042
7254
  if (!isTextBlock(current)) return null;
6043
7255
  if (key === "ArrowRight" && pos.offset !== endOf(current).offset) return null;
6044
7256
  if (key === "ArrowLeft" && pos.offset !== 0) return null;
6045
7257
  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;
7258
+ const content = contentElement(this.renderer.elementFor(current.id));
7259
+ if (content && !this.onEdgeLine(content, forward)) return null;
7260
+ }
7261
+ if (next.type === "table") {
7262
+ const row = forward ? 0 : next.rows.length - 1;
7263
+ return { blockId: next.id, offset: forward ? 0 : inlineLength(next.rows[row][0]), cell: { row, col: 0 } };
6049
7264
  }
6050
7265
  return viewEntry(next, forward);
6051
7266
  }
7267
+ /**
7268
+ * ArrowUp or ArrowDown on the first or last line of a table cell: the
7269
+ * position in the cell above or below (same column), or past the table in
7270
+ * the next block that holds a caret. Null when the caret is not on that
7271
+ * line, or when the table ends the document that way (`exitBlock` adds a
7272
+ * paragraph there).
7273
+ */
7274
+ tableCellPast(dir) {
7275
+ const sel = this.state.selection;
7276
+ const pos = sel.focus;
7277
+ if (!isCollapsed(sel) || !pos.cell) return null;
7278
+ const blocks = this.state.doc.blocks;
7279
+ const index = blockIndex(this.state.doc, pos.blockId);
7280
+ const table2 = blocks[index];
7281
+ if (table2?.type !== "table") return null;
7282
+ const content = contentElement(this.renderer.elementFor(table2.id), pos.cell);
7283
+ if (content && !this.onEdgeLine(content, dir === 1)) return null;
7284
+ const { row, col } = pos.cell;
7285
+ const target = table2.rows[row + dir];
7286
+ if (target) {
7287
+ const offset = Math.min(pos.offset, inlineLength(target[col]));
7288
+ return { blockId: table2.id, offset, cell: { row: row + dir, col } };
7289
+ }
7290
+ for (let i = index + dir; i >= 0 && i < blocks.length; i += dir) {
7291
+ const next = blocks[i];
7292
+ if (next.type === "divider") continue;
7293
+ if (next.type === "table") {
7294
+ const r = dir === 1 ? 0 : next.rows.length - 1;
7295
+ const c = Math.min(col, next.align.length - 1);
7296
+ return { blockId: next.id, offset: dir === 1 ? 0 : inlineLength(next.rows[r][c]), cell: { row: r, col: c } };
7297
+ }
7298
+ if (next.type === "raw" && this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block")) return viewEntry(next, dir === 1);
7299
+ return dir === 1 ? startOf(next) : endOf(next);
7300
+ }
7301
+ return null;
7302
+ }
7303
+ /**
7304
+ * Whether the caret is on the last (`forward`) or first line of the text in
7305
+ * `content`. Lines are measured from the text, not the element's box, which
7306
+ * has padding (a table cell) and may be taller than its text.
7307
+ */
7308
+ onEdgeLine(content, forward) {
7309
+ const caret2 = this.selectionRect();
7310
+ if (!caret2 || caret2.height === 0) return true;
7311
+ const range = content.ownerDocument.createRange();
7312
+ range.selectNodeContents(content);
7313
+ const lines = Array.from(range.getClientRects()).filter((r) => r.height > 0);
7314
+ if (lines.length === 0) return true;
7315
+ const half = caret2.height / 2;
7316
+ return forward ? Math.max(...lines.map((r) => r.bottom)) - caret2.bottom <= half : caret2.top - Math.min(...lines.map((r) => r.top)) <= half;
7317
+ }
6052
7318
  /** 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
7319
  revealView(view) {
6054
7320
  const block3 = view.hasAttribute(BLOCK_ATTR) ? getBlock(this.state.doc, view.getAttribute(BLOCK_ATTR)) : null;
@@ -6108,11 +7374,7 @@ var Editor = class {
6108
7374
  return;
6109
7375
  }
6110
7376
  case "insertParagraph": {
6111
- const menu = this.openMenu();
6112
- if (menu && menu !== this.blockMenu && menu.count > 0) {
6113
- menu.pick();
6114
- return;
6115
- }
7377
+ if (this.suggestions.isOpen && this.suggestions.accept()) return;
6116
7378
  this.run(splitBlock);
6117
7379
  return;
6118
7380
  }
@@ -6185,7 +7447,7 @@ var Editor = class {
6185
7447
  if (text.length === 1 && "*_`~".includes(text)) this.run((s) => applyInlineInputRules(s));
6186
7448
  if (this.markdown.inline.length > 0) this.run((s) => applyTokenInputRules(s, this.markdown.inline) ?? s);
6187
7449
  if (text === " " && this.markdown.autolinks) this.run((s) => applyAutolinkInputRule(s) ?? s);
6188
- if ([...text].length === 1) this.maybeOpenSuggestion(text);
7450
+ if (!text.includes("\n")) this.typedForSuggestion();
6189
7451
  }
6190
7452
  onCompositionStart(e) {
6191
7453
  if (this.fromControl(e)) return;
@@ -6205,6 +7467,7 @@ var Editor = class {
6205
7467
  }
6206
7468
  this.syncComposition();
6207
7469
  this.composing = false;
7470
+ if (isSafari) this.compositionEndedAt = Date.now();
6208
7471
  this.unsettled.add(this.composition.blockId);
6209
7472
  if (this.settleFrame === null) {
6210
7473
  const settle = () => {
@@ -6223,17 +7486,14 @@ var Editor = class {
6223
7486
  this.unsettled.clear();
6224
7487
  this.paint();
6225
7488
  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);
7489
+ if (composed) this.typedForSuggestion();
6232
7490
  }
6233
7491
  onInput(e) {
6234
7492
  if (this.fromControl(e)) return;
6235
7493
  if (this.composing || this.composition && COMPOSITION_INPUT.has(e.inputType)) {
7494
+ const before2 = this.composedLength();
6236
7495
  this.syncComposition();
7496
+ if (this.composing && this.composedLength() > before2) this.typedForSuggestion();
6237
7497
  return;
6238
7498
  }
6239
7499
  if (e.isComposing) return;
@@ -6241,6 +7501,27 @@ var Editor = class {
6241
7501
  this.reconcileFromDom("typing");
6242
7502
  if (e.inputType === "insertText" && e.data && this.state !== before) this.afterTyping(e.data);
6243
7503
  }
7504
+ /** The length of the composed block's or cell's text. */
7505
+ composedLength() {
7506
+ const pos = this.state.selection.focus;
7507
+ const block3 = this.state.doc.blocks.find((b) => b.id === this.composition?.blockId);
7508
+ const content = block3 && containerContent(block3, block3.id === pos.blockId ? pos.cell : void 0);
7509
+ return content ? inlineLength(content) : 0;
7510
+ }
7511
+ /**
7512
+ * Ends the composition on purpose: reads the composed text into the model
7513
+ * and renders the block from it, which ends the browser's composition.
7514
+ * Picking a suggestion item while composing does this first.
7515
+ */
7516
+ endComposition() {
7517
+ if (!this.composing || !this.composition) return;
7518
+ this.syncComposition();
7519
+ this.composing = false;
7520
+ this.unsettled.add(this.composition.blockId);
7521
+ if (this.settleFrame !== null) cancelAnimationFrame(this.settleFrame);
7522
+ this.settleFrame = null;
7523
+ this.settleComposition();
7524
+ }
6244
7525
  /**
6245
7526
  * Reads the composed text into the model while composing. The browser's
6246
7527
  * DOM for the block already shows it, so the block is not re-rendered.
@@ -6288,8 +7569,8 @@ var Editor = class {
6288
7569
  if (blockId !== void 0 && block3.id !== blockId) continue;
6289
7570
  const el = this.renderer.elementFor(block3.id);
6290
7571
  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) {
7572
+ const containers2 = block3.type === "table" ? block3.rows.flatMap((row, r) => row.map((_, c) => ({ cell: { row: r, col: c } }))) : block3.type === "divider" ? [] : [{}];
7573
+ for (const { cell } of containers2) {
6293
7574
  const contentEl = contentElement(el, cell);
6294
7575
  const content = containerContent(getBlock(state.doc, block3.id), cell);
6295
7576
  if (!contentEl || !content) continue;
@@ -6314,6 +7595,7 @@ var Editor = class {
6314
7595
  return changed ? state : null;
6315
7596
  }
6316
7597
  onKeyDown(e) {
7598
+ this.caretKey = null;
6317
7599
  if (this.fromControl(e)) return;
6318
7600
  if (e.isComposing || e.keyCode === 229) return;
6319
7601
  const mod2 = isMac ? e.metaKey : e.ctrlKey;
@@ -6323,17 +7605,28 @@ var Editor = class {
6323
7605
  this.refreshSelection();
6324
7606
  fn();
6325
7607
  };
6326
- const menu = this.openMenu();
7608
+ const justComposed = Date.now() - this.compositionEndedAt < 100;
7609
+ this.compositionEndedAt = 0;
7610
+ if (this.suggestions.isOpen && !justComposed) {
7611
+ this.refreshSelection();
7612
+ if (this.suggestions.keydown(e)) {
7613
+ e.preventDefault();
7614
+ return;
7615
+ }
7616
+ }
7617
+ const menu = this.blockMenu.isOpen ? this.blockMenu : null;
6327
7618
  if (menu) {
6328
7619
  if (e.key === "ArrowDown" || e.key === "Tab" && !e.shiftKey) return handled(() => this.moveMenu(menu, 1));
6329
7620
  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());
7621
+ if (e.key === "Enter" && menu.count > 0) return handled(() => menu.pick());
7622
+ if (e.key === "Escape") return handled(() => this.closeBlockMenu());
7623
+ }
7624
+ if (e.key === "Escape" && this.toolbar?.isOpen) {
7625
+ return handled(() => {
7626
+ this.toolbarClosedFor = this.state.selection;
7627
+ this.toolbar.hide();
7628
+ });
6335
7629
  }
6336
- if (e.key === "Escape" && this.toolbar?.isOpen) return handled(() => this.toolbar.hide());
6337
7630
  if (this.readOnly) return;
6338
7631
  if (this.blockSel && this.onBlockKey(e)) {
6339
7632
  e.preventDefault();
@@ -6349,6 +7642,15 @@ var Editor = class {
6349
7642
  return;
6350
7643
  }
6351
7644
  }
7645
+ if (e.key === "Backspace" && !e.ctrlKey && !e.metaKey && !e.altKey) {
7646
+ this.refreshSelection();
7647
+ const { selection } = this.state;
7648
+ if (isCollapsed(selection) && selection.focus.offset === 0) {
7649
+ e.preventDefault();
7650
+ this.run(deleteBackward);
7651
+ return;
7652
+ }
7653
+ }
6352
7654
  if (mod2 && !e.altKey) {
6353
7655
  if (e.key === "/" && !e.shiftKey && this.hasBlockMenu(this.state.selection.focus.blockId)) {
6354
7656
  return handled(() => this.openBlockMenu(this.state.selection.focus.blockId));
@@ -6360,25 +7662,53 @@ var Editor = class {
6360
7662
  }
6361
7663
  if (e.key.startsWith("Arrow") && !mod2 && !e.shiftKey && !e.altKey) {
6362
7664
  this.refreshSelection();
6363
- const into = this.renderer.views ? this.viewBlockPast(e.key) : null;
7665
+ const into = this.blockPast(e.key);
6364
7666
  if (into) {
6365
7667
  e.preventDefault();
6366
7668
  this.setSelection({ anchor: into, focus: into });
6367
7669
  return;
6368
7670
  }
6369
7671
  const vertical = e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
7672
+ const cell = vertical ? this.tableCellPast(vertical) : null;
7673
+ if (cell) {
7674
+ e.preventDefault();
7675
+ this.setSelection({ anchor: cell, focus: cell });
7676
+ return;
7677
+ }
6370
7678
  const next = vertical ? exitBlock(this.state, vertical) : this.state;
6371
7679
  if (next !== this.state) {
6372
7680
  e.preventDefault();
6373
7681
  this.run(() => next);
7682
+ return;
6374
7683
  }
6375
7684
  }
7685
+ if (CARET_KEY.test(e.key)) {
7686
+ this.refreshSelection();
7687
+ const plain2 = !mod2 && !e.shiftKey && !e.altKey;
7688
+ const vertical = !plain2 ? 0 : e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
7689
+ const from = blockIndex(this.state.doc, this.state.selection.focus.blockId);
7690
+ this.caretKey = { from, x: this.selectionRect()?.left ?? 0, vertical };
7691
+ }
7692
+ }
7693
+ /** Selects all the text of the block (or table cell) holding `target`. False if it holds none. */
7694
+ selectBlockText(target) {
7695
+ const blockEl = target.closest?.(`[${BLOCK_ATTR}]`);
7696
+ if (!blockEl || !this.root.contains(blockEl)) return false;
7697
+ const block3 = getBlock(this.state.doc, blockEl.getAttribute(BLOCK_ATTR));
7698
+ const cellEl = target.closest("[data-row]");
7699
+ const cell = block3.type === "table" && cellEl ? { row: Number(cellEl.dataset.row), col: Number(cellEl.dataset.col) } : void 0;
7700
+ const content = containerContent(block3, cell);
7701
+ if (!content || block3.type === "raw" && blockEl.classList.contains("mbe-view-block")) return false;
7702
+ const at = (offset) => cell ? { blockId: block3.id, offset, cell } : { blockId: block3.id, offset };
7703
+ this.setSelection({ anchor: at(0), focus: at(inlineLength(content)) });
7704
+ return true;
6376
7705
  }
6377
- moveMenu(menu, delta) {
6378
- menu.move(delta);
7706
+ moveMenu(menu, delta2) {
7707
+ menu.move(delta2);
6379
7708
  this.syncActiveDescendant();
6380
7709
  }
6381
7710
  onMouseDown(e) {
7711
+ this.caretKey = null;
6382
7712
  const target = e.target;
6383
7713
  this.dropBlockSelection();
6384
7714
  if (target === this.root && e.button === 0 && !this.readOnly && this.clickBelowLastBlock(e)) return;
@@ -6388,11 +7718,14 @@ var Editor = class {
6388
7718
  this.revealView(view);
6389
7719
  return;
6390
7720
  }
7721
+ if (e.button === 0 && e.detail === 3 && !this.readOnly && this.selectBlockText(target)) {
7722
+ e.preventDefault();
7723
+ return;
7724
+ }
6391
7725
  if (e.button === 0) this.pointerDown = true;
6392
7726
  if (target.classList?.contains("mbe-checkbox")) {
6393
7727
  e.preventDefault();
6394
- const blockEl = target.closest("[data-block-id]");
6395
- if (blockEl && !this.readOnly) this.run((s) => toggleTask(s, blockEl.dataset.blockId));
7728
+ if (e.button === 0) this.toggleTaskAt(target);
6396
7729
  }
6397
7730
  }
6398
7731
  /**
@@ -6416,6 +7749,7 @@ var Editor = class {
6416
7749
  const target = e.target;
6417
7750
  if (target.classList?.contains("mbe-checkbox")) {
6418
7751
  e.preventDefault();
7752
+ if (e.detail === 0) this.toggleTaskAt(target);
6419
7753
  return;
6420
7754
  }
6421
7755
  const link = target.closest?.("a.mbe-link");
@@ -6459,7 +7793,7 @@ var Editor = class {
6459
7793
  }
6460
7794
  onScroll() {
6461
7795
  this.handle.hide();
6462
- if (this.suggest || this.toolbar?.isOpen || this.blockMenu.isOpen) this.updateUi();
7796
+ if (this.suggestions.isActive || this.toolbar?.isOpen || this.blockMenu.isOpen) this.updateUi();
6463
7797
  }
6464
7798
  // -------------------------------------------------------------------------
6465
7799
  // Clipboard
@@ -6555,105 +7889,21 @@ var Editor = class {
6555
7889
  return domToPosition(this.root, node, offset);
6556
7890
  }
6557
7891
  // -------------------------------------------------------------------------
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 });
7892
+ // Suggestion menus (see suggest/controller.ts)
7893
+ /** After typing: opens the suggestion whose token is at the caret, if any. */
7894
+ typedForSuggestion() {
7895
+ if (this.suggestions.typed()) this.updateUi();
6648
7896
  }
6649
7897
  /** The slash menu, as a suggestion. */
6650
7898
  slashSuggestion() {
6651
7899
  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 }));
7900
+ 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
7901
  return {
6654
- char: SLASH_CHARS,
7902
+ name: "slash",
7903
+ trigger: SLASH_CHARS,
6655
7904
  allowSpaces: true,
6656
7905
  emptyLabel: this.labels.noResults,
7906
+ label: this.labels.commands,
6657
7907
  className: "mbe-slash-menu",
6658
7908
  items: ({ query }) => items.filter((item) => matches(item, query)),
6659
7909
  command: ({ range, item }) => {
@@ -6688,7 +7938,7 @@ var Editor = class {
6688
7938
  this.blockSel = { anchor, head };
6689
7939
  this.current = { ...this.current, selection: spanBlocks(this.current.doc.blocks, this.blockRange()), storedMarks: null };
6690
7940
  this.history.breakGroup();
6691
- this.closeSuggestion();
7941
+ this.suggestions.close();
6692
7942
  this.toolbar?.hide();
6693
7943
  this.blockMenu.hide();
6694
7944
  this.refreshRevealed();
@@ -6803,29 +8053,34 @@ var Editor = class {
6803
8053
  }
6804
8054
  // -------------------------------------------------------------------------
6805
8055
  // Block menu
8056
+ /** @internal The icon for a UI control: the `icons` option's entry, or the built-in Lucide icon. */
8057
+ icon(name) {
8058
+ return this.options.icons?.[name] ?? builtinIcon(this.root.ownerDocument, name);
8059
+ }
6806
8060
  blockMenuSections(blockId) {
6807
8061
  const block3 = getBlock(this.state.doc, blockId);
6808
- const sections = [];
8062
+ const sections2 = [];
6809
8063
  if (block3.type === "table" && this.state.selection.focus.blockId === blockId && this.state.selection.focus.cell) {
6810
- sections.push({
8064
+ sections2.push({
6811
8065
  title: this.labels.tableSection,
6812
- items: TABLE_ITEMS.map(({ id, icon, action }) => ({
8066
+ items: TABLE_ITEMS.map(({ id, action }) => ({
6813
8067
  id,
6814
8068
  label: this.labels[id],
6815
- icon,
8069
+ icon: this.icon(id),
6816
8070
  run: () => this.run((s) => tableAction(s, action))
6817
8071
  }))
6818
8072
  });
6819
8073
  }
6820
- sections.push({
8074
+ sections2.push({
6821
8075
  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)) }
8076
+ { id: "duplicate", label: this.labels.duplicate, icon: this.icon("duplicate"), run: () => this.run((s) => duplicateBlock(s, blockId)) },
8077
+ { id: "delete", label: this.labels.delete, icon: this.icon("delete"), danger: true, run: () => this.run((s) => deleteBlock(s, blockId)) }
6824
8078
  ]
6825
8079
  });
6826
- return sections;
8080
+ return sections2;
6827
8081
  }
6828
8082
  /**
8083
+ * @internal
6829
8084
  * Only large blocks get the handle and block menu: tables and code blocks.
6830
8085
  * Other blocks change type through the slash menu or Markdown shortcuts.
6831
8086
  */
@@ -6833,10 +8088,11 @@ var Editor = class {
6833
8088
  const block3 = this.state.doc.blocks.find((b) => b.id === blockId);
6834
8089
  return block3?.type === "table" || block3?.type === "code";
6835
8090
  }
8091
+ /** @internal Opens the block menu of a table or code block, as the block handle and Mod+/ do. */
6836
8092
  openBlockMenu(blockId, anchor) {
6837
8093
  if (this.readOnly || !this.hasBlockMenu(blockId)) return;
6838
8094
  this.dropBlockSelection();
6839
- this.closeSuggestion();
8095
+ this.suggestions.close();
6840
8096
  this.toolbar?.hide();
6841
8097
  if (this.state.selection.focus.blockId !== blockId) {
6842
8098
  const block3 = getBlock(this.state.doc, blockId);
@@ -6855,6 +8111,7 @@ var Editor = class {
6855
8111
  }
6856
8112
  // -------------------------------------------------------------------------
6857
8113
  // Toolbar and link popover (see ui/toolbar.ts)
8114
+ /** @internal Opens the link popover for the selection, as Mod+K does. */
6858
8115
  openLinkPopover() {
6859
8116
  if (this.readOnly) return;
6860
8117
  const block3 = getBlock(this.state.doc, this.state.selection.focus.blockId);
@@ -6885,15 +8142,12 @@ var Editor = class {
6885
8142
  nextHint?.classList.add("mbe-show-hint");
6886
8143
  this.hintEl = nextHint;
6887
8144
  }
6888
- const query = focused ? this.suggestionQuery() : null;
6889
- if (query === null) {
6890
- if (this.suggest) this.closeSuggestion();
6891
- } else {
6892
- this.refreshSuggestion(query);
6893
- }
8145
+ this.suggestions.update(focused);
6894
8146
  if (this.toolbar) {
6895
8147
  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";
8148
+ const closed = this.toolbarClosedFor;
8149
+ if (closed && !(samePosition(closed.anchor, this.state.selection.anchor) && samePosition(closed.focus, pos))) this.toolbarClosedFor = null;
8150
+ 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
8151
  if (show) this.toolbar.show();
6898
8152
  else this.toolbar.hide();
6899
8153
  }
@@ -6904,24 +8158,31 @@ var Editor = class {
6904
8158
  if (!focused && this.blockMenu.isOpen && !this.root.ownerDocument.activeElement?.closest?.(".mbe-ui")) this.blockMenu.hide();
6905
8159
  this.syncActiveDescendant();
6906
8160
  }
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
8161
  syncActiveDescendant() {
6912
- const id = this.openMenu()?.activeDescendant;
8162
+ const id = this.suggestions.activeDescendant ?? (this.blockMenu.isOpen ? this.blockMenu.activeDescendant : null);
6913
8163
  if (id) this.root.setAttribute("aria-activedescendant", id);
6914
8164
  else this.root.removeAttribute("aria-activedescendant");
6915
8165
  }
6916
8166
  hideUi() {
6917
8167
  this.dropBlockSelection();
6918
- this.closeSuggestion();
8168
+ this.suggestions.close();
6919
8169
  this.blockMenu.hide();
6920
8170
  this.toolbar?.hide();
6921
8171
  this.handle.hide();
6922
8172
  this.hintEl?.classList.remove("mbe-show-hint");
6923
8173
  this.hintEl = null;
6924
8174
  }
8175
+ /** Wraps an input event handler so the changes it makes keep the caret in view. */
8176
+ typed(fn) {
8177
+ return (e) => {
8178
+ this.typing++;
8179
+ try {
8180
+ fn(e);
8181
+ } finally {
8182
+ this.typing--;
8183
+ }
8184
+ };
8185
+ }
6925
8186
  listen(target, type, fn, capture = false) {
6926
8187
  target.addEventListener(type, fn, capture);
6927
8188
  this.cleanup.push(() => target.removeEventListener(type, fn, capture));
@@ -6971,11 +8232,9 @@ function selectionFromJSON(doc, value) {
6971
8232
  if (!anchor || !focus) return null;
6972
8233
  return clampSelection(doc, { anchor, focus });
6973
8234
  }
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";
8235
+ function taskName(box, fallback) {
8236
+ const text = box.closest("[data-block-id]")?.querySelector(".mbe-content")?.textContent?.trim();
8237
+ return text || fallback;
6979
8238
  }
6980
8239
 
6981
8240
  // src/extensions/math.ts
@@ -7185,8 +8444,7 @@ function build(name, char, scan, defaultClass, options) {
7185
8444
  return {
7186
8445
  name,
7187
8446
  markdown: { inline: [escapeSyntax(char)] },
7188
- decorations: decorate2(options.scan ?? scan, options.class ?? defaultClass, options.attributes),
7189
- suggestion: options.suggestion && { ...options.suggestion, char }
8447
+ decorations: decorate2(options.scan ?? scan, options.class ?? defaultClass, options.attributes)
7190
8448
  };
7191
8449
  }
7192
8450
  function tags(options = {}) {
@@ -7198,7 +8456,7 @@ function mentions(options = {}) {
7198
8456
 
7199
8457
  // src/extensions/suggestion.ts
7200
8458
  function suggestion(config) {
7201
- return { name: config.name ?? "suggestion", suggestion: config };
8459
+ return { name: config.name, suggestion: config };
7202
8460
  }
7203
8461
 
7204
8462
  // src/extensions/fileHandler.ts
@@ -7268,6 +8526,7 @@ export {
7268
8526
  listItem,
7269
8527
  loadMarkdown,
7270
8528
  marksAt,
8529
+ matchToken,
7271
8530
  math,
7272
8531
  mentions,
7273
8532
  normalizeInline,
@@ -7301,4 +8560,17 @@ export {
7301
8560
  withContainerContent,
7302
8561
  withContent
7303
8562
  };
8563
+ /*! Icons from Lucide (lucide-static 1.55.0), https://lucide.dev
8564
+ * ISC License. Copyright (c) 2026 Lucide Icons and Contributors.
8565
+ * Permission to use, copy, modify, and/or distribute this software for any
8566
+ * purpose with or without fee is hereby granted, provided that the above
8567
+ * copyright notice and this permission notice appear in all copies.
8568
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8569
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
8570
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
8571
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
8572
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
8573
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
8574
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
8575
+ */
7304
8576
  //# sourceMappingURL=index.js.map