@usememos/editor 26.10.2 → 26.10.3

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
@@ -3997,7 +3997,26 @@ function representableInline(inline3) {
3997
3997
  endRun();
3998
3998
  for (const [from, to] of removals) spans = setMarkInRange(spans, from, to, mark, false);
3999
3999
  }
4000
- return spans;
4000
+ return dropLineEndSpaces(spans);
4001
+ }
4002
+ var isPlainSpan = (s) => !s.link && !s.image && !s.token && !s.marks.includes("code") && !s.marks.includes("html");
4003
+ function dropLineEndSpaces(spans) {
4004
+ const text = spans.map((s) => s.text).join("");
4005
+ if (!/[ \t](\n|$)/.test(text)) return spans;
4006
+ const plain2 = [];
4007
+ for (const s of spans) for (let i = 0; i < s.text.length; i++) plain2.push(isPlainSpan(s));
4008
+ const removals = [];
4009
+ let lineStart = 0;
4010
+ for (let i = 0; i <= text.length; i++) {
4011
+ if (i < text.length && text[i] !== "\n") continue;
4012
+ let from = i;
4013
+ while (from > lineStart && (text[from - 1] === " " || text[from - 1] === " ") && plain2[from - 1]) from--;
4014
+ if (from < i && /[^ \t]/.test(text.slice(lineStart, from))) removals.push([from, i]);
4015
+ lineStart = i + 1;
4016
+ }
4017
+ let out = spans;
4018
+ for (let k = removals.length - 1; k >= 0; k--) out = deleteInline(out, removals[k][0], removals[k][1]);
4019
+ return normalizeInline(out);
4001
4020
  }
