@usememos/editor 26.10.8 → 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,16 +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",
2075
- /** Shown in place of an image that did not load and has no alt text. */
2076
- imageUnavailable: "Image unavailable",
2077
- /** The button over a selected image that edits its alt text, and the field's name. */
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. */
2078
2173
  altText: "Alt text",
2079
2174
  altTextPlaceholder: "Describe the image\u2026",
2080
- /** Accessible name of the handles that resize an image. */
2175
+ /** Shown in place of an image that did not load and has no alt text. */
2176
+ imageUnavailable: "Image unavailable",
2177
+ /** Accessible name of an image's resize handles. */
2081
2178
  resizeImage: "Resize image"
2082
2179
  };
2083
2180
 
@@ -2122,12 +2219,36 @@ var ICONS = {
2122
2219
  addColumnLeft: ["m12 19-7-7 7-7", "M19 12H5"],
2123
2220
  /** `arrow-right` */
2124
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"],
2125
2224
  /** `text-align-start` */
2126
2225
  alignLeft: ["M21 5H3", "M15 12H3", "M17 19H3"],
2127
2226
  /** `text-align-center` */
2128
2227
  alignCenter: ["M21 5H3", "M17 12H7", "M19 19H5"],
2129
2228
  /** `text-align-end` */
2130
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
+ ],
2131
2252
  /** `trash` */
2132
2253
  deleteRow: TRASH,
2133
2254
  /** `trash` */
@@ -2151,6 +2272,12 @@ var ICONS = {
2151
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",
2152
2273
  "M21 15V5a2 2 0 0 0-2-2H9"
2153
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"],
2154
2281
  /** `grip-vertical` */
2155
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" }]]
2156
2283
  };
