@usememos/editor 26.10.9 → 26.10.10

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
@@ -16,6 +16,7 @@ __export(commands_exports, {
16
16
  applyTokenInputRules: () => applyTokenInputRules,
17
17
  clampListIndents: () => clampListIndents,
18
18
  cloneBlock: () => cloneBlock,
19
+ convertibleBlocks: () => convertibleBlocks,
19
20
  deleteBackward: () => deleteBackward,
20
21
  deleteBlock: () => deleteBlock,
21
22
  deleteBlocks: () => deleteBlocks,
@@ -42,6 +43,7 @@ __export(commands_exports, {
42
43
  selectImage: () => selectImage,
43
44
  selectedBlocks: () => selectedBlocks,
44
45
  selectedImage: () => selectedImage,
46
+ selectedImageBlock: () => selectedImageBlock,
45
47
  setBlockType: () => setBlockType,
46
48
  setCodeLanguage: () => setCodeLanguage,
47
49
  setLink: () => setLink,
@@ -120,6 +122,24 @@ function isTextBlock(block3) {
120
122
  function isPlainTextBlock(block3) {
121
123
  return block3.type === "code" || block3.type === "raw";
122
124
  }
125
+ function imageBlockOffset(block3) {
126
+ if (block3.type !== "paragraph") return null;
127
+ let offset = null;
128
+ let at = 0;
129
+ for (const span of block3.content) {
130
+ if (span.image) {
131
+ if (offset !== null || span.link || span.marks.length > 0) return null;
132
+ offset = at;
133
+ } else if (span.token || span.link || !/^[ \t]*$/.test(span.text)) {
134
+ return null;
135
+ }
136
+ at += span.text.length;
137
+ }
138
+ return offset;
139
+ }
140
+ function isImageBlock(block3) {
141
+ return imageBlockOffset(block3) !== null;
142
+ }
123
143
  function containerContent(block3, cell) {
124
144
  if (block3.type === "table") {
125
145
  if (!cell) return null;
@@ -568,7 +588,10 @@ function nextGrapheme(text, offset) {
568
588
  return text.length;
569
589
  }
570
590
  function deleteBackward(state) {
571
- if (!isCollapsed(state.selection)) return deleteSelection(state);
591
+ if (!isCollapsed(state.selection)) {
592
+ const image = selectedImageBlock(state);
593
+ return image ? removeBlockAt(state, blockIndex(state.doc, image.pos.blockId), -1) : deleteSelection(state);
594
+ }
572
595
  const pos = state.selection.focus;
573
596
  const index = blockIndex(state.doc, pos.blockId);
574
597
  const block3 = state.doc.blocks[index];
@@ -589,6 +612,11 @@ function deleteBackward(state) {
589
612
  const prev = state.doc.blocks[index - 1];
590
613
  if (!prev) return state;
591
614
  if (prev.type === "divider") return withBlocks(state, splice(state, index - 1, 1));
615
+ const prevImage = imageBlockOffset(prev);
616
+ if (prevImage !== null) {
617
+ const selection = imageSelection(prev.id, prevImage);
618
+ return inlineLength(block3.content) === 0 ? withBlocks(state, splice(state, index, 1), selection) : { ...state, selection, storedMarks: null };
619
+ }
592
620
  if (prev.type === "table") {
593
621
  const end = endOf(prev);
594
622
  const selection = { anchor: end, focus: end };
@@ -597,7 +625,10 @@ function deleteBackward(state) {
597
625
  return deleteRange(state, endOf(prev), { blockId: block3.id, offset: 0 });
598
626
  }
599
627
  function deleteForward(state) {
600
- if (!isCollapsed(state.selection)) return deleteSelection(state);
628
+ if (!isCollapsed(state.selection)) {
629
+ const image = selectedImageBlock(state);
630
+ return image ? removeBlockAt(state, blockIndex(state.doc, image.pos.blockId), 1) : deleteSelection(state);
631
+ }
601
632
  const pos = state.selection.focus;
602
633
  const index = blockIndex(state.doc, pos.blockId);
603
634
  const block3 = state.doc.blocks[index];
@@ -610,6 +641,11 @@ function deleteForward(state) {
610
641
  const next = state.doc.blocks[index + 1];
611
642
  if (!next || next.type === "table") return state;
612
643
  if (next.type === "divider") return withBlocks(state, splice(state, index + 1, 1));
644
+ const nextImage = imageBlockOffset(next);
645
+ if (nextImage !== null) {
646
+ const selection = imageSelection(next.id, nextImage);
647
+ return block3.type === "paragraph" && inlineLength(block3.content) === 0 ? withBlocks(state, splice(state, index, 1), selection) : { ...state, selection, storedMarks: null };
648
+ }
613
649
  return deleteRange(state, pos, { blockId: next.id, offset: 0 });
614
650
  }
615
651
  function removeBlockAt(state, index, prefer) {
@@ -638,11 +674,12 @@ function insertText(state, text) {
638
674
  return replaceBlock(s, withContainerContent(block3, pos.cell, next), caret(block3.id, pos.offset + value.length, pos.cell));
639
675
  }
640
676
  function exitBlock(state, dir) {
641
- if (!isCollapsed(state.selection)) return state;
642
- const pos = state.selection.focus;
677
+ const image = selectedImageBlock(state);
678
+ if (!isCollapsed(state.selection) && !image) return state;
679
+ const pos = image?.pos ?? state.selection.focus;
643
680
  const index = blockIndex(state.doc, pos.blockId);
644
681
  const block3 = state.doc.blocks[index];
645
- if (block3.type !== "code" && block3.type !== "table" && block3.type !== "divider") return state;
682
+ if (block3.type !== "code" && block3.type !== "table" && block3.type !== "divider" && !image) return state;
646
683
  if (index !== (dir === 1 ? state.doc.blocks.length - 1 : 0)) return state;
647
684
  if (block3.type === "table") {
648
685
  const row = pos.cell?.row ?? -1;
@@ -806,6 +843,14 @@ function selectedImage(state) {
806
843
  const image = content ? sliceInline(content, from, from + 1)[0]?.image : void 0;
807
844
  return image ? { pos: { ...anchor, offset: from }, image } : null;
808
845
  }
846
+ function imageSelection(blockId, offset) {
847
+ return { anchor: { blockId, offset }, focus: { blockId, offset: offset + 1 } };
848
+ }
849
+ function selectedImageBlock(state) {
850
+ const selected = selectedImage(state);
851
+ if (!selected || selected.pos.cell) return null;
852
+ return imageBlockOffset(getBlock(state.doc, selected.pos.blockId)) === selected.pos.offset ? selected : null;
853
+ }
809
854
  function selectImage(state, pos) {
810
855
  const block3 = state.doc.blocks.find((b) => b.id === pos.blockId);
811
856
  const content = block3 && containerContent(block3, pos.cell);
@@ -817,9 +862,10 @@ function updateImage(state, pos, change) {
817
862
  const content = block3 && containerContent(block3, pos.cell);
818
863
  const span = content ? sliceInline(content, pos.offset, pos.offset + 1)[0] : void 0;
819
864
  if (!block3 || !content || !span?.image) return state;
820
- const { title: _title, width: _width, height: _height, ...rest } = span.image;
865
+ const { title: _title, align: _align, width: _width, height: _height, ...rest } = span.image;
821
866
  let title = span.image.title;
822
867
  if (change.title !== void 0) title = change.title || void 0;
868
+ const align = change.align !== void 0 ? change.align ?? void 0 : span.image.align;
823
869
  let width = span.image.width;
824
870
  let height = span.image.height;
825
871
  if (change.width !== void 0) {
@@ -830,11 +876,12 @@ function updateImage(state, pos, change) {
830
876
  ...rest,
831
877
  ...change.alt !== void 0 ? { alt: change.alt } : {},
832
878
  ...title ? { title } : {},
879
+ ...align ? { align } : {},
833
880
  ...width ? { width } : {},
834
881
  ...width && height ? { height } : {}
835
882
  };
836
883
  const selected = selectImage(state, pos).selection;
837
- const same = image.alt === span.image.alt && image.title === span.image.title && image.width === span.image.width && image.height === span.image.height;
884
+ const same = image.alt === span.image.alt && image.title === span.image.title && image.align === span.image.align && image.width === span.image.width && image.height === span.image.height;
838
885
  if (same) return selected === state.selection ? state : { ...state, selection: selected, storedMarks: null };
839
886
  const next = concatInline(sliceInline(content, 0, pos.offset), [{ ...span, text: ATOM_CHAR, image }], sliceInline(content, pos.offset + 1));
840
887
  return replaceBlock(state, withContainerContent(block3, pos.cell, next), selected);
@@ -860,15 +907,48 @@ function convert(block3, spec) {
860
907
  return block3;
861
908
  }
862
909
  }
910
+ function isConvertible(block3) {
911
+ return isTextBlock(block3) && block3.type !== "raw";
912
+ }
863
913
  function setBlockType(state, spec) {
864
914
  if (spec.type === "table" || spec.type === "divider") return insertBlock(state, spec);
865
915
  const { from, to } = orderedRange(state.doc, state.selection);
866
916
  const start = blockIndex(state.doc, from.blockId);
867
917
  const end = blockIndex(state.doc, to.blockId);
868
- const updated = state.doc.blocks.slice(start, end + 1).map((b) => isTextBlock(b) && b.type !== "raw" ? convert(b, spec) : b);
918
+ const range = state.doc.blocks.slice(start, end + 1);
919
+ if (spec.type === "code" && range.filter(isConvertible).length > 1) return mergeIntoCode(state, start, range, spec.language);
920
+ const updated = range.map((b) => isConvertible(b) ? convert(b, spec) : b);
869
921
  const doc = { blocks: splice(state, start, updated.length, ...updated) };
870
922
  return { doc, selection: clampSelection(doc, state.selection), storedMarks: null };
871
923
  }
924
+ function mergeIntoCode(state, start, range, language) {
925
+ const out = [];
926
+ const merged = [];
927
+ let run = [];
928
+ const flush = () => {
929
+ const first = run[0];
930
+ if (!first) return;
931
+ const text = run.map((b) => inlineText(toPlain(b.content))).join("\n");
932
+ const code = codeBlock(language ?? (first.type === "code" ? first.language : ""), text, first.id);
933
+ out.push(code);
934
+ merged.push(code);
935
+ run = [];
936
+ };
937
+ for (const block3 of range) {
938
+ if (isConvertible(block3)) run.push(block3);
939
+ else {
940
+ flush();
941
+ out.push(block3);
942
+ }
943
+ }
944
+ flush();
945
+ const selection = { anchor: startOf(merged[0]), focus: endOf(merged[merged.length - 1]) };
946
+ return { doc: { blocks: splice(state, start, range.length, ...out) }, selection, storedMarks: null };
947
+ }
948
+ function convertibleBlocks(state) {
949
+ const { from, to } = orderedRange(state.doc, state.selection);
950
+ return state.doc.blocks.slice(blockIndex(state.doc, from.blockId), blockIndex(state.doc, to.blockId) + 1).filter(isConvertible);
951
+ }
872
952
  function hasType(block3, spec) {
873
953
  switch (spec.type) {
874
954
  case "heading":
@@ -882,9 +962,7 @@ function hasType(block3, spec) {
882
962
  }
883
963
  }
884
964
  function toggleBlockType(state, spec) {
885
- const { from, to } = orderedRange(state.doc, state.selection);
886
- const blocks = state.doc.blocks.slice(blockIndex(state.doc, from.blockId), blockIndex(state.doc, to.blockId) + 1);
887
- const text = blocks.filter((b) => isTextBlock(b) && b.type !== "raw");
965
+ const text = convertibleBlocks(state);
888
966
  if (text.length === 0) return state;
889
967
  const on = text.every((b) => hasType(b, spec));
890
968
  return setBlockType(state, on ? { type: "paragraph" } : spec);
@@ -1176,6 +1254,7 @@ function applyInlineInputRules(state) {
1176
1254
  const innerEnd = end - rule.delim;
1177
1255
  const innerStart = innerEnd - inner.length;
1178
1256
  const start = innerStart - rule.delim;
1257
+ if (isEscaped(before, start) || rule.mark !== "code" && isEscaped(before, innerEnd)) continue;
1179
1258
  if (rangeHasMark(content, start, end, "code") || sliceInline(content, start, end).some((s) => s.image)) continue;
1180
1259
  let next = setMarkInRange(content, innerStart, innerEnd, rule.mark, true);
1181
1260
  next = deleteInline(next, innerEnd, end);
@@ -1188,6 +1267,11 @@ function applyInlineInputRules(state) {
1188
1267
  }
1189
1268
  return null;
1190
1269
  }
1270
+ function isEscaped(text, index) {
1271
+ let count = 0;
1272
+ while (index - count - 1 >= 0 && text[index - count - 1] === "\\") count++;
1273
+ return count % 2 === 1;
1274
+ }
1191
1275
  function applyTokenInputRules(state, syntax) {
1192
1276
  const at = syntax.length > 0 ? inlineAtCaret(state) : null;
1193
1277
  if (!at) return null;
@@ -1441,8 +1525,11 @@ function docToHtml(doc) {
1441
1525
  }
1442
1526
  function blockHtml(block3) {
1443
1527
  switch (block3.type) {
1444
- case "paragraph":
1445
- return `<p>${inlineHtml(block3.content)}</p>`;
1528
+ case "paragraph": {
1529
+ const at = imageBlockOffset(block3);
1530
+ const align = at === null ? void 0 : sliceInline(block3.content, at, at + 1)[0]?.image?.align;
1531
+ return `<p${align ? ` style="text-align:${align}"` : ""}>${inlineHtml(block3.content)}</p>`;
1532
+ }
1446
1533
  case "heading":
1447
1534
  return `<h${block3.level}>${inlineHtml(block3.content)}</h${block3.level}>`;
1448
1535
  case "code": {
@@ -2049,6 +2136,10 @@ var DEFAULT_LABELS = {
2049
2136
  strike: "Strikethrough",
2050
2137
  inlineCode: "Code",
2051
2138
  link: "Link",
2139
+ /** The formatting toolbar's menu of paragraph and heading styles. */
2140
+ textStyle: "Text style",
2141
+ /** The formatting toolbar's menu of list types. */
2142
+ list: "List",
2052
2143
  linkPlaceholder: "Paste or type a link\u2026",
2053
2144
  removeLink: "Remove link",
2054
2145
  slashHint: "Type '/' for commands",
@@ -2068,13 +2159,22 @@ var DEFAULT_LABELS = {
2068
2159
  addColumnRight: "Add column right",
2069
2160
  deleteRow: "Delete row",
2070
2161
  deleteColumn: "Delete column",
2071
- alignLeft: "Align left",
2072
- alignCenter: "Align center",
2073
- alignRight: "Align right",
2162
+ /** The block menu row that opens the Align submenu, and the submenu's title. */
2163
+ align: "Align",
2164
+ alignLeft: "Left",
2165
+ alignCenter: "Center",
2166
+ alignRight: "Right",
2074
2167
  tableSection: "Table",
2168
+ /** The title of the block menu's section of image block actions. */
2169
+ imageSection: "Image",
2170
+ /** Removes an image's width, so it shows at its own size. */
2171
+ resetImageSize: "Reset size",
2172
+ /** Edits an image's alt text, and names the field that edits it. */
2173
+ altText: "Alt text",
2174
+ altTextPlaceholder: "Describe the image\u2026",
2075
2175
  /** Shown in place of an image that did not load and has no alt text. */
2076
2176
  imageUnavailable: "Image unavailable",
2077
- /** Accessible name of the handles that resize an image. */
2177
+ /** Accessible name of an image's resize handles. */
2078
2178
  resizeImage: "Resize image"
2079
2179
  };
2080
2180
 
@@ -2119,12 +2219,36 @@ var ICONS = {
2119
2219
  addColumnLeft: ["m12 19-7-7 7-7", "M19 12H5"],
2120
2220
  /** `arrow-right` */
2121
2221
  addColumnRight: ["M5 12h14", "m12 5 7 7-7 7"],
2222
+ /** `text-align-start`, the table menu's Align row */
2223
+ align: ["M21 5H3", "M15 12H3", "M17 19H3"],
2122
2224
  /** `text-align-start` */
2123
2225
  alignLeft: ["M21 5H3", "M15 12H3", "M17 19H3"],
2124
2226
  /** `text-align-center` */
2125
2227
  alignCenter: ["M21 5H3", "M17 12H7", "M19 19H5"],
2126
2228
  /** `text-align-end` */
2127
2229
  alignRight: ["M21 5H3", "M21 12H9", "M21 19H7"],
2230
+ /** `align-start-vertical`, an image block's Align row and its Left item */
2231
+ imageAlignLeft: [["rect", { width: "9", height: "6", x: "6", y: "14", rx: "2" }], ["rect", { width: "16", height: "6", x: "6", y: "4", rx: "2" }], "M2 2v20"],
2232
+ /** `align-center-vertical` */
2233
+ imageAlignCenter: [
2234
+ "M12 2v20",
2235
+ "M8 10H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2h4",
2236
+ "M16 10h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-4",
2237
+ "M8 20H7a2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2h1",
2238
+ "M16 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1"
2239
+ ],
2240
+ /** `align-end-vertical` */
2241
+ imageAlignRight: [["rect", { width: "16", height: "6", x: "2", y: "4", rx: "2" }], ["rect", { width: "9", height: "6", x: "9", y: "14", rx: "2" }], "M22 22V2"],
2242
+ /** `rotate-ccw` */
2243
+ resetImageSize: ["M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8", "M3 3v5h5"],
2244
+ /** `text-cursor-input` */
2245
+ altText: [
2246
+ "M12 20h-1a2 2 0 0 1-2-2 2 2 0 0 1-2 2H6",
2247
+ "M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7",
2248
+ "M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1",
2249
+ "M6 4h1a2 2 0 0 1 2 2 2 2 0 0 1 2-2h1",
2250
+ "M9 6v12"
2251
+ ],
2128
2252
  /** `trash` */
2129
2253
  deleteRow: TRASH,
2130
2254
  /** `trash` */
@@ -2148,6 +2272,12 @@ var ICONS = {
2148
2272
  "M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",
2149
2273
  "M21 15V5a2 2 0 0 0-2-2H9"
2150
2274
  ],
2275
+ /** `chevron-down`, after the icon of a toolbar button that opens a menu */
2276
+ chevronDown: ["m6 9 6 6 6-6"],
2277
+ /** `check`, after the current item of a menu */
2278
+ selected: ["M20 6 9 17l-5-5"],
2279
+ /** `chevron-right`, at the end of a menu row that opens a submenu */
2280
+ chevronRight: ["m9 18 6-6-6-6"],
2151
2281
  /** `grip-vertical` */
2152
2282
  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" }]]
2153
2283
  };
@@ -2181,6 +2311,28 @@ function iconNode(doc, icon) {
2181
2311
 
2182
2312
  // src/markdown/ast.ts
2183
2313
  var IMAGE_SIZE = /\|([1-9][0-9]{0,4})(?:x([1-9][0-9]{0,4}))?$/;
2314
+ var IMAGE_ALIGN = /\|(left|center|right)(?:\|([1-9][0-9]{0,4})(?:x([1-9][0-9]{0,4}))?)?$/;
2315
+ var escapedAfter = (before) => /(^|[^\\])(\\\\)*\\$/.test(before);
2316
+ function imageSuffix(text, source = true) {
2317
+ const aligned = IMAGE_ALIGN.exec(text);
2318
+ if (aligned && !(source && escapedAfter(text.slice(0, aligned.index)))) {
2319
+ return {
2320
+ align: aligned[1],
2321
+ ...aligned[2] ? { width: Number(aligned[2]) } : {},
2322
+ ...aligned[3] ? { height: Number(aligned[3]) } : {},
2323
+ index: aligned.index
2324
+ };
2325
+ }
2326
+ const size = IMAGE_SIZE.exec(text);
2327
+ if (size && !(source && escapedAfter(text.slice(0, size.index)))) {
2328
+ return { width: Number(size[1]), ...size[2] ? { height: Number(size[2]) } : {}, index: size.index };
2329
+ }
2330
+ return null;
2331
+ }
2332
+ function imageSuffixText(s) {
2333
+ const size = s.width ? `|${s.width}${s.height ? `x${s.height}` : ""}` : "";
2334
+ return (s.align ? `|${s.align}` : "") + size;
2335
+ }
2184
2336
  function inlineNodesText(nodes, soft) {
2185
2337
  let s = "";
2186
2338
  for (const node of nodes) {
@@ -2292,11 +2444,13 @@ function lowerInto(nodes, marks, link, out, soft) {
2292
2444
  }
2293
2445
  function imageAtom(node) {
2294
2446
  let alt = inlineNodesText(node.children, " ");
2295
- if (node.width) alt = alt.replace(IMAGE_SIZE, "");
2447
+ const suffix = imageSuffixText(node);
2448
+ if (suffix && alt.endsWith(suffix)) alt = alt.slice(0, -suffix.length);
2296
2449
  return {
2297
2450
  src: node.destination,
2298
2451
  alt,
2299
2452
  ...node.title ? { title: node.title } : {},
2453
+ ...node.align ? { align: node.align } : {},
2300
2454
  ...node.width ? { width: node.width } : {},
2301
2455
  ...node.height ? { height: node.height } : {}
2302
2456
  };
@@ -2500,7 +2654,9 @@ var Node2 = class {
2500
2654
  depth = 0;
2501
2655
  destination = "";
2502
2656
  title = "";
2503
- /** An image's size (see `IMAGE_SIZE`), 0 when none. */
2657
+ /** An image's alignment (see `imageSuffix`), '' when none. */
2658
+ align = "";
2659
+ /** An image's size (see `imageSuffix`), 0 when none. */
2504
2660
  width = 0;
2505
2661
  height = 0;
2506
2662
  /** An escaped "@": kept apart from the text around it, so it does not join an e-mail literal. */
@@ -2583,8 +2739,15 @@ function toAst(parent) {
2583
2739
  out.push({ type: n.type, destination: n.destination, title: n.title, children: toAst(n) });
2584
2740
  break;
2585
2741
  case "image": {
2586
- const image = { type: n.type, destination: n.destination, title: n.title, children: toAst(n) };
2587
- out.push(n.width ? { ...image, width: n.width, ...n.height ? { height: n.height } : {} } : image);
2742
+ out.push({
2743
+ type: n.type,
2744
+ destination: n.destination,
2745
+ title: n.title,
2746
+ children: toAst(n),
2747
+ ...n.align ? { align: n.align } : {},
2748
+ ...n.width ? { width: n.width } : {},
2749
+ ...n.width && n.height ? { height: n.height } : {}
2750
+ });
2588
2751
  break;
2589
2752
  }
2590
2753
  case "root":
@@ -3043,11 +3206,11 @@ var InlineParser = class {
3043
3206
  link.destination = dest ?? "";
3044
3207
  link.title = title ?? "";
3045
3208
  if (opener.image) {
3046
- const label = this.subject.slice(opener.index + 1, startPos - 1);
3047
- const size = IMAGE_SIZE.exec(label);
3048
- if (size && !/(^|[^\\])(\\\\)*\\$/.test(label.slice(0, size.index))) {
3049
- link.width = Number(size[1]);
3050
- link.height = size[2] ? Number(size[2]) : 0;
3209
+ const suffix = imageSuffix(this.subject.slice(opener.index + 1, startPos - 1));
3210
+ if (suffix) {
3211
+ link.align = suffix.align ?? "";
3212
+ link.width = suffix.width ?? 0;
3213
+ link.height = suffix.height ?? 0;
3051
3214
  }
3052
3215
  }
3053
3216
  let n = opener.node.next;
@@ -3922,14 +4085,14 @@ function serializeBlocks(blocks, options) {
3922
4085
  for (const block3 of blocks) {
3923
4086
  if (block3.type === "quote" && block3.content.length === 0) continue;
3924
4087
  let text;
3925
- let separator2 = "\n\n";
4088
+ let separator = "\n\n";
3926
4089
  switch (block3.type) {
3927
4090
  case "paragraph":
3928
4091
  text = block3.content.length === 0 ? "&nbsp;" : inlineToMarkdown(block3.content, ctx.paragraph);
3929
4092
  break;
3930
4093
  case "quote": {
3931
4094
  text = prefixLines(inlineToMarkdown(block3.content, ctx.paragraph), "> ", ">");
3932
- if (prev?.type === "quote") separator2 = "\n>\n";
4095
+ if (prev?.type === "quote") separator = "\n>\n";
3933
4096
  break;
3934
4097
  }
3935
4098
  case "heading":
@@ -3938,7 +4101,7 @@ function serializeBlocks(blocks, options) {
3938
4101
  case "listItem": {
3939
4102
  const item = lists.next(block3, prev?.type === "listItem" ? prev : null);
3940
4103
  text = item.text;
3941
- if (prev?.type === "listItem" && !item.blankLineBefore) separator2 = "\n";
4104
+ if (prev?.type === "listItem" && !item.blankLineBefore) separator = "\n";
3942
4105
  break;
3943
4106
  }
3944
4107
  case "code":
@@ -3954,7 +4117,7 @@ function serializeBlocks(blocks, options) {
3954
4117
  text = "---";
3955
4118
  break;
3956
4119
  }
3957
- if (out) out += separator2;
4120
+ if (out) out += separator;
3958
4121
  out += text;
3959
4122
  prev = block3;
3960
4123
  }
@@ -4065,7 +4228,7 @@ var STRATEGIES = [
4065
4228
  function sameInline(a, b) {
4066
4229
  return a.length === b.length && a.every((s, i) => {
4067
4230
  const t = b[i];
4068
- return s.text === t.text && s.link === t.link && sameMarks(s.marks, t.marks) && s.image?.src === t.image?.src && s.image?.alt === t.image?.alt && s.image?.title === t.image?.title && s.image?.width === t.image?.width && s.image?.height === t.image?.height;
4231
+ return s.text === t.text && s.link === t.link && sameMarks(s.marks, t.marks) && s.image?.src === t.image?.src && s.image?.alt === t.image?.alt && s.image?.title === t.image?.title && s.image?.align === t.image?.align && s.image?.width === t.image?.width && s.image?.height === t.image?.height;
4069
4232
  });
4070
4233
  }
4071
4234
  var reSpecWhitespace = /^[\t\n\f\r\p{Zs}]+|[\t\n\f\r\p{Zs}]+$/gu;
@@ -4446,8 +4609,10 @@ function imageMarkdown(image, ctx) {
4446
4609
  atEnd: false
4447
4610
  });
4448
4611
  const title = image.title ? ` "${escapeEntities(image.title.replace(/["\\]/g, "\\$&"))}"` : "";
4449
- const size = image.width ? `|${image.width}${image.height ? `x${image.height}` : ""}` : "";
4450
- const text = size ? alt + size : IMAGE_SIZE.test(alt) ? alt.replace(/\|(?=[^|]*$)/, "&#124;") : alt;
4612
+ const suffix = imageSuffixText(image);
4613
+ const read = imageSuffix(alt + suffix);
4614
+ const same = read ? read.index === alt.length && imageSuffixText(read) === suffix : !suffix;
4615
+ const text = (same ? alt : alt.replace(/\|(?=[^|]*$)/, "&#124;")) + suffix;
4451
4616
  return `![${text}](${linkDestination(image.src)}${title})`;
4452
4617
  }
4453
4618
 
@@ -4734,6 +4899,28 @@ var Popup = class {
4734
4899
  this.el.style.left = `${Math.round(left - offset.x)}px`;
4735
4900
  this.el.style.top = `${Math.round(top - offset.y)}px`;
4736
4901
  }
4902
+ /**
4903
+ * Shows the popup beside `menu` (a menu's rectangle, viewport coordinates),
4904
+ * with its point `offsetY` from its top level with `top`: on the right, or
4905
+ * on the left when there is no room, as a submenu opens.
4906
+ */
4907
+ showBeside(menu, top, offsetY, gap = 4) {
4908
+ const doc = this.owner.ownerDocument;
4909
+ if (!this.open) this.copyTheme();
4910
+ this.el.hidden = false;
4911
+ this.open = true;
4912
+ const offset = attach(this.el, this.owner);
4913
+ const vp = visibleViewport(doc.defaultView);
4914
+ this.el.style.maxHeight = "";
4915
+ const w = this.el.offsetWidth;
4916
+ const h = this.el.offsetHeight;
4917
+ let left = menu.right + gap;
4918
+ if (left + w > vp.left + vp.width - 8 && menu.left - gap - w >= vp.left + 8) left = menu.left - gap - w;
4919
+ left = Math.max(vp.left + 8, Math.min(left, vp.left + vp.width - w - 8));
4920
+ const y = Math.max(vp.top + 8, Math.min(top - offsetY, vp.top + vp.height - h - 8));
4921
+ this.el.style.left = `${Math.round(left - offset.x)}px`;
4922
+ this.el.style.top = `${Math.round(y - offset.y)}px`;
4923
+ }
4737
4924
  hide() {
4738
4925
  if (!this.open) return;
4739
4926
  this.open = false;
@@ -4752,20 +4939,29 @@ var Popup = class {
4752
4939
  }
4753
4940
  };
4754
4941
  var menuCounter = 0;
4755
- var Menu = class {
4942
+ var Menu = class _Menu {
4943
+ constructor(owner, className, role = "listbox") {
4944
+ this.owner = owner;
4945
+ this.className = className;
4946
+ this.popup = new Popup(owner, `mbe-menu ${className}`);
4947
+ this.popup.el.setAttribute("role", role);
4948
+ this.popup.el.id = this.id;
4949
+ }
4756
4950
  popup;
4757
4951
  items = [];
4758
4952
  index = 0;
4759
4953
  id = `mbe-menu-${++menuCounter}`;
4954
+ /** The submenu of the item at `childIndex`, while it is open. */
4955
+ child = null;
4956
+ childIndex = -1;
4957
+ /** Shown after the label of a `checked` item. */
4958
+ checkIcon;
4959
+ /** Shown at the end of a row that opens a submenu. */
4960
+ submenuIcon;
4760
4961
  /** Called after an item runs. */
4761
4962
  onPicked = null;
4762
4963
  /** Called when the highlight moves, by key, by mouse or because the items changed. */
4763
4964
  onHighlight = null;
4764
- constructor(owner, className, role = "listbox") {
4765
- this.popup = new Popup(owner, `mbe-menu ${className}`);
4766
- this.popup.el.setAttribute("role", role);
4767
- this.popup.el.id = this.id;
4768
- }
4769
4965
  get el() {
4770
4966
  return this.popup.el;
4771
4967
  }
@@ -4773,10 +4969,59 @@ var Menu = class {
4773
4969
  return this.popup.isOpen;
4774
4970
  }
4775
4971
  get activeDescendant() {
4972
+ if (this.child?.isOpen) return this.child.activeDescendant;
4776
4973
  return this.items.length ? `${this.id}-${this.index}` : null;
4777
4974
  }
4975
+ /** The open submenu, if any. */
4976
+ get submenu() {
4977
+ return this.child?.isOpen ? this.child : null;
4978
+ }
4979
+ /** True if `node` is in this menu or its submenu. */
4980
+ contains(node) {
4981
+ return this.el.contains(node) || !!this.child?.contains(node);
4982
+ }
4983
+ /** Opens the submenu of the item at `i` (default: the highlighted one) and highlights its checked or first item. Returns false when it has none. */
4984
+ openSubmenu(i = this.index) {
4985
+ const item = this.items[i];
4986
+ const row = this.el.querySelector(`#${this.id}-${i}`);
4987
+ if (!item?.submenu || !row) return false;
4988
+ if (this.child?.isOpen && this.childIndex === i) return true;
4989
+ this.highlight(i);
4990
+ if (!this.child) {
4991
+ this.child = new _Menu(this.owner, `mbe-submenu ${this.className}-submenu`, "menu");
4992
+ this.child.onPicked = () => {
4993
+ this.closeSubmenu();
4994
+ this.onPicked?.();
4995
+ };
4996
+ this.child.onHighlight = () => this.onHighlight?.(this.index);
4997
+ }
4998
+ this.child.checkIcon = this.checkIcon;
4999
+ this.child.el.setAttribute("aria-label", item.submenu.title ?? item.label);
5000
+ this.child.setSections([item.submenu]);
5001
+ const checked = item.submenu.items.find((it) => it.checked);
5002
+ if (checked) this.child.highlightId(checked.id);
5003
+ this.childIndex = i;
5004
+ row.setAttribute("aria-expanded", "true");
5005
+ const menuRect = this.el.getBoundingClientRect();
5006
+ const rowTop = row.getBoundingClientRect().top;
5007
+ this.child.popup.showBeside(menuRect, rowTop, 0);
5008
+ const first = this.child.el.querySelector(".mbe-menu-item");
5009
+ const shift = first ? first.getBoundingClientRect().top - this.child.el.getBoundingClientRect().top : 0;
5010
+ if (shift) this.child.popup.showBeside(menuRect, rowTop, shift);
5011
+ this.onHighlight?.(this.index);
5012
+ return true;
5013
+ }
5014
+ /** Closes the submenu, keeping its item highlighted. */
5015
+ closeSubmenu() {
5016
+ if (!this.child?.isOpen) return;
5017
+ this.child.hide();
5018
+ this.el.querySelector(`#${this.id}-${this.childIndex}`)?.setAttribute("aria-expanded", "false");
5019
+ this.childIndex = -1;
5020
+ this.onHighlight?.(this.index);
5021
+ }
4778
5022
  setSections(sections2, emptyLabel) {
4779
5023
  const doc = this.el.ownerDocument;
5024
+ this.closeSubmenu();
4780
5025
  this.el.replaceChildren();
4781
5026
  this.items = [];
4782
5027
  this.index = 0;
@@ -4795,14 +5040,17 @@ var Menu = class {
4795
5040
  const row = doc.createElement("div");
4796
5041
  row.className = "mbe-menu-item";
4797
5042
  row.id = `${this.id}-${i}`;
4798
- row.setAttribute("role", this.el.getAttribute("role") === "menu" ? "menuitem" : "option");
5043
+ const role = this.el.getAttribute("role") === "menu" ? item.checked === void 0 ? "menuitem" : "menuitemradio" : "option";
5044
+ row.setAttribute("role", role);
5045
+ if (item.checked !== void 0) row.setAttribute("aria-checked", String(item.checked));
5046
+ if (item.keyShortcuts) row.setAttribute("aria-keyshortcuts", item.keyShortcuts);
4799
5047
  if (item.danger) row.classList.add("mbe-danger");
4800
5048
  const icon = doc.createElement("span");
4801
5049
  icon.className = "mbe-menu-icon";
4802
5050
  const content = iconNode(doc, item.icon);
4803
5051
  if (content) icon.appendChild(content);
4804
5052
  const label = doc.createElement("span");
4805
- label.className = "mbe-menu-label";
5053
+ label.className = item.labelClass ? `mbe-menu-label ${item.labelClass}` : "mbe-menu-label";
4806
5054
  setMarked(label, item.label, item.mark);
4807
5055
  row.append(icon, label);
4808
5056
  if (item.detail) {
@@ -4811,7 +5059,27 @@ var Menu = class {
4811
5059
  detail.textContent = item.detail;
4812
5060
  row.appendChild(detail);
4813
5061
  }
4814
- row.addEventListener("mousemove", () => this.highlight(i));
5062
+ if (item.checked) {
5063
+ const check = doc.createElement("span");
5064
+ check.className = "mbe-menu-check";
5065
+ const content2 = iconNode(doc, this.checkIcon);
5066
+ if (content2) check.appendChild(content2);
5067
+ row.appendChild(check);
5068
+ }
5069
+ if (item.submenu) {
5070
+ row.setAttribute("aria-haspopup", "menu");
5071
+ row.setAttribute("aria-expanded", "false");
5072
+ const arrow = doc.createElement("span");
5073
+ arrow.className = "mbe-menu-submenu";
5074
+ const content2 = iconNode(doc, this.submenuIcon);
5075
+ if (content2) arrow.appendChild(content2);
5076
+ row.appendChild(arrow);
5077
+ }
5078
+ row.addEventListener("mousemove", () => {
5079
+ if (this.index !== i || !this.child?.isOpen) this.highlight(i);
5080
+ if (item.submenu) this.openSubmenu(i);
5081
+ else this.closeSubmenu();
5082
+ });
4815
5083
  row.addEventListener("click", () => this.pick(i));
4816
5084
  this.el.appendChild(row);
4817
5085
  }
@@ -4879,13 +5147,19 @@ var Menu = class {
4879
5147
  pick(i = this.index) {
4880
5148
  const item = this.items[i];
4881
5149
  if (!item) return;
5150
+ if (item.submenu) {
5151
+ this.openSubmenu(i);
5152
+ return;
5153
+ }
4882
5154
  item.run();
4883
5155
  this.onPicked?.();
4884
5156
  }
4885
5157
  hide() {
5158
+ this.closeSubmenu();
4886
5159
  this.popup.hide();
4887
5160
  }
4888
5161
  destroy() {
5162
+ this.child?.destroy();
4889
5163
  this.popup.destroy();
4890
5164
  }
4891
5165
  };
@@ -4916,7 +5190,8 @@ function defaultKeymap() {
4916
5190
  "Mod-e": ({ editor }) => editor.commands.toggleCode(),
4917
5191
  "Mod-Shift-x": ({ editor }) => editor.commands.toggleStrike(),
4918
5192
  "Mod-Shift-s": ({ editor }) => editor.commands.toggleStrike(),
4919
- "Mod-k": ({ editor }) => (editor.openLinkPopover(), true),
5193
+ // Without selected text or a link at the caret, Mod+K is left to the app, for example for a command menu.
5194
+ "Mod-k": ({ editor }) => editor.openLinkPopover(),
4920
5195
  "Mod-Alt-0": ({ editor }) => editor.commands.setParagraph() || true,
4921
5196
  "Mod-Alt-1": ({ editor }) => editor.commands.toggleHeading({ level: 1 }) || true,
4922
5197
  "Mod-Alt-2": ({ editor }) => editor.commands.toggleHeading({ level: 2 }) || true,
@@ -5618,93 +5893,314 @@ function matchesKey(binding, e) {
5618
5893
  }
5619
5894
 
5620
5895
  // src/ui/toolbar.ts
5621
- var mod = (key) => isMac ? `\u2318${key}` : `Ctrl+${key}`;
5622
- var MARK_BUTTONS = [
5623
- { mark: "bold", name: "bold", shortcut: mod("B") },
5624
- { mark: "italic", name: "italic", shortcut: mod("I") },
5625
- { mark: "strike", name: "strike", shortcut: isMac ? "\u2318\u21E7X" : "Ctrl+Shift+X" },
5626
- { mark: "code", name: "inlineCode", shortcut: mod("E") }
5896
+ var GROUPS = [
5897
+ ["textStyle"],
5898
+ ["bold", "italic", "strike", "inlineCode", "link"],
5899
+ ["quote", "codeBlock", "list"]
5627
5900
  ];
5901
+ var TOOLBAR_ITEMS = GROUPS.flat();
5902
+ var BLOCK_ITEMS = ["textStyle", "quote", "codeBlock", "list"];
5903
+ var mod = (keys) => `${isMac ? "Meta" : "Control"}+${keys}`;
5904
+ var MARKS = {
5905
+ bold: { mark: "bold", className: "mbe-tool-bold", keys: mod("B") },
5906
+ italic: { mark: "italic", className: "mbe-tool-italic", keys: mod("I") },
5907
+ strike: { mark: "strike", className: "mbe-tool-strike", keys: mod("Shift+X") },
5908
+ inlineCode: { mark: "code", className: "mbe-tool-code", keys: mod("E") }
5909
+ };
5910
+ var TEXT_STYLES = [
5911
+ { id: "text", spec: { type: "paragraph" }, keys: mod("Alt+0") },
5912
+ { id: "heading1", spec: { type: "heading", level: 1 }, keys: mod("Alt+1") },
5913
+ { id: "heading2", spec: { type: "heading", level: 2 }, keys: mod("Alt+2") },
5914
+ { id: "heading3", spec: { type: "heading", level: 3 }, keys: mod("Alt+3") }
5915
+ ];
5916
+ var LIST_TYPES = [
5917
+ { id: "bulletList", listType: "bullet", keys: mod("Shift+8") },
5918
+ { id: "numberedList", listType: "ordered", keys: mod("Shift+7") },
5919
+ { id: "todoList", listType: "task", keys: mod("Shift+9") }
5920
+ ];
5921
+ var TOOLTIP_DELAY = 500;
5922
+ var TOOLTIP_GRACE = 300;
5923
+ function blockState(editor) {
5924
+ const blocks = convertibleBlocks(editor.state);
5925
+ const styleOf2 = (b) => b.type === "paragraph" ? "text" : b.type === "heading" && b.level <= 3 ? `heading${b.level}` : null;
5926
+ const every = (f) => {
5927
+ const first = blocks[0] ? f(blocks[0]) : null;
5928
+ return blocks.every((b) => f(b) === first) ? first : null;
5929
+ };
5930
+ const some = blocks.length > 0;
5931
+ return {
5932
+ style: every(styleOf2),
5933
+ allHeadings: some && blocks.every((b) => b.type === "heading"),
5934
+ listType: every((b) => b.type === "listItem" ? b.listType : null),
5935
+ allListItems: some && blocks.every((b) => b.type === "listItem"),
5936
+ allQuotes: some && blocks.every((b) => b.type === "quote")
5937
+ };
5938
+ }
5628
5939
  var FormatToolbar = class {
5629
- constructor(editor) {
5940
+ constructor(editor, items = TOOLBAR_ITEMS) {
5630
5941
  this.editor = editor;
5631
5942
  const doc = editor.root.ownerDocument;
5632
5943
  this.popup = new Popup(editor.root, "mbe-toolbar");
5633
5944
  const el = this.popup.el;
5634
5945
  el.setAttribute("role", "toolbar");
5635
- const button = (icon, label, className, onClick) => {
5946
+ this.tooltip = new Popup(editor.root, "mbe-tooltip");
5947
+ this.tooltip.el.setAttribute("aria-hidden", "true");
5948
+ const labels = editor.labels;
5949
+ const button = (item, icon, className, keys, onClick) => {
5636
5950
  const b = doc.createElement("button");
5637
5951
  b.type = "button";
5638
5952
  b.className = `mbe-tool ${className}`;
5639
5953
  const content = iconNode(doc, editor.icon(icon));
5640
5954
  if (content) b.appendChild(content);
5641
- b.title = label;
5642
- b.setAttribute("aria-label", label);
5955
+ b.setAttribute("aria-label", labels[item === "codeBlock" ? "code" : item]);
5956
+ if (keys) b.setAttribute("aria-keyshortcuts", keys);
5643
5957
  b.addEventListener("click", onClick);
5644
- el.appendChild(b);
5958
+ b.addEventListener("pointerenter", (e) => {
5959
+ if (e.pointerType === "mouse") this.scheduleTooltip(b);
5960
+ });
5961
+ b.addEventListener("pointerleave", () => this.hideTooltip());
5962
+ this.buttons.set(item, b);
5645
5963
  return b;
5646
5964
  };
5647
- const labels = editor.labels;
5648
- for (const b of MARK_BUTTONS) {
5649
- const btn = button(b.name, `${labels[b.name]} (${b.shortcut})`, `mbe-tool-${b.mark}`, () => {
5650
- editor.run((s) => toggleMark(s, b.mark));
5651
- this.update();
5652
- });
5653
- btn.setAttribute("aria-pressed", "false");
5654
- this.markButtons.set(b.mark, btn);
5965
+ const trigger = (item, className, menuClass) => {
5966
+ const b = button(item, item === "list" ? "bulletList" : "text", className, null, () => this.toggleMenu(t));
5967
+ b.classList.add("mbe-tool-menu");
5968
+ b.setAttribute("aria-haspopup", "menu");
5969
+ b.setAttribute("aria-expanded", "false");
5970
+ const icon = doc.createElement("span");
5971
+ icon.className = "mbe-tool-icon";
5972
+ icon.append(...b.childNodes);
5973
+ const chevron = doc.createElement("span");
5974
+ chevron.className = "mbe-tool-chevron";
5975
+ const content = iconNode(doc, editor.icon("chevronDown"));
5976
+ if (content) chevron.appendChild(content);
5977
+ b.append(icon, chevron);
5978
+ const menu = new Menu(editor.root, menuClass, "menu");
5979
+ menu.el.setAttribute("aria-label", labels[item]);
5980
+ menu.checkIcon = editor.icon("selected");
5981
+ menu.onPicked = () => this.closeMenu();
5982
+ menu.onHighlight = () => this.onMenuChange?.();
5983
+ b.setAttribute("aria-controls", menu.el.id);
5984
+ const t = { button: b, icon, menu, iconName: item === "list" ? "bulletList" : "text" };
5985
+ return t;
5986
+ };
5987
+ const shown = new Set(items);
5988
+ for (const group of GROUPS) {
5989
+ const present = group.filter((item) => shown.has(item));
5990
+ if (present.length === 0) continue;
5991
+ if (this.buttons.size > 0) {
5992
+ const sep = doc.createElement("span");
5993
+ sep.className = "mbe-tool-sep";
5994
+ el.appendChild(sep);
5995
+ this.separators.push(sep);
5996
+ }
5997
+ for (const item of present) {
5998
+ const mark = MARKS[item];
5999
+ let b;
6000
+ if (mark) {
6001
+ b = button(item, item, mark.className, mark.keys, () => this.apply((s) => toggleMark(s, mark.mark)));
6002
+ b.setAttribute("aria-pressed", "false");
6003
+ } else if (item === "link") {
6004
+ b = button(item, "link", "mbe-tool-link", mod("K"), () => editor.openLinkPopover());
6005
+ b.setAttribute("aria-pressed", "false");
6006
+ } else if (item === "quote") {
6007
+ b = button(item, "quote", "mbe-tool-quote", null, () => this.apply((s) => toggleBlockType(s, { type: "quote" })));
6008
+ b.setAttribute("aria-pressed", "false");
6009
+ } else if (item === "codeBlock") {
6010
+ b = button(item, "code", "mbe-tool-code-block", mod("Alt+C"), () => this.apply((s) => toggleBlockType(s, { type: "code" })));
6011
+ } else if (item === "textStyle") {
6012
+ this.textStyle = trigger(item, "mbe-tool-text-style", "mbe-text-style-menu");
6013
+ b = this.textStyle.button;
6014
+ } else {
6015
+ this.list = trigger("list", "mbe-tool-list", "mbe-list-menu");
6016
+ b = this.list.button;
6017
+ }
6018
+ el.appendChild(b);
6019
+ }
5655
6020
  }
5656
- el.appendChild(separator(doc));
5657
- this.linkButton = button("link", `${labels.link} (${mod("K")})`, "mbe-tool-link", () => editor.openLinkPopover());
5658
6021
  }
5659
6022
  popup;
5660
- markButtons = /* @__PURE__ */ new Map();
5661
- linkButton;
6023
+ tooltip;
6024
+ buttons = /* @__PURE__ */ new Map();
6025
+ separators = [];
6026
+ textStyle = null;
6027
+ list = null;
6028
+ openTrigger = null;
6029
+ tooltipTimer;
6030
+ tooltipHiddenAt = 0;
6031
+ /** Called when a menu opens, closes or moves its highlight, so the editor can update `aria-activedescendant`. */
6032
+ onMenuChange = null;
5662
6033
  get isOpen() {
5663
6034
  return this.popup.isOpen;
5664
6035
  }
6036
+ /** The open menu of the text style or list button, if any. */
6037
+ get menu() {
6038
+ return this.openTrigger?.menu ?? null;
6039
+ }
6040
+ /** True if `node` is in the toolbar or one of its menus. */
6041
+ contains(node) {
6042
+ return this.popup.el.contains(node) || !!this.openTrigger?.menu.el.contains(node);
6043
+ }
5665
6044
  show() {
5666
6045
  const rect = this.editor.selectionRect();
5667
6046
  if (!rect) return this.hide();
5668
6047
  this.update();
6048
+ const view = this.editor.root.ownerDocument.defaultView;
6049
+ this.popup.el.style.maxWidth = `${Math.max(visibleViewport(view).width - 16, 0)}px`;
5669
6050
  this.popup.show(rect, isTouch() ? "below" : "above", 8);
6051
+ if (this.openTrigger) this.placeMenu(this.openTrigger);
5670
6052
  }
5671
6053
  hide() {
6054
+ this.closeMenu();
6055
+ this.hideTooltip();
5672
6056
  this.popup.hide();
5673
6057
  }
6058
+ /** Closes the open menu and leaves the toolbar open. */
6059
+ closeMenu() {
6060
+ const t = this.openTrigger;
6061
+ if (!t) return;
6062
+ this.openTrigger = null;
6063
+ t.menu.hide();
6064
+ t.button.classList.remove("mbe-open");
6065
+ t.button.setAttribute("aria-expanded", "false");
6066
+ this.onMenuChange?.();
6067
+ }
5674
6068
  destroy() {
6069
+ clearTimeout(this.tooltipTimer);
5675
6070
  this.popup.destroy();
6071
+ this.tooltip.destroy();
6072
+ this.textStyle?.menu.destroy();
6073
+ this.list?.menu.destroy();
6074
+ }
6075
+ /** Applies a command to the selection and updates the buttons' states. */
6076
+ apply(command) {
6077
+ this.hideTooltip();
6078
+ this.editor.run(command);
6079
+ if (this.isOpen) this.update();
5676
6080
  }
5677
6081
  update() {
5678
- for (const [mark, btn] of this.markButtons) {
5679
- const on = this.editor.isActive(mark);
5680
- btn.classList.toggle("mbe-active", on);
5681
- btn.setAttribute("aria-pressed", String(on));
5682
- }
5683
- this.linkButton.classList.toggle("mbe-active", this.editor.isActive("link"));
6082
+ const editor = this.editor;
6083
+ for (const [item, btn] of this.buttons) {
6084
+ const mark = MARKS[item];
6085
+ if (mark) setPressed(btn, editor.isActive(mark.mark));
6086
+ }
6087
+ const link = this.buttons.get("link");
6088
+ if (link) setPressed(link, editor.isActive("link"));
6089
+ const { anchor, focus } = editor.state.selection;
6090
+ const inCell = !!focus.cell && anchor.blockId === focus.blockId;
6091
+ for (const item of BLOCK_ITEMS) this.buttons.get(item)?.toggleAttribute("hidden", inCell);
6092
+ if (inCell) this.closeMenu();
6093
+ for (const sep of this.separators) {
6094
+ const visible = (start, step) => {
6095
+ for (let e = start; e && !e.classList.contains("mbe-tool-sep"); e = e[step]) if (!e.hidden) return true;
6096
+ return false;
6097
+ };
6098
+ sep.hidden = !visible(sep.previousElementSibling, "previousElementSibling") || !visible(sep.nextElementSibling, "nextElementSibling");
6099
+ }
6100
+ if (inCell) return;
6101
+ const state = blockState(editor);
6102
+ const quote2 = this.buttons.get("quote");
6103
+ if (quote2) setPressed(quote2, state.allQuotes);
6104
+ if (this.textStyle) {
6105
+ this.setTriggerIcon(this.textStyle, state.style ?? "text");
6106
+ this.textStyle.button.classList.toggle("mbe-active", state.allHeadings);
6107
+ }
6108
+ if (this.list) {
6109
+ const current = LIST_TYPES.find((l) => l.listType === state.listType);
6110
+ this.setTriggerIcon(this.list, current?.id ?? "bulletList");
6111
+ this.list.button.classList.toggle("mbe-active", state.allListItems);
6112
+ }
6113
+ }
6114
+ setTriggerIcon(t, name) {
6115
+ if (t.iconName === name) return;
6116
+ t.iconName = name;
6117
+ const content = iconNode(t.icon.ownerDocument, this.editor.icon(name));
6118
+ t.icon.replaceChildren(...content ? [content] : []);
6119
+ }
6120
+ toggleMenu(t) {
6121
+ const wasOpen = this.openTrigger === t;
6122
+ this.closeMenu();
6123
+ this.hideTooltip();
6124
+ if (wasOpen) return;
6125
+ const state = blockState(this.editor);
6126
+ const labels = this.editor.labels;
6127
+ let items;
6128
+ let current;
6129
+ if (t === this.textStyle) {
6130
+ current = state.style ?? void 0;
6131
+ items = TEXT_STYLES.map(({ id, spec, keys }) => ({
6132
+ id,
6133
+ label: labels[id],
6134
+ icon: this.editor.icon(id),
6135
+ labelClass: `mbe-menu-${id}`,
6136
+ keyShortcuts: keys,
6137
+ checked: id === current,
6138
+ // Sets the style; picking the current one changes nothing.
6139
+ run: () => id !== current && this.apply((s) => setBlockType(s, spec))
6140
+ }));
6141
+ } else {
6142
+ current = LIST_TYPES.find((l) => l.listType === state.listType)?.id;
6143
+ items = LIST_TYPES.map(({ id, listType, keys }) => ({
6144
+ id,
6145
+ label: labels[id],
6146
+ icon: this.editor.icon(id),
6147
+ keyShortcuts: keys,
6148
+ checked: id === current,
6149
+ run: () => this.apply((s) => toggleBlockType(s, { type: "listItem", listType }))
6150
+ }));
6151
+ }
6152
+ t.menu.setSections([{ items }]);
6153
+ if (current) t.menu.highlightId(current);
6154
+ this.openTrigger = t;
6155
+ t.button.classList.add("mbe-open");
6156
+ t.button.setAttribute("aria-expanded", "true");
6157
+ this.placeMenu(t);
6158
+ this.onMenuChange?.();
6159
+ }
6160
+ /** Puts the menu next to its button, on the side of the toolbar away from the selection. */
6161
+ placeMenu(t) {
6162
+ const rtl = this.editor.root.ownerDocument.defaultView.getComputedStyle(this.editor.root).direction === "rtl";
6163
+ t.menu.popup.show(t.button.getBoundingClientRect(), this.popup.side, 4, rtl ? "end" : "start");
6164
+ }
6165
+ scheduleTooltip(button) {
6166
+ clearTimeout(this.tooltipTimer);
6167
+ if (this.openTrigger) return;
6168
+ const delay = Date.now() - this.tooltipHiddenAt < TOOLTIP_GRACE ? 0 : TOOLTIP_DELAY;
6169
+ this.tooltipTimer = setTimeout(() => {
6170
+ if (!this.isOpen || this.openTrigger || !button.isConnected) return;
6171
+ this.tooltip.el.textContent = button.getAttribute("aria-label");
6172
+ this.tooltip.show(button.getBoundingClientRect(), this.popup.side, 6);
6173
+ const b = button.getBoundingClientRect();
6174
+ const t = this.tooltip.el.getBoundingClientRect();
6175
+ const view = this.editor.root.ownerDocument.defaultView;
6176
+ const left = Math.max(8, Math.min(b.left + (b.width - t.width) / 2, view.innerWidth - t.width - 8));
6177
+ this.tooltip.el.style.left = `${parseFloat(this.tooltip.el.style.left) + left - t.left}px`;
6178
+ }, delay);
6179
+ }
6180
+ hideTooltip() {
6181
+ clearTimeout(this.tooltipTimer);
6182
+ if (!this.tooltip.isOpen) return;
6183
+ this.tooltip.hide();
6184
+ this.tooltipHiddenAt = Date.now();
5684
6185
  }
5685
6186
  };
5686
- function separator(doc) {
5687
- const s = doc.createElement("span");
5688
- s.className = "mbe-tool-sep";
5689
- return s;
6187
+ function setPressed(button, on) {
6188
+ button.classList.toggle("mbe-active", on);
6189
+ button.setAttribute("aria-pressed", String(on));
5690
6190
  }
5691
- var LinkPopover = class {
6191
+ var InputPopover = class {
5692
6192
  popup;
5693
6193
  input;
5694
6194
  removeButton;
5695
6195
  done = null;
5696
6196
  constructor(editor) {
5697
6197
  const doc = editor.root.ownerDocument;
5698
- this.popup = new Popup(editor.root, "mbe-link-popover");
6198
+ this.popup = new Popup(editor.root, "mbe-input-popover");
5699
6199
  this.input = doc.createElement("input");
5700
- this.input.type = "url";
5701
- this.input.className = "mbe-link-input";
5702
- this.input.placeholder = editor.labels.linkPlaceholder;
5703
- this.input.setAttribute("aria-label", editor.labels.link);
6200
+ this.input.className = "mbe-popover-input";
5704
6201
  this.removeButton = doc.createElement("button");
5705
6202
  this.removeButton.type = "button";
5706
6203
  this.removeButton.className = "mbe-tool";
5707
- this.removeButton.textContent = editor.labels.removeLink;
5708
6204
  this.popup.el.append(this.input, this.removeButton);
5709
6205
  this.input.addEventListener("keydown", (e) => {
5710
6206
  if (e.key === "Enter") {
@@ -5728,10 +6224,14 @@ var LinkPopover = class {
5728
6224
  contains(node) {
5729
6225
  return this.popup.el.contains(node);
5730
6226
  }
5731
- open(rect, value, done) {
6227
+ open(rect, options, done) {
5732
6228
  this.done = done;
5733
- this.input.value = value;
5734
- this.removeButton.hidden = value === "";
6229
+ this.input.type = options.type;
6230
+ this.input.value = options.value;
6231
+ this.input.placeholder = options.placeholder;
6232
+ this.input.setAttribute("aria-label", options.label);
6233
+ this.removeButton.textContent = options.removeLabel ?? "";
6234
+ this.removeButton.hidden = !options.removeLabel || options.value === "";
5735
6235
  this.popup.show(rect, "below");
5736
6236
  this.input.focus();
5737
6237
  this.input.select();
@@ -5741,11 +6241,11 @@ var LinkPopover = class {
5741
6241
  this.done = null;
5742
6242
  this.popup.hide();
5743
6243
  }
5744
- finish(href) {
6244
+ finish(value) {
5745
6245
  const done = this.done;
5746
6246
  this.done = null;
5747
6247
  this.popup.hide();
5748
- done?.(href);
6248
+ done?.(value);
5749
6249
  }
5750
6250
  destroy() {
5751
6251
  this.popup.destroy();
@@ -5809,6 +6309,13 @@ function sameReveal(a, b) {
5809
6309
  for (const key of a) if (!b.has(key)) return false;
5810
6310
  return true;
5811
6311
  }
6312
+ function markImageBlock(el, block3) {
6313
+ const offset = imageBlockOffset(block3);
6314
+ if (offset === null) return;
6315
+ el.classList.add("mbe-image-block");
6316
+ const align = sliceInline(block3.content, offset, offset + 1)[0]?.image?.align;
6317
+ if (align) el.dataset.align = align;
6318
+ }
5812
6319
  function renderBlock(block3, ctx, reveal) {
5813
6320
  const { doc, labels } = ctx;
5814
6321
  const el = (tag, className2) => {
@@ -5824,6 +6331,7 @@ function renderBlock(block3, ctx, reveal) {
5824
6331
  root = el(block3.type === "paragraph" ? "p" : block3.type === "quote" ? "blockquote" : `h${block3.level}`);
5825
6332
  root.dir = "auto";
5826
6333
  fillContent(root, block3.content, ctx, block3, reveal);
6334
+ if (block3.type === "paragraph") markImageBlock(root, block3);
5827
6335
  break;
5828
6336
  case "listItem": {
5829
6337
  root = el("div");
@@ -6066,20 +6574,24 @@ function renderSpan(span, ctx, viewed = false) {
6066
6574
  const image = span.image;
6067
6575
  const src = ctx.resolveUrl(image.src, "image");
6068
6576
  if (src === null) return unavailableImage(image, ctx);
6069
- const img = doc.createElement("img");
6070
- img.setAttribute("loading", "lazy");
6071
- img.setAttribute("decoding", "async");
6072
- if (ctx.referrerPolicy) img.setAttribute("referrerpolicy", ctx.referrerPolicy);
6073
- img.src = src;
6577
+ let img = ctx.loadedImage?.(src);
6578
+ if (!img) {
6579
+ const el = doc.createElement("img");
6580
+ el.setAttribute("loading", "lazy");
6581
+ el.setAttribute("decoding", "async");
6582
+ if (ctx.referrerPolicy) el.setAttribute("referrerpolicy", ctx.referrerPolicy);
6583
+ el.src = src;
6584
+ el.addEventListener("error", () => {
6585
+ if (!el.parentNode) return;
6586
+ el.replaceWith(unavailableImage({ src, alt: el.alt, title: el.title || void 0 }, ctx));
6587
+ ctx.onImageError?.();
6588
+ });
6589
+ img = el;
6590
+ }
6074
6591
  img.alt = image.alt;
6075
- if (image.title) img.title = image.title;
6076
- if (image.width) img.width = image.width;
6077
- if (image.height) img.height = image.height;
6078
- img.addEventListener("error", () => {
6079
- if (!img.parentNode) return;
6080
- img.replaceWith(unavailableImage(image, ctx));
6081
- ctx.onImageError?.();
6082
- });
6592
+ setAttribute(img, "title", image.title);
6593
+ setAttribute(img, "width", image.width ? String(image.width) : void 0);
6594
+ setAttribute(img, "height", image.height ? String(image.height) : void 0);
6083
6595
  return atom(img, classes("mbe-image", ctx.classes.image));
6084
6596
  }
6085
6597
  let node = doc.createTextNode(span.text);
@@ -6092,6 +6604,10 @@ function renderSpan(span, ctx, viewed = false) {
6092
6604
  }
6093
6605
  return wrapMarks(span, node, ctx);
6094
6606
  }
6607
+ function setAttribute(el, name, value) {
6608
+ if (value === void 0) el.removeAttribute(name);
6609
+ else el.setAttribute(name, value);
6610
+ }
6095
6611
  function unavailableImage(image, ctx) {
6096
6612
  const doc = ctx.doc;
6097
6613
  const el = doc.createElement("span");
@@ -6167,6 +6683,8 @@ var BlockRenderer = class {
6167
6683
  failedViews = /* @__PURE__ */ new Set();
6168
6684
  /** The block being rendered, so a pending view knows which blocks to render again. */
6169
6685
  renderingBlock = "";
6686
+ /** During a render, the loaded images of the block elements it replaces, by `src`. */
6687
+ loadedImages = /* @__PURE__ */ new Map();
6170
6688
  context() {
6171
6689
  return {
6172
6690
  doc: this.root.ownerDocument,
@@ -6180,7 +6698,8 @@ var BlockRenderer = class {
6180
6698
  classes: this.classes,
6181
6699
  icon: this.icon,
6182
6700
  codeCopy: this.codeCopy,
6183
- onImageError: this.onImageError
6701
+ onImageError: this.onImageError,
6702
+ loadedImage: (src) => this.loadedImages.get(src)?.shift()
6184
6703
  };
6185
6704
  }
6186
6705
  renderView(syntax, source, kind) {
@@ -6233,14 +6752,31 @@ var BlockRenderer = class {
6233
6752
  */
6234
6753
  render(doc, force = false, lazy = false) {
6235
6754
  const ctx = this.context();
6755
+ const kept = /* @__PURE__ */ new Set();
6756
+ for (const block3 of doc.blocks) {
6757
+ const prev = this.rendered.get(block3.id);
6758
+ if (!force && prev && prev.block === block3 && prev.el.parentNode === this.root && sameReveal(prev.reveal, this.revealed.get(block3.id))) kept.add(prev.el);
6759
+ }
6760
+ if (!force) {
6761
+ for (const { el } of this.rendered.values()) {
6762
+ if (kept.has(el)) continue;
6763
+ for (const img of Array.from(el.querySelectorAll("img.mbe-image"))) {
6764
+ const src = img.getAttribute("src");
6765
+ if (src === null || !img.complete || img.naturalWidth === 0) continue;
6766
+ const list = this.loadedImages.get(src);
6767
+ if (list) list.push(img);
6768
+ else this.loadedImages.set(src, [img]);
6769
+ }
6770
+ }
6771
+ }
6236
6772
  const next = /* @__PURE__ */ new Map();
6237
6773
  for (const block3 of doc.blocks) {
6238
6774
  this.renderingBlock = block3.id;
6239
6775
  const prev = this.rendered.get(block3.id);
6240
6776
  const reveal = this.revealed.get(block3.id);
6241
- const reuse = !force && prev && prev.block === block3 && prev.el.parentNode === this.root && sameReveal(prev.reveal, reveal);
6242
- next.set(block3.id, { block: block3, el: reuse ? prev.el : renderBlock(block3, ctx, reveal), reveal });
6777
+ next.set(block3.id, { block: block3, el: prev && kept.has(prev.el) ? prev.el : renderBlock(block3, ctx, reveal), reveal });
6243
6778
  }
6779
+ this.loadedImages.clear();
6244
6780
  const nodes = [];
6245
6781
  for (const [id, { el }] of next) {
6246
6782
  nodes.push(el);
@@ -6449,7 +6985,7 @@ function positionToDom(blockEl, pos) {
6449
6985
  return { node: last.parentNode, offset: childIndex(last) + 1 };
6450
6986
  }
6451
6987
 
6452
- // src/ui/handle.ts
6988
+ // src/ui/blockHandle.ts
6453
6989
  var BlockHandle = class {
6454
6990
  constructor(editor) {
6455
6991
  this.editor = editor;
@@ -6457,7 +6993,7 @@ var BlockHandle = class {
6457
6993
  const doc = root.ownerDocument;
6458
6994
  this.el = doc.createElement("button");
6459
6995
  this.el.type = "button";
6460
- this.el.className = "mbe-ui mbe-handle";
6996
+ this.el.className = "mbe-ui mbe-block-handle";
6461
6997
  const icon = iconNode(doc, editor.icon("blockHandle"));
6462
6998
  if (icon) this.el.appendChild(icon);
6463
6999
  this.el.setAttribute("aria-label", editor.labels.blockHandle);
@@ -6491,7 +7027,7 @@ var BlockHandle = class {
6491
7027
  if (this.editor.hasBlockMenu(blockId)) this.showFor(blockId);
6492
7028
  else if (this.blockId !== null) this.scheduleHide();
6493
7029
  }
6494
- /** Shows the handle next to a block. */
7030
+ /** Shows the block handle next to a block. */
6495
7031
  showFor(blockId) {
6496
7032
  this.cancelHide();
6497
7033
  const blockEl = this.editor.blockElement(blockId);
@@ -6507,7 +7043,7 @@ var BlockHandle = class {
6507
7043
  this.el.style.left = `${Math.round(rect.left - (this.el.offsetWidth || 20) - 6 - offset.x)}px`;
6508
7044
  this.el.style.top = `${Math.round(rect.top + firstLine / 2 - size / 2 - offset.y)}px`;
6509
7045
  }
6510
- /** True when `node` is the handle or inside it. */
7046
+ /** True when `node` is the block handle or inside it. */
6511
7047
  contains(node) {
6512
7048
  return this.el.contains(node);
6513
7049
  }
@@ -6531,10 +7067,10 @@ var BlockHandle = class {
6531
7067
  }
6532
7068
  };
6533
7069
 
6534
- // src/ui/image.ts
7070
+ // src/ui/resizeHandles.ts
6535
7071
  var MIN_WIDTH = 24;
6536
7072
  var SNAP = 8;
6537
- var ImageControls = class {
7073
+ var ResizeHandles = class {
6538
7074
  constructor(editor) {
6539
7075
  this.editor = editor;
6540
7076
  const root = editor.root;
@@ -6543,16 +7079,16 @@ var ImageControls = class {
6543
7079
  this.frame = doc.createElement("div");
6544
7080
  this.frame.className = "mbe-ui mbe-image-frame";
6545
7081
  this.frame.hidden = true;
6546
- const handle = (side) => {
7082
+ const resizeHandle = (side) => {
6547
7083
  const el = doc.createElement("div");
6548
- el.className = `mbe-image-handle mbe-image-handle-${side}`;
7084
+ el.className = `mbe-resize-handle mbe-resize-handle-${side}`;
6549
7085
  el.dataset.side = side;
6550
7086
  el.title = labels.resizeImage;
6551
7087
  el.setAttribute("aria-hidden", "true");
6552
7088
  this.frame.appendChild(el);
6553
7089
  return el;
6554
7090
  };
6555
- this.handles = { left: handle("left"), right: handle("right") };
7091
+ this.handles = { left: resizeHandle("left"), right: resizeHandle("right") };
6556
7092
  const on = (target, type, fn) => {
6557
7093
  target.addEventListener(type, fn);
6558
7094
  this.cleanup.push(() => target.removeEventListener(type, fn));
@@ -6582,7 +7118,7 @@ var ImageControls = class {
6582
7118
  drag = null;
6583
7119
  hideTimer = null;
6584
7120
  cleanup = [];
6585
- /** True when `node` is part of these controls. */
7121
+ /** True when `node` is the frame or one of its resize handles. */
6586
7122
  contains(node) {
6587
7123
  return this.frame.contains(node);
6588
7124
  }
@@ -6591,7 +7127,7 @@ var ImageControls = class {
6591
7127
  this.selected = selected;
6592
7128
  if (!this.drag) this.placeFrame();
6593
7129
  }
6594
- /** Moves the controls to where their image is now, after scrolling. */
7130
+ /** Moves the resize handles to where their image is now, after scrolling. */
6595
7131
  reposition() {
6596
7132
  if (this.drag) return;
6597
7133
  if (this.selected && !this.selected.el.isConnected) this.selected = null;
@@ -6668,7 +7204,8 @@ var ImageControls = class {
6668
7204
  const width = el.getBoundingClientRect().width;
6669
7205
  const others = Array.from(this.editor.root.querySelectorAll("img.mbe-image")).filter((other) => other !== el).map((other) => other.getBoundingClientRect().width).filter((w) => w > 0);
6670
7206
  const max = Math.max(MIN_WIDTH, columnWidth(el));
6671
- this.drag = { el, side, pointer: e.pointerId, startX: e.clientX, startWidth: width, max, snaps: [...others, max], width };
7207
+ const factor = el.closest(".mbe-image-block")?.getAttribute("data-align") === "center" ? 2 : 1;
7208
+ this.drag = { el, side, pointer: e.pointerId, startX: e.clientX, startWidth: width, max, snaps: [...others, max], width, factor };
6672
7209
  this.frame.classList.add("mbe-image-resizing");
6673
7210
  this.editor.selectImageAt(target.pos);
6674
7211
  }
@@ -6676,7 +7213,7 @@ var ImageControls = class {
6676
7213
  const drag = this.drag;
6677
7214
  if (!drag || e.pointerId !== drag.pointer) return;
6678
7215
  e.preventDefault();
6679
- const dx = (e.clientX - drag.startX) * (drag.side === "right" ? 1 : -1);
7216
+ const dx = (e.clientX - drag.startX) * (drag.side === "right" ? 1 : -1) * drag.factor;
6680
7217
  let width = Math.min(drag.max, Math.max(MIN_WIDTH, drag.startWidth + dx));
6681
7218
  const snap = drag.snaps.find((w) => Math.abs(w - width) <= SNAP);
6682
7219
  if (snap !== void 0) width = Math.min(drag.max, snap);
@@ -6856,7 +7393,7 @@ var SLASH_ITEM_IDS = [
6856
7393
  "table",
6857
7394
  "divider"
6858
7395
  ];
6859
- var BLOCK_ITEMS = [
7396
+ var BLOCK_ITEMS2 = [
6860
7397
  { id: "text", aliases: ["paragraph", "plain"], spec: { type: "paragraph" } },
6861
7398
  { id: "heading1", aliases: ["h1", "title"], spec: { type: "heading", level: 1 } },
6862
7399
  { id: "heading2", aliases: ["h2", "subtitle"], spec: { type: "heading", level: 2 } },
@@ -6869,17 +7406,19 @@ var BLOCK_ITEMS = [
6869
7406
  { id: "table", aliases: ["grid"], spec: { type: "table" } },
6870
7407
  { id: "divider", aliases: ["hr", "separator", "line", "rule"], spec: { type: "divider" } }
6871
7408
  ];
6872
- var TABLE_ITEMS = [
7409
+ var TABLE_ACTIONS = [
6873
7410
  { id: "addRowAbove", action: { kind: "addRowAbove" } },
6874
7411
  { id: "addRowBelow", action: { kind: "addRowBelow" } },
6875
7412
  { id: "addColumnLeft", action: { kind: "addColumnLeft" } },
6876
7413
  { id: "addColumnRight", action: { kind: "addColumnRight" } },
6877
- { id: "alignLeft", action: { kind: "align", align: "left" } },
6878
- { id: "alignCenter", action: { kind: "align", align: "center" } },
6879
- { id: "alignRight", action: { kind: "align", align: "right" } },
6880
7414
  { id: "deleteRow", action: { kind: "deleteRow" } },
6881
7415
  { id: "deleteColumn", action: { kind: "deleteColumn" } }
6882
7416
  ];
7417
+ var ALIGN_CHOICES = [
7418
+ { id: "alignLeft", align: "left", image: "imageAlignLeft" },
7419
+ { id: "alignCenter", align: "center", image: "imageAlignCenter" },
7420
+ { id: "alignRight", align: "right", image: "imageAlignRight" }
7421
+ ];
6883
7422
  var SLASH_CHARS = ["/", "\uFF0F"];
6884
7423
  var CARET_KEY = /^(Arrow(Up|Down|Left|Right)|Home|End|PageUp|PageDown)$/;
6885
7424
  var COMPOSITION_INPUT = /* @__PURE__ */ new Set(["insertCompositionText", "deleteCompositionText", "insertFromComposition", "deleteByComposition"]);
@@ -6906,6 +7445,12 @@ var Editor = class {
6906
7445
  composition = null;
6907
7446
  /** When the last composition ended (Safari only): the next key may be the Enter that committed it. */
6908
7447
  compositionEndedAt = 0;
7448
+ /**
7449
+ * The last Markdown shortcut that typing applied: the state with the typed
7450
+ * characters, and the state the shortcut made. Backspace right after it
7451
+ * goes back to the typed characters.
7452
+ */
7453
+ shortcut = null;
6909
7454
  /** Blocks the browser edited during a composition that ended, rendered again on the next frame. */
6910
7455
  unsettled = /* @__PURE__ */ new Set();
6911
7456
  settleFrame = null;
@@ -6945,9 +7490,10 @@ var Editor = class {
6945
7490
  suggestions;
6946
7491
  blockMenu;
6947
7492
  toolbar;
6948
- linkPopover;
6949
- handle;
6950
- imageControls;
7493
+ /** The link popover, and the field for an image's alt text. */
7494
+ inputPopover;
7495
+ blockHandle;
7496
+ resizeHandles;
6951
7497
  /** The selected image's element, which carries the selected class. */
6952
7498
  selectedImageEl = null;
6953
7499
  hintEl = null;
@@ -7047,10 +7593,14 @@ var Editor = class {
7047
7593
  };
7048
7594
  this.blockMenu = new Menu(root, "mbe-block-menu", "menu");
7049
7595
  this.blockMenu.onPicked = () => this.blockMenu.hide();
7050
- this.linkPopover = new LinkPopover(this);
7051
- this.toolbar = options.toolbar === false ? null : new FormatToolbar(this);
7052
- this.handle = new BlockHandle(this);
7053
- this.imageControls = new ImageControls(this);
7596
+ this.blockMenu.onHighlight = () => this.syncActiveDescendant();
7597
+ this.blockMenu.checkIcon = this.icon("selected");
7598
+ this.blockMenu.submenuIcon = this.icon("chevronRight");
7599
+ this.inputPopover = new InputPopover(this);
7600
+ this.toolbar = options.toolbar === false ? null : new FormatToolbar(this, typeof options.toolbar === "object" ? options.toolbar.items : void 0);
7601
+ if (this.toolbar) this.toolbar.onMenuChange = () => this.syncActiveDescendant();
7602
+ this.blockHandle = new BlockHandle(this);
7603
+ this.resizeHandles = new ResizeHandles(this);
7054
7604
  this.renderer.onImageError = () => {
7055
7605
  if (this.destroyed) return;
7056
7606
  if (!this.composing) this.syncDomSelection();
@@ -7146,7 +7696,7 @@ var Editor = class {
7146
7696
  case "image": {
7147
7697
  const selected = selectedImage(s);
7148
7698
  if (!selected || !attrs) return selected !== null;
7149
- const actual2 = { ...selected.image };
7699
+ const actual2 = { ...selected.image, block: selectedImageBlock(s) !== null };
7150
7700
  return Object.entries(attrs).every(([k, v]) => actual2[k] === v);
7151
7701
  }
7152
7702
  }
@@ -7156,14 +7706,17 @@ var Editor = class {
7156
7706
  const actual = this.getAttributes(name);
7157
7707
  return Object.entries(attrs).every(([k, v]) => actual[k] === v);
7158
7708
  }
7159
- /** Attributes of `name` at the selection: `src`, `alt`, `title`, `width` and `height` for a selected image, `href` for a link, `level` for a heading, `language` for a code block, `checked` for a task, `syntax` for a raw block. */
7709
+ /** Attributes of `name` at the selection: `src`, `alt`, `title`, `align`, `width`, `height` and `block` (true for an image block) for a selected image, `href` for a link, `level` for a heading, `language` for a code block, `checked` for a task, `syntax` for a raw block. */
7160
7710
  getAttributes(name) {
7161
7711
  const s = this.current;
7162
7712
  if (name === "link") {
7163
7713
  const link = activeLink(s);
7164
7714
  return link ? { href: link.href } : {};
7165
7715
  }
7166
- if (name === "image") return { ...selectedImage(s)?.image };
7716
+ if (name === "image") {
7717
+ const selected = selectedImage(s);
7718
+ return selected ? { ...selected.image, block: selectedImageBlock(s) !== null } : {};
7719
+ }
7167
7720
  const block3 = getBlock(s.doc, s.selection.focus.blockId);
7168
7721
  if (blockName(block3) !== name) return {};
7169
7722
  switch (block3.type) {
@@ -7526,9 +8079,9 @@ var Editor = class {
7526
8079
  for (const widget of [...this.widgets]) widget.remove();
7527
8080
  this.blockMenu.destroy();
7528
8081
  this.toolbar?.destroy();
7529
- this.linkPopover.destroy();
7530
- this.handle.destroy();
7531
- this.imageControls.destroy();
8082
+ this.inputPopover.destroy();
8083
+ this.blockHandle.destroy();
8084
+ this.resizeHandles.destroy();
7532
8085
  setPopupContainer(this.root, void 0);
7533
8086
  for (const name of Object.keys(this.runtime.attributes ?? {})) this.root.removeAttribute(name);
7534
8087
  for (const name of this.tokenNames) this.root.style.removeProperty(name);
@@ -7698,8 +8251,13 @@ var Editor = class {
7698
8251
  this.updateUi();
7699
8252
  return;
7700
8253
  }
8254
+ this.shortcut = null;
7701
8255
  const skipped = key?.vertical ? this.skippedBlock(key.from, key.vertical, key.x, selection.focus) : null;
7702
- if (skipped) {
8256
+ const image = this.imageBlockAt(skipped ? { anchor: skipped, focus: skipped } : selection);
8257
+ if (image) {
8258
+ if (!samePosition(image.anchor, cur.anchor) || !samePosition(image.focus, cur.focus)) this.setSelection(image);
8259
+ else this.updateUi();
8260
+ } else if (skipped) {
7703
8261
  this.setSelection({ anchor: skipped, focus: skipped });
7704
8262
  } else {
7705
8263
  this.current = { ...this.state, selection, storedMarks: null };
@@ -7710,6 +8268,14 @@ var Editor = class {
7710
8268
  }
7711
8269
  if (key) this.scrollCaretIntoView();
7712
8270
  }
8271
+ /** The selection of an image block's image, when `sel` is a caret in that block. */
8272
+ imageBlockAt(sel) {
8273
+ if (!isCollapsed(sel) || sel.focus.cell) return null;
8274
+ const block3 = this.state.doc.blocks.find((b) => b.id === sel.focus.blockId);
8275
+ const offset = block3 ? imageBlockOffset(block3) : null;
8276
+ if (offset === null) return null;
8277
+ return { anchor: { blockId: block3.id, offset }, focus: { blockId: block3.id, offset: offset + 1 } };
8278
+ }
7713
8279
  /**
7714
8280
  * After the browser moved the caret from block `from` with ArrowDown
7715
8281
  * (`dir` 1) or ArrowUp to `to`: the position in the first block it passed
@@ -7862,6 +8428,44 @@ var Editor = class {
7862
8428
  }
7863
8429
  return viewEntry(view, forward);
7864
8430
  }
8431
+ /**
8432
+ * An arrow key next to an image block: from the edge of the block before
8433
+ * or after it, the selection of its image; from a selected image block, a
8434
+ * caret in the next block that holds one, or the same selection when there
8435
+ * is none. Null when no image block is involved.
8436
+ */
8437
+ imageBlockStep(key) {
8438
+ const sel = this.state.selection;
8439
+ const blocks = this.state.doc.blocks;
8440
+ const forward = key === "ArrowDown" || key === "ArrowRight";
8441
+ const selected = selectedImageBlock(this.state);
8442
+ if (selected) {
8443
+ const index2 = blockIndex(this.state.doc, selected.pos.blockId);
8444
+ for (let i = index2 + (forward ? 1 : -1); i >= 0 && i < blocks.length; i += forward ? 1 : -1) {
8445
+ const block3 = blocks[i];
8446
+ if (block3.type === "divider") continue;
8447
+ const offset2 = imageBlockOffset(block3);
8448
+ if (offset2 !== null) return { anchor: { blockId: block3.id, offset: offset2 }, focus: { blockId: block3.id, offset: offset2 + 1 } };
8449
+ const vertical = key === "ArrowDown" || key === "ArrowUp";
8450
+ const pos = vertical ? this.blockEntry(block3, forward, this.selectionRect()?.left ?? 0) : forward ? startOf(block3) : endOf(block3);
8451
+ return { anchor: pos, focus: pos };
8452
+ }
8453
+ return sel;
8454
+ }
8455
+ if (!isCollapsed(sel) || sel.focus.cell) return null;
8456
+ const index = blockIndex(this.state.doc, sel.focus.blockId);
8457
+ const current = blocks[index];
8458
+ const next = blocks[index + (forward ? 1 : -1)];
8459
+ const offset = next ? imageBlockOffset(next) : null;
8460
+ if (!next || offset === null || !isTextBlock(current)) return null;
8461
+ if (key === "ArrowRight" && sel.focus.offset !== endOf(current).offset) return null;
8462
+ if (key === "ArrowLeft" && sel.focus.offset !== 0) return null;
8463
+ if (key === "ArrowDown" || key === "ArrowUp") {
8464
+ const content = contentElement(this.renderer.elementFor(current.id));
8465
+ if (content && !this.onEdgeLine(content, forward)) return null;
8466
+ }
8467
+ return { anchor: { blockId: next.id, offset }, focus: { blockId: next.id, offset: offset + 1 } };
8468
+ }
7865
8469
  /**
7866
8470
  * ArrowUp or ArrowDown on the first or last line of a table cell: the
7867
8471
  * position in the cell above or below (same column), or past the table in
@@ -7957,6 +8561,7 @@ var Editor = class {
7957
8561
  return;
7958
8562
  }
7959
8563
  this.refreshSelection();
8564
+ if ((type === "insertText" || type === "insertReplacementText") && selectedImageBlock(this.state)) return;
7960
8565
  switch (type) {
7961
8566
  case "insertText": {
7962
8567
  const text = e.data ?? "";
@@ -7981,7 +8586,7 @@ var Editor = class {
7981
8586
  this.run(insertLineBreak);
7982
8587
  return;
7983
8588
  case "deleteContentBackward":
7984
- this.run(deleteBackward);
8589
+ if (!this.undoShortcut()) this.run(deleteBackward);
7985
8590
  return;
7986
8591
  case "deleteContentForward":
7987
8592
  this.run(deleteForward);
@@ -8042,12 +8647,27 @@ var Editor = class {
8042
8647
  }
8043
8648
  /** Markdown shortcuts and suggestion menus that typing `text` triggers. */
8044
8649
  afterTyping(text) {
8650
+ const typed = this.state;
8045
8651
  if (text === " " || text === "-") this.run((s) => applyBlockInputRules(s));
8046
8652
  if (text.length === 1 && "*_`~".includes(text)) this.run((s) => applyInlineInputRules(s));
8047
8653
  if (this.markdown.inline.length > 0) this.run((s) => applyTokenInputRules(s, this.markdown.inline) ?? s);
8048
8654
  if (text === " " && this.markdown.autolinks) this.run((s) => applyAutolinkInputRule(s) ?? s);
8655
+ this.shortcut = this.state.doc !== typed.doc ? { typed, applied: this.state } : null;
8049
8656
  if (!text.includes("\n")) this.typedForSuggestion();
8050
8657
  }
8658
+ /**
8659
+ * Backspace right after a Markdown shortcut, with no edit or caret move since,
8660
+ * restores the characters that were typed: `**a**` stays text. It is its
8661
+ * own undo step.
8662
+ */
8663
+ undoShortcut() {
8664
+ const shortcut = this.shortcut;
8665
+ this.shortcut = null;
8666
+ const { doc, selection } = this.state;
8667
+ if (!shortcut || doc !== shortcut.applied.doc || !isCollapsed(selection)) return false;
8668
+ if (!samePosition(selection.focus, shortcut.applied.selection.focus)) return false;
8669
+ return this.run(() => shortcut.typed);
8670
+ }
8051
8671
  onCompositionStart(e) {
8052
8672
  if (this.fromControl(e)) return;
8053
8673
  this.dropBlockSelection();
@@ -8198,6 +8818,7 @@ var Editor = class {
8198
8818
  this.caretKey = null;
8199
8819
  if (this.fromControl(e)) return;
8200
8820
  if (e.isComposing || e.keyCode === 229) return;
8821
+ if (CARET_KEY.test(e.key)) this.shortcut = null;
8201
8822
  const mod2 = isMac ? e.metaKey : e.ctrlKey;
8202
8823
  const key = e.key.toLowerCase();
8203
8824
  const handled = (fn) => {
@@ -8214,12 +8835,20 @@ var Editor = class {
8214
8835
  return;
8215
8836
  }
8216
8837
  }
8217
- const menu = this.blockMenu.isOpen ? this.blockMenu : null;
8838
+ const menu = this.blockMenu.isOpen ? this.blockMenu : this.toolbar?.menu ?? null;
8218
8839
  if (menu) {
8840
+ const sub = menu.submenu;
8841
+ if (sub) {
8842
+ if (e.key === "ArrowLeft" || e.key === "Escape") return handled(() => menu.closeSubmenu());
8843
+ if (e.key === "ArrowDown" || e.key === "Tab" && !e.shiftKey) return handled(() => this.moveMenu(sub, 1));
8844
+ if (e.key === "ArrowUp" || e.key === "Tab" && e.shiftKey) return handled(() => this.moveMenu(sub, -1));
8845
+ if (e.key === "Enter" && sub.count > 0) return handled(() => sub.pick());
8846
+ }
8847
+ if (e.key === "ArrowRight" && menu.openSubmenu()) return handled(() => this.syncActiveDescendant());
8219
8848
  if (e.key === "ArrowDown" || e.key === "Tab" && !e.shiftKey) return handled(() => this.moveMenu(menu, 1));
8220
8849
  if (e.key === "ArrowUp" || e.key === "Tab" && e.shiftKey) return handled(() => this.moveMenu(menu, -1));
8221
8850
  if (e.key === "Enter" && menu.count > 0) return handled(() => menu.pick());
8222
- if (e.key === "Escape") return handled(() => this.closeBlockMenu());
8851
+ if (e.key === "Escape") return handled(() => menu === this.blockMenu ? this.closeBlockMenu() : this.toolbar.closeMenu());
8223
8852
  }
8224
8853
  if (e.key === "Escape" && this.toolbar?.isOpen) {
8225
8854
  return handled(() => {
@@ -8252,6 +8881,10 @@ var Editor = class {
8252
8881
  }
8253
8882
  if (e.key === "Backspace" && !e.ctrlKey && !e.metaKey && !e.altKey) {
8254
8883
  this.refreshSelection();
8884
+ if (this.undoShortcut()) {
8885
+ e.preventDefault();
8886
+ return;
8887
+ }
8255
8888
  const { selection } = this.state;
8256
8889
  if (isCollapsed(selection) && selection.focus.offset === 0) {
8257
8890
  e.preventDefault();
@@ -8276,6 +8909,13 @@ var Editor = class {
8276
8909
  this.setSelection({ anchor: into, focus: into });
8277
8910
  return;
8278
8911
  }
8912
+ const image = this.imageBlockStep(e.key);
8913
+ if (image) {
8914
+ e.preventDefault();
8915
+ if (image !== this.state.selection) this.setSelection(image);
8916
+ else if (e.key === "ArrowDown" || e.key === "ArrowUp") this.run((s) => exitBlock(s, e.key === "ArrowDown" ? 1 : -1));
8917
+ return;
8918
+ }
8279
8919
  const vertical = e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
8280
8920
  const cell = vertical ? this.tableCellPast(vertical) : null;
8281
8921
  if (cell) {
@@ -8378,20 +9018,22 @@ var Editor = class {
8378
9018
  }
8379
9019
  }
8380
9020
  /**
8381
- * A click in the empty space below a final code block, table or divider
9021
+ * A click in the empty space below a final code block, table, divider or image block
8382
9022
  * adds a paragraph there. The browser would put the caret inside the
8383
9023
  * block, or in the block above a table.
8384
9024
  */
8385
9025
  clickBelowLastBlock(e) {
8386
9026
  const blocks = this.state.doc.blocks;
8387
9027
  const last = blocks[blocks.length - 1];
8388
- if (!last || last.type !== "code" && last.type !== "table" && last.type !== "divider") return false;
9028
+ const image = last ? imageBlockOffset(last) : null;
9029
+ if (!last || last.type !== "code" && last.type !== "table" && last.type !== "divider" && image === null) return false;
8389
9030
  const el = this.root.querySelector(`:scope > [data-block-id="${last.id}"]`);
8390
9031
  if (!el || e.clientY <= el.getBoundingClientRect().bottom) return false;
8391
9032
  e.preventDefault();
8392
9033
  this.root.focus({ preventScroll: true });
8393
9034
  const end = endOf(last);
8394
- this.run((s) => exitBlock({ ...s, selection: { anchor: end, focus: end } }, 1));
9035
+ const selection = image !== null ? { anchor: { blockId: last.id, offset: image }, focus: { blockId: last.id, offset: image + 1 } } : { anchor: end, focus: end };
9036
+ this.run((s) => exitBlock({ ...s, selection }, 1));
8395
9037
  return true;
8396
9038
  }
8397
9039
  onClick(e) {
@@ -8467,9 +9109,9 @@ var Editor = class {
8467
9109
  }
8468
9110
  onFocusOut(e) {
8469
9111
  const next = e.relatedTarget;
8470
- if (next && (this.root.contains(next) || this.linkPopover.contains(next))) return;
9112
+ if (next && (this.root.contains(next) || this.inputPopover.contains(next))) return;
8471
9113
  queueMicrotask(() => {
8472
- if (this.hasFocus() || this.linkPopover.isOpen) return;
9114
+ if (this.hasFocus() || this.inputPopover.isOpen) return;
8473
9115
  if (!this.focused) return;
8474
9116
  this.focused = false;
8475
9117
  this.root.classList.remove("mbe-focused");
@@ -8481,8 +9123,8 @@ var Editor = class {
8481
9123
  });
8482
9124
  }
8483
9125
  onScroll() {
8484
- this.handle.hide();
8485
- this.imageControls.reposition();
9126
+ this.blockHandle.hide();
9127
+ this.resizeHandles.reposition();
8486
9128
  if (this.suggestions.isActive || this.toolbar?.isOpen || this.blockMenu.isOpen) this.updateUi();
8487
9129
  }
8488
9130
  // -------------------------------------------------------------------------
@@ -8587,7 +9229,7 @@ var Editor = class {
8587
9229
  /** The slash menu, as a suggestion. */
8588
9230
  slashSuggestion() {
8589
9231
  const ids = this.options.slashMenu || SLASH_ITEM_IDS;
8590
- 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 }));
9232
+ const items = ids.map((id) => BLOCK_ITEMS2.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 }));
8591
9233
  return {
8592
9234
  name: "slash",
8593
9235
  trigger: SLASH_CHARS,
@@ -8750,16 +9392,42 @@ var Editor = class {
8750
9392
  blockMenuSections(blockId) {
8751
9393
  const block3 = getBlock(this.state.doc, blockId);
8752
9394
  const sections2 = [];
8753
- if (block3.type === "table" && this.state.selection.focus.blockId === blockId && this.state.selection.focus.cell) {
8754
- sections2.push({
8755
- title: this.labels.tableSection,
8756
- items: TABLE_ITEMS.map(({ id, action }) => ({
8757
- id,
8758
- label: this.labels[id],
8759
- icon: this.icon(id),
8760
- run: () => this.run((s) => tableAction(s, action))
8761
- }))
8762
- });
9395
+ const cell = this.state.selection.focus.cell;
9396
+ if (block3.type === "table" && this.state.selection.focus.blockId === blockId && cell) {
9397
+ const items = TABLE_ACTIONS.map(({ id, action }) => ({
9398
+ id,
9399
+ label: this.labels[id],
9400
+ icon: this.icon(id),
9401
+ run: () => this.run((s) => tableAction(s, action))
9402
+ }));
9403
+ const current = block3.align[cell.col] ?? "left";
9404
+ items.splice(4, 0, this.alignMenuItem("align", current, (align) => ({
9405
+ icon: this.icon(align.id),
9406
+ run: () => this.run((s) => tableAction(s, { kind: "align", align: align.align }))
9407
+ })));
9408
+ sections2.push({ title: this.labels.tableSection, items });
9409
+ }
9410
+ const imageOffset = imageBlockOffset(block3);
9411
+ if (imageOffset !== null) {
9412
+ const pos = { blockId, offset: imageOffset };
9413
+ const image = sliceInline(block3.content, imageOffset, imageOffset + 1)[0].image;
9414
+ const items = [
9415
+ this.alignMenuItem("imageAlignLeft", image.align ?? "left", (align) => ({
9416
+ icon: this.icon(align.image),
9417
+ // An image without an alignment sits on the left, so Left removes the word.
9418
+ run: () => this.updateImageAt(pos, { align: align.align === "left" ? null : align.align })
9419
+ })),
9420
+ { id: "altText", label: this.labels.altText, icon: this.icon("altText"), run: () => this.editAltText(pos, image.alt) }
9421
+ ];
9422
+ if (image.width) {
9423
+ items.push({
9424
+ id: "resetImageSize",
9425
+ label: this.labels.resetImageSize,
9426
+ icon: this.icon("resetImageSize"),
9427
+ run: () => this.updateImageAt(pos, { width: null })
9428
+ });
9429
+ }
9430
+ sections2.push({ title: this.labels.imageSection, items });
8763
9431
  }
8764
9432
  sections2.push({
8765
9433
  items: [
@@ -8769,22 +9437,41 @@ var Editor = class {
8769
9437
  });
8770
9438
  return sections2;
8771
9439
  }
9440
+ /** The Align row of the block menu: a submenu of Left, Center and Right with the current one checked. */
9441
+ alignMenuItem(icon, current, choice) {
9442
+ return {
9443
+ id: "align",
9444
+ label: this.labels.align,
9445
+ icon: this.icon(icon),
9446
+ run: () => {
9447
+ },
9448
+ submenu: {
9449
+ title: this.labels.align,
9450
+ items: ALIGN_CHOICES.map((align) => ({ id: align.id, label: this.labels[align.id], checked: current === align.align, ...choice(align) }))
9451
+ }
9452
+ };
9453
+ }
8772
9454
  /**
8773
9455
  * @internal
8774
- * Only large blocks get the handle and block menu: tables and code blocks.
8775
- * Other blocks change type through the slash menu or Markdown shortcuts.
9456
+ * Only large blocks get the block handle and block menu: tables, code blocks and
9457
+ * image blocks. Other blocks change type through the slash menu or Markdown
9458
+ * shortcuts.
8776
9459
  */
8777
9460
  hasBlockMenu(blockId) {
8778
9461
  const block3 = this.state.doc.blocks.find((b) => b.id === blockId);
8779
- return block3?.type === "table" || block3?.type === "code";
9462
+ return block3?.type === "table" || block3?.type === "code" || !!block3 && isImageBlock(block3);
8780
9463
  }
8781
- /** @internal Opens the block menu of a table or code block, as the block handle and Mod+/ do. */
9464
+ /** @internal Opens the block menu of a table, code block or image block, as the block handle and Mod+/ do. */
8782
9465
  openBlockMenu(blockId, anchor) {
8783
9466
  if (this.readOnly || !this.hasBlockMenu(blockId)) return;
8784
9467
  this.dropBlockSelection();
8785
9468
  this.suggestions.close();
8786
9469
  this.toolbar?.hide();
8787
- if (this.state.selection.focus.blockId !== blockId) {
9470
+ const imageOffset = imageBlockOffset(getBlock(this.state.doc, blockId));
9471
+ if (imageOffset !== null) {
9472
+ this.current = selectImage(this.state, { blockId, offset: imageOffset });
9473
+ if (!this.hasFocus()) this.focus();
9474
+ } else if (this.state.selection.focus.blockId !== blockId) {
8788
9475
  const block3 = getBlock(this.state.doc, blockId);
8789
9476
  const start = startOf(block3);
8790
9477
  this.current = { ...this.state, selection: { anchor: start, focus: start } };
@@ -8801,30 +9488,41 @@ var Editor = class {
8801
9488
  this.blockMenu.hide();
8802
9489
  this.syncActiveDescendant();
8803
9490
  }
8804
- /** A press anywhere but the block menu or the block handle closes the menu, in the editor's text too. */
9491
+ /**
9492
+ * A press anywhere but the block menu or the block handle closes the block menu,
9493
+ * in the editor's text too. The same goes for a toolbar menu and the toolbar.
9494
+ */
8805
9495
  onDocumentPointerDown(e) {
8806
- if (!this.blockMenu.isOpen) return;
8807
9496
  const target = e.target;
8808
- if (target && (this.blockMenu.popup.el.contains(target) || this.handle.contains(target))) return;
9497
+ if (this.toolbar?.menu && !(target && this.toolbar.contains(target))) this.toolbar.closeMenu();
9498
+ if (!this.blockMenu.isOpen) return;
9499
+ if (target && (this.blockMenu.contains(target) || this.blockHandle.contains(target))) return;
8809
9500
  this.closeBlockMenu();
8810
9501
  }
8811
9502
  // -------------------------------------------------------------------------
8812
9503
  // Toolbar and link popover (see ui/toolbar.ts)
8813
- /** @internal Opens the link popover for the selection, as Mod+K does. */
9504
+ /**
9505
+ * @internal Opens the link popover for the selection, as Mod+K does. Returns
9506
+ * false when there is nothing to link: no selected text and no link at the caret.
9507
+ */
8814
9508
  openLinkPopover() {
8815
- if (this.readOnly) return;
9509
+ if (this.readOnly) return false;
8816
9510
  const block3 = getBlock(this.state.doc, this.state.selection.focus.blockId);
8817
- if (isPlainTextBlock(block3)) return;
8818
- if (isCollapsed(this.state.selection) && !activeLink(this.state)) return;
9511
+ if (isPlainTextBlock(block3)) return false;
9512
+ if (isCollapsed(this.state.selection) && !activeLink(this.state)) return false;
8819
9513
  const rect = this.selectionRect();
8820
- if (!rect) return;
9514
+ if (!rect) return false;
8821
9515
  this.toolbar?.hide();
8822
9516
  const saved = this.state.selection;
8823
- this.linkPopover.open(rect, activeLink(this.current)?.href ?? "", (href) => {
9517
+ const value = activeLink(this.current)?.href ?? "";
9518
+ const { labels } = this;
9519
+ const options = { value, label: labels.link, placeholder: labels.linkPlaceholder, type: "url", removeLabel: labels.removeLink };
9520
+ this.inputPopover.open(rect, options, (href) => {
8824
9521
  this.current = { ...this.state, selection: saved };
8825
9522
  if (href !== null) this.run((s) => setLink(s, href === "" ? null : href));
8826
9523
  this.focus();
8827
9524
  });
9525
+ return true;
8828
9526
  }
8829
9527
  // -------------------------------------------------------------------------
8830
9528
  // UI that follows the selection
@@ -8844,7 +9542,7 @@ var Editor = class {
8844
9542
  this.suggestions.update(focused);
8845
9543
  const image = focused && !this.readOnly && !this.blockSel ? this.imageTargetAt(this.state) : null;
8846
9544
  this.paintSelectedImage(image?.el ?? null);
8847
- this.imageControls.update(image);
9545
+ this.resizeHandles.update(image);
8848
9546
  if (this.toolbar) {
8849
9547
  const block3 = this.state.doc.blocks.find((b) => b.id === pos.blockId);
8850
9548
  const closed = this.toolbarClosedFor;
@@ -8854,8 +9552,8 @@ var Editor = class {
8854
9552
  else this.toolbar.hide();
8855
9553
  }
8856
9554
  if (focused && !this.readOnly && isTouch()) {
8857
- if (this.hasBlockMenu(pos.blockId)) this.handle.showFor(pos.blockId);
8858
- else this.handle.hide();
9555
+ if (this.hasBlockMenu(pos.blockId)) this.blockHandle.showFor(pos.blockId);
9556
+ else this.blockHandle.hide();
8859
9557
  }
8860
9558
  if (!focused && this.blockMenu.isOpen && !this.root.ownerDocument.activeElement?.closest?.(".mbe-ui")) this.blockMenu.hide();
8861
9559
  this.syncActiveDescendant();
@@ -8870,7 +9568,7 @@ var Editor = class {
8870
9568
  this.root.classList.toggle("mbe-image-selection", el !== null);
8871
9569
  }
8872
9570
  // -------------------------------------------------------------------------
8873
- // Images (see ui/image.ts)
9571
+ // Images (see ui/resizeHandles.ts)
8874
9572
  /** The selected image of `state` and its element, or null. */
8875
9573
  imageTargetAt(state) {
8876
9574
  const selected = selectedImage(state);
@@ -8901,12 +9599,28 @@ var Editor = class {
8901
9599
  updateImageAt(pos, change) {
8902
9600
  this.run((s) => updateImage(s, pos, change));
8903
9601
  }
8904
- /** @internal Shows the image controls again, after a resize that changed nothing. */
9602
+ /**
9603
+ * Opens the alt text field under the image after `pos`. Enter saves the text,
9604
+ * Escape keeps the old one. Either way the image stays selected.
9605
+ */
9606
+ editAltText(pos, alt) {
9607
+ const rect = (this.imageTargetAt(this.state)?.el ?? this.blockElement(pos.blockId))?.getBoundingClientRect();
9608
+ if (!rect) return;
9609
+ const { labels } = this;
9610
+ const options = { value: alt, label: labels.altText, placeholder: labels.altTextPlaceholder, type: "text" };
9611
+ this.inputPopover.open(rect, options, (value) => {
9612
+ if (value !== null) this.updateImageAt(pos, { alt: value });
9613
+ else this.current = selectImage(this.state, pos);
9614
+ this.focus();
9615
+ });
9616
+ }
9617
+ /** @internal Shows the resize handles again, after a resize that changed nothing. */
8905
9618
  refreshImageUi() {
8906
9619
  this.updateUi();
8907
9620
  }
8908
9621
  syncActiveDescendant() {
8909
- const id = this.suggestions.activeDescendant ?? (this.blockMenu.isOpen ? this.blockMenu.activeDescendant : null);
9622
+ const menu = this.blockMenu.isOpen ? this.blockMenu : this.toolbar?.menu;
9623
+ const id = this.suggestions.activeDescendant ?? menu?.activeDescendant ?? null;
8910
9624
  if (id) this.root.setAttribute("aria-activedescendant", id);
8911
9625
  else this.root.removeAttribute("aria-activedescendant");
8912
9626
  }
@@ -8915,8 +9629,8 @@ var Editor = class {
8915
9629
  this.suggestions.close();
8916
9630
  this.blockMenu.hide();
8917
9631
  this.toolbar?.hide();
8918
- this.handle.hide();
8919
- this.imageControls.hide();
9632
+ this.blockHandle.hide();
9633
+ this.resizeHandles.hide();
8920
9634
  this.paintSelectedImage(null);
8921
9635
  this.hintEl?.classList.remove("mbe-show-hint");
8922
9636
  this.hintEl = null;
@@ -9287,6 +10001,7 @@ export {
9287
10001
  MARK_ORDER,
9288
10002
  MAX_INDENT,
9289
10003
  SLASH_ITEM_IDS,
10004
+ TOOLBAR_ITEMS,
9290
10005
  blockIndex,
9291
10006
  caret,
9292
10007
  clampSelection,
@@ -9311,10 +10026,12 @@ export {
9311
10026
  heading,
9312
10027
  htmlBlock,
9313
10028
  htmlToDoc,
10029
+ imageBlockOffset,
9314
10030
  inlineLength,
9315
10031
  inlineText,
9316
10032
  insertInline,
9317
10033
  isCollapsed,
10034
+ isImageBlock,
9318
10035
  isPlainTextBlock,
9319
10036
  isTextBlock,
9320
10037
  linkAt,