4002
4021
  function emphasisMarks(span) {
4003
4022
  return span.marks.filter(isEmphasis);
@@ -5621,6 +5640,9 @@ var LinkPopover = class {
5621
5640
 
5622
5641
  // src/view/dom.ts
5623
5642
  var BLOCK_ATTR = "data-block-id";
5643
+ function codeViewName(language) {
5644
+ return `code:${language.trim().toLowerCase()}`;
5645
+ }
5624
5646
  var CONTENT_ATTR = "data-content";
5625
5647
  var FILL_ATTR = "data-mbe-fill";
5626
5648
  var ATOM_ATTR = "data-atom";
@@ -5657,12 +5679,12 @@ function blockClasses(block3, theme) {
5657
5679
  return void 0;
5658
5680
  }
5659
5681
  }
5660
- function safeHref(href) {
5661
- const trimmed = href.trim();
5682
+ var defaultResolveUrl = (url) => {
5683
+ const trimmed = url.trim();
5662
5684
  const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(trimmed);
5663
5685
  if (!scheme) return trimmed;
5664
5686
  return ["http", "https", "mailto", "tel"].includes(scheme[1].toLowerCase()) ? trimmed : null;
5665
- }
5687
+ };
5666
5688
  var REVEAL_BLOCK = "block";
5667
5689
  function tokenKey(cell, from) {
5668
5690
  return cell ? `${cell.row}:${cell.col}@${from}` : `@${from}`;
@@ -5709,6 +5731,14 @@ function renderBlock(block3, ctx, reveal) {
5709
5731
  break;
5710
5732
  }
5711
5733
  case "code": {
5734
+ const view = reveal?.has(REVEAL_BLOCK) ? null : ctx.view?.(codeViewName(block3.language), inlineText(block3.content), "block");
5735
+ if (view) {
5736
+ root = view;
5737
+ root.classList.add("mbe-view-block");
5738
+ root.contentEditable = "false";
5739
+ root.dataset.language = block3.language;
5740
+ break;
5741
+ }
5712
5742
  root = el("div");
5713
5743
  root.dataset.language = block3.language;
5714
5744
  const bar = el("div", "mbe-code-bar");
@@ -5788,7 +5818,7 @@ function fillContent(target, inline3, ctx, block3, reveal, cell, decorated = tru
5788
5818
  target.appendChild(fill(doc));
5789
5819
  return;
5790
5820
  }
5791
- const decorations = decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
5821
+ const decorations = block3.type === "code" ? ctx.decorateCode?.(block3) ?? [] : decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
5792
5822
  const only = inline3.length === 1 ? inline3[0] : null;
5793
5823
  if (only && decorations.length === 0 && only.marks.length === 0 && !only.link && !only.token && !only.image) {
5794
5824
  target.appendChild(doc.createTextNode(only.text));
@@ -5803,18 +5833,73 @@ function fill(doc) {
5803
5833
  br.setAttribute(FILL_ATTR, "");
5804
5834
  return br;
5805
5835
  }
5836
+ var VOID_TAGS = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
5837
+ function htmlRuns(inline3) {
5838
+ const spans = [];
5839
+ let pos = 0;
5840
+ for (const span of inline3) {
5841
+ spans.push({ span, from: pos, to: pos + span.text.length });
5842
+ pos += span.text.length;
5843
+ }
5844
+ const isHtml = (span) => span.marks.includes("html");
5845
+ const runs = [];
5846
+ for (let i = 0; i < spans.length; i++) {
5847
+ const { span, from, to } = spans[i];
5848
+ if (!isHtml(span)) continue;
5849
+ const open = /^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*?(\/?)>$/.exec(span.text);
5850
+ let end = i;
5851
+ if (open && !open[2] && !VOID_TAGS.has(open[1].toLowerCase())) {
5852
+ const name = open[1].toLowerCase();
5853
+ let depth = 0;
5854
+ for (let j = i + 1; j < spans.length; j++) {
5855
+ const t = spans[j].span;
5856
+ if (t.link) break;
5857
+ if (!isHtml(t)) continue;
5858
+ const tag = /^<(\/?)([A-Za-z][A-Za-z0-9-]*)\b[^>]*?(\/?)>$/.exec(t.text);
5859
+ if (!tag || tag[2].toLowerCase() !== name || tag[3]) continue;
5860
+ if (!tag[1]) depth++;
5861
+ else if (depth > 0) depth--;
5862
+ else {
5863
+ end = j;
5864
+ break;
5865
+ }
5866
+ }
5867
+ }
5868
+ if (spans.slice(i, end + 1).some((s) => s.span.link)) continue;
5869
+ runs.push({ from, to: end === i ? to : spans[end].to });
5870
+ i = end;
5871
+ }
5872
+ return runs;
5873
+ }
5806
5874
  function renderInline(inline3, parent, ctx, decorations, reveal, cell) {
5807
5875
  const doc = ctx.doc;
5808
5876
  const views = ctx.views;
5809
5877
  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);
5878
+ const runs = views?.has("html") && inline3.some((s) => s.marks.includes("html")) ? htmlRuns(inline3).filter((run) => !reveal?.has(tokenKey(cell, run.from))) : [];
5879
+ const inRun = (from) => runs.some((run) => from >= run.from && from < run.to);
5880
+ const atomic = viewed || runs.length > 0 ? (span, from) => !!viewed?.(span, from) || inRun(from) : void 0;
5881
+ const pieces = splitByDecorations(inline3, decorations, atomic);
5882
+ const render2 = (piece) => decorate(renderSpan(piece.span, ctx, piece.atomic && !inRun(offsets.get(piece) ?? -1)), piece.decorations, doc);
5883
+ const offsets = /* @__PURE__ */ new Map();
5884
+ let offset = 0;
5885
+ for (const piece of pieces) {
5886
+ offsets.set(piece, offset);
5887
+ offset += piece.span.text.length;
5888
+ }
5812
5889
  let i = 0;
5813
5890
  while (i < pieces.length) {
5814
5891
  const span = pieces[i].span;
5892
+ const run = runs.find((r) => r.from === offsets.get(pieces[i]));
5893
+ const view = run && ctx.view?.("html", serializeInline(sliceInline(inline3, run.from, run.to)), "inline");
5894
+ if (run && view) {
5895
+ const text = inlineText(sliceInline(inline3, run.from, run.to));
5896
+ parent.appendChild(atom(view, classes("mbe-view", "mbe-view-html", ctx.classes.token?.html), text));
5897
+ while (i < pieces.length && offsets.get(pieces[i]) < run.to) i++;
5898
+ continue;
5899
+ }
5815
5900
  if (span.link) {
5816
5901
  const a = doc.createElement("a");
5817
- const href = safeHref(span.link);
5902
+ const href = ctx.resolveUrl(span.link, "link");
5818
5903
  if (href !== null) a.setAttribute("href", href);
5819
5904
  a.dataset.href = span.link;
5820
5905
  a.className = classes("mbe-link", ctx.classes.link);
@@ -5853,7 +5938,10 @@ function renderSpan(span, ctx, viewed = false) {
5853
5938
  if (view) return wrapMarks(span, atom(view, classes("mbe-view", `mbe-view-${span.token}`, ctx.classes.token?.[span.token]), span.text), ctx);
5854
5939
  if (span.image) {
5855
5940
  const img = doc.createElement("img");
5856
- const src = safeHref(ctx.resolveImageSrc ? ctx.resolveImageSrc(span.image.src) : span.image.src);
5941
+ img.setAttribute("loading", "lazy");
5942
+ img.setAttribute("decoding", "async");
5943
+ if (ctx.referrerPolicy) img.setAttribute("referrerpolicy", ctx.referrerPolicy);
5944
+ const src = ctx.resolveUrl(span.image.src, "image");
5857
5945
  if (src !== null) img.src = src;
5858
5946
  img.alt = span.image.alt;
5859
5947
  if (span.image.title) img.title = span.image.title;
@@ -5890,10 +5978,20 @@ var BlockRenderer = class {
5890
5978
  rendered = /* @__PURE__ */ new Map();
5891
5979
  /** Last number written into each ordered item's marker, keyed by element. */
5892
5980
  numbers = /* @__PURE__ */ new WeakMap();
5893
- /** Maps an image `src` to the URL to display. Set before a full render. */
5894
- resolveImageSrc;
5981
+ /** The URL policy for links and images. Set before a full render. */
5982
+ resolveUrl = defaultResolveUrl;
5983
+ /** `referrerpolicy` for images. */
5984
+ referrerPolicy;
5895
5985
  /** Decorations for a text container. */
5896
5986
  decorate;
5987
+ /** Decorations for a code block's code. */
5988
+ decorateCode;
5989
+ /**
5990
+ * Called when views that returned a promise settle, with the blocks that
5991
+ * showed them. Those blocks must render again to show the finished view,
5992
+ * or their source if it failed.
5993
+ */
5994
+ onViewSettled;
5897
5995
  /** Widget elements to place after a block. */
5898
5996
  widgetsAfter;
5899
5997
  /** Views of extension syntaxes, by syntax name. */
@@ -5907,12 +6005,20 @@ var BlockRenderer = class {
5907
6005
  * Cloned on reuse: typing re-renders a block and every formula in it.
5908
6006
  */
5909
6007
  viewCache = /* @__PURE__ */ new Map();
6008
+ /** Views whose promise has not settled, by cache key, with the blocks showing them. */
6009
+ pendingViews = /* @__PURE__ */ new Map();
6010
+ /** Views whose promise rejected or resolved to false: their source shows. */
6011
+ failedViews = /* @__PURE__ */ new Set();
6012
+ /** The block being rendered, so a pending view knows which blocks to render again. */
6013
+ renderingBlock = "";
5910
6014
  context() {
5911
6015
  return {
5912
6016
  doc: this.root.ownerDocument,
5913
6017
  labels: this.labels,
5914
- resolveImageSrc: this.resolveImageSrc,
6018
+ resolveUrl: this.resolveUrl,
6019
+ referrerPolicy: this.referrerPolicy,
5915
6020
  decorate: this.decorate,
6021
+ decorateCode: this.decorateCode,
5916
6022
  views: this.views,
5917
6023
  view: this.views && ((syntax, source, kind) => this.renderView(syntax, source, kind)),
5918
6024
  classes: this.classes
@@ -5922,21 +6028,46 @@ var BlockRenderer = class {
5922
6028
  const view = this.views?.get(syntax);
5923
6029
  if (!view) return null;
5924
6030
  const key = `${kind}\0${syntax}\0${source}`;
6031
+ if (this.failedViews.has(key)) return null;
5925
6032
  let el = this.viewCache.get(key);
5926
6033
  if (el) {
5927
6034
  this.viewCache.delete(key);
5928
6035
  } else {
5929
6036
  el = this.root.ownerDocument.createElement(kind === "inline" ? "span" : "div");
6037
+ let result;
5930
6038
  try {
5931
- if (view(source, el, kind) === false) return null;
6039
+ result = view(source, el, kind);
5932
6040
  } catch {
5933
6041
  return null;
5934
6042
  }
6043
+ if (result === false) return null;
6044
+ if (result && typeof result.then === "function") this.awaitView(key, result);
5935
6045
  if (this.viewCache.size >= 500) this.viewCache.delete(this.viewCache.keys().next().value);
5936
6046
  }
6047
+ this.pendingViews.get(key)?.add(this.renderingBlock);
5937
6048
  this.viewCache.set(key, el);
5938
6049
  return el.cloneNode(true);
5939
6050
  }
6051
+ /**
6052
+ * A view that renders later (a diagram, a lazily loaded renderer) shows what
6053
+ * it filled in at once, and its blocks render again when it settles.
6054
+ */
6055
+ awaitView(key, result) {
6056
+ this.pendingViews.set(key, /* @__PURE__ */ new Set());
6057
+ const settle = (ok) => {
6058
+ const blocks = this.pendingViews.get(key);
6059
+ this.pendingViews.delete(key);
6060
+ if (!ok) {
6061
+ this.failedViews.add(key);
6062
+ this.viewCache.delete(key);
6063
+ }
6064
+ if (blocks && blocks.size > 0) this.onViewSettled?.([...blocks]);
6065
+ };
6066
+ result.then(
6067
+ (value) => settle(value !== false),
6068
+ () => settle(false)
6069
+ );
6070
+ }
5940
6071
  /**
5941
6072
  * `force` re-renders every block. `lazy` (with a full render) lets blocks
5942
6073
  * skip layout while off screen; use it only when loading a document.
@@ -5945,6 +6076,7 @@ var BlockRenderer = class {
5945
6076
  const ctx = this.context();
5946
6077
  const next = /* @__PURE__ */ new Map();
5947
6078
  for (const block3 of doc.blocks) {
6079
+ this.renderingBlock = block3.id;
5948
6080
  const prev = this.rendered.get(block3.id);
5949
6081
  const reveal = this.revealed.get(block3.id);
5950
6082
  const reuse = !force && prev && prev.block === block3 && prev.el.parentNode === this.root && sameReveal(prev.reveal, reveal);
@@ -6239,10 +6371,16 @@ function revealedViews(state, views, active) {
6239
6371
  const keys = out.get(block3.id) ?? /* @__PURE__ */ new Set();
6240
6372
  if (block3.type === "raw") {
6241
6373
  if (views.has(block3.syntax)) keys.add(REVEAL_BLOCK);
6374
+ } else if (block3.type === "code") {
6375
+ if (views.has(codeViewName(block3.language))) keys.add(REVEAL_BLOCK);
6242
6376
  } else {
6243
- for (const { token, from } of tokensAt(containerContent(block3, pos.cell) ?? [], pos.offset)) {
6377
+ const content = containerContent(block3, pos.cell) ?? [];
6378
+ for (const { token, from } of tokensAt(content, pos.offset)) {
6244
6379
  if (views.has(token)) keys.add(tokenKey(pos.cell, from));
6245
6380
  }
6381
+ if (views.has("html") && content.some((s) => s.marks.includes("html"))) {
6382
+ for (const run of htmlRuns(content)) if (run.from <= pos.offset && pos.offset <= run.to) keys.add(tokenKey(pos.cell, run.from));
6383
+ }
6246
6384
  }
6247
6385
  if (keys.size > 0) out.set(block3.id, keys);
6248
6386
  }
@@ -6253,6 +6391,7 @@ function sameRevealed(a, b) {
6253
6391
  }
6254
6392
  function viewEntry(block3, forward) {
6255
6393
  const text = inlineText(block3.content);
6394
+ if (block3.type === "code") return { blockId: block3.id, offset: forward ? 0 : text.length };
6256
6395
  if (forward) {
6257
6396
  const firstBreak = text.indexOf("\n");
6258
6397
  return { blockId: block3.id, offset: firstBreak >= 0 && firstBreak < text.length - 1 ? firstBreak + 1 : 0 };
@@ -6465,6 +6604,12 @@ var Editor = class {
6465
6604
  blockSel = null;
6466
6605
  /** Block elements that carry the selected class. */
6467
6606
  selectedEls = [];
6607
+ /** The ids `headingIds` gave the headings of `doc`, by block ID. */
6608
+ headingIdsFor = null;
6609
+ /** `redecorate()` was called during a composition; it runs when the composition settles. */
6610
+ redecoratePending = false;
6611
+ /** The frame that renders blocks again after their views settled. */
6612
+ viewFrame = 0;
6468
6613
  constructor(options) {
6469
6614
  const root = options.element;
6470
6615
  this.root = root;
@@ -6491,6 +6636,14 @@ var Editor = class {
6491
6636
  };
6492
6637
  const views = new Map(this.extensions.flatMap((e) => Object.entries(e.views ?? {})));
6493
6638
  if (views.size > 0) this.renderer.views = views;
6639
+ this.renderer.onViewSettled = (ids) => this.viewsSettled(ids);
6640
+ const codeDecorators = this.extensions.flatMap((e) => e.codeDecorations ? [e.codeDecorations] : []);
6641
+ if (codeDecorators.length > 0) {
6642
+ this.renderer.decorateCode = (block3) => {
6643
+ const ctx = { block: block3, text: inlineText(block3.content), language: block3.language };
6644
+ return codeDecorators.flatMap((fn) => fn(ctx));
6645
+ };
6646
+ }
6494
6647
  const decorators = this.extensions.flatMap((e) => e.decorations ? [e.decorations] : []);
6495
6648
  if (decorators.length > 0) {
6496
6649
  this.renderer.decorate = (block3, content, cell) => {
@@ -6506,8 +6659,9 @@ var Editor = class {
6506
6659
  root.translate = false;
6507
6660
  root.style.setProperty("--mbe-slash-hint", JSON.stringify(this.labels.slashHint));
6508
6661
  this.applyRuntime({ placeholder: options.placeholder, attributes: options.attributes });
6509
- this.runtime = { ...this.runtime, resolveImageSrc: options.resolveImageSrc };
6510
- this.renderer.resolveImageSrc = options.resolveImageSrc;
6662
+ this.runtime = { ...this.runtime, resolveUrl: options.resolveUrl, onLinkClick: options.onLinkClick };
6663
+ this.renderer.resolveUrl = options.resolveUrl ?? defaultResolveUrl;
6664
+ this.renderer.referrerPolicy = options.referrerPolicy;
6511
6665
  this.applyTheme(options.theme);
6512
6666
  setPopupContainer(root, options.popupContainer);
6513
6667
  const configs = this.extensions.flatMap((e) => e.suggestion ? [e.suggestion] : []);
@@ -6752,7 +6906,7 @@ var Editor = class {
6752
6906
  // Options and events
6753
6907
  /**
6754
6908
  * Changes `placeholder`, `editable`, `taskToggle`, `attributes`,
6755
- * `resolveImageSrc` or `theme`. `extensions` only updates the callbacks of
6909
+ * `resolveUrl`, `onLinkClick` or `theme`. `extensions` only updates the callbacks of
6756
6910
  * `suggestion()` extensions (`items`, `command`, `match`, `allow`), matched
6757
6911
  * by name; other changes to extensions need a new editor.
6758
6912
  */
@@ -6794,11 +6948,12 @@ var Editor = class {
6794
6948
  for (const [name, value] of Object.entries(options.attributes ?? {})) root.setAttribute(name, value);
6795
6949
  this.runtime = { ...this.runtime, attributes: options.attributes };
6796
6950
  }
6797
- if ("resolveImageSrc" in options && options.resolveImageSrc !== this.runtime.resolveImageSrc) {
6798
- this.runtime = { ...this.runtime, resolveImageSrc: options.resolveImageSrc };
6799
- this.renderer.resolveImageSrc = options.resolveImageSrc;
6951
+ if ("resolveUrl" in options && options.resolveUrl !== this.runtime.resolveUrl) {
6952
+ this.runtime = { ...this.runtime, resolveUrl: options.resolveUrl };
6953
+ this.renderer.resolveUrl = options.resolveUrl ?? defaultResolveUrl;
6800
6954
  this.paint(true);
6801
6955
  }
6956
+ if ("onLinkClick" in options) this.runtime = { ...this.runtime, onLinkClick: options.onLinkClick };
6802
6957
  if ("theme" in options && this.applyTheme(options.theme)) this.paint(true);
6803
6958
  }
6804
6959
  /** Sets the theme. Returns true when blocks must re-render for new classes. */
@@ -7192,7 +7347,8 @@ var Editor = class {
7192
7347
  /** Where the caret goes moving into `block` from above (`forward`) or below: its first or last line, at `x`. */
7193
7348
  blockEntry(block3, forward, x) {
7194
7349
  const el = this.renderer.elementFor(block3.id);
7195
- if (block3.type === "raw" && el?.classList.contains("mbe-view-block")) return viewEntry(block3, forward);
7350
+ const viewed = this.viewBlock(block3);
7351
+ if (viewed) return viewEntry(viewed, forward);
7196
7352
  if (el) {
7197
7353
  const range = el.ownerDocument.createRange();
7198
7354
  range.selectNodeContents(contentElement(el) ?? el);
@@ -7217,10 +7373,70 @@ var Editor = class {
7217
7373
  const views = this.renderer.views;
7218
7374
  if (views && !this.pointerDown && !this.composing) this.renderer.revealed = revealedViews(this.state, views, !this.readOnly && hadFocus);
7219
7375
  this.renderer.render(this.state.doc, force, lazy);
7376
+ this.applyHeadingIds();
7220
7377
  this.applyReadOnly();
7221
7378
  this.paintBlockSelection();
7222
7379
  if (!this.composing) this.syncDomSelection(hadFocus);
7223
7380
  }
7381
+ /** Heading ids from the `headingIds` option, computed again only when the document changes. */
7382
+ applyHeadingIds() {
7383
+ const headingIds = this.options.headingIds;
7384
+ if (!headingIds) return;
7385
+ const doc = this.state.doc;
7386
+ if (this.headingIdsFor?.doc !== doc) {
7387
+ const headings = doc.blocks.filter((b) => b.type === "heading");
7388
+ const ids = headingIds(headings.map((h) => ({ text: inlineText(h.content), level: h.level })));
7389
+ this.headingIdsFor = { doc, ids: new Map(headings.map((h, i) => [h.id, ids[i]])) };
7390
+ }
7391
+ for (const [blockId, id] of this.headingIdsFor.ids) {
7392
+ const el = this.renderer.elementFor(blockId);
7393
+ if (!el) continue;
7394
+ if (id) {
7395
+ if (el.id !== id) el.id = id;
7396
+ } else if (el.id) {
7397
+ el.removeAttribute("id");
7398
+ }
7399
+ }
7400
+ }
7401
+ /**
7402
+ * Computes decorations again for every block and renders the blocks whose
7403
+ * decorations depend on something outside the document changed, such as
7404
+ * which mentioned people exist or a highlighter's language that finished
7405
+ * loading. Waits for an input method to finish composing.
7406
+ */
7407
+ redecorate() {
7408
+ if (this.destroyed) return;
7409
+ if (this.composing || this.composition) {
7410
+ this.redecoratePending = true;
7411
+ return;
7412
+ }
7413
+ this.redecoratePending = false;
7414
+ this.paint(true);
7415
+ this.afterRender();
7416
+ }
7417
+ /**
7418
+ * Views that returned a promise settled: their blocks render again on the
7419
+ * next frame, or when a composition settles, since rendering would end it.
7420
+ */
7421
+ viewsSettled(ids) {
7422
+ if (this.destroyed) return;
7423
+ if (this.composing || this.composition) {
7424
+ for (const id of ids) this.unsettled.add(id);
7425
+ return;
7426
+ }
7427
+ for (const id of ids) this.renderer.invalidate(id);
7428
+ this.viewFrame ||= requestAnimationFrame(() => {
7429
+ this.viewFrame = 0;
7430
+ if (this.destroyed || this.composing || this.composition) return;
7431
+ this.paint();
7432
+ this.afterRender();
7433
+ });
7434
+ }
7435
+ /** A block rendered by a view (a formula block, a diagram), or null. */
7436
+ viewBlock(block3) {
7437
+ if (!block3 || block3.type !== "raw" && block3.type !== "code") return null;
7438
+ return this.renderer.elementFor(block3.id)?.classList.contains("mbe-view-block") ? block3 : null;
7439
+ }
7224
7440
  /** Re-renders if the views that show their source changed: after the selection, focus or editability changes. */
7225
7441
  refreshRevealed() {
7226
7442
  const views = this.renderer.views;
@@ -7248,7 +7464,7 @@ var Editor = class {
7248
7464
  const index = blockIndex(this.state.doc, pos.blockId);
7249
7465
  const forward = key === "ArrowDown" || key === "ArrowRight";
7250
7466
  const next = blocks[index + (forward ? 1 : -1)];
7251
- const view = next?.type === "raw" && this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block");
7467
+ const view = this.viewBlock(next);
7252
7468
  if (!next || !view && next.type !== "table") return null;
7253
7469
  const current = blocks[index];
7254
7470
  if (!isTextBlock(current)) return null;
@@ -7262,7 +7478,7 @@ var Editor = class {
7262
7478
  const row = forward ? 0 : next.rows.length - 1;
7263
7479
  return { blockId: next.id, offset: forward ? 0 : inlineLength(next.rows[row][0]), cell: { row, col: 0 } };
7264
7480
  }
7265
- return viewEntry(next, forward);
7481
+ return viewEntry(view, forward);
7266
7482
  }
7267
7483
  /**
7268
7484
  * ArrowUp or ArrowDown on the first or last line of a table cell: the
@@ -7295,7 +7511,8 @@ var Editor = class {
7295
7511
  const c = Math.min(col, next.align.length - 1);
7296
7512
  return { blockId: next.id, offset: dir === 1 ? 0 : inlineLength(next.rows[r][c]), cell: { row: r, col: c } };
7297
7513
  }
7298
- if (next.type === "raw" && this.renderer.elementFor(next.id)?.classList.contains("mbe-view-block")) return viewEntry(next, dir === 1);
7514
+ const viewed = this.viewBlock(next);
7515
+ if (viewed) return viewEntry(viewed, dir === 1);
7299
7516
  return dir === 1 ? startOf(next) : endOf(next);
7300
7517
  }
7301
7518
  return null;
@@ -7318,7 +7535,7 @@ var Editor = class {
7318
7535
  /** 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
7536
  revealView(view) {
7320
7537
  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);
7538
+ const pos = block3 ? block3.type === "raw" || block3.type === "code" ? viewEntry(block3, false) : null : domToPosition(this.root, view.parentNode, childIndex(view) + 1);
7322
7539
  if (!pos) return;
7323
7540
  this.root.focus({ preventScroll: true });
7324
7541
  this.setSelection({ anchor: pos, focus: pos });
@@ -7484,7 +7701,8 @@ var Editor = class {
7484
7701
  this.composition = null;
7485
7702
  for (const id of this.unsettled) this.renderer.invalidate(id);
7486
7703
  this.unsettled.clear();
7487
- this.paint();
7704
+ this.paint(this.redecoratePending);
7705
+ this.redecoratePending = false;
7488
7706
  this.afterRender();
7489
7707
  if (composed) this.typedForSuggestion();
7490
7708
  }
@@ -7687,9 +7905,39 @@ var Editor = class {
7687
7905
  const plain2 = !mod2 && !e.shiftKey && !e.altKey;
7688
7906
  const vertical = !plain2 ? 0 : e.key === "ArrowDown" ? 1 : e.key === "ArrowUp" ? -1 : 0;
7689
7907
  const from = blockIndex(this.state.doc, this.state.selection.focus.blockId);
7690
- this.caretKey = { from, x: this.selectionRect()?.left ?? 0, vertical };
7908
+ const key2 = { from, x: this.selectionRect()?.left ?? 0, vertical };
7909
+ this.caretKey = key2;
7910
+ if (vertical) this.unlessCaretMoves(key2);
7691
7911
  }
7692
7912
  }
7913
+ /**
7914
+ * WebKit skips code blocks and tables with ArrowDown and ArrowUp. When no
7915
+ * editable text follows them (a rendered footnote or formula is not), it
7916
+ * does not move the caret at all. If the browser left the caret on the edge
7917
+ * line of its block, move it into the next block that holds a caret.
7918
+ */
7919
+ unlessCaretMoves(key) {
7920
+ const before = this.state.selection.focus;
7921
+ if (before.cell || !isCollapsed(this.state.selection)) return;
7922
+ const content = contentElement(this.renderer.elementFor(before.blockId) ?? this.root);
7923
+ if (!content || !this.onEdgeLine(content, key.vertical === 1)) return;
7924
+ setTimeout(() => {
7925
+ if (this.destroyed || this.caretKey !== key) return;
7926
+ const now = this.readDomSelection();
7927
+ if (!now || !samePosition(now.focus, before)) return;
7928
+ const blocks = this.state.doc.blocks;
7929
+ for (let i = key.from + key.vertical; i >= 0 && i < blocks.length; i += key.vertical) {
7930
+ const block3 = blocks[i];
7931
+ if (block3.type === "divider") continue;
7932
+ this.caretKey = null;
7933
+ const row = key.vertical === 1 ? 0 : block3.type === "table" ? block3.rows.length - 1 : 0;
7934
+ 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);
7935
+ this.setSelection({ anchor: pos, focus: pos });
7936
+ this.scrollCaretIntoView();
7937
+ return;
7938
+ }
7939
+ });
7940
+ }
7693
7941
  /** Selects all the text of the block (or table cell) holding `target`. False if it holds none. */
7694
7942
  selectBlockText(target) {
7695
7943
  const blockEl = target.closest?.(`[${BLOCK_ATTR}]`);
@@ -7698,7 +7946,7 @@ var Editor = class {
7698
7946
  const cellEl = target.closest("[data-row]");
7699
7947
  const cell = block3.type === "table" && cellEl ? { row: Number(cellEl.dataset.row), col: Number(cellEl.dataset.col) } : void 0;
7700
7948
  const content = containerContent(block3, cell);
7701
- if (!content || block3.type === "raw" && blockEl.classList.contains("mbe-view-block")) return false;
7949
+ if (!content || blockEl.classList.contains("mbe-view-block")) return false;
7702
7950
  const at = (offset) => cell ? { blockId: block3.id, offset, cell } : { blockId: block3.id, offset };
7703
7951
  this.setSelection({ anchor: at(0), focus: at(inlineLength(content)) });
7704
7952
  return true;
@@ -7756,8 +8004,9 @@ var Editor = class {
7756
8004
  if (!link) return;
7757
8005
  e.preventDefault();
7758
8006
  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");
8007
+ const href = link.getAttribute("href");
8008
+ if (!href || this.runtime.onLinkClick?.({ editor: this, href, event: e })) return;
8009
+ this.root.ownerDocument.defaultView?.open(href, "_blank", "noopener,noreferrer");
7761
8010
  }
7762
8011
  }
7763
8012
  /** The code block language input. */
@@ -8310,7 +8559,10 @@ function math(options = {}) {
8310
8559
  math(source, element, kind) {
8311
8560
  const tex = mathSource(source, kind);
8312
8561
  if (!tex.trim()) return false;
8313
- render2(tex, element, { displayMode: kind === "block" });
8562
+ const result = render2(tex, element, { displayMode: kind === "block" });
8563
+ if (!result) return;
8564
+ if (!element.hasChildNodes()) element.textContent = source;
8565
+ return result;
8314
8566
  }
8315
8567
  }
8316
8568
  };
@@ -8341,8 +8593,46 @@ var block2 = {
8341
8593
  };
8342
8594
  }
8343
8595
  };
8344
- function footnotes() {
8345
- return { name: "footnotes", markdown: { inline: [inline2], block: [block2] } };
8596
+ var labelOf = (source) => /^\[\^((?:[^\]\\]|\\.)+)\]/.exec(source)?.[1]?.replace(/\\(.)/g, "$1") ?? "";
8597
+ var renderReference = (source, element) => {
8598
+ const label = labelOf(source);
8599
+ const sup = element.ownerDocument.createElement("sup");
8600
+ sup.className = "mbe-footnote-ref";
8601
+ sup.dataset.label = label;
8602
+ sup.textContent = label;
8603
+ element.appendChild(sup);
8604
+ };
8605
+ var renderDefinition = (source, element) => {
8606
+ const label = labelOf(source);
8607
+ const doc = element.ownerDocument;
8608
+ element.classList.add("mbe-footnote");
8609
+ element.dataset.label = label;
8610
+ const sup = doc.createElement("sup");
8611
+ sup.className = "mbe-footnote-label";
8612
+ sup.textContent = label;
8613
+ const text = doc.createElement("span");
8614
+ text.textContent = source.replace(/^\[\^(?:[^\]\\]|\\.)+\]:[ \t]*/, "").split("\n").map((line) => line.trim()).filter(Boolean).join(" ");
8615
+ element.append(sup, text);
8616
+ };
8617
+ function footnotes(options = {}) {
8618
+ if (options.render === false) return { name: "footnotes", markdown: { inline: [inline2], block: [block2] } };
8619
+ return {
8620
+ name: "footnotes",
8621
+ markdown: { inline: [inline2], block: [block2] },
8622
+ views: { footnote: (source, element, kind) => (kind === "inline" ? renderReference : renderDefinition)(source, element, kind) },
8623
+ onCreate: ({ editor }) => {
8624
+ const onClick = (e) => {
8625
+ const ref = e.target.closest?.(".mbe-footnote-ref");
8626
+ if (!ref || editor.isEditable) return;
8627
+ const definition = [...editor.root.querySelectorAll(".mbe-footnote")].find((d) => d.dataset.label === ref.dataset.label);
8628
+ if (!definition) return;
8629
+ e.preventDefault();
8630
+ definition.scrollIntoView({ block: "center", behavior: "smooth" });
8631
+ };
8632
+ editor.root.addEventListener("click", onClick);
8633
+ return () => editor.root.removeEventListener("click", onClick);
8634
+ }
8635
+ };
8346
8636
  }
8347
8637
 
8348
8638
  // src/extensions/textDecorator.ts
@@ -8429,7 +8719,11 @@ function decorate2(scan, cls, attributes) {
8429
8719
  for (const r of scan(text, pos, end)) {
8430
8720
  const from = Math.max(r.from, pos);
8431
8721
  const to = Math.min(r.to, end);
8432
- if (to > from) out.push(attributes ? { from, to, class: cls, attributes } : { from, to, class: cls });
8722
+ if (to <= from) continue;
8723
+ const match = text.slice(from, to);
8724
+ const className = typeof cls === "function" ? cls(match) : cls;
8725
+ const attrs = typeof attributes === "function" ? attributes(match) : attributes;
8726
+ out.push(attrs ? { from, to, class: className, attributes: attrs } : { from, to, class: className });
8433
8727
  }
8434
8728
  }
8435
8729
  pos = end;
@@ -8504,6 +8798,7 @@ export {
8504
8798
  createId,
8505
8799
  createState,
8506
8800
  defaultKeymap,
8801
+ defaultResolveUrl,
8507
8802
  deleteInline,
8508
8803
  divider,
8509
8804
  docToHtml,