@@ -2184,6 +2311,28 @@ function iconNode(doc, icon) {
2184
2311
 
2185
2312
  // src/markdown/ast.ts
2186
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
+ }
2187
2336
  function inlineNodesText(nodes, soft) {
2188
2337
  let s = "";
2189
2338
  for (const node of nodes) {
@@ -2295,11 +2444,13 @@ function lowerInto(nodes, marks, link, out, soft) {
2295
2444
  }
2296
2445
  function imageAtom(node) {
2297
2446
  let alt = inlineNodesText(node.children, " ");
2298
- 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);
2299
2449
  return {
2300
2450
  src: node.destination,
2301
2451
  alt,
2302
2452
  ...node.title ? { title: node.title } : {},
2453
+ ...node.align ? { align: node.align } : {},
2303
2454
  ...node.width ? { width: node.width } : {},
2304
2455
  ...node.height ? { height: node.height } : {}
2305
2456
  };
@@ -2503,7 +2654,9 @@ var Node2 = class {
2503
2654
  depth = 0;
2504
2655
  destination = "";
2505
2656
  title = "";
2506
- /** 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. */
2507
2660
  width = 0;
2508
2661
  height = 0;
2509
2662
  /** An escaped "@": kept apart from the text around it, so it does not join an e-mail literal. */
@@ -2586,8 +2739,15 @@ function toAst(parent) {
2586
2739
  out.push({ type: n.type, destination: n.destination, title: n.title, children: toAst(n) });
2587
2740
  break;
2588
2741
  case "image": {
2589
- const image = { type: n.type, destination: n.destination, title: n.title, children: toAst(n) };
2590
- 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
+ });
2591
2751
  break;
2592
2752
  }
2593
2753
  case "root":
@@ -3046,11 +3206,11 @@ var InlineParser = class {
3046
3206
  link.destination = dest ?? "";
3047
3207
  link.title = title ?? "";
3048
3208
  if (opener.image) {
3049
- const label = this.subject.slice(opener.index + 1, startPos - 1);
3050
- const size = IMAGE_SIZE.exec(label);
3051
- if (size && !/(^|[^\\])(\\\\)*\\$/.test(label.slice(0, size.index))) {
3052
- link.width = Number(size[1]);
3053
- 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;
3054
3214
  }
3055
3215
  }
3056
3216
  let n = opener.node.next;
@@ -3925,14 +4085,14 @@ function serializeBlocks(blocks, options) {
3925
4085
  for (const block3 of blocks) {
3926
4086
  if (block3.type === "quote" && block3.content.length === 0) continue;
3927
4087
  let text;
3928
- let separator2 = "\n\n";
4088
+ let separator = "\n\n";
3929
4089
  switch (block3.type) {
3930
4090
  case "paragraph":
3931
4091
  text = block3.content.length === 0 ? "&nbsp;" : inlineToMarkdown(block3.content, ctx.paragraph);
3932
4092
  break;
3933
4093
  case "quote": {
3934
4094
  text = prefixLines(inlineToMarkdown(block3.content, ctx.paragraph), "> ", ">");
3935
- if (prev?.type === "quote") separator2 = "\n>\n";
4095
+ if (prev?.type === "quote") separator = "\n>\n";
3936
4096
  break;
3937
4097
  }
3938
4098
  case "heading":
@@ -3941,7 +4101,7 @@ function serializeBlocks(blocks, options) {
3941
4101
  case "listItem": {
3942
4102
  const item = lists.next(block3, prev?.type === "listItem" ? prev : null);
3943
4103
  text = item.text;
3944
- if (prev?.type === "listItem" && !item.blankLineBefore) separator2 = "\n";
4104
+ if (prev?.type === "listItem" && !item.blankLineBefore) separator = "\n";
3945
4105
  break;
3946
4106
  }
3947
4107
  case "code":
@@ -3957,7 +4117,7 @@ function serializeBlocks(blocks, options) {
3957
4117
  text = "---";
3958
4118
  break;
3959
4119
  }
3960
- if (out) out += separator2;
4120
+ if (out) out += separator;
3961
4121
  out += text;
3962
4122
  prev = block3;
3963
4123
  }
@@ -4068,7 +4228,7 @@ var STRATEGIES = [
4068
4228
  function sameInline(a, b) {
4069
4229
  return a.length === b.length && a.every((s, i) => {
4070
4230
  const t = b[i];
4071
- 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;
4072
4232
  });
4073
4233
  }
4074
4234
  var reSpecWhitespace = /^[\t\n\f\r\p{Zs}]+|[\t\n\f\r\p{Zs}]+$/gu;
@@ -4449,8 +4609,10 @@ function imageMarkdown(image, ctx) {
4449
4609
  atEnd: false
4450
4610
  });
4451
4611
  const title = image.title ? ` "${escapeEntities(image.title.replace(/["\\]/g, "\\$&"))}"` : "";
4452
- const size = image.width ? `|${image.width}${image.height ? `x${image.height}` : ""}` : "";
4453
- 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;
4454
4616
  return `![${text}](${linkDestination(image.src)}${title})`;
4455
4617
  }
4456
4618
 
@@ -4737,6 +4899,28 @@ var Popup = class {
4737
4899
  this.el.style.left = `${Math.round(left - offset.x)}px`;
4738
4900
  this.el.style.top = `${Math.round(top - offset.y)}px`;
4739
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
+ }
4740
4924
  hide() {
4741
4925
  if (!this.open) return;
4742
4926
  this.open = false;
@@ -4755,20 +4939,29 @@ var Popup = class {
4755
4939
  }
4756
4940
  };
4757
4941
  var menuCounter = 0;
4758
- 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
+ }
4759
4950
  popup;
4760
4951
  items = [];
4761
4952
  index = 0;
4762
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;
4763
4961
  /** Called after an item runs. */
4764
4962
  onPicked = null;
4765
4963
  /** Called when the highlight moves, by key, by mouse or because the items changed. */
4766
4964
  onHighlight = null;
4767
- constructor(owner, className, role = "listbox") {
4768
- this.popup = new Popup(owner, `mbe-menu ${className}`);
4769
- this.popup.el.setAttribute("role", role);
4770
- this.popup.el.id = this.id;
4771
- }
4772
4965
  get el() {
4773
4966
  return this.popup.el;
4774
4967
  }
@@ -4776,10 +4969,59 @@ var Menu = class {
4776
4969
  return this.popup.isOpen;
4777
4970
  }
4778
4971
  get activeDescendant() {
4972
+ if (this.child?.isOpen) return this.child.activeDescendant;
4779
4973
  return this.items.length ? `${this.id}-${this.index}` : null;
4780
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
+ }
4781
5022
  setSections(sections2, emptyLabel) {
4782
5023
  const doc = this.el.ownerDocument;
5024
+ this.closeSubmenu();
4783
5025
  this.el.replaceChildren();
4784
5026
  this.items = [];
4785
5027
  this.index = 0;
@@ -4798,14 +5040,17 @@ var Menu = class {
4798
5040
  const row = doc.createElement("div");
4799
5041
  row.className = "mbe-menu-item";
4800
5042
  row.id = `${this.id}-${i}`;
4801
- 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);
4802
5047
  if (item.danger) row.classList.add("mbe-danger");
4803
5048
  const icon = doc.createElement("span");
4804
5049
  icon.className = "mbe-menu-icon";
4805
5050
  const content = iconNode(doc, item.icon);
4806
5051
  if (content) icon.appendChild(content);
4807
5052
  const label = doc.createElement("span");
4808
- label.className = "mbe-menu-label";
5053
+ label.className = item.labelClass ? `mbe-menu-label ${item.labelClass}` : "mbe-menu-label";
4809
5054
  setMarked(label, item.label, item.mark);
4810
5055
  row.append(icon, label);
4811
5056
  if (item.detail) {
@@ -4814,7 +5059,27 @@ var Menu = class {
4814
5059
  detail.textContent = item.detail;
4815
5060
  row.appendChild(detail);
4816
5061
  }
4817
- 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
+ });
4818
5083
  row.addEventListener("click", () => this.pick(i));
4819
5084
  this.el.appendChild(row);
4820
5085
  }
@@ -4882,13 +5147,19 @@ var Menu = class {
4882
5147
  pick(i = this.index) {
4883
5148
  const item = this.items[i];
4884
5149
  if (!item) return;
5150
+ if (item.submenu) {
5151
+ this.openSubmenu(i);
5152
+ return;
5153
+ }
4885
5154
  item.run();
4886
5155
  this.onPicked?.();
4887
5156
  }
4888
5157
  hide() {
5158
+ this.closeSubmenu();
4889
5159
  this.popup.hide();
4890
5160
  }
4891
5161
  destroy() {
5162
+ this.child?.destroy();
4892
5163
  this.popup.destroy();
4893
5164
  }
4894
5165
  };
@@ -4919,7 +5190,8 @@ function defaultKeymap() {
4919
5190
  "Mod-e": ({ editor }) => editor.commands.toggleCode(),
4920
5191
  "Mod-Shift-x": ({ editor }) => editor.commands.toggleStrike(),
4921
5192
  "Mod-Shift-s": ({ editor }) => editor.commands.toggleStrike(),
4922
- "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(),
4923
5195
  "Mod-Alt-0": ({ editor }) => editor.commands.setParagraph() || true,
4924
5196
  "Mod-Alt-1": ({ editor }) => editor.commands.toggleHeading({ level: 1 }) || true,
4925
5197
  "Mod-Alt-2": ({ editor }) => editor.commands.toggleHeading({ level: 2 }) || true,
@@ -5621,93 +5893,314 @@ function matchesKey(binding, e) {
5621
5893
  }
5622
5894
 
5623
5895
  // src/ui/toolbar.ts
5624
- var mod = (key) => isMac ? `\u2318${key}` : `Ctrl+${key}`;
5625
- var MARK_BUTTONS = [
5626
- { mark: "bold", name: "bold", shortcut: mod("B") },
5627
- { mark: "italic", name: "italic", shortcut: mod("I") },
5628
- { mark: "strike", name: "strike", shortcut: isMac ? "\u2318\u21E7X" : "Ctrl+Shift+X" },
5629
- { mark: "code", name: "inlineCode", shortcut: mod("E") }
5896
+ var GROUPS = [
5897
+ ["textStyle"],
5898
+ ["bold", "italic", "strike", "inlineCode", "link"],
5899
+ ["quote", "codeBlock", "list"]
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") }
5630
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
+ }
5631
5939
  var FormatToolbar = class {
5632
- constructor(editor) {
5940
+ constructor(editor, items = TOOLBAR_ITEMS) {
5633
5941
  this.editor = editor;
5634
5942
  const doc = editor.root.ownerDocument;
5635
5943
  this.popup = new Popup(editor.root, "mbe-toolbar");
5636
5944
  const el = this.popup.el;
5637
5945
  el.setAttribute("role", "toolbar");
5638
- 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) => {
5639
5950
  const b = doc.createElement("button");
5640
5951
  b.type = "button";
5641
5952
  b.className = `mbe-tool ${className}`;
5642
5953
  const content = iconNode(doc, editor.icon(icon));
5643
5954
  if (content) b.appendChild(content);
5644
- b.title = label;
5645
- b.setAttribute("aria-label", label);
5955
+ b.setAttribute("aria-label", labels[item === "codeBlock" ? "code" : item]);
5956
+ if (keys) b.setAttribute("aria-keyshortcuts", keys);
5646
5957
  b.addEventListener("click", onClick);
5647
- 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);
5648
5963
  return b;
5649
5964
  };
5650
- const labels = editor.labels;
5651
- for (const b of MARK_BUTTONS) {
5652
- const btn = button(b.name, `${labels[b.name]} (${b.shortcut})`, `mbe-tool-${b.mark}`, () => {
5653
- editor.run((s) => toggleMark(s, b.mark));
5654
- this.update();
5655
- });
5656
- btn.setAttribute("aria-pressed", "false");
5657
- 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
+ }
5658
6020
  }
5659
- el.appendChild(separator(doc));
5660
- this.linkButton = button("link", `${labels.link} (${mod("K")})`, "mbe-tool-link", () => editor.openLinkPopover());
5661
6021
  }
5662
6022
  popup;
5663
- markButtons = /* @__PURE__ */ new Map();
5664
- 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;
5665
6033
  get isOpen() {
5666
6034
  return this.popup.isOpen;
5667
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
+ }
5668
6044
  show() {
5669
6045
  const rect = this.editor.selectionRect();
5670
6046
  if (!rect) return this.hide();
5671
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`;
5672
6050
  this.popup.show(rect, isTouch() ? "below" : "above", 8);
6051
+ if (this.openTrigger) this.placeMenu(this.openTrigger);
5673
6052
  }
5674
6053
  hide() {
6054
+ this.closeMenu();
6055
+ this.hideTooltip();
5675
6056
  this.popup.hide();
5676
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
+ }
5677
6068
  destroy() {
6069
+ clearTimeout(this.tooltipTimer);
5678
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();
5679
6080
  }
5680
6081
  update() {
5681
- for (const [mark, btn] of this.markButtons) {
5682
- const on = this.editor.isActive(mark);
5683
- btn.classList.toggle("mbe-active", on);
5684
- btn.setAttribute("aria-pressed", String(on));
5685
- }
5686
- 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();
5687
6185
  }
5688
6186
  };
5689
- function separator(doc) {
5690
- const s = doc.createElement("span");
5691
- s.className = "mbe-tool-sep";
5692
- return s;
6187
+ function setPressed(button, on) {
6188
+ button.classList.toggle("mbe-active", on);
6189
+ button.setAttribute("aria-pressed", String(on));
5693
6190
  }
5694
- var LinkPopover = class {
6191
+ var InputPopover = class {
5695
6192
  popup;
5696
6193
  input;
5697
6194
  removeButton;
5698
6195
  done = null;
5699
6196
  constructor(editor) {
5700
6197
  const doc = editor.root.ownerDocument;
5701
- this.popup = new Popup(editor.root, "mbe-link-popover");
6198
+ this.popup = new Popup(editor.root, "mbe-input-popover");
5702
6199
  this.input = doc.createElement("input");
5703
- this.input.type = "url";
5704
- this.input.className = "mbe-link-input";
5705
- this.input.placeholder = editor.labels.linkPlaceholder;
5706
- this.input.setAttribute("aria-label", editor.labels.link);
6200
+ this.input.className = "mbe-popover-input";
5707
6201
  this.removeButton = doc.createElement("button");
5708
6202
  this.removeButton.type = "button";
5709
6203
  this.removeButton.className = "mbe-tool";
5710
- this.removeButton.textContent = editor.labels.removeLink;
5711
6204
  this.popup.el.append(this.input, this.removeButton);
5712
6205
  this.input.addEventListener("keydown", (e) => {
5713
6206
  if (e.key === "Enter") {
@@ -5731,10 +6224,14 @@ var LinkPopover = class {
5731
6224
  contains(node) {
5732
6225
  return this.popup.el.contains(node);
5733
6226
  }
5734
- open(rect, value, done) {
6227
+ open(rect, options, done) {
5735
6228
  this.done = done;
5736
- this.input.value = value;
5737
- 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 === "";
5738
6235
  this.popup.show(rect, "below");
5739
6236
  this.input.focus();
5740
6237
  this.input.select();
@@ -5744,11 +6241,11 @@ var LinkPopover = class {
5744
6241
  this.done = null;
5745
6242
  this.popup.hide();
5746
6243
  }
5747
- finish(href) {
6244
+ finish(value) {
5748
6245
  const done = this.done;
5749
6246
  this.done = null;
5750
6247
  this.popup.hide();
5751
- done?.(href);
6248
+ done?.(value);
5752
6249
  }
5753
6250
  destroy() {
5754
6251
  this.popup.destroy();
@@ -5812,6 +6309,13 @@ function sameReveal(a, b) {
5812
6309
  for (const key of a) if (!b.has(key)) return false;
5813
6310
  return true;
5814
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
+ }
5815
6319
  function renderBlock(block3, ctx, reveal) {
5816
6320
  const { doc, labels } = ctx;
5817
6321
  const el = (tag, className2) => {
@@ -5827,6 +6331,7 @@ function renderBlock(block3, ctx, reveal) {
5827
6331
  root = el(block3.type === "paragraph" ? "p" : block3.type === "quote" ? "blockquote" : `h${block3.level}`);
5828
6332
  root.dir = "auto";
5829
6333
  fillContent(root, block3.content, ctx, block3, reveal);
6334
+ if (block3.type === "paragraph") markImageBlock(root, block3);
5830
6335
  break;
5831
6336
  case "listItem": {
5832
6337
  root = el("div");
@@ -6069,20 +6574,24 @@ function renderSpan(span, ctx, viewed = false) {
6069
6574
  const image = span.image;
6070
6575
  const src = ctx.resolveUrl(image.src, "image");
6071
6576
  if (src === null) return unavailableImage(image, ctx);
6072
- const img = doc.createElement("img");
6073
- img.setAttribute("loading", "lazy");
6074
- img.setAttribute("decoding", "async");
6075
- if (ctx.referrerPolicy) img.setAttribute("referrerpolicy", ctx.referrerPolicy);
6076
- 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
+ }
6077
6591
  img.alt = image.alt;
6078
- if (image.title) img.title = image.title;
6079
- if (image.width) img.width = image.width;
6080
- if (image.height) img.height = image.height;
6081
- img.addEventListener("error", () => {
6082
- if (!img.parentNode) return;
6083
- img.replaceWith(unavailableImage(image, ctx));
6084
- ctx.onImageError?.();
6085
- });
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);
6086
6595
  return atom(img, classes("mbe-image", ctx.classes.image));
6087
6596
  }
6088
6597
  let node = doc.createTextNode(span.text);
@@ -6095,6 +6604,10 @@ function renderSpan(span, ctx, viewed = false) {
6095
6604
  }
6096
6605
  return wrapMarks(span, node, ctx);
6097
6606
  }
6607
+ function setAttribute(el, name, value) {
6608
+ if (value === void 0) el.removeAttribute(name);
6609
+ else el.setAttribute(name, value);
6610
+ }
6098
6611
  function unavailableImage(image, ctx) {
6099
6612
  const doc = ctx.doc;
6100
6613
  const el = doc.createElement("span");
@@ -6170,6 +6683,8 @@ var BlockRenderer = class {
6170
6683
  failedViews = /* @__PURE__ */ new Set();
6171
6684
  /** The block being rendered, so a pending view knows which blocks to render again. */
6172
6685
  renderingBlock = "";
6686
+ /** During a render, the loaded images of the block elements it replaces, by `src`. */
6687
+ loadedImages = /* @__PURE__ */ new Map();
6173
6688
  context() {
6174
6689
  return {
6175
6690
  doc: this.root.ownerDocument,
@@ -6183,7 +6698,8 @@ var BlockRenderer = class {
6183
6698
  classes: this.classes,
6184
6699
  icon: this.icon,
6185
6700
  codeCopy: this.codeCopy,
6186
- onImageError: this.onImageError
6701
+ onImageError: this.onImageError,
6702
+ loadedImage: (src) => this.loadedImages.get(src)?.shift()
6187
6703
  };
6188
6704
  }
6189
6705
  renderView(syntax, source, kind) {
@@ -6236,14 +6752,31 @@ var BlockRenderer = class {
6236
6752
  */
6237
6753
  render(doc, force = false, lazy = false) {
6238
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
+ }
6239
6772
  const next = /* @__PURE__ */ new Map();
6240
6773
  for (const block3 of doc.blocks) {
6241
6774
  this.renderingBlock = block3.id;
6242
6775
  const prev = this.rendered.get(block3.id);
6243
6776
  const reveal = this.revealed.get(block3.id);
6244
- const reuse = !force && prev && prev.block === block3 && prev.el.parentNode === this.root && sameReveal(prev.reveal, reveal);
6245
- 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 });
6246
6778
  }
6779
+ this.loadedImages.clear();
6247
6780
  const nodes = [];
6248
6781
  for (const [id, { el }] of next) {
6249
6782
  nodes.push(el);
@@ -6452,7 +6985,7 @@ function positionToDom(blockEl, pos) {
6452
6985
  return { node: last.parentNode, offset: childIndex(last) + 1 };
6453
6986
  }
6454
6987
 
6455
- // src/ui/handle.ts
6988
+ // src/ui/blockHandle.ts
6456
6989
  var BlockHandle = class {
6457
6990
  constructor(editor) {
6458
6991
  this.editor = editor;
@@ -6460,7 +6993,7 @@ var BlockHandle = class {
6460
6993
  const doc = root.ownerDocument;
6461
6994
  this.el = doc.createElement("button");
6462
6995
  this.el.type = "button";
6463
- this.el.className = "mbe-ui mbe-handle";
6996
+ this.el.className = "mbe-ui mbe-block-handle";
6464
6997
  const icon = iconNode(doc, editor.icon("blockHandle"));
6465
6998
  if (icon) this.el.appendChild(icon);
6466
6999
  this.el.setAttribute("aria-label", editor.labels.blockHandle);
@@ -6494,7 +7027,7 @@ var BlockHandle = class {
6494
7027
  if (this.editor.hasBlockMenu(blockId)) this.showFor(blockId);
6495
7028
  else if (this.blockId !== null) this.scheduleHide();
6496
7029
  }
6497
- /** Shows the handle next to a block. */
7030
+ /** Shows the block handle next to a block. */
6498
7031
  showFor(blockId) {
6499
7032
  this.cancelHide();
6500
7033
  const blockEl = this.editor.blockElement(blockId);
@@ -6510,7 +7043,7 @@ var BlockHandle = class {
6510
7043
  this.el.style.left = `${Math.round(rect.left - (this.el.offsetWidth || 20) - 6 - offset.x)}px`;
6511
7044
  this.el.style.top = `${Math.round(rect.top + firstLine / 2 - size / 2 - offset.y)}px`;
6512
7045
  }
6513
- /** True when `node` is the handle or inside it. */
7046
+ /** True when `node` is the block handle or inside it. */
6514
7047
  contains(node) {
6515
7048
  return this.el.contains(node);
6516
7049
  }
@@ -6534,10 +7067,10 @@ var BlockHandle = class {
6534
7067
  }
6535
7068
  };
6536
7069
 
6537
- // src/ui/image.ts
7070
+ // src/ui/resizeHandles.ts
6538
7071
  var MIN_WIDTH = 24;
6539
7072
  var SNAP = 8;
6540
- var ImageControls = class {
7073
+ var ResizeHandles = class {
6541
7074
  constructor(editor) {
6542
7075
  this.editor = editor;
6543
7076
  const root = editor.root;
@@ -6546,31 +7079,16 @@ var ImageControls = class {
6546
7079
  this.frame = doc.createElement("div");
6547
7080
  this.frame.className = "mbe-ui mbe-image-frame";
6548
7081
  this.frame.hidden = true;
6549
- const handle = (side) => {
7082
+ const resizeHandle = (side) => {
6550
7083
  const el = doc.createElement("div");
6551
- el.className = `mbe-image-handle mbe-image-handle-${side}`;
7084
+ el.className = `mbe-resize-handle mbe-resize-handle-${side}`;
6552
7085
  el.dataset.side = side;
6553
7086
  el.title = labels.resizeImage;
6554
7087
  el.setAttribute("aria-hidden", "true");
6555
7088
  this.frame.appendChild(el);
6556
7089
  return el;
6557
7090
  };
6558
- this.handles = { left: handle("left"), right: handle("right") };
6559
- this.toolbar = new Popup(root, "mbe-toolbar mbe-image-toolbar");
6560
- this.toolbar.el.setAttribute("role", "toolbar");
6561
- const altButton = doc.createElement("button");
6562
- altButton.type = "button";
6563
- altButton.className = "mbe-tool mbe-tool-alt";
6564
- altButton.textContent = labels.altText;
6565
- altButton.addEventListener("click", () => this.openAlt());
6566
- this.toolbar.el.appendChild(altButton);
6567
- this.altPopover = new Popup(root, "mbe-link-popover mbe-alt-popover");
6568
- this.altInput = doc.createElement("input");
6569
- this.altInput.type = "text";
6570
- this.altInput.className = "mbe-link-input mbe-alt-input";
6571
- this.altInput.placeholder = labels.altTextPlaceholder;
6572
- this.altInput.setAttribute("aria-label", labels.altText);
6573
- this.altPopover.el.appendChild(this.altInput);
7091
+ this.handles = { left: resizeHandle("left"), right: resizeHandle("right") };
6574
7092
  const on = (target, type, fn) => {
6575
7093
  target.addEventListener(type, fn);
6576
7094
  this.cleanup.push(() => target.removeEventListener(type, fn));
@@ -6587,98 +7105,44 @@ var ImageControls = class {
6587
7105
  on(this.frame, "pointerup", (e) => this.endDrag(e, true));
6588
7106
  on(this.frame, "pointercancel", (e) => this.endDrag(e, false));
6589
7107
  on(this.frame, "lostpointercapture", (e) => this.endDrag(e, true));
6590
- on(this.altInput, "keydown", (e) => {
6591
- if (e.key === "Enter") {
6592
- e.preventDefault();
6593
- this.finishAlt(this.altInput.value.trim());
6594
- } else if (e.key === "Escape") {
6595
- e.preventDefault();
6596
- this.finishAlt(null);
6597
- }
6598
- });
6599
- on(this.altInput, "blur", () => {
6600
- setTimeout(() => {
6601
- if (this.altPopover.isOpen && doc.activeElement !== this.altInput) this.closeAlt();
6602
- }, 150);
6603
- });
6604
7108
  }
6605
7109
  /** A frame over the image, holding the two handles. It takes no pointer events itself. */
6606
7110
  frame;
6607
7111
  handles;
6608
- toolbar;
6609
- altPopover;
6610
- altInput;
6611
7112
  /** The image under the pointer, which shows handles while it is hovered. */
6612
7113
  hovered = null;
6613
- /** The selected image, which shows handles and the toolbar. */
7114
+ /** The selected image, which shows handles. */
6614
7115
  selected = null;
6615
7116
  /** The image the frame is shown for. */
6616
7117
  framed = null;
6617
7118
  drag = null;
6618
- altDone = null;
6619
7119
  hideTimer = null;
6620
7120
  cleanup = [];
6621
- /** True while the alt text field is open. */
6622
- get isEditingAlt() {
6623
- return this.altPopover.isOpen;
6624
- }
6625
- /** True while an image is being resized. */
6626
- get isResizing() {
6627
- return this.drag !== null;
6628
- }
6629
- /** True when `node` is part of these controls. */
7121
+ /** True when `node` is the frame or one of its resize handles. */
6630
7122
  contains(node) {
6631
- return this.frame.contains(node) || this.toolbar.el.contains(node) || this.altPopover.el.contains(node);
7123
+ return this.frame.contains(node);
6632
7124
  }
6633
- /**
6634
- * Shows the controls for the selected image, or hides them for none. The
6635
- * toolbar shows only when `toolbar` is true (the editor is focused and not
6636
- * busy with something else).
6637
- */
6638
- update(selected, toolbar) {
7125
+ /** Shows the handles for the selected image, or for none. */
7126
+ update(selected) {
6639
7127
  this.selected = selected;
6640
- if (this.drag) return;
6641
- if (!selected) {
6642
- this.toolbar.hide();
6643
- if (this.altPopover.isOpen) this.closeAlt();
6644
- } else if (toolbar && !this.altPopover.isOpen) {
6645
- this.showToolbar(selected.el);
6646
- } else if (!toolbar) {
6647
- this.toolbar.hide();
6648
- }
6649
- this.placeFrame();
7128
+ if (!this.drag) this.placeFrame();
6650
7129
  }
6651
- /** Moves the controls to where their image is now, after scrolling. */
7130
+ /** Moves the resize handles to where their image is now, after scrolling. */
6652
7131
  reposition() {
6653
7132
  if (this.drag) return;
6654
7133
  if (this.selected && !this.selected.el.isConnected) this.selected = null;
6655
- if (this.toolbar.isOpen && this.selected) this.showToolbar(this.selected.el);
6656
- if (this.altPopover.isOpen && this.selected) this.altPopover.show(this.selected.el.getBoundingClientRect(), "below");
6657
7134
  this.placeFrame();
6658
7135
  }
6659
7136
  hide() {
6660
7137
  if (this.drag) return;
6661
7138
  this.hovered = null;
6662
7139
  this.selected = null;
6663
- this.toolbar.hide();
6664
- if (this.altPopover.isOpen) this.closeAlt();
6665
7140
  this.placeFrame();
6666
7141
  }
6667
7142
  destroy() {
6668
7143
  this.cancelUnhover();
6669
7144
  for (const fn of this.cleanup) fn();
6670
7145
  this.frame.remove();
6671
- this.toolbar.destroy();
6672
- this.altPopover.destroy();
6673
- }
6674
- /** The toolbar goes inside the image's top corner, as in Notion, or above an image too small to hold it. */
6675
- showToolbar(el) {
6676
- const rect = el.getBoundingClientRect();
6677
- if (rect.width < 120 || rect.height < 60) return this.toolbar.show(rect, "above", 8);
6678
- const rtl = el.ownerDocument.defaultView.getComputedStyle(el).direction === "rtl";
6679
- const inset = 8;
6680
- const corner = { left: rect.left + inset, right: rect.right - inset, top: rect.top, bottom: rect.top + inset };
6681
- this.toolbar.show(corner, "below", 0, rtl ? "start" : "end");
6682
7146
  }
6683
7147
  // -- Hover ----------------------------------------------------------------
6684
7148
  onOver(e) {
@@ -6740,8 +7204,8 @@ var ImageControls = class {
6740
7204
  const width = el.getBoundingClientRect().width;
6741
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);
6742
7206
  const max = Math.max(MIN_WIDTH, columnWidth(el));
6743
- this.drag = { el, side, pointer: e.pointerId, startX: e.clientX, startWidth: width, max, snaps: [...others, max], width };
6744
- this.toolbar.hide();
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 };
6745
7209
  this.frame.classList.add("mbe-image-resizing");
6746
7210
  this.editor.selectImageAt(target.pos);
6747
7211
  }
@@ -6749,7 +7213,7 @@ var ImageControls = class {
6749
7213
  const drag = this.drag;
6750
7214
  if (!drag || e.pointerId !== drag.pointer) return;
6751
7215
  e.preventDefault();
6752
- 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;
6753
7217
  let width = Math.min(drag.max, Math.max(MIN_WIDTH, drag.startWidth + dx));
6754
7218
  const snap = drag.snaps.find((w) => Math.abs(w - width) <= SNAP);
6755
7219
  if (snap !== void 0) width = Math.min(drag.max, snap);
@@ -6773,32 +7237,6 @@ var ImageControls = class {
6773
7237
  this.editor.refreshImageUi();
6774
7238
  }
6775
7239
  }
6776
- // -- Alt text -------------------------------------------------------------
6777
- openAlt() {
6778
- const selected = this.selected;
6779
- if (!selected) return;
6780
- const { pos, image } = selected;
6781
- this.toolbar.hide();
6782
- this.altDone = (alt) => {
6783
- if (alt !== null) this.editor.updateImageAt(pos, { alt });
6784
- this.editor.focus();
6785
- if (alt === null) this.editor.selectImageAt(pos);
6786
- };
6787
- this.altInput.value = image.alt;
6788
- this.altPopover.show(selected.el.getBoundingClientRect(), "below");
6789
- this.altInput.focus();
6790
- this.altInput.select();
6791
- }
6792
- closeAlt() {
6793
- this.altDone = null;
6794
- this.altPopover.hide();
6795
- }
6796
- finishAlt(alt) {
6797
- const done = this.altDone;
6798
- this.altDone = null;
6799
- this.altPopover.hide();
6800
- done?.(alt);
6801
- }
6802
7240
  };
6803
7241
  function columnWidth(el) {
6804
7242
  let box = el.parentElement;
@@ -6955,7 +7393,7 @@ var SLASH_ITEM_IDS = [
6955
7393
  "table",
6956
7394
  "divider"
6957
7395
  ];
6958
- var BLOCK_ITEMS = [
7396
+ var BLOCK_ITEMS2 = [
6959
7397
  { id: "text", aliases: ["paragraph", "plain"], spec: { type: "paragraph" } },
6960
7398
  { id: "heading1", aliases: ["h1", "title"], spec: { type: "heading", level: 1 } },
6961
7399
  { id: "heading2", aliases: ["h2", "subtitle"], spec: { type: "heading", level: 2 } },
@@ -6968,17 +7406,19 @@ var BLOCK_ITEMS = [
6968
7406
  { id: "table", aliases: ["grid"], spec: { type: "table" } },
6969
7407
  { id: "divider", aliases: ["hr", "separator", "line", "rule"], spec: { type: "divider" } }
6970
7408
  ];
6971
- var TABLE_ITEMS = [
7409
+ var TABLE_ACTIONS = [
6972
7410
  { id: "addRowAbove", action: { kind: "addRowAbove" } },
6973
7411
  { id: "addRowBelow", action: { kind: "addRowBelow" } },
6974
7412
  { id: "addColumnLeft", action: { kind: "addColumnLeft" } },
6975
7413
  { id: "addColumnRight", action: { kind: "addColumnRight" } },
6976
- { id: "alignLeft", action: { kind: "align", align: "left" } },
6977
- { id: "alignCenter", action: { kind: "align", align: "center" } },
6978
- { id: "alignRight", action: { kind: "align", align: "right" } },
6979
7414
  { id: "deleteRow", action: { kind: "deleteRow" } },
6980
7415
  { id: "deleteColumn", action: { kind: "deleteColumn" } }
6981
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
+ ];
6982
7422
  var SLASH_CHARS = ["/", "\uFF0F"];
6983
7423
  var CARET_KEY = /^(Arrow(Up|Down|Left|Right)|Home|End|PageUp|PageDown)$/;
6984
7424
  var COMPOSITION_INPUT = /* @__PURE__ */ new Set(["insertCompositionText", "deleteCompositionText", "insertFromComposition", "deleteByComposition"]);
@@ -7005,6 +7445,12 @@ var Editor = class {
7005
7445
  composition = null;
7006
7446
  /** When the last composition ended (Safari only): the next key may be the Enter that committed it. */
7007
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;
7008
7454
  /** Blocks the browser edited during a composition that ended, rendered again on the next frame. */
7009
7455
  unsettled = /* @__PURE__ */ new Set();
7010
7456
  settleFrame = null;
@@ -7044,9 +7490,10 @@ var Editor = class {
7044
7490
  suggestions;
7045
7491
  blockMenu;
7046
7492
  toolbar;
7047
- linkPopover;
7048
- handle;
7049
- imageControls;
7493
+ /** The link popover, and the field for an image's alt text. */
7494
+ inputPopover;
7495
+ blockHandle;
7496
+ resizeHandles;
7050
7497
  /** The selected image's element, which carries the selected class. */
7051
7498
  selectedImageEl = null;
7052
7499
  hintEl = null;
@@ -7146,10 +7593,14 @@ var Editor = class {
7146
7593
  };
7147
7594
  this.blockMenu = new Menu(root, "mbe-block-menu", "menu");
7148
7595
  this.blockMenu.onPicked = () => this.blockMenu.hide();
7149
- this.linkPopover = new LinkPopover(this);
7150
- this.toolbar = options.toolbar === false ? null : new FormatToolbar(this);
7151
- this.handle = new BlockHandle(this);
7152
- 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);
7153
7604
  this.renderer.onImageError = () => {
7154
7605
  if (this.destroyed) return;
7155
7606
  if (!this.composing) this.syncDomSelection();
@@ -7245,7 +7696,7 @@ var Editor = class {
7245
7696
  case "image": {
7246
7697
  const selected = selectedImage(s);
7247
7698
  if (!selected || !attrs) return selected !== null;
7248
- const actual2 = { ...selected.image };
7699
+ const actual2 = { ...selected.image, block: selectedImageBlock(s) !== null };
7249
7700
  return Object.entries(attrs).every(([k, v]) => actual2[k] === v);
7250
7701
  }
7251
7702
  }
@@ -7255,14 +7706,17 @@ var Editor = class {
7255
7706
  const actual = this.getAttributes(name);
7256
7707
  return Object.entries(attrs).every(([k, v]) => actual[k] === v);
7257
7708
  }
7258
- /** 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. */
7259
7710
  getAttributes(name) {
7260
7711
  const s = this.current;
7261
7712
  if (name === "link") {
7262
7713
  const link = activeLink(s);
7263
7714
  return link ? { href: link.href } : {};
7264
7715
  }
7265
- 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
+ }
7266
7720
  const block3 = getBlock(s.doc, s.selection.focus.blockId);
7267
7721
  if (blockName(block3) !== name) return {};
7268
7722
  switch (block3.type) {
@@ -7625,9 +8079,9 @@ var Editor = class {
7625
8079
  for (const widget of [...this.widgets]) widget.remove();
7626
8080
  this.blockMenu.destroy();
7627
8081
  this.toolbar?.destroy();
7628
- this.linkPopover.destroy();
7629
- this.handle.destroy();
7630
- this.imageControls.destroy();
8082
+ this.inputPopover.destroy();
8083
+ this.blockHandle.destroy();
8084
+ this.resizeHandles.destroy();
7631
8085
  setPopupContainer(this.root, void 0);
7632
8086
  for (const name of Object.keys(this.runtime.attributes ?? {})) this.root.removeAttribute(name);
7633
8087
  for (const name of this.tokenNames) this.root.style.removeProperty(name);
@@ -7797,8 +8251,13 @@ var Editor = class {
7797
8251
  this.updateUi();
7798
8252
  return;
7799
8253
  }
8254
+ this.shortcut = null;
7800
8255
  const skipped = key?.vertical ? this.skippedBlock(key.from, key.vertical, key.x, selection.focus) : null;
7801
- 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) {
7802
8261
  this.setSelection({ anchor: skipped, focus: skipped });
7803
8262
  } else {
7804
8263
  this.current = { ...this.state, selection, storedMarks: null };
@@ -7809,6 +8268,14 @@ var Editor = class {
7809
8268
  }
7810
8269
  if (key) this.scrollCaretIntoView();
7811
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
+ }
7812
8279
  /**
7813
8280
  * After the browser moved the caret from block `from` with ArrowDown
7814
8281
  * (`dir` 1) or ArrowUp to `to`: the position in the first block it passed
@@ -7961,6 +8428,44 @@ var Editor = class {
7961
8428
  }
7962
8429
  return viewEntry(view, forward);
7963
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
+ }
7964
8469
  /**
7965
8470
  * ArrowUp or ArrowDown on the first or last line of a table cell: the
7966
8471
  * position in the cell above or below (same column), or past the table in
@@ -8056,6 +8561,7 @@ var Editor = class {
8056
8561
  return;
8057
8562
  }
8058
8563
  this.refreshSelection();
8564
+ if ((type === "insertText" || type === "insertReplacementText") && selectedImageBlock(this.state)) return;
8059
8565
  switch (type) {
8060
8566
  case "insertText": {
8061
8567
  const text = e.data ?? "";
@@ -8080,7 +8586,7 @@ var Editor = class {
8080
8586
  this.run(insertLineBreak);
8081
8587
  return;
8082
8588
  case "deleteContentBackward":
8083
- this.run(deleteBackward);
8589
+ if (!this.undoShortcut()) this.run(deleteBackward);
8084
8590
  return;
8085
8591
  case "deleteContentForward":
8086
8592
  this.run(deleteForward);
@@ -8141,12 +8647,27 @@ var Editor = class {
8141
8647
  }
8142
8648
  /** Markdown shortcuts and suggestion menus that typing `text` triggers. */
8143
8649
  afterTyping(text) {
8650
+ const typed = this.state;
8144
8651
  if (text === " " || text === "-") this.run((s) => applyBlockInputRules(s));
8145
8652
  if (text.length === 1 && "*_`~".includes(text)) this.run((s) => applyInlineInputRules(s));
8146
8653
  if (this.markdown.inline.length > 0) this.run((s) => applyTokenInputRules(s, this.markdown.inline) ?? s);
8147
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;
8148
8656
  if (!text.includes("\n")) this.typedForSuggestion();
8149
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
+ }
8150
8671
  onCompositionStart(e) {
8151
8672
  if (this.fromControl(e)) return;
8152
8673
  this.dropBlockSelection();
@@ -8297,6 +8818,7 @@ var Editor = class {
8297
8818
  this.caretKey = null;
8298
8819
  if (this.fromControl(e)) return;
8299
8820
  if (e.isComposing || e.keyCode === 229) return;
8821
+ if (CARET_KEY.test(e.key)) this.shortcut = null;
8300
8822
  const mod2 = isMac ? e.metaKey : e.ctrlKey;
8301
8823
  const key = e.key.toLowerCase();
8302
8824
  const handled = (fn) => {
@@ -8313,12 +8835,20 @@ var Editor = class {
8313
8835
  return;
8314
8836
  }
8315
8837
  }
8316
- const menu = this.blockMenu.isOpen ? this.blockMenu : null;
8838
+ const menu = this.blockMenu.isOpen ? this.blockMenu : this.toolbar?.menu ?? null;
8317
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());
8318
8848
  if (e.key === "ArrowDown" || e.key === "Tab" && !e.shiftKey) return handled(() => this.moveMenu(menu, 1));
8319
8849
  if (e.key === "ArrowUp" || e.key === "Tab" && e.shiftKey) return handled(() => this.moveMenu(menu, -1));
8320
8850
  if (e.key === "Enter" && menu.count > 0) return handled(() => menu.pick());
8321
- if (e.key === "Escape") return handled(() => this.closeBlockMenu());
8851
+ if (e.key === "Escape") return handled(() => menu === this.blockMenu ? this.closeBlockMenu() : this.toolbar.closeMenu());
8322
8852
  }
8323
8853
  if (e.key === "Escape" && this.toolbar?.isOpen) {
8324
8854
  return handled(() => {
@@ -8351,6 +8881,10 @@ var Editor = class {
8351
8881
  }
8352
8882
  if (e.key === "Backspace" && !e.ctrlKey && !e.metaKey && !e.altKey) {
8353
8883
  this.refreshSelection();
8884
+ if (this.undoShortcut()) {
8885
+ e.preventDefault();
8886
+ return;
8887
+ }
8354
8888
  const { selection } = this.state;
8355
8889
  if (isCollapsed(selection) && selection.focus.offset === 0) {
8356
8890
  e.preventDefault();
@@ -8375,6 +8909,13 @@ var Editor = class {
8375
8909
  this.setSelection({ anchor: into, focus: into });
8376
8910
  return;
8377
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
+ }
8378
8919
  const vertical = e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
8379
8920
  const cell = vertical ? this.tableCellPast(vertical) : null;
8380
8921
  if (cell) {
@@ -8477,20 +9018,22 @@ var Editor = class {
8477
9018
  }
8478
9019
  }
8479
9020
  /**
8480
- * 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
8481
9022
  * adds a paragraph there. The browser would put the caret inside the
8482
9023
  * block, or in the block above a table.
8483
9024
  */
8484
9025
  clickBelowLastBlock(e) {
8485
9026
  const blocks = this.state.doc.blocks;
8486
9027
  const last = blocks[blocks.length - 1];
8487
- 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;
8488
9030
  const el = this.root.querySelector(`:scope > [data-block-id="${last.id}"]`);
8489
9031
  if (!el || e.clientY <= el.getBoundingClientRect().bottom) return false;
8490
9032
  e.preventDefault();
8491
9033
  this.root.focus({ preventScroll: true });
8492
9034
  const end = endOf(last);
8493
- 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));
8494
9037
  return true;
8495
9038
  }
8496
9039
  onClick(e) {
@@ -8566,9 +9109,9 @@ var Editor = class {
8566
9109
  }
8567
9110
  onFocusOut(e) {
8568
9111
  const next = e.relatedTarget;
8569
- if (next && (this.root.contains(next) || this.linkPopover.contains(next) || this.imageControls.contains(next))) return;
9112
+ if (next && (this.root.contains(next) || this.inputPopover.contains(next))) return;
8570
9113
  queueMicrotask(() => {
8571
- if (this.hasFocus() || this.linkPopover.isOpen || this.imageControls.isEditingAlt) return;
9114
+ if (this.hasFocus() || this.inputPopover.isOpen) return;
8572
9115
  if (!this.focused) return;
8573
9116
  this.focused = false;
8574
9117
  this.root.classList.remove("mbe-focused");
@@ -8580,8 +9123,8 @@ var Editor = class {
8580
9123
  });
8581
9124
  }
8582
9125
  onScroll() {
8583
- this.handle.hide();
8584
- this.imageControls.reposition();
9126
+ this.blockHandle.hide();
9127
+ this.resizeHandles.reposition();
8585
9128
  if (this.suggestions.isActive || this.toolbar?.isOpen || this.blockMenu.isOpen) this.updateUi();
8586
9129
  }
8587
9130
  // -------------------------------------------------------------------------
@@ -8686,7 +9229,7 @@ var Editor = class {
8686
9229
  /** The slash menu, as a suggestion. */
8687
9230
  slashSuggestion() {
8688
9231
  const ids = this.options.slashMenu || SLASH_ITEM_IDS;
8689
- 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 }));
8690
9233
  return {
8691
9234
  name: "slash",
8692
9235
  trigger: SLASH_CHARS,
@@ -8849,16 +9392,42 @@ var Editor = class {
8849
9392
  blockMenuSections(blockId) {
8850
9393
  const block3 = getBlock(this.state.doc, blockId);
8851
9394
  const sections2 = [];
8852
- if (block3.type === "table" && this.state.selection.focus.blockId === blockId && this.state.selection.focus.cell) {
8853
- sections2.push({
8854
- title: this.labels.tableSection,
8855
- items: TABLE_ITEMS.map(({ id, action }) => ({
8856
- id,
8857
- label: this.labels[id],
8858
- icon: this.icon(id),
8859
- run: () => this.run((s) => tableAction(s, action))
8860
- }))
8861
- });
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 });
8862
9431
  }
8863
9432
  sections2.push({
8864
9433
  items: [
@@ -8868,22 +9437,41 @@ var Editor = class {
8868
9437
  });
8869
9438
  return sections2;
8870
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
+ }
8871
9454
  /**
8872
9455
  * @internal
8873
- * Only large blocks get the handle and block menu: tables and code blocks.
8874
- * 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.
8875
9459
  */
8876
9460
  hasBlockMenu(blockId) {
8877
9461
  const block3 = this.state.doc.blocks.find((b) => b.id === blockId);
8878
- return block3?.type === "table" || block3?.type === "code";
9462
+ return block3?.type === "table" || block3?.type === "code" || !!block3 && isImageBlock(block3);
8879
9463
  }
8880
- /** @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. */
8881
9465
  openBlockMenu(blockId, anchor) {
8882
9466
  if (this.readOnly || !this.hasBlockMenu(blockId)) return;
8883
9467
  this.dropBlockSelection();
8884
9468
  this.suggestions.close();
8885
9469
  this.toolbar?.hide();
8886
- 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) {
8887
9475
  const block3 = getBlock(this.state.doc, blockId);
8888
9476
  const start = startOf(block3);
8889
9477
  this.current = { ...this.state, selection: { anchor: start, focus: start } };
@@ -8900,30 +9488,41 @@ var Editor = class {
8900
9488
  this.blockMenu.hide();
8901
9489
  this.syncActiveDescendant();
8902
9490
  }
8903
- /** 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
+ */
8904
9495
  onDocumentPointerDown(e) {
8905
- if (!this.blockMenu.isOpen) return;
8906
9496
  const target = e.target;
8907
- 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;
8908
9500
  this.closeBlockMenu();
8909
9501
  }
8910
9502
  // -------------------------------------------------------------------------
8911
9503
  // Toolbar and link popover (see ui/toolbar.ts)
8912
- /** @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
+ */
8913
9508
  openLinkPopover() {
8914
- if (this.readOnly) return;
9509
+ if (this.readOnly) return false;
8915
9510
  const block3 = getBlock(this.state.doc, this.state.selection.focus.blockId);
8916
- if (isPlainTextBlock(block3)) return;
8917
- 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;
8918
9513
  const rect = this.selectionRect();
8919
- if (!rect) return;
9514
+ if (!rect) return false;
8920
9515
  this.toolbar?.hide();
8921
9516
  const saved = this.state.selection;
8922
- 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) => {
8923
9521
  this.current = { ...this.state, selection: saved };
8924
9522
  if (href !== null) this.run((s) => setLink(s, href === "" ? null : href));
8925
9523
  this.focus();
8926
9524
  });
9525
+ return true;
8927
9526
  }
8928
9527
  // -------------------------------------------------------------------------
8929
9528
  // UI that follows the selection
@@ -8941,12 +9540,9 @@ var Editor = class {
8941
9540
  this.hintEl = nextHint;
8942
9541
  }
8943
9542
  this.suggestions.update(focused);
8944
- const image = !this.readOnly && !this.blockSel && (focused || this.imageControls.isEditingAlt) ? this.imageTargetAt(this.state) : null;
9543
+ const image = focused && !this.readOnly && !this.blockSel ? this.imageTargetAt(this.state) : null;
8945
9544
  this.paintSelectedImage(image?.el ?? null);
8946
- this.imageControls.update(
8947
- image,
8948
- focused && !this.composing && !this.suggestions.isActive && !this.blockMenu.isOpen && !this.imageControls.isResizing
8949
- );
9545
+ this.resizeHandles.update(image);
8950
9546
  if (this.toolbar) {
8951
9547
  const block3 = this.state.doc.blocks.find((b) => b.id === pos.blockId);
8952
9548
  const closed = this.toolbarClosedFor;
@@ -8956,8 +9552,8 @@ var Editor = class {
8956
9552
  else this.toolbar.hide();
8957
9553
  }
8958
9554
  if (focused && !this.readOnly && isTouch()) {
8959
- if (this.hasBlockMenu(pos.blockId)) this.handle.showFor(pos.blockId);
8960
- else this.handle.hide();
9555
+ if (this.hasBlockMenu(pos.blockId)) this.blockHandle.showFor(pos.blockId);
9556
+ else this.blockHandle.hide();
8961
9557
  }
8962
9558
  if (!focused && this.blockMenu.isOpen && !this.root.ownerDocument.activeElement?.closest?.(".mbe-ui")) this.blockMenu.hide();
8963
9559
  this.syncActiveDescendant();
@@ -8972,7 +9568,7 @@ var Editor = class {
8972
9568
  this.root.classList.toggle("mbe-image-selection", el !== null);
8973
9569
  }
8974
9570
  // -------------------------------------------------------------------------
8975
- // Images (see ui/image.ts)
9571
+ // Images (see ui/resizeHandles.ts)
8976
9572
  /** The selected image of `state` and its element, or null. */
8977
9573
  imageTargetAt(state) {
8978
9574
  const selected = selectedImage(state);
@@ -9003,12 +9599,28 @@ var Editor = class {
9003
9599
  updateImageAt(pos, change) {
9004
9600
  this.run((s) => updateImage(s, pos, change));
9005
9601
  }
9006
- /** @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. */
9007
9618
  refreshImageUi() {
9008
9619
  this.updateUi();
9009
9620
  }
9010
9621
  syncActiveDescendant() {
9011
- 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;
9012
9624
  if (id) this.root.setAttribute("aria-activedescendant", id);
9013
9625
  else this.root.removeAttribute("aria-activedescendant");
9014
9626
  }
@@ -9017,8 +9629,8 @@ var Editor = class {
9017
9629
  this.suggestions.close();
9018
9630
  this.blockMenu.hide();
9019
9631
  this.toolbar?.hide();
9020
- this.handle.hide();
9021
- this.imageControls.hide();
9632
+ this.blockHandle.hide();
9633
+ this.resizeHandles.hide();
9022
9634
  this.paintSelectedImage(null);
9023
9635
  this.hintEl?.classList.remove("mbe-show-hint");
9024
9636
  this.hintEl = null;
@@ -9389,6 +10001,7 @@ export {
9389
10001
  MARK_ORDER,
9390
10002
  MAX_INDENT,
9391
10003
  SLASH_ITEM_IDS,
10004
+ TOOLBAR_ITEMS,
9392
10005
  blockIndex,
9393
10006
  caret,
9394
10007
  clampSelection,
@@ -9413,10 +10026,12 @@ export {
9413
10026
  heading,
9414
10027
  htmlBlock,
9415
10028
  htmlToDoc,
10029
+ imageBlockOffset,
9416
10030
  inlineLength,
9417
10031
  inlineText,
9418
10032
  insertInline,
9419
10033
  isCollapsed,
10034
+ isImageBlock,
9420
10035
  isPlainTextBlock,
9421
10036
  isTextBlock,
9422
10037
  linkAt,