@usememos/editor 26.10.7 → 26.10.8

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
@@ -39,7 +39,9 @@ __export(commands_exports, {
39
39
  previousGrapheme: () => previousGrapheme,
40
40
  replaceBlocks: () => replaceBlocks,
41
41
  selectAll: () => selectAll,
42
+ selectImage: () => selectImage,
42
43
  selectedBlocks: () => selectedBlocks,
44
+ selectedImage: () => selectedImage,
43
45
  setBlockType: () => setBlockType,
44
46
  setCodeLanguage: () => setCodeLanguage,
45
47
  setLink: () => setLink,
@@ -48,7 +50,8 @@ __export(commands_exports, {
48
50
  tableAction: () => tableAction,
49
51
  toggleBlockType: () => toggleBlockType,
50
52
  toggleMark: () => toggleMark,
51
- toggleTask: () => toggleTask
53
+ toggleTask: () => toggleTask,
54
+ updateImage: () => updateImage
52
55
  });
53
56
 
54
57
  // src/model.ts
@@ -794,6 +797,48 @@ function setLink(state, href) {
794
797
  const blocks = mapTextInRange(state, from, to, (content, a, b) => setLinkInRange(content, a, b, href));
795
798
  return { ...state, doc: { blocks }, storedMarks: null };
796
799
  }
800
+ function selectedImage(state) {
801
+ const { anchor, focus } = state.selection;
802
+ if (anchor.blockId !== focus.blockId || !sameCell(anchor.cell, focus.cell)) return null;
803
+ if (Math.abs(anchor.offset - focus.offset) !== 1) return null;
804
+ const from = Math.min(anchor.offset, focus.offset);
805
+ const content = containerContent(getBlock(state.doc, anchor.blockId), anchor.cell);
806
+ const image = content ? sliceInline(content, from, from + 1)[0]?.image : void 0;
807
+ return image ? { pos: { ...anchor, offset: from }, image } : null;
808
+ }
809
+ function selectImage(state, pos) {
810
+ const block3 = state.doc.blocks.find((b) => b.id === pos.blockId);
811
+ const content = block3 && containerContent(block3, pos.cell);
812
+ if (!content || !sliceInline(content, pos.offset, pos.offset + 1)[0]?.image) return state;
813
+ return { ...state, selection: { anchor: pos, focus: { ...pos, offset: pos.offset + 1 } }, storedMarks: null };
814
+ }
815
+ function updateImage(state, pos, change) {
816
+ const block3 = state.doc.blocks.find((b) => b.id === pos.blockId);
817
+ const content = block3 && containerContent(block3, pos.cell);
818
+ const span = content ? sliceInline(content, pos.offset, pos.offset + 1)[0] : void 0;
819
+ if (!block3 || !content || !span?.image) return state;
820
+ const { title: _title, width: _width, height: _height, ...rest } = span.image;
821
+ let title = span.image.title;
822
+ if (change.title !== void 0) title = change.title || void 0;
823
+ let width = span.image.width;
824
+ let height = span.image.height;
825
+ if (change.width !== void 0) {
826
+ width = change.width === null ? void 0 : Math.max(1, Math.min(99999, Math.round(change.width)));
827
+ if (width !== span.image.width) height = void 0;
828
+ }
829
+ const image = {
830
+ ...rest,
831
+ ...change.alt !== void 0 ? { alt: change.alt } : {},
832
+ ...title ? { title } : {},
833
+ ...width ? { width } : {},
834
+ ...width && height ? { height } : {}
835
+ };
836
+ 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;
838
+ if (same) return selected === state.selection ? state : { ...state, selection: selected, storedMarks: null };
839
+ const next = concatInline(sliceInline(content, 0, pos.offset), [{ ...span, text: ATOM_CHAR, image }], sliceInline(content, pos.offset + 1));
840
+ return replaceBlock(state, withContainerContent(block3, pos.cell, next), selected);
841
+ }
797
842
  function convert(block3, spec) {
798
843
  const content = block3.content;
799
844
  switch (spec.type) {
@@ -1474,8 +1519,10 @@ function inlineHtml(inline3) {
1474
1519
  function spanHtml(span) {
1475
1520
  let html;
1476
1521
  if (span.image) {
1477
- const { src, alt, title } = span.image;
1478
- html = `<img src="${escapeHtml(src)}" alt="${escapeHtml(alt)}"${title ? ` title="${escapeHtml(title)}"` : ""}>`;
1522
+ const { src, alt, title, width, height } = span.image;
1523
+ html = `<img src="${escapeHtml(src)}" alt="${escapeHtml(alt)}"${title ? ` title="${escapeHtml(title)}"` : ""}`;
1524
+ if (width) html += ` width="${width}"${height ? ` height="${height}"` : ""}`;
1525
+ html += ">";
1479
1526
  } else if (span.marks.includes("html")) {
1480
1527
  html = span.text;
1481
1528
  } else {
@@ -1730,7 +1777,20 @@ var Converter = class _Converter {
1730
1777
  if (!src || /^(?:javascript|vbscript):/i.test(src)) return;
1731
1778
  const alt = el.getAttribute("alt") ?? "";
1732
1779
  const title = el.getAttribute("title");
1733
- this.push(ATOM_CHAR, format, { image: title ? { src, alt, title } : { src, alt } });
1780
+ const size = (name) => {
1781
+ const value = el.getAttribute(name)?.trim() ?? "";
1782
+ return /^[1-9][0-9]{0,4}$/.test(value) ? Number(value) : 0;
1783
+ };
1784
+ const width = size("width");
1785
+ const height = width ? size("height") : 0;
1786
+ const image = {
1787
+ src,
1788
+ alt,
1789
+ ...title ? { title } : {},
1790
+ ...width ? { width } : {},
1791
+ ...height ? { height } : {}
1792
+ };
1793
+ this.push(ATOM_CHAR, format, { image });
1734
1794
  return;
1735
1795
  }
1736
1796
  const block3 = BLOCKS.has(tag);
@@ -2011,7 +2071,14 @@ var DEFAULT_LABELS = {
2011
2071
  alignLeft: "Align left",
2012
2072
  alignCenter: "Align center",
2013
2073
  alignRight: "Align right",
2014
- tableSection: "Table"
2074
+ 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. */
2078
+ altText: "Alt text",
2079
+ altTextPlaceholder: "Describe the image\u2026",
2080
+ /** Accessible name of the handles that resize an image. */
2081
+ resizeImage: "Resize image"
2015
2082
  };
2016
2083
 
2017
2084
  // src/icons.ts
@@ -2075,6 +2142,15 @@ var ICONS = {
2075
2142
  inlineCode: ["m16 18 6-6-6-6", "m8 6-6 6 6 6"],
2076
2143
  /** `link` */
2077
2144
  link: ["M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71", "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"],
2145
+ /** `image-off` */
2146
+ imageUnavailable: [
2147
+ ["line", { x1: "2", x2: "22", y1: "2", y2: "22" }],
2148
+ "M10.41 10.41a2 2 0 1 1-2.83-2.83",
2149
+ ["line", { x1: "13.5", x2: "6", y1: "13.5", y2: "21" }],
2150
+ ["line", { x1: "18", x2: "21", y1: "12", y2: "15" }],
2151
+ "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
+ "M21 15V5a2 2 0 0 0-2-2H9"
2153
+ ],
2078
2154
  /** `grip-vertical` */
2079
2155
  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" }]]
2080
2156
  };
@@ -2106,10 +2182,8 @@ function iconNode(doc, icon) {
2106
2182
  return typeof icon === "string" ? doc.createTextNode(icon) : doc.importNode(icon, true);
2107
2183
  }
2108
2184
 
2109
- // src/markdown/inline.ts
2110
- import { lookupEntity } from "#entities";
2111
-
2112
2185
  // src/markdown/ast.ts
2186
+ var IMAGE_SIZE = /\|([1-9][0-9]{0,4})(?:x([1-9][0-9]{0,4}))?$/;
2113
2187
  function inlineNodesText(nodes, soft) {
2114
2188
  let s = "";
2115
2189
  for (const node of nodes) {
@@ -2133,6 +2207,9 @@ function inlineNodesText(nodes, soft) {
2133
2207
  return s;
2134
2208
  }
2135
2209
 
2210
+ // src/markdown/inline.ts
2211
+ import { lookupEntity } from "#entities";
2212
+
2136
2213
  // src/markdown/options.ts
2137
2214
  var DEFAULT_MARKDOWN = { breaks: false, setext: true, autolinks: true, syntax: [], inline: [], block: [], escape: "" };
2138
2215
  var resolved = /* @__PURE__ */ new WeakMap();
@@ -2210,14 +2287,23 @@ function lowerInto(nodes, marks, link, out, soft) {
2210
2287
  case "link":
2211
2288
  lowerInto(node.children, marks, node.destination, out, soft);
2212
2289
  break;
2213
- case "image": {
2214
- const alt = inlineNodesText(node.children, " ");
2215
- push({ text: ATOM_CHAR, marks, image: node.title ? { src: node.destination, alt, title: node.title } : { src: node.destination, alt } });
2290
+ case "image":
2291
+ push({ text: ATOM_CHAR, marks, image: imageAtom(node) });
2216
2292
  break;
2217
- }
2218
2293
  }
2219
2294
  }
2220
2295
  }
2296
+ function imageAtom(node) {
2297
+ let alt = inlineNodesText(node.children, " ");
2298
+ if (node.width) alt = alt.replace(IMAGE_SIZE, "");
2299
+ return {
2300
+ src: node.destination,
2301
+ alt,
2302
+ ...node.title ? { title: node.title } : {},
2303
+ ...node.width ? { width: node.width } : {},
2304
+ ...node.height ? { height: node.height } : {}
2305
+ };
2306
+ }
2221
2307
  function withMark(marks, mark) {
2222
2308
  return marks.includes(mark) ? marks : sortMarks([...marks, mark]);
2223
2309
  }
@@ -2417,6 +2503,9 @@ var Node2 = class {
2417
2503
  depth = 0;
2418
2504
  destination = "";
2419
2505
  title = "";
2506
+ /** An image's size (see `IMAGE_SIZE`), 0 when none. */
2507
+ width = 0;
2508
+ height = 0;
2420
2509
  /** An escaped "@": kept apart from the text around it, so it does not join an e-mail literal. */
2421
2510
  apart = false;
2422
2511
  parent = null;
@@ -2494,9 +2583,13 @@ function toAst(parent) {
2494
2583
  out.push({ type: n.type, children: toAst(n) });
2495
2584
  break;
2496
2585
  case "link":
2497
- case "image":
2498
2586
  out.push({ type: n.type, destination: n.destination, title: n.title, children: toAst(n) });
2499
2587
  break;
2588
+ 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);
2591
+ break;
2592
+ }
2500
2593
  case "root":
2501
2594
  break;
2502
2595
  }
@@ -2952,6 +3045,14 @@ var InlineParser = class {
2952
3045
  const link = new Node2(opener.image ? "image" : "link");
2953
3046
  link.destination = dest ?? "";
2954
3047
  link.title = title ?? "";
3048
+ 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;
3054
+ }
3055
+ }
2955
3056
  let n = opener.node.next;
2956
3057
  while (n) {
2957
3058
  const next = n.next;
@@ -3967,7 +4068,7 @@ var STRATEGIES = [
3967
4068
  function sameInline(a, b) {
3968
4069
  return a.length === b.length && a.every((s, i) => {
3969
4070
  const t = b[i];
3970
- 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;
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;
3971
4072
  });
3972
4073
  }
3973
4074
  var reSpecWhitespace = /^[\t\n\f\r\p{Zs}]+|[\t\n\f\r\p{Zs}]+$/gu;
@@ -4348,7 +4449,9 @@ function imageMarkdown(image, ctx) {
4348
4449
  atEnd: false
4349
4450
  });
4350
4451
  const title = image.title ? ` "${escapeEntities(image.title.replace(/["\\]/g, "\\$&"))}"` : "";
4351
- return `![${alt}](${linkDestination(image.src)}${title})`;
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;
4454
+ return `![${text}](${linkDestination(image.src)}${title})`;
4352
4455
  }
4353
4456
 
4354
4457
  // src/markdown/source.ts
@@ -5963,14 +6066,23 @@ function renderSpan(span, ctx, viewed = false) {
5963
6066
  const view = viewed ? ctx.view?.(span.token, span.text, "inline") : null;
5964
6067
  if (view) return wrapMarks(span, atom(view, classes("mbe-view", `mbe-view-${span.token}`, ctx.classes.token?.[span.token]), span.text), ctx);
5965
6068
  if (span.image) {
6069
+ const image = span.image;
6070
+ const src = ctx.resolveUrl(image.src, "image");
6071
+ if (src === null) return unavailableImage(image, ctx);
5966
6072
  const img = doc.createElement("img");
5967
6073
  img.setAttribute("loading", "lazy");
5968
6074
  img.setAttribute("decoding", "async");
5969
6075
  if (ctx.referrerPolicy) img.setAttribute("referrerpolicy", ctx.referrerPolicy);
5970
- const src = ctx.resolveUrl(span.image.src, "image");
5971
- if (src !== null) img.src = src;
5972
- img.alt = span.image.alt;
5973
- if (span.image.title) img.title = span.image.title;
6076
+ img.src = src;
6077
+ 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
+ });
5974
6086
  return atom(img, classes("mbe-image", ctx.classes.image));
5975
6087
  }
5976
6088
  let node = doc.createTextNode(span.text);
@@ -5983,6 +6095,21 @@ function renderSpan(span, ctx, viewed = false) {
5983
6095
  }
5984
6096
  return wrapMarks(span, node, ctx);
5985
6097
  }
6098
+ function unavailableImage(image, ctx) {
6099
+ const doc = ctx.doc;
6100
+ const el = doc.createElement("span");
6101
+ const text = image.alt || ctx.labels.imageUnavailable;
6102
+ el.setAttribute("role", "img");
6103
+ el.setAttribute("aria-label", text);
6104
+ if (image.title) el.title = image.title;
6105
+ const icon = ctx.icon?.("imageUnavailable");
6106
+ if (icon) el.appendChild(icon);
6107
+ const label = doc.createElement("span");
6108
+ label.className = "mbe-image-alt";
6109
+ label.textContent = text;
6110
+ el.appendChild(label);
6111
+ return atom(el, classes("mbe-image", "mbe-image-unavailable", ctx.classes.image));
6112
+ }
5986
6113
  function wrapMarks(span, node, ctx) {
5987
6114
  for (let i = MARK_ORDER.length - 1; i >= 0; i--) {
5988
6115
  const mark = MARK_ORDER[i];
@@ -6028,6 +6155,8 @@ var BlockRenderer = class {
6028
6155
  icon;
6029
6156
  /** Code blocks get a copy button. */
6030
6157
  codeCopy = false;
6158
+ /** An image failed to load and now shows as unavailable. */
6159
+ onImageError;
6031
6160
  /** Per block, the views that show their source. A block re-renders when its entry changes. */
6032
6161
  revealed = /* @__PURE__ */ new Map();
6033
6162
  /**
@@ -6053,7 +6182,8 @@ var BlockRenderer = class {
6053
6182
  view: this.views && ((syntax, source, kind) => this.renderView(syntax, source, kind)),
6054
6183
  classes: this.classes,
6055
6184
  icon: this.icon,
6056
- codeCopy: this.codeCopy
6185
+ codeCopy: this.codeCopy,
6186
+ onImageError: this.onImageError
6057
6187
  };
6058
6188
  }
6059
6189
  renderView(syntax, source, kind) {
@@ -6281,6 +6411,17 @@ function domToPosition(root, node, offset) {
6281
6411
  if (!content) return { blockId, offset: 0 };
6282
6412
  return { blockId, offset: offsetIn(content, target, off) };
6283
6413
  }
6414
+ function atomAt(blockEl, pos) {
6415
+ const content = contentElement(blockEl, pos.cell);
6416
+ if (!content) return null;
6417
+ let acc = 0;
6418
+ for (const leaf of leaves(content)) {
6419
+ if (acc === pos.offset && leaf.nodeType !== 3) return leaf;
6420
+ acc += leafLength(leaf);
6421
+ if (acc > pos.offset) return null;
6422
+ }
6423
+ return null;
6424
+ }
6284
6425
  function positionToDom(blockEl, pos) {
6285
6426
  const content = contentElement(blockEl, pos.cell);
6286
6427
  if (!content) {
@@ -6393,6 +6534,281 @@ var BlockHandle = class {
6393
6534
  }
6394
6535
  };
6395
6536
 
6537
+ // src/ui/image.ts
6538
+ var MIN_WIDTH = 24;
6539
+ var SNAP = 8;
6540
+ var ImageControls = class {
6541
+ constructor(editor) {
6542
+ this.editor = editor;
6543
+ const root = editor.root;
6544
+ const doc = root.ownerDocument;
6545
+ const labels = editor.labels;
6546
+ this.frame = doc.createElement("div");
6547
+ this.frame.className = "mbe-ui mbe-image-frame";
6548
+ this.frame.hidden = true;
6549
+ const handle = (side) => {
6550
+ const el = doc.createElement("div");
6551
+ el.className = `mbe-image-handle mbe-image-handle-${side}`;
6552
+ el.dataset.side = side;
6553
+ el.title = labels.resizeImage;
6554
+ el.setAttribute("aria-hidden", "true");
6555
+ this.frame.appendChild(el);
6556
+ return el;
6557
+ };
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);
6574
+ const on = (target, type, fn) => {
6575
+ target.addEventListener(type, fn);
6576
+ this.cleanup.push(() => target.removeEventListener(type, fn));
6577
+ };
6578
+ on(root, "mouseover", (e) => this.onOver(e));
6579
+ on(root, "mouseleave", () => this.scheduleUnhover());
6580
+ for (const el of [this.frame, this.handles.left, this.handles.right]) {
6581
+ on(el, "mouseenter", () => this.cancelUnhover());
6582
+ on(el, "mouseleave", () => this.scheduleUnhover());
6583
+ }
6584
+ on(this.frame, "mousedown", (e) => e.preventDefault());
6585
+ for (const side of ["left", "right"]) on(this.handles[side], "pointerdown", (e) => this.startDrag(e, side));
6586
+ on(this.frame, "pointermove", (e) => this.moveDrag(e));
6587
+ on(this.frame, "pointerup", (e) => this.endDrag(e, true));
6588
+ on(this.frame, "pointercancel", (e) => this.endDrag(e, false));
6589
+ 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
+ }
6605
+ /** A frame over the image, holding the two handles. It takes no pointer events itself. */
6606
+ frame;
6607
+ handles;
6608
+ toolbar;
6609
+ altPopover;
6610
+ altInput;
6611
+ /** The image under the pointer, which shows handles while it is hovered. */
6612
+ hovered = null;
6613
+ /** The selected image, which shows handles and the toolbar. */
6614
+ selected = null;
6615
+ /** The image the frame is shown for. */
6616
+ framed = null;
6617
+ drag = null;
6618
+ altDone = null;
6619
+ hideTimer = null;
6620
+ 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. */
6630
+ contains(node) {
6631
+ return this.frame.contains(node) || this.toolbar.el.contains(node) || this.altPopover.el.contains(node);
6632
+ }
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) {
6639
+ 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();
6650
+ }
6651
+ /** Moves the controls to where their image is now, after scrolling. */
6652
+ reposition() {
6653
+ if (this.drag) return;
6654
+ 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
+ this.placeFrame();
6658
+ }
6659
+ hide() {
6660
+ if (this.drag) return;
6661
+ this.hovered = null;
6662
+ this.selected = null;
6663
+ this.toolbar.hide();
6664
+ if (this.altPopover.isOpen) this.closeAlt();
6665
+ this.placeFrame();
6666
+ }
6667
+ destroy() {
6668
+ this.cancelUnhover();
6669
+ for (const fn of this.cleanup) fn();
6670
+ 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
+ }
6683
+ // -- Hover ----------------------------------------------------------------
6684
+ onOver(e) {
6685
+ if (this.drag || !this.editor.isEditable) return;
6686
+ const target = e.target;
6687
+ const img = target instanceof HTMLImageElement && target.classList.contains("mbe-image") ? target : null;
6688
+ if (img) {
6689
+ this.cancelUnhover();
6690
+ this.hovered = img;
6691
+ this.placeFrame();
6692
+ } else if (this.hovered) {
6693
+ this.scheduleUnhover();
6694
+ }
6695
+ }
6696
+ scheduleUnhover() {
6697
+ this.cancelUnhover();
6698
+ this.hideTimer = setTimeout(() => {
6699
+ this.hideTimer = null;
6700
+ this.hovered = null;
6701
+ this.placeFrame();
6702
+ }, 250);
6703
+ }
6704
+ cancelUnhover() {
6705
+ if (this.hideTimer !== null) clearTimeout(this.hideTimer);
6706
+ this.hideTimer = null;
6707
+ }
6708
+ /** Shows the handles over the hovered image, else the selected one. Only images that loaded can be resized. */
6709
+ placeFrame() {
6710
+ const editable = this.editor.isEditable;
6711
+ const hovered = this.hovered?.isConnected ? this.hovered : null;
6712
+ const el = this.drag?.el ?? (editable ? hovered ?? this.selected?.el ?? null : null);
6713
+ const img = el instanceof HTMLImageElement && el.isConnected ? el : null;
6714
+ const rect = img?.getBoundingClientRect();
6715
+ if (!img || !rect || rect.width === 0 || rect.height === 0) {
6716
+ this.frame.hidden = true;
6717
+ this.framed = null;
6718
+ return;
6719
+ }
6720
+ if (this.framed !== img) {
6721
+ this.framed = img;
6722
+ if (!img.complete) img.addEventListener("load", () => this.framed === img && this.placeFrame(), { once: true });
6723
+ }
6724
+ this.frame.hidden = false;
6725
+ const offset = attach(this.frame, this.editor.root);
6726
+ this.frame.style.left = `${Math.round(rect.left - offset.x)}px`;
6727
+ this.frame.style.top = `${Math.round(rect.top - offset.y)}px`;
6728
+ this.frame.style.width = `${Math.round(rect.width)}px`;
6729
+ this.frame.style.height = `${Math.round(rect.height)}px`;
6730
+ this.frame.classList.toggle("mbe-image-frame-small", rect.width < 64 || rect.height < 40);
6731
+ }
6732
+ // -- Resizing -------------------------------------------------------------
6733
+ startDrag(e, side) {
6734
+ const el = this.framed;
6735
+ if (!el || this.drag || e.button !== 0 || !this.editor.isEditable) return;
6736
+ const target = this.editor.imageTarget(el);
6737
+ if (!target) return;
6738
+ e.preventDefault();
6739
+ this.handles[side].setPointerCapture?.(e.pointerId);
6740
+ const width = el.getBoundingClientRect().width;
6741
+ 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
+ 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();
6745
+ this.frame.classList.add("mbe-image-resizing");
6746
+ this.editor.selectImageAt(target.pos);
6747
+ }
6748
+ moveDrag(e) {
6749
+ const drag = this.drag;
6750
+ if (!drag || e.pointerId !== drag.pointer) return;
6751
+ e.preventDefault();
6752
+ const dx = (e.clientX - drag.startX) * (drag.side === "right" ? 1 : -1);
6753
+ let width = Math.min(drag.max, Math.max(MIN_WIDTH, drag.startWidth + dx));
6754
+ const snap = drag.snaps.find((w) => Math.abs(w - width) <= SNAP);
6755
+ if (snap !== void 0) width = Math.min(drag.max, snap);
6756
+ drag.width = Math.round(width);
6757
+ drag.el.style.width = `${drag.width}px`;
6758
+ drag.el.style.height = "auto";
6759
+ this.placeFrame();
6760
+ }
6761
+ endDrag(e, commit) {
6762
+ const drag = this.drag;
6763
+ if (!drag || e.pointerId !== drag.pointer) return;
6764
+ this.drag = null;
6765
+ this.frame.classList.remove("mbe-image-resizing");
6766
+ this.handles[drag.side].releasePointerCapture?.(e.pointerId);
6767
+ drag.el.style.width = "";
6768
+ drag.el.style.height = "";
6769
+ const target = drag.el.isConnected ? this.editor.imageTarget(drag.el) : null;
6770
+ if (commit && target && Math.round(drag.width) !== Math.round(drag.startWidth)) {
6771
+ this.editor.updateImageAt(target.pos, { width: drag.width });
6772
+ } else {
6773
+ this.editor.refreshImageUi();
6774
+ }
6775
+ }
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
+ };
6803
+ function columnWidth(el) {
6804
+ let box = el.parentElement;
6805
+ const view = el.ownerDocument.defaultView;
6806
+ while (box && view.getComputedStyle(box).display.startsWith("inline")) box = box.parentElement;
6807
+ if (!box) return el.getBoundingClientRect().width;
6808
+ const cs = view.getComputedStyle(box);
6809
+ return box.clientWidth - parseFloat(cs.paddingLeft || "0") - parseFloat(cs.paddingRight || "0");
6810
+ }
6811
+
6396
6812
  // src/view/reveal.ts
6397
6813
  function revealedViews(state, views, active) {
6398
6814
  const out = /* @__PURE__ */ new Map();
@@ -6630,6 +7046,9 @@ var Editor = class {
6630
7046
  toolbar;
6631
7047
  linkPopover;
6632
7048
  handle;
7049
+ imageControls;
7050
+ /** The selected image's element, which carries the selected class. */
7051
+ selectedImageEl = null;
6633
7052
  hintEl = null;
6634
7053
  /**
6635
7054
  * The block selection, by block ID, or null for a text selection. While it
@@ -6730,6 +7149,12 @@ var Editor = class {
6730
7149
  this.linkPopover = new LinkPopover(this);
6731
7150
  this.toolbar = options.toolbar === false ? null : new FormatToolbar(this);
6732
7151
  this.handle = new BlockHandle(this);
7152
+ this.imageControls = new ImageControls(this);
7153
+ this.renderer.onImageError = () => {
7154
+ if (this.destroyed) return;
7155
+ if (!this.composing) this.syncDomSelection();
7156
+ this.updateUi();
7157
+ };
6733
7158
  this.listen(root, "beforeinput", this.typed((e) => this.onBeforeInput(e)));
6734
7159
  this.listen(root, "input", this.typed((e) => this.onInput(e)));
6735
7160
  this.listen(root, "compositionstart", (e) => this.onCompositionStart(e));
@@ -6817,6 +7242,12 @@ var Editor = class {
6817
7242
  return isMarkActive(s, name);
6818
7243
  case "link":
6819
7244
  return activeLink(s) !== null;
7245
+ case "image": {
7246
+ const selected = selectedImage(s);
7247
+ if (!selected || !attrs) return selected !== null;
7248
+ const actual2 = { ...selected.image };
7249
+ return Object.entries(attrs).every(([k, v]) => actual2[k] === v);
7250
+ }
6820
7251
  }
6821
7252
  const block3 = getBlock(s.doc, s.selection.focus.blockId);
6822
7253
  if (blockName(block3) !== name) return false;
@@ -6824,13 +7255,14 @@ var Editor = class {
6824
7255
  const actual = this.getAttributes(name);
6825
7256
  return Object.entries(attrs).every(([k, v]) => actual[k] === v);
6826
7257
  }
6827
- /** Attributes of `name` at the selection: `href` for a link, `level` for a heading, `language` for a code block, `checked` for a task, `syntax` for a raw block. */
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. */
6828
7259
  getAttributes(name) {
6829
7260
  const s = this.current;
6830
7261
  if (name === "link") {
6831
7262
  const link = activeLink(s);
6832
7263
  return link ? { href: link.href } : {};
6833
7264
  }
7265
+ if (name === "image") return { ...selectedImage(s)?.image };
6834
7266
  const block3 = getBlock(s.doc, s.selection.focus.blockId);
6835
7267
  if (blockName(block3) !== name) return {};
6836
7268
  switch (block3.type) {
@@ -7050,6 +7482,10 @@ var Editor = class {
7050
7482
  toggleCodeBlock: (attrs = {}) => block3({ type: "code", language: attrs.language }),
7051
7483
  setLink: ({ href }) => run((s) => setLink(s, href)),
7052
7484
  unsetLink: () => run((s) => setLink(s, null)),
7485
+ updateImage: (attrs) => run((s) => {
7486
+ const selected = selectedImage(s);
7487
+ return selected ? updateImage(s, selected.pos, attrs) : null;
7488
+ }),
7053
7489
  insertText: (text, options = {}) => run((s) => {
7054
7490
  const range = options.range;
7055
7491
  if (!range) return insertText(s, text);
@@ -7191,6 +7627,7 @@ var Editor = class {
7191
7627
  this.toolbar?.destroy();
7192
7628
  this.linkPopover.destroy();
7193
7629
  this.handle.destroy();
7630
+ this.imageControls.destroy();
7194
7631
  setPopupContainer(this.root, void 0);
7195
7632
  for (const name of Object.keys(this.runtime.attributes ?? {})) this.root.removeAttribute(name);
7196
7633
  for (const name of this.tokenNames) this.root.style.removeProperty(name);
@@ -7894,6 +8331,14 @@ var Editor = class {
7894
8331
  e.preventDefault();
7895
8332
  return;
7896
8333
  }
8334
+ if (e.key === "Enter" && !mod2 && !e.altKey) {
8335
+ this.refreshSelection();
8336
+ const image = selectedImage(this.state);
8337
+ if (image) {
8338
+ const after = { ...image.pos, offset: image.pos.offset + 1 };
8339
+ this.setSelection({ anchor: after, focus: after });
8340
+ }
8341
+ }
7897
8342
  let refreshed = false;
7898
8343
  for (const binding of this.bindings) {
7899
8344
  if (!matchesKey(binding, e)) continue;
@@ -8008,6 +8453,13 @@ var Editor = class {
8008
8453
  }
8009
8454
  this.dropBlockSelection();
8010
8455
  if (target === this.root && e.button === 0 && !this.readOnly && this.clickBelowLastBlock(e)) return;
8456
+ const imageEl = e.button === 0 && !e.shiftKey && !this.readOnly ? target.closest?.(".mbe-image") : null;
8457
+ const image = imageEl && this.root.contains(imageEl) ? this.imageTarget(imageEl) : null;
8458
+ if (image) {
8459
+ e.preventDefault();
8460
+ this.selectImageAt(image.pos);
8461
+ return;
8462
+ }
8011
8463
  const view = e.button === 0 && !this.readOnly ? target.closest?.(".mbe-view, .mbe-view-block") : null;
8012
8464
  if (view && this.root.contains(view)) {
8013
8465
  e.preventDefault();
@@ -8114,9 +8566,9 @@ var Editor = class {
8114
8566
  }
8115
8567
  onFocusOut(e) {
8116
8568
  const next = e.relatedTarget;
8117
- if (next && (this.root.contains(next) || this.linkPopover.contains(next))) return;
8569
+ if (next && (this.root.contains(next) || this.linkPopover.contains(next) || this.imageControls.contains(next))) return;
8118
8570
  queueMicrotask(() => {
8119
- if (this.hasFocus() || this.linkPopover.isOpen) return;
8571
+ if (this.hasFocus() || this.linkPopover.isOpen || this.imageControls.isEditingAlt) return;
8120
8572
  if (!this.focused) return;
8121
8573
  this.focused = false;
8122
8574
  this.root.classList.remove("mbe-focused");
@@ -8129,6 +8581,7 @@ var Editor = class {
8129
8581
  }
8130
8582
  onScroll() {
8131
8583
  this.handle.hide();
8584
+ this.imageControls.reposition();
8132
8585
  if (this.suggestions.isActive || this.toolbar?.isOpen || this.blockMenu.isOpen) this.updateUi();
8133
8586
  }
8134
8587
  // -------------------------------------------------------------------------
@@ -8488,11 +8941,17 @@ var Editor = class {
8488
8941
  this.hintEl = nextHint;
8489
8942
  }
8490
8943
  this.suggestions.update(focused);
8944
+ const image = !this.readOnly && !this.blockSel && (focused || this.imageControls.isEditingAlt) ? this.imageTargetAt(this.state) : null;
8945
+ 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
+ );
8491
8950
  if (this.toolbar) {
8492
8951
  const block3 = this.state.doc.blocks.find((b) => b.id === pos.blockId);
8493
8952
  const closed = this.toolbarClosedFor;
8494
8953
  if (closed && !(samePosition(closed.anchor, this.state.selection.anchor) && samePosition(closed.focus, pos))) this.toolbarClosedFor = null;
8495
- const show = !this.toolbarClosedFor && focused && !this.readOnly && !this.composing && !isCollapsed(this.state.selection) && !this.blockSel && !this.suggestions.isActive && !this.blockMenu.isOpen && !!block3 && !isPlainTextBlock(block3) && block3.type !== "divider";
8954
+ const show = !this.toolbarClosedFor && focused && !this.readOnly && !this.composing && !isCollapsed(this.state.selection) && !this.blockSel && !image && !this.suggestions.isActive && !this.blockMenu.isOpen && !!block3 && !isPlainTextBlock(block3) && block3.type !== "divider";
8496
8955
  if (show) this.toolbar.show();
8497
8956
  else this.toolbar.hide();
8498
8957
  }
@@ -8503,6 +8962,51 @@ var Editor = class {
8503
8962
  if (!focused && this.blockMenu.isOpen && !this.root.ownerDocument.activeElement?.closest?.(".mbe-ui")) this.blockMenu.hide();
8504
8963
  this.syncActiveDescendant();
8505
8964
  }
8965
+ /** Marks the selected image's element, and hides the browser's selection highlight over it. */
8966
+ paintSelectedImage(el) {
8967
+ if (this.selectedImageEl !== el) {
8968
+ this.selectedImageEl?.classList.remove("mbe-image-selected");
8969
+ el?.classList.add("mbe-image-selected");
8970
+ this.selectedImageEl = el;
8971
+ }
8972
+ this.root.classList.toggle("mbe-image-selection", el !== null);
8973
+ }
8974
+ // -------------------------------------------------------------------------
8975
+ // Images (see ui/image.ts)
8976
+ /** The selected image of `state` and its element, or null. */
8977
+ imageTargetAt(state) {
8978
+ const selected = selectedImage(state);
8979
+ if (!selected) return null;
8980
+ const blockEl = this.renderer.elementFor(selected.pos.blockId);
8981
+ const el = blockEl ? atomAt(blockEl, selected.pos) : null;
8982
+ if (!el?.classList.contains("mbe-image")) return null;
8983
+ return { el, ...selected };
8984
+ }
8985
+ /** @internal The image an element shows, and the position before it. Null when it is not an image in this editor. */
8986
+ imageTarget(el) {
8987
+ if (!el.parentNode || !this.root.contains(el)) return null;
8988
+ const pos = domToPosition(this.root, el.parentNode, childIndex(el));
8989
+ if (!pos) return null;
8990
+ const next = selectImage(this.current, pos);
8991
+ const selected = next === this.current ? null : selectedImage(next);
8992
+ return selected ? { el, ...selected } : null;
8993
+ }
8994
+ /** @internal Selects the image after `pos` and focuses the editor. */
8995
+ selectImageAt(pos) {
8996
+ if (this.readOnly || this.destroyed) return;
8997
+ const next = selectImage(this.current, pos);
8998
+ if (next === this.current) return;
8999
+ if (!this.hasFocus()) this.root.focus({ preventScroll: true });
9000
+ this.setSelection(next.selection);
9001
+ }
9002
+ /** @internal Changes the image after `pos` and selects it, as one undo step. */
9003
+ updateImageAt(pos, change) {
9004
+ this.run((s) => updateImage(s, pos, change));
9005
+ }
9006
+ /** @internal Shows the image controls again, after a resize that changed nothing. */
9007
+ refreshImageUi() {
9008
+ this.updateUi();
9009
+ }
8506
9010
  syncActiveDescendant() {
8507
9011
  const id = this.suggestions.activeDescendant ?? (this.blockMenu.isOpen ? this.blockMenu.activeDescendant : null);
8508
9012
  if (id) this.root.setAttribute("aria-activedescendant", id);
@@ -8514,6 +9018,8 @@ var Editor = class {
8514
9018
  this.blockMenu.hide();
8515
9019
  this.toolbar?.hide();
8516
9020
  this.handle.hide();
9021
+ this.imageControls.hide();
9022
+ this.paintSelectedImage(null);
8517
9023
  this.hintEl?.classList.remove("mbe-show-hint");
8518
9024
  this.hintEl = null;
8519
9025
  }