@usememos/editor 26.10.2 → 26.10.4

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
@@ -1998,6 +1998,10 @@ var DEFAULT_LABELS = {
1998
1998
  language: "Language",
1999
1999
  /** Shown in a code block's language field when it has none. */
2000
2000
  plainText: "text",
2001
+ /** The copy button of a code block. */
2002
+ copyCode: "Copy code",
2003
+ /** The copy button of a code block, just after copying. */
2004
+ copied: "Copied",
2001
2005
  addRowAbove: "Add row above",
2002
2006
  addRowBelow: "Add row below",
2003
2007
  addColumnLeft: "Add column left",
@@ -2037,6 +2041,10 @@ var ICONS = {
2037
2041
  divider: ["M5 12h14"],
2038
2042
  /** `copy` */
2039
2043
  duplicate: [["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }], "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"],
2044
+ /** `copy` */
2045
+ copyCode: [["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }], "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"],
2046
+ /** `check` */
2047
+ copied: ["M20 6 9 17l-5-5"],
2040
2048
  /** `trash` */
2041
2049
  delete: TRASH,
2042
2050
  /** `arrow-up` */
@@ -3997,7 +4005,26 @@ function representableInline(inline3) {
3997
4005
  endRun();
3998
4006
  for (const [from, to] of removals) spans = setMarkInRange(spans, from, to, mark, false);
3999
4007
  }
4000
- return spans;
4008
+ return dropLineEndSpaces(spans);
4009
+ }
4010
+ var isPlainSpan = (s) => !s.link && !s.image && !s.token && !s.marks.includes("code") && !s.marks.includes("html");
4011
+ function dropLineEndSpaces(spans) {
4012
+ const text = spans.map((s) => s.text).join("");
4013
+ if (!/[ \t](\n|$)/.test(text)) return spans;
4014
+ const plain2 = [];
4015
+ for (const s of spans) for (let i = 0; i < s.text.length; i++) plain2.push(isPlainSpan(s));
4016
+ const removals = [];
4017
+ let lineStart = 0;
4018
+ for (let i = 0; i <= text.length; i++) {
4019
+ if (i < text.length && text[i] !== "\n") continue;
4020
+ let from = i;
4021
+ while (from > lineStart && (text[from - 1] === " " || text[from - 1] === " ") && plain2[from - 1]) from--;
4022
+ if (from < i && /[^ \t]/.test(text.slice(lineStart, from))) removals.push([from, i]);
4023
+ lineStart = i + 1;
4024
+ }
4025
+ let out = spans;
4026
+ for (let k = removals.length - 1; k >= 0; k--) out = deleteInline(out, removals[k][0], removals[k][1]);
4027
+ return normalizeInline(out);
4001
4028
  }
4002
4029
  function emphasisMarks(span) {
4003
4030
  return span.marks.filter(isEmphasis);
@@ -5621,6 +5648,9 @@ var LinkPopover = class {
5621
5648
 
5622
5649
  // src/view/dom.ts
5623
5650
  var BLOCK_ATTR = "data-block-id";
5651
+ function codeViewName(language) {
5652
+ return `code:${language.trim().toLowerCase()}`;
5653
+ }
5624
5654
  var CONTENT_ATTR = "data-content";
5625
5655
  var FILL_ATTR = "data-mbe-fill";
5626
5656
  var ATOM_ATTR = "data-atom";
@@ -5657,12 +5687,12 @@ function blockClasses(block3, theme) {
5657
5687
  return void 0;
5658
5688
  }
5659
5689
  }
5660
- function safeHref(href) {
5661
- const trimmed = href.trim();
5690
+ var defaultResolveUrl = (url) => {
5691
+ const trimmed = url.trim();
5662
5692
  const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(trimmed);
5663
5693
  if (!scheme) return trimmed;
5664
5694
  return ["http", "https", "mailto", "tel"].includes(scheme[1].toLowerCase()) ? trimmed : null;
5665
- }
5695
+ };
5666
5696
  var REVEAL_BLOCK = "block";
5667
5697
  function tokenKey(cell, from) {
5668
5698
  return cell ? `${cell.row}:${cell.col}@${from}` : `@${from}`;
@@ -5709,6 +5739,14 @@ function renderBlock(block3, ctx, reveal) {
5709
5739
  break;
5710
5740
  }
5711
5741
  case "code": {
5742
+ const view = reveal?.has(REVEAL_BLOCK) ? null : ctx.view?.(codeViewName(block3.language), inlineText(block3.content), "block");
5743
+ if (view) {
5744
+ root = view;
5745
+ root.classList.add("mbe-view-block");
5746
+ root.contentEditable = "false";
5747
+ root.dataset.language = block3.language;
5748
+ break;
5749
+ }
5712
5750
  root = el("div");
5713
5751
  root.dataset.language = block3.language;
5714
5752
  const bar = el("div", "mbe-code-bar");
@@ -5719,6 +5757,7 @@ function renderBlock(block3, ctx, reveal) {
5719
5757
  lang.setAttribute("aria-label", labels.language);
5720
5758
  lang.placeholder = labels.plainText;
5721
5759
  bar.appendChild(lang);
5760
+ if (ctx.codeCopy) bar.appendChild(copyButton(ctx));
5722
5761
  const pre = el("pre");
5723
5762
  const code = el("code");
5724
5763
  code.spellcheck = false;
@@ -5788,7 +5827,7 @@ function fillContent(target, inline3, ctx, block3, reveal, cell, decorated = tru
5788
5827
  target.appendChild(fill(doc));
5789
5828
  return;
5790
5829
  }
5791
- const decorations = decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
5830
+ const decorations = block3.type === "code" ? ctx.decorateCode?.(block3) ?? [] : decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
5792
5831
  const only = inline3.length === 1 ? inline3[0] : null;
5793
5832
  if (only && decorations.length === 0 && only.marks.length === 0 && !only.link && !only.token && !only.image) {
5794
5833
  target.appendChild(doc.createTextNode(only.text));
@@ -5798,23 +5837,89 @@ function fillContent(target, inline3, ctx, block3, reveal, cell, decorated = tru
5798
5837
  const last = inline3[inline3.length - 1];
5799
5838
  if (last && last.text.endsWith("\n")) target.appendChild(fill(doc));
5800
5839
  }
5840
+ function copyButton(ctx) {
5841
+ const button = ctx.doc.createElement("button");
5842
+ button.type = "button";
5843
+ button.className = "mbe-code-copy";
5844
+ button.tabIndex = -1;
5845
+ button.setAttribute("aria-label", ctx.labels.copyCode);
5846
+ button.title = ctx.labels.copyCode;
5847
+ const icon = ctx.icon?.("copyCode");
5848
+ if (icon) button.appendChild(icon);
5849
+ return button;
5850
+ }
5801
5851
  function fill(doc) {
5802
5852
  const br = doc.createElement("br");
5803
5853
  br.setAttribute(FILL_ATTR, "");
5804
5854
  return br;
5805
5855
  }
5856
+ var VOID_TAGS = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
5857
+ function htmlRuns(inline3) {
5858
+ const spans = [];
5859
+ let pos = 0;
5860
+ for (const span of inline3) {
5861
+ spans.push({ span, from: pos, to: pos + span.text.length });
5862
+ pos += span.text.length;
5863
+ }
5864
+ const isHtml = (span) => span.marks.includes("html");
5865
+ const runs = [];
5866
+ for (let i = 0; i < spans.length; i++) {
5867
+ const { span, from, to } = spans[i];
5868
+ if (!isHtml(span)) continue;
5869
+ const open = /^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*?(\/?)>$/.exec(span.text);
5870
+ let end = i;
5871
+ if (open && !open[2] && !VOID_TAGS.has(open[1].toLowerCase())) {
5872
+ const name = open[1].toLowerCase();
5873
+ let depth = 0;
5874
+ for (let j = i + 1; j < spans.length; j++) {
5875
+ const t = spans[j].span;
5876
+ if (t.link) break;
5877
+ if (!isHtml(t)) continue;
5878
+ const tag = /^<(\/?)([A-Za-z][A-Za-z0-9-]*)\b[^>]*?(\/?)>$/.exec(t.text);
5879
+ if (!tag || tag[2].toLowerCase() !== name || tag[3]) continue;
5880
+ if (!tag[1]) depth++;
5881
+ else if (depth > 0) depth--;
5882
+ else {
5883
+ end = j;
5884
+ break;
5885
+ }
5886
+ }
5887
+ }
5888
+ if (spans.slice(i, end + 1).some((s) => s.span.link)) continue;
5889
+ runs.push({ from, to: end === i ? to : spans[end].to });
5890
+ i = end;
5891
+ }
5892
+ return runs;
5893
+ }
5806
5894
  function renderInline(inline3, parent, ctx, decorations, reveal, cell) {
5807
5895
  const doc = ctx.doc;
5808
5896
  const views = ctx.views;
5809
5897
  const viewed = views ? (span, from) => !!span.token && views.has(span.token) && !reveal?.has(tokenKey(cell, from)) : void 0;
5810
- const pieces = splitByDecorations(inline3, decorations, viewed);
5811
- const render2 = (piece) => decorate(renderSpan(piece.span, ctx, piece.atomic), piece.decorations, doc);
5898
+ const runs = views?.has("html") && inline3.some((s) => s.marks.includes("html")) ? htmlRuns(inline3).filter((run) => !reveal?.has(tokenKey(cell, run.from))) : [];
5899
+ const inRun = (from) => runs.some((run) => from >= run.from && from < run.to);
5900
+ const atomic = viewed || runs.length > 0 ? (span, from) => !!viewed?.(span, from) || inRun(from) : void 0;
5901
+ const pieces = splitByDecorations(inline3, decorations, atomic);
5902
+ const render2 = (piece) => decorate(renderSpan(piece.span, ctx, piece.atomic && !inRun(offsets.get(piece) ?? -1)), piece.decorations, doc);
5903
+ const offsets = /* @__PURE__ */ new Map();
5904
+ let offset = 0;
5905
+ for (const piece of pieces) {
5906
+ offsets.set(piece, offset);
5907
+ offset += piece.span.text.length;
5908
+ }
5812
5909
  let i = 0;
5813
5910
  while (i < pieces.length) {
5814
5911
  const span = pieces[i].span;
5912
+ const run = runs.find((r) => r.from === offsets.get(pieces[i]));
5913
+ const view = run && ctx.view?.("html", serializeInline(sliceInline(inline3, run.from, run.to)), "inline");
5914
+ if (run && view) {
5915
+ const text = inlineText(sliceInline(inline3, run.from, run.to));
5916
+ parent.appendChild(atom(view, classes("mbe-view", "mbe-view-html", ctx.classes.token?.html), text));
5917
+ while (i < pieces.length && offsets.get(pieces[i]) < run.to) i++;
5918
+ continue;
5919
+ }
5815
5920
  if (span.link) {
5816
5921
  const a = doc.createElement("a");
5817
- const href = safeHref(span.link);
5922
+ const href = ctx.resolveUrl(span.link, "link");
5818
5923
  if (href !== null) a.setAttribute("href", href);
5819
5924
  a.dataset.href = span.link;
5820
5925
  a.className = classes("mbe-link", ctx.classes.link);
@@ -5853,7 +5958,10 @@ function renderSpan(span, ctx, viewed = false) {
5853
5958
  if (view) return wrapMarks(span, atom(view, classes("mbe-view", `mbe-view-${span.token}`, ctx.classes.token?.[span.token]), span.text), ctx);
5854
5959
  if (span.image) {
5855
5960
  const img = doc.createElement("img");
5856
- const src = safeHref(ctx.resolveImageSrc ? ctx.resolveImageSrc(span.image.src) : span.image.src);
5961
+ img.setAttribute("loading", "lazy");
5962
+ img.setAttribute("decoding", "async");
5963
+ if (ctx.referrerPolicy) img.setAttribute("referrerpolicy", ctx.referrerPolicy);
5964
+ const src = ctx.resolveUrl(span.image.src, "image");
5857
5965
  if (src !== null) img.src = src;
5858
5966
  img.alt = span.image.alt;
5859
5967
  if (span.image.title) img.title = span.image.title;
@@ -5890,16 +5998,30 @@ var BlockRenderer = class {
5890
5998
  rendered = /* @__PURE__ */ new Map();
5891
5999
  /** Last number written into each ordered item's marker, keyed by element. */
5892
6000
  numbers = /* @__PURE__ */ new WeakMap();
5893
- /** Maps an image `src` to the URL to display. Set before a full render. */
5894
- resolveImageSrc;
6001
+ /** The URL policy for links and images. Set before a full render. */
6002
+ resolveUrl = defaultResolveUrl;
6003
+ /** `referrerpolicy` for images. */
6004
+ referrerPolicy;
5895
6005
  /** Decorations for a text container. */
5896
6006
  decorate;
6007
+ /** Decorations for a code block's code. */
6008
+ decorateCode;
6009
+ /**
6010
+ * Called when views that returned a promise settle, with the blocks that
6011
+ * showed them. Those blocks must render again to show the finished view,
6012
+ * or their source if it failed.
6013
+ */
6014
+ onViewSettled;
5897
6015
  /** Widget elements to place after a block. */
5898
6016
  widgetsAfter;
5899
6017
  /** Views of extension syntaxes, by syntax name. */
5900
6018
  views;
5901
6019
  /** Theme classes for rendered elements. Set before a full render. */
5902
6020
  classes = NO_CLASSES;
6021
+ /** The icon of a UI control. */
6022
+ icon;
6023
+ /** Code blocks get a copy button. */
6024
+ codeCopy = false;
5903
6025
  /** Per block, the views that show their source. A block re-renders when its entry changes. */
5904
6026
  revealed = /* @__PURE__ */ new Map();
5905
6027
  /**
@@ -5907,36 +6029,71 @@ var BlockRenderer = class {
5907
6029
  * Cloned on reuse: typing re-renders a block and every formula in it.
5908
6030
  */
5909
6031
  viewCache = /* @__PURE__ */ new Map();
6032
+ /** Views whose promise has not settled, by cache key, with the blocks showing them. */
6033
+ pendingViews = /* @__PURE__ */ new Map();
6034
+ /** Views whose promise rejected or resolved to false: their source shows. */
6035
+ failedViews = /* @__PURE__ */ new Set();
6036
+ /** The block being rendered, so a pending view knows which blocks to render again. */
6037
+ renderingBlock = "";
5910
6038
  context() {
5911
6039
  return {
5912
6040
  doc: this.root.ownerDocument,
5913
6041
  labels: this.labels,
5914
- resolveImageSrc: this.resolveImageSrc,
6042
+ resolveUrl: this.resolveUrl,
6043
+ referrerPolicy: this.referrerPolicy,
5915
6044
  decorate: this.decorate,
6045
+ decorateCode: this.decorateCode,
5916
6046
  views: this.views,
5917
6047
  view: this.views && ((syntax, source, kind) => this.renderView(syntax, source, kind)),
5918
- classes: this.classes
6048
+ classes: this.classes,
6049
+ icon: this.icon,
6050
+ codeCopy: this.codeCopy
5919
6051
  };
5920
6052
  }
5921
6053
  renderView(syntax, source, kind) {
5922
6054
  const view = this.views?.get(syntax);
5923
6055
  if (!view) return null;
5924
6056
  const key = `${kind}\0${syntax}\0${source}`;
6057
+ if (this.failedViews.has(key)) return null;
5925
6058
  let el = this.viewCache.get(key);
5926
6059
  if (el) {
5927
6060
  this.viewCache.delete(key);
5928
6061
  } else {
5929
6062
  el = this.root.ownerDocument.createElement(kind === "inline" ? "span" : "div");
6063
+ let result;
5930
6064
  try {
5931
- if (view(source, el, kind) === false) return null;
6065
+ result = view(source, el, kind);
5932
6066
  } catch {
5933
6067
  return null;
5934
6068
  }
6069
+ if (result === false) return null;
6070
+ if (result && typeof result.then === "function") this.awaitView(key, result);
5935
6071
  if (this.viewCache.size >= 500) this.viewCache.delete(this.viewCache.keys().next().value);
5936
6072
  }
6073
+ this.pendingViews.get(key)?.add(this.renderingBlock);
5937
6074
  this.viewCache.set(key, el);
5938
6075
  return el.cloneNode(true);
5939
6076
  }
6077
+ /**
6078
+ * A view that renders later (a diagram, a lazily loaded renderer) shows what
6079
+ * it filled in at once, and its blocks render again when it settles.
6080
+ */
6081
+ awaitView(key, result) {
6082
+ this.pendingViews.set(key, /* @__PURE__ */ new Set());
6083
+ const settle = (ok) => {
6084
+ const blocks = this.pendingViews.get(key);
6085
+ this.pendingViews.delete(key);
6086
+ if (!ok) {
6087
+ this.failedViews.add(key);
6088
+ this.viewCache.delete(key);
6089
+ }
6090
+ if (blocks && blocks.size > 0) this.onViewSettled?.([...blocks]);
6091
+ };
6092
+ result.then(
6093
+ (value) => settle(value !== false),
6094
+ () => settle(false)
6095
+ );
6096
+ }
5940
6097
  /**
5941
6098
  * `force` re-renders every block. `lazy` (with a full render) lets blocks
5942
6099
  * skip layout while off screen; use it only when loading a document.
@@ -5945,6 +6102,7 @@ var BlockRenderer = class {
5945
6102
  const ctx = this.context();
5946
6103
  const next = /* @__PURE__ */ new Map();
5947
6104
  for (const block3 of doc.blocks) {
6105
+ this.renderingBlock = block3.id;
5948
6106
  const prev = this.rendered.get(block3.id);
5949
6107
  const reveal = this.revealed.get(block3.id);
5950
6108
  const reuse = !force && prev && prev.block === block3 && prev.el.parentNode === this.root && sameReveal(prev.reveal, reveal);
@@ -6239,10 +6397,16 @@ function revealedViews(state, views, active) {
6239
6397
  const keys = out.get(block3.id) ?? /* @__PURE__ */ new Set();
6240
6398
  if (block3.type === "raw") {
6241
6399
  if (views.has(block3.syntax)) keys.add(REVEAL_BLOCK);
6400
+ } else if (block3.type === "code") {
6401
+ if (views.has(codeViewName(block3.language))) keys.add(REVEAL_BLOCK);
6242
6402
  } else {
6243
- for (const { token, from } of tokensAt(containerContent(block3, pos.cell) ?? [], pos.offset)) {
6403
+ const content = containerContent(block3, pos.cell) ?? [];
6404
+ for (const { token, from } of tokensAt(content, pos.offset)) {
6244
6405
  if (views.has(token)) keys.add(tokenKey(pos.cell, from));
6245
6406
  }
6407
+ if (views.has("html") && content.some((s) => s.marks.includes("html"))) {
6408
+ for (const run of htmlRuns(content)) if (run.from <= pos.offset && pos.offset <= run.to) keys.add(tokenKey(pos.cell, run.from));
6409
+ }
6246
6410
  }
6247
6411
  if (keys.size > 0) out.set(block3.id, keys);
6248
6412
  }
@@ -6253,6 +6417,7 @@ function sameRevealed(a, b) {
6253
6417
  }
6254
6418
  function viewEntry(block3, forward) {
6255
6419
  const text = inlineText(block3.content);
6420
+ if (block3.type === "code") return { blockId: block3.id, offset: forward ? 0 : text.length };
6256
6421
  if (forward) {
6257
6422
  const firstBreak = text.indexOf("\n");
6258
6423
  return { blockId: block3.id, offset: firstBreak >= 0 && firstBreak < text.length - 1 ? firstBreak + 1 : 0 };
@@ -6465,6 +6630,12 @@ var Editor = class {
6465
6630
  blockSel = null;
6466
6631
  /** Block elements that carry the selected class. */
6467
6632
  selectedEls = [];
6633
+ /** The ids `headingIds` gave the headings of `doc`, by block ID. */
6634
+ headingIdsFor = null;
6635
+ /** `redecorate()` was called during a composition; it runs when the composition settles. */
6636
+ redecoratePending = false;
6637
+ /** The frame that renders blocks again after their views settled. */
6638
+ viewFrame = 0;
6468
6639
  constructor(options) {
6469
6640
  const root = options.element;
6470
6641
  this.root = root;
@@ -6491,6 +6662,14 @@ var Editor = class {
6491
6662
  };
6492
6663
  const views = new Map(this.extensions.flatMap((e) => Object.entries(e.views ?? {})));
6493
6664
  if (views.size > 0) this.renderer.views = views;
6665
+ this.renderer.onViewSettled = (ids) => this.viewsSettled(ids);
6666
+ const codeDecorators = this.extensions.flatMap((e) => e.codeDecorations ? [e.codeDecorations] : []);
6667
+ if (codeDecorators.length > 0) {
6668
+ this.renderer.decorateCode = (block3) => {
6669
+ const ctx = { block: block3, text: inlineText(block3.content), language: block3.language };
6670
+ return codeDecorators.flatMap((fn) => fn(ctx));
6671
+ };
6672
+ }
6494
6673
  const decorators = this.extensions.flatMap((e) => e.decorations ? [e.decorations] : []);
6495
6674
  if (decorators.length > 0) {
6496
6675
  this.renderer.decorate = (block3, content, cell) => {
@@ -6506,8 +6685,11 @@ var Editor = class {
6506
6685
  root.translate = false;
6507
6686
  root.style.setProperty("--mbe-slash-hint", JSON.stringify(this.labels.slashHint));
6508
6687
  this.applyRuntime({ placeholder: options.placeholder, attributes: options.attributes });
6509
- this.runtime = { ...this.runtime, resolveImageSrc: options.resolveImageSrc };
6510
- this.renderer.resolveImageSrc = options.resolveImageSrc;
6688
+ this.runtime = { ...this.runtime, resolveUrl: options.resolveUrl, onLinkClick: options.onLinkClick };
6689
+ this.renderer.resolveUrl = options.resolveUrl ?? defaultResolveUrl;
6690
+ this.renderer.referrerPolicy = options.referrerPolicy;
6691
+ this.renderer.codeCopy = options.codeCopy !== false;
6692
+ this.renderer.icon = (name) => iconNode(root.ownerDocument, this.icon(name));
6511
6693
  this.applyTheme(options.theme);
6512
6694
  setPopupContainer(root, options.popupContainer);
6513
6695
  const configs = this.extensions.flatMap((e) => e.suggestion ? [e.suggestion] : []);
@@ -6752,7 +6934,7 @@ var Editor = class {
6752
6934
  // Options and events
6753
6935
  /**
6754
6936
  * Changes `placeholder`, `editable`, `taskToggle`, `attributes`,
6755
- * `resolveImageSrc` or `theme`. `extensions` only updates the callbacks of
6937
+ * `resolveUrl`, `onLinkClick` or `theme`. `extensions` only updates the callbacks of
6756
6938
  * `suggestion()` extensions (`items`, `command`, `match`, `allow`), matched
6757
6939
  * by name; other changes to extensions need a new editor.
6758
6940
  */
@@ -6794,11 +6976,12 @@ var Editor = class {
6794
6976
  for (const [name, value] of Object.entries(options.attributes ?? {})) root.setAttribute(name, value);
6795
6977
  this.runtime = { ...this.runtime, attributes: options.attributes };
6796
6978
  }
6797
- if ("resolveImageSrc" in options && options.resolveImageSrc !== this.runtime.resolveImageSrc) {
6798
- this.runtime = { ...this.runtime, resolveImageSrc: options.resolveImageSrc };
6799
- this.renderer.resolveImageSrc = options.resolveImageSrc;
6979
+ if ("resolveUrl" in options && options.resolveUrl !== this.runtime.resolveUrl) {
6980
+ this.runtime = { ...this.runtime, resolveUrl: options.resolveUrl };
6981
+ this.renderer.resolveUrl = options.resolveUrl ?? defaultResolveUrl;
6800
6982
  this.paint(true);
6801
6983
  }
6984
+ if ("onLinkClick" in options) this.runtime = { ...this.runtime, onLinkClick: options.onLinkClick };
6802
6985
  if ("theme" in options && this.applyTheme(options.theme)) this.paint(true);
6803
6986
  }
6804
6987
  /** Sets the theme. Returns true when blocks must re-render for new classes. */
@@ -7192,7 +7375,8 @@ var Editor = class {
7192
7375
  /** Where the caret goes moving into `block` from above (`forward`) or below: its first or last line, at `x`. */
7193
7376
  blockEntry(block3, forward, x) {
7194
7377
  const el = this.renderer.elementFor(block3.id);
7195
- if (block3.type === "raw" && el?.classList.contains("mbe-view-block")) return viewEntry(block3, forward);
7378
+ const viewed = this.viewBlock(block3);
7379
+ if (viewed) return viewEntry(viewed, forward);
7196
7380
  if (el) {
7197
7381
  const range = el.ownerDocument.createRange();
7198
7382
  range.selectNodeContents(contentElement(el) ?? el);
@@ -7217,10 +7401,70 @@ var Editor = class {
7217
7401
  const views = this.renderer.views;
7218
7402
  if (views && !this.pointerDown && !this.composing) this.renderer.revealed = revealedViews(this.state, views, !this.readOnly && hadFocus);
7219
7403
  this.renderer.render(this.state.doc, force, lazy);
7404
+ this.applyHeadingIds();
7220
7405
  this.applyReadOnly();
7221
7406
  this.paintBlockSelection();
7222
7407
  if (!this.composing) this.syncDomSelection(hadFocus);
7223
7408
  }
7409
+ /** Heading ids from the `headingIds` option, computed again only when the document changes. */
7410
+ applyHeadingIds() {
7411
+ const headingIds = this.options.headingIds;
7412
+ if (!headingIds) return;
7413
+ const doc = this.state.doc;
7414
+ if (this.headingIdsFor?.doc !== doc) {
7415
+ const headings = doc.blocks.filter((b) => b.type === "heading");
7416
+ const ids = headingIds(headings.map((h) => ({ text: inlineText(h.content), level: h.level })));
7417
+ this.headingIdsFor = { doc, ids: new Map(headings.map((h, i) => [h.id, ids[i]])) };
7418
+ }
7419
+ for (const [blockId, id] of this.headingIdsFor.ids) {
7420
+ const el = this.renderer.elementFor(blockId);
7421
+ if (!el) continue;
7422
+ if (id) {
7423
+ if (el.id !== id) el.id = id;
7424
+ } else if (el.id) {
7425
+ el.removeAttribute("id");
7426
+ }
7427
+ }
7428
+ }
7429
+ /**
7430
+ * Computes decorations again for every block and renders the blocks whose
7431
+ * decorations depend on something outside the document changed, such as
7432
+ * which mentioned people exist or a highlighter's language that finished
7433
+ * loading. Waits for an input method to finish composing.
7434
+ */
7435
+ redecorate() {
7436
+ if (this.destroyed) return;
7437
+ if (this.composing || this.composition) {
7438
+ this.redecoratePending = true;
7439
+ return;
7440
+ }
7441
+ this.redecoratePending = false;
7442
+ this.paint(true);
7443
+ this.afterRender();
7444
+ }
7445
+ /**
7446
+ * Views that returned a promise settled: their blocks render again on the
7447
+ * next frame, or when a composition settles, since rendering would end it.
7448
+ */
7449
+ viewsSettled(ids) {
7450
+ if (this.destroyed) return;
7451
+ if (this.composing || this.composition) {
7452
+ for (const id of ids) this.unsettled.add(id);
7453
+ return;
7454
+ }
7455
+ for (const id of ids) this.renderer.invalidate(id);
7456
+ this.viewFrame ||= requestAnimationFrame(() => {
7457
+ this.viewFrame = 0;
7458
+ if (this.destroyed || this.composing || this.composition) return;
7459
+ this.paint();
7460
+ this.afterRender();
7461
+ });
7462
+ }
7463
+ /** A block rendered by a view (a formula block, a diagram), or null. */
7464
+ viewBlock(block3) {
7465
+ if (!block3 || block3.type !== "raw" && block3.type !== "code") return null;
7466
+ return this.renderer.elementFor(block3.id)?.classList.contains("mbe-view-block") ? block3 : null;
7467
+ }
7224
7468
  /** Re-renders if the views that show their source changed: after the selection, focus or editability changes. */
7225
7469
  refreshRevealed() {
7226
7470
  const views = this.renderer.views;
@@ -7248,7 +7492,7 @@ var Editor = class {
7248
7492
  const index = blockIndex(this.state.doc, pos.blockId);
7249
7493
  const forward = key === "ArrowDown" || key === "ArrowRight";
7250
7494
  const next = blocks[index + (forward ? 1 : -1)];
7251
- const view = next?.type === "raw" && this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block");
7495
+ const view = this.viewBlock(next);
7252
7496
  if (!next || !view && next.type !== "table") return null;
7253
7497
  const current = blocks[index];
7254
7498
  if (!isTextBlock(current)) return null;
@@ -7262,7 +7506,7 @@ var Editor = class {
7262
7506
  const row = forward ? 0 : next.rows.length - 1;
7263
7507
  return { blockId: next.id, offset: forward ? 0 : inlineLength(next.rows[row][0]), cell: { row, col: 0 } };
7264
7508
  }
7265
- return viewEntry(next, forward);
7509
+ return viewEntry(view, forward);
7266
7510
  }
7267
7511
  /**
7268
7512
  * ArrowUp or ArrowDown on the first or last line of a table cell: the
@@ -7295,7 +7539,8 @@ var Editor = class {
7295
7539
  const c = Math.min(col, next.align.length - 1);
7296
7540
  return { blockId: next.id, offset: dir === 1 ? 0 : inlineLength(next.rows[r][c]), cell: { row: r, col: c } };
7297
7541
  }
7298
- if (next.type === "raw" && this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block")) return viewEntry(next, dir === 1);
7542
+ const viewed = this.viewBlock(next);
7543
+ if (viewed) return viewEntry(viewed, dir === 1);
7299
7544
  return dir === 1 ? startOf(next) : endOf(next);
7300
7545
  }
7301
7546
  return null;
@@ -7318,7 +7563,7 @@ var Editor = class {
7318
7563
  /** A click on a rendered view puts the caret in its source: at the end of a token, or of a block's formula. */
7319
7564
  revealView(view) {
7320
7565
  const block3 = view.hasAttribute(BLOCK_ATTR) ? getBlock(this.state.doc, view.getAttribute(BLOCK_ATTR)) : null;
7321
- const pos = block3 ? block3.type === "raw" ? viewEntry(block3, false) : null : domToPosition(this.root, view.parentNode, childIndex(view) + 1);
7566
+ const pos = block3 ? block3.type === "raw" || block3.type === "code" ? viewEntry(block3, false) : null : domToPosition(this.root, view.parentNode, childIndex(view) + 1);
7322
7567
  if (!pos) return;
7323
7568
  this.root.focus({ preventScroll: true });
7324
7569
  this.setSelection({ anchor: pos, focus: pos });
@@ -7484,7 +7729,8 @@ var Editor = class {
7484
7729
  this.composition = null;
7485
7730
  for (const id of this.unsettled) this.renderer.invalidate(id);
7486
7731
  this.unsettled.clear();
7487
- this.paint();
7732
+ this.paint(this.redecoratePending);
7733
+ this.redecoratePending = false;
7488
7734
  this.afterRender();
7489
7735
  if (composed) this.typedForSuggestion();
7490
7736
  }
@@ -7687,9 +7933,39 @@ var Editor = class {
7687
7933
  const plain2 = !mod2 && !e.shiftKey && !e.altKey;
7688
7934
  const vertical = !plain2 ? 0 : e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
7689
7935
  const from = blockIndex(this.state.doc, this.state.selection.focus.blockId);
7690
- this.caretKey = { from, x: this.selectionRect()?.left ?? 0, vertical };
7936
+ const key2 = { from, x: this.selectionRect()?.left ?? 0, vertical };
7937
+ this.caretKey = key2;
7938
+ if (vertical) this.unlessCaretMoves(key2);
7691
7939
  }
7692
7940
  }
7941
+ /**
7942
+ * WebKit skips code blocks and tables with ArrowDown and ArrowUp. When no
7943
+ * editable text follows them (a rendered footnote or formula is not), it
7944
+ * does not move the caret at all. If the browser left the caret on the edge
7945
+ * line of its block, move it into the next block that holds a caret.
7946
+ */
7947
+ unlessCaretMoves(key) {
7948
+ const before = this.state.selection.focus;
7949
+ if (before.cell || !isCollapsed(this.state.selection)) return;
7950
+ const content = contentElement(this.renderer.elementFor(before.blockId) ?? this.root);
7951
+ if (!content || !this.onEdgeLine(content, key.vertical === 1)) return;
7952
+ setTimeout(() => {
7953
+ if (this.destroyed || this.caretKey !== key) return;
7954
+ const now = this.readDomSelection();
7955
+ if (!now || !samePosition(now.focus, before)) return;
7956
+ const blocks = this.state.doc.blocks;
7957
+ for (let i = key.from + key.vertical; i >= 0 && i < blocks.length; i += key.vertical) {
7958
+ const block3 = blocks[i];
7959
+ if (block3.type === "divider") continue;
7960
+ this.caretKey = null;
7961
+ const row = key.vertical === 1 ? 0 : block3.type === "table" ? block3.rows.length - 1 : 0;
7962
+ const pos = block3.type === "table" ? { blockId: block3.id, offset: key.vertical === 1 ? 0 : inlineLength(block3.rows[row][0]), cell: { row, col: 0 } } : this.blockEntry(block3, key.vertical === 1, key.x);
7963
+ this.setSelection({ anchor: pos, focus: pos });
7964
+ this.scrollCaretIntoView();
7965
+ return;
7966
+ }
7967
+ });
7968
+ }
7693
7969
  /** Selects all the text of the block (or table cell) holding `target`. False if it holds none. */
7694
7970
  selectBlockText(target) {
7695
7971
  const blockEl = target.closest?.(`[${BLOCK_ATTR}]`);
@@ -7698,7 +7974,7 @@ var Editor = class {
7698
7974
  const cellEl = target.closest("[data-row]");
7699
7975
  const cell = block3.type === "table" && cellEl ? { row: Number(cellEl.dataset.row), col: Number(cellEl.dataset.col) } : void 0;
7700
7976
  const content = containerContent(block3, cell);
7701
- if (!content || block3.type === "raw" && blockEl.classList.contains("mbe-view-block")) return false;
7977
+ if (!content || blockEl.classList.contains("mbe-view-block")) return false;
7702
7978
  const at = (offset) => cell ? { blockId: block3.id, offset, cell } : { blockId: block3.id, offset };
7703
7979
  this.setSelection({ anchor: at(0), focus: at(inlineLength(content)) });
7704
7980
  return true;
@@ -7710,6 +7986,10 @@ var Editor = class {
7710
7986
  onMouseDown(e) {
7711
7987
  this.caretKey = null;
7712
7988
  const target = e.target;
7989
+ if (target.closest?.(".mbe-code-copy")) {
7990
+ e.preventDefault();
7991
+ return;
7992
+ }
7713
7993
  this.dropBlockSelection();
7714
7994
  if (target === this.root && e.button === 0 && !this.readOnly && this.clickBelowLastBlock(e)) return;
7715
7995
  const view = e.button === 0 && !this.readOnly ? target.closest?.(".mbe-view, .mbe-view-block") : null;
@@ -7752,14 +8032,54 @@ var Editor = class {
7752
8032
  if (e.detail === 0) this.toggleTaskAt(target);
7753
8033
  return;
7754
8034
  }
8035
+ const copy = target.closest?.(".mbe-code-copy");
8036
+ if (copy) {
8037
+ e.preventDefault();
8038
+ this.copyCode(copy);
8039
+ return;
8040
+ }
7755
8041
  const link = target.closest?.("a.mbe-link");
7756
8042
  if (!link) return;
7757
8043
  e.preventDefault();
7758
8044
  if (this.readOnly || (isMac ? e.metaKey : e.ctrlKey)) {
7759
- const href = safeHref(link.dataset.href ?? "");
7760
- if (href) this.root.ownerDocument.defaultView?.open(href, "_blank", "noopener,noreferrer");
8045
+ const href = link.getAttribute("href");
8046
+ if (!href || this.runtime.onLinkClick?.({ editor: this, href, event: e })) return;
8047
+ this.root.ownerDocument.defaultView?.open(href, "_blank", "noopener,noreferrer");
7761
8048
  }
7762
8049
  }
8050
+ /** Copies the code of the code block holding `button`, and shows that it did for a moment. */
8051
+ copyCode(button) {
8052
+ const blockEl = button.closest(`[${BLOCK_ATTR}]`);
8053
+ const block3 = blockEl && this.state.doc.blocks.find((b) => b.id === blockEl.getAttribute(BLOCK_ATTR));
8054
+ if (!block3 || block3.type !== "code") return;
8055
+ const text = inlineText(block3.content);
8056
+ const doc = this.root.ownerDocument;
8057
+ const show = (name) => {
8058
+ const icon = iconNode(doc, this.icon(name));
8059
+ button.replaceChildren(...icon ? [icon] : []);
8060
+ button.setAttribute("aria-label", this.labels[name]);
8061
+ button.title = this.labels[name];
8062
+ button.classList.toggle("mbe-copied", name === "copied");
8063
+ };
8064
+ const done = () => {
8065
+ show("copied");
8066
+ setTimeout(() => button.isConnected && show("copyCode"), 1500);
8067
+ };
8068
+ const fallback = () => {
8069
+ const area = doc.createElement("textarea");
8070
+ area.value = text;
8071
+ area.style.cssText = "position:fixed;top:0;left:0;opacity:0";
8072
+ doc.body.appendChild(area);
8073
+ area.select();
8074
+ const ok = doc.execCommand("copy");
8075
+ area.remove();
8076
+ this.syncDomSelection(this.hasFocus());
8077
+ if (ok) done();
8078
+ };
8079
+ const clipboard = doc.defaultView?.navigator.clipboard;
8080
+ if (clipboard?.writeText) clipboard.writeText(text).then(done, fallback);
8081
+ else fallback();
8082
+ }
7763
8083
  /** The code block language input. */
7764
8084
  onControlChange(e) {
7765
8085
  const input = e.target;
@@ -8310,7 +8630,10 @@ function math(options = {}) {
8310
8630
  math(source, element, kind) {
8311
8631
  const tex = mathSource(source, kind);
8312
8632
  if (!tex.trim()) return false;
8313
- render2(tex, element, { displayMode: kind === "block" });
8633
+ const result = render2(tex, element, { displayMode: kind === "block" });
8634
+ if (!result) return;
8635
+ if (!element.hasChildNodes()) element.textContent = source;
8636
+ return result;
8314
8637
  }
8315
8638
  }
8316
8639
  };
@@ -8341,8 +8664,46 @@ var block2 = {
8341
8664
  };
8342
8665
  }
8343
8666
  };
8344
- function footnotes() {
8345
- return { name: "footnotes", markdown: { inline: [inline2], block: [block2] } };
8667
+ var labelOf = (source) => /^\[\^((?:[^\]\\]|\\.)+)\]/.exec(source)?.[1]?.replace(/\\(.)/g, "$1") ?? "";
8668
+ var renderReference = (source, element) => {
8669
+ const label = labelOf(source);
8670
+ const sup = element.ownerDocument.createElement("sup");
8671
+ sup.className = "mbe-footnote-ref";
8672
+ sup.dataset.label = label;
8673
+ sup.textContent = label;
8674
+ element.appendChild(sup);
8675
+ };
8676
+ var renderDefinition = (source, element) => {
8677
+ const label = labelOf(source);
8678
+ const doc = element.ownerDocument;
8679
+ element.classList.add("mbe-footnote");
8680
+ element.dataset.label = label;
8681
+ const sup = doc.createElement("sup");
8682
+ sup.className = "mbe-footnote-label";
8683
+ sup.textContent = label;
8684
+ const text = doc.createElement("span");
8685
+ text.textContent = source.replace(/^\[\^(?:[^\]\\]|\\.)+\]:[ \t]*/, "").split("\n").map((line) => line.trim()).filter(Boolean).join(" ");
8686
+ element.append(sup, text);
8687
+ };
8688
+ function footnotes(options = {}) {
8689
+ if (options.render === false) return { name: "footnotes", markdown: { inline: [inline2], block: [block2] } };
8690
+ return {
8691
+ name: "footnotes",
8692
+ markdown: { inline: [inline2], block: [block2] },
8693
+ views: { footnote: (source, element, kind) => (kind === "inline" ? renderReference : renderDefinition)(source, element, kind) },
8694
+ onCreate: ({ editor }) => {
8695
+ const onClick = (e) => {
8696
+ const ref = e.target.closest?.(".mbe-footnote-ref");
8697
+ if (!ref || editor.isEditable) return;
8698
+ const definition = [...editor.root.querySelectorAll(".mbe-footnote")].find((d) => d.dataset.label === ref.dataset.label);
8699
+ if (!definition) return;
8700
+ e.preventDefault();
8701
+ definition.scrollIntoView({ block: "center", behavior: "smooth" });
8702
+ };
8703
+ editor.root.addEventListener("click", onClick);
8704
+ return () => editor.root.removeEventListener("click", onClick);
8705
+ }
8706
+ };
8346
8707
  }
8347
8708
 
8348
8709
  // src/extensions/textDecorator.ts
@@ -8429,7 +8790,11 @@ function decorate2(scan, cls, attributes) {
8429
8790
  for (const r of scan(text, pos, end)) {
8430
8791
  const from = Math.max(r.from, pos);
8431
8792
  const to = Math.min(r.to, end);
8432
- if (to > from) out.push(attributes ? { from, to, class: cls, attributes } : { from, to, class: cls });
8793
+ if (to <= from) continue;
8794
+ const match = text.slice(from, to);
8795
+ const className = typeof cls === "function" ? cls(match) : cls;
8796
+ const attrs = typeof attributes === "function" ? attributes(match) : attributes;
8797
+ out.push(attrs ? { from, to, class: className, attributes: attrs } : { from, to, class: className });
8433
8798
  }
8434
8799
  }
8435
8800
  pos = end;
@@ -8504,6 +8869,7 @@ export {
8504
8869
  createId,
8505
8870
  createState,
8506
8871
  defaultKeymap,
8872
+ defaultResolveUrl,
8507
8873
  deleteInline,
8508
8874
  divider,
8509
8875
  docToHtml,