@vectojs/markdown 0.5.0 → 0.6.0

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
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -23,7 +33,9 @@ __export(index_exports, {
23
33
  CodeBlock: () => CodeBlock,
24
34
  Markdown: () => Markdown,
25
35
  codeAtlas: () => codeAtlas,
26
- codeAtlasStats: () => codeAtlasStats
36
+ codeAtlasStats: () => codeAtlasStats,
37
+ isMathJaxReady: () => isMathJaxReady,
38
+ preloadMathJax: () => preloadMathJax
27
39
  });
28
40
  module.exports = __toCommonJS(index_exports);
29
41
 
@@ -58,7 +70,10 @@ var StreamControllerImpl = class {
58
70
  this.signal = options.signal;
59
71
  this.onSignalAbort = () => this.abort(this.signal?.reason);
60
72
  if (this.signal?.aborted) this.abort(this.signal.reason);
61
- else this.signal?.addEventListener("abort", this.onSignalAbort, { once: true });
73
+ else
74
+ this.signal?.addEventListener("abort", this.onSignalAbort, {
75
+ once: true
76
+ });
62
77
  }
63
78
  host;
64
79
  maxBufferedChars;
@@ -146,10 +161,33 @@ var StreamControllerImpl = class {
146
161
  return closePromise;
147
162
  }
148
163
  this.currentState = "closed";
149
- this.cleanup();
150
- this.resolveClose?.();
151
- this.resolveClose = null;
152
- this.rejectClose = null;
164
+ let settled;
165
+ try {
166
+ settled = this.host.onClose?.();
167
+ } catch (error) {
168
+ this.cleanup();
169
+ this.rejectPendingClose(error);
170
+ return closePromise;
171
+ }
172
+ if (settled === void 0) {
173
+ this.cleanup();
174
+ this.resolveClose?.();
175
+ this.resolveClose = null;
176
+ this.rejectClose = null;
177
+ return closePromise;
178
+ }
179
+ void Promise.resolve(settled).then(
180
+ () => {
181
+ this.cleanup();
182
+ this.resolveClose?.();
183
+ this.resolveClose = null;
184
+ this.rejectClose = null;
185
+ },
186
+ (error) => {
187
+ this.cleanup();
188
+ this.rejectPendingClose(error);
189
+ }
190
+ );
153
191
  return closePromise;
154
192
  }
155
193
  abort(reason) {
@@ -415,12 +453,6 @@ function createStreamController(host, options = {}) {
415
453
  }
416
454
 
417
455
  // src/Markdown.ts
418
- var import_mathjax = require("mathjax-full/js/mathjax.js");
419
- var import_tex = require("mathjax-full/js/input/tex.js");
420
- var import_svg = require("mathjax-full/js/output/svg.js");
421
- var import_liteAdaptor = require("mathjax-full/js/adaptors/liteAdaptor.js");
422
- var import_html = require("mathjax-full/js/handlers/html.js");
423
- var import_AllPackages = require("mathjax-full/js/input/tex/AllPackages.js");
424
456
  var import_ui = require("@vectojs/ui");
425
457
 
426
458
  // src/MarkdownWorkerSource.ts
@@ -462,23 +494,183 @@ import_marked.marked.use({
462
494
  }
463
495
  ]
464
496
  });
465
- var adaptor = (0, import_liteAdaptor.liteAdaptor)();
466
- (0, import_html.RegisterHTMLHandler)(adaptor);
467
- var tex = new import_tex.TeX({ packages: import_AllPackages.AllPackages });
468
- var svg = new import_svg.SVG({ fontCache: "local" });
469
- var htmlMathJax = import_mathjax.mathjax.document("", { InputJax: tex, OutputJax: svg });
497
+ var mathConverter = null;
498
+ var mathLoad = null;
499
+ function interop(mod, key) {
500
+ const ns = mod;
501
+ if (typeof ns?.[key] !== "undefined") return ns;
502
+ const fallback = ns?.default;
503
+ if (fallback && typeof fallback[key] !== "undefined") return fallback;
504
+ throw new Error(`mathjax-full module is missing export "${key}"`);
505
+ }
506
+ function preloadMathJax() {
507
+ if (mathLoad) return mathLoad;
508
+ mathLoad = (async () => {
509
+ const [mathjaxMod, texMod, svgMod, adaptorMod, handlerMod, packagesMod] = await Promise.all([
510
+ import("mathjax-full/js/mathjax.js"),
511
+ import("mathjax-full/js/input/tex.js"),
512
+ import("mathjax-full/js/output/svg.js"),
513
+ import("mathjax-full/js/adaptors/liteAdaptor.js"),
514
+ import("mathjax-full/js/handlers/html.js"),
515
+ import("mathjax-full/js/input/tex/AllPackages.js")
516
+ ]);
517
+ const { mathjax } = interop(mathjaxMod, "mathjax");
518
+ const { TeX } = interop(texMod, "TeX");
519
+ const { SVG } = interop(svgMod, "SVG");
520
+ const { liteAdaptor } = interop(adaptorMod, "liteAdaptor");
521
+ const { RegisterHTMLHandler } = interop(handlerMod, "RegisterHTMLHandler");
522
+ const { AllPackages } = interop(packagesMod, "AllPackages");
523
+ const adaptor = liteAdaptor();
524
+ RegisterHTMLHandler(adaptor);
525
+ const tex = new TeX({ packages: AllPackages });
526
+ const svg = new SVG({ fontCache: "local" });
527
+ const htmlMathJax = mathjax.document("", { InputJax: tex, OutputJax: svg });
528
+ mathConverter = (formula, displayMode) => convertMathToSVGDataURI(
529
+ formula,
530
+ displayMode,
531
+ (f, d) => adaptor.innerHTML(htmlMathJax.convert(f, { display: d }))
532
+ );
533
+ })().catch((e) => {
534
+ console.error("MathJax failed to load; formulas will render as TeX source", e);
535
+ });
536
+ return mathLoad;
537
+ }
538
+ function isMathJaxReady() {
539
+ return mathConverter !== null;
540
+ }
541
+ var EX_PER_EM = 0.4421;
542
+ function exToPx(ex, fontSize) {
543
+ return ex * fontSize * EX_PER_EM;
544
+ }
545
+ function fontSizeFromFont(font) {
546
+ const pxIndex = font.indexOf("px");
547
+ if (pxIndex <= 0) return void 0;
548
+ let start = pxIndex;
549
+ while (start > 0) {
550
+ const ch = font[start - 1];
551
+ if (ch >= "0" && ch <= "9" || ch === ".") start--;
552
+ else break;
553
+ }
554
+ if (start === pxIndex) return void 0;
555
+ const size = parseFloat(font.slice(start, pxIndex));
556
+ return Number.isFinite(size) ? size : void 0;
557
+ }
558
+ var mathCache = /* @__PURE__ */ new Map();
559
+ var MATH_CACHE_LIMIT = 256;
560
+ var inlineMathRasters = /* @__PURE__ */ new Map();
561
+ var inlineMathRasterWaiters = /* @__PURE__ */ new Set();
562
+ function ensureInlineMathRaster(uri) {
563
+ const existing = inlineMathRasters.get(uri);
564
+ if (existing) return existing;
565
+ const entry = { decoded: false };
566
+ inlineMathRasters.set(uri, entry);
567
+ if (typeof globalThis.Image !== "undefined") {
568
+ const bitmap = new globalThis.Image();
569
+ bitmap.onload = () => {
570
+ entry.decoded = true;
571
+ for (const notify of inlineMathRasterWaiters) notify();
572
+ };
573
+ bitmap.src = uri;
574
+ entry.bitmap = bitmap;
575
+ }
576
+ return entry;
577
+ }
578
+ function paintInlineMath(uri, surface, box) {
579
+ const raster = ensureInlineMathRaster(uri);
580
+ if (!raster.decoded || !raster.bitmap) return;
581
+ surface.drawImage(raster.bitmap, box.x, box.y, box.width, box.height);
582
+ }
583
+ var MATH_LANGS = /* @__PURE__ */ new Set(["math", "latex", "tex"]);
584
+ function containsInlineMath(token) {
585
+ if (token.type === "inlineMath") return true;
586
+ const anyToken = token;
587
+ if (Array.isArray(anyToken.tokens) && anyToken.tokens.some(containsInlineMath)) {
588
+ return true;
589
+ }
590
+ if (Array.isArray(anyToken.items) && anyToken.items.some(containsInlineMath)) {
591
+ return true;
592
+ }
593
+ if (Array.isArray(anyToken.header) && anyToken.header.some(containsInlineMath)) {
594
+ return true;
595
+ }
596
+ if (Array.isArray(anyToken.rows)) {
597
+ for (const row of anyToken.rows) {
598
+ if (Array.isArray(row) && row.some(containsInlineMath)) return true;
599
+ }
600
+ }
601
+ return false;
602
+ }
603
+ var FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})/;
604
+ var FENCE_CLOSE_RE = /^ {0,3}(`+|~+)[ \t]*$/;
605
+ function isFenceClosed(raw) {
606
+ const lines = raw.split("\n");
607
+ const open = FENCE_OPEN_RE.exec(lines[0]);
608
+ if (!open) return false;
609
+ const marker = open[1][0];
610
+ const minLen = open[1].length;
611
+ for (let i = 1; i < lines.length; i++) {
612
+ const close = FENCE_CLOSE_RE.exec(lines[i]);
613
+ if (close && close[1][0] === marker && close[1].length >= minLen) return true;
614
+ }
615
+ return false;
616
+ }
617
+ function paragraphHasImage(token) {
618
+ return token.tokens?.some((child) => child.type === "image") === true;
619
+ }
620
+ function lastIndexOfImage(tokens) {
621
+ for (let i = tokens.length - 1; i >= 0; i--) {
622
+ if (tokens[i].type === "image") return i;
623
+ }
624
+ return -1;
625
+ }
626
+ function expectedImageParagraphChildren(tokens) {
627
+ let children = 0;
628
+ let inTextRun = false;
629
+ for (const token of tokens) {
630
+ if (token.type === "image") {
631
+ children++;
632
+ inTextRun = false;
633
+ } else if (!inTextRun) {
634
+ children++;
635
+ inTextRun = true;
636
+ }
637
+ }
638
+ return children;
639
+ }
640
+ function rendersAsMath(token) {
641
+ return MATH_LANGS.has((token.lang ?? "").toLowerCase()) && token.text.trim() !== "" && isFenceClosed(token.raw);
642
+ }
470
643
  function renderMathToSVGDataURI(formula, displayMode) {
644
+ const key = `${displayMode ? 1 : 0}\0${formula}`;
645
+ const hit = mathCache.get(key);
646
+ if (hit) return hit;
647
+ if (!mathConverter) return null;
648
+ const converted = mathConverter(formula, displayMode);
649
+ if (converted) {
650
+ if (mathCache.size >= MATH_CACHE_LIMIT) {
651
+ const oldest = mathCache.keys().next().value;
652
+ if (oldest !== void 0) mathCache.delete(oldest);
653
+ }
654
+ mathCache.set(key, converted);
655
+ }
656
+ return converted;
657
+ }
658
+ function convertMathToSVGDataURI(formula, displayMode, typeset) {
471
659
  try {
472
- const node = htmlMathJax.convert(formula, { display: displayMode });
473
- const svgString = adaptor.innerHTML(node);
660
+ const svgString = typeset(formula, displayMode);
474
661
  const wMatch = svgString.match(/width="([^"]+)ex"/);
475
662
  const hMatch = svgString.match(/height="([^"]+)ex"/);
476
663
  const wEx = wMatch ? parseFloat(wMatch[1]) : 10;
477
664
  const hEx = hMatch ? parseFloat(hMatch[1]) : 2;
478
- const width = wEx * 8;
479
- const height = hEx * 8;
665
+ const vMatch = svgString.match(/vertical-align:\s*(-?[\d.]+)ex/);
666
+ const depthEx = vMatch ? Math.max(0, -parseFloat(vMatch[1])) : 0;
480
667
  const base64 = btoa(unescape(encodeURIComponent(svgString)));
481
- return { uri: `data:image/svg+xml;base64,${base64}`, width, height };
668
+ return {
669
+ uri: `data:image/svg+xml;base64,${base64}`,
670
+ widthEx: wEx,
671
+ heightEx: hEx,
672
+ depthEx
673
+ };
482
674
  } catch (e) {
483
675
  console.error("MathJax error", e);
484
676
  return null;
@@ -493,6 +685,7 @@ function runSyncFallback(entry) {
493
685
  entry.cb(0, lexMarkdown(entry.text, entry.userTiming), true);
494
686
  } catch (err) {
495
687
  console.warn("Markdown sync fallback parse failed", err);
688
+ entry.onDropped?.();
496
689
  }
497
690
  }
498
691
  if (typeof Worker !== "undefined") {
@@ -1018,13 +1211,13 @@ function codeAtlas() {
1018
1211
  function decodeEntities(text) {
1019
1212
  return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
1020
1213
  }
1021
- function collectSpans(tokens, inherited, theme, out) {
1214
+ function collectSpans(tokens, inherited, theme, out, blockFontSize) {
1022
1215
  for (const token of tokens) {
1023
1216
  switch (token.type) {
1024
1217
  case "strong": {
1025
1218
  const t = token;
1026
1219
  if (t.tokens) {
1027
- collectSpans(t.tokens, { ...inherited, bold: true }, theme, out);
1220
+ collectSpans(t.tokens, { ...inherited, bold: true }, theme, out, blockFontSize);
1028
1221
  } else {
1029
1222
  out.push({
1030
1223
  text: decodeEntities(t.text),
@@ -1036,7 +1229,7 @@ function collectSpans(tokens, inherited, theme, out) {
1036
1229
  case "em": {
1037
1230
  const t = token;
1038
1231
  if (t.tokens) {
1039
- collectSpans(t.tokens, { ...inherited, italic: true }, theme, out);
1232
+ collectSpans(t.tokens, { ...inherited, italic: true }, theme, out, blockFontSize);
1040
1233
  } else {
1041
1234
  out.push({
1042
1235
  text: decodeEntities(t.text),
@@ -1072,10 +1265,31 @@ function collectSpans(tokens, inherited, theme, out) {
1072
1265
  }
1073
1266
  case "inlineMath": {
1074
1267
  const t = token;
1075
- out.push({
1076
- text: decodeEntities(t.raw),
1077
- style: { ...inherited, color: "#fcd34d" }
1078
- });
1268
+ const runSize = inherited.fontSize ?? blockFontSize ?? theme.fontSize;
1269
+ const rendered = renderMathToSVGDataURI(t.text, false);
1270
+ if (rendered) {
1271
+ const uri = rendered.uri;
1272
+ out.push({
1273
+ text: import_core.OBJECT_REPLACEMENT,
1274
+ style: inherited,
1275
+ object: {
1276
+ width: exToPx(rendered.widthEx, runSize),
1277
+ height: exToPx(rendered.heightEx, runSize),
1278
+ depth: exToPx(rendered.depthEx, runSize),
1279
+ // The TeX source is the accessible name: without it a screen reader
1280
+ // receives only the invisible U+FFFC sentinel.
1281
+ alt: t.text,
1282
+ // Without this the box is reserved and stays empty. The engine does
1283
+ // not draw objects, and nothing else in the tree holds the raster.
1284
+ paint: (surface, box) => paintInlineMath(uri, surface, box)
1285
+ }
1286
+ });
1287
+ } else {
1288
+ out.push({
1289
+ text: decodeEntities(t.raw),
1290
+ style: { ...inherited, color: "#fcd34d" }
1291
+ });
1292
+ }
1079
1293
  break;
1080
1294
  }
1081
1295
  case "link": {
@@ -1086,7 +1300,7 @@ function collectSpans(tokens, inherited, theme, out) {
1086
1300
  color: "#38bdf8"
1087
1301
  };
1088
1302
  if (t.tokens && t.tokens.length > 0) {
1089
- collectSpans(t.tokens, linkStyle, theme, out);
1303
+ collectSpans(t.tokens, linkStyle, theme, out, blockFontSize);
1090
1304
  } else {
1091
1305
  out.push({ text: decodeEntities(t.text), style: linkStyle });
1092
1306
  }
@@ -1095,7 +1309,7 @@ function collectSpans(tokens, inherited, theme, out) {
1095
1309
  case "text": {
1096
1310
  const t = token;
1097
1311
  if ("tokens" in t && t.tokens?.length) {
1098
- collectSpans(t.tokens, inherited, theme, out);
1312
+ collectSpans(t.tokens, inherited, theme, out, blockFontSize);
1099
1313
  } else {
1100
1314
  const decoded = decodeEntities(t.text);
1101
1315
  if (decoded) {
@@ -1118,10 +1332,37 @@ function collectSpans(tokens, inherited, theme, out) {
1118
1332
  }
1119
1333
  }
1120
1334
  }
1335
+ function findUnclosedInline(text) {
1336
+ let best = null;
1337
+ const tick = text.lastIndexOf("`");
1338
+ if (tick !== -1 && tick < text.length - 1) {
1339
+ return { kind: "codespan", at: tick, contentAt: tick + 1 };
1340
+ }
1341
+ if (tick !== -1) return null;
1342
+ const emphasis = /(\*{1,2}(?!\*)|_{1,2}(?!_))(?=[^\s])/g;
1343
+ for (let match = emphasis.exec(text); match !== null; match = emphasis.exec(text)) {
1344
+ const marker = match[1];
1345
+ const at = match.index;
1346
+ if (marker[0] === "_" && at > 0 && /[\w]/.test(text[at - 1])) continue;
1347
+ best = {
1348
+ kind: marker.length === 2 ? "strong" : "em",
1349
+ at,
1350
+ contentAt: at + marker.length
1351
+ };
1352
+ }
1353
+ const bracket = text.lastIndexOf("[");
1354
+ if (bracket !== -1 && bracket < text.length - 1 && (best === null || bracket > best.at)) {
1355
+ const closed = /\]\([^)]*\)/.test(text.slice(bracket));
1356
+ if (!closed) {
1357
+ best = { kind: "link", at: bracket, contentAt: bracket + 1 };
1358
+ }
1359
+ }
1360
+ return best;
1361
+ }
1121
1362
  function renderInlineToRichText(tokens, fallbackText, font, color, maxWidth, theme, selectable, onLinkClick) {
1122
1363
  const spans = [];
1123
1364
  if (tokens && tokens.length > 0) {
1124
- collectSpans(tokens, {}, theme, spans);
1365
+ collectSpans(tokens, {}, theme, spans, fontSizeFromFont(font));
1125
1366
  }
1126
1367
  if (spans.length === 0) {
1127
1368
  spans.push({ text: decodeEntities(fallbackText) });
@@ -1153,6 +1394,51 @@ var Markdown = class extends import_ui.UIComponent {
1153
1394
  onLayoutUpdated;
1154
1395
  rawMarkdown;
1155
1396
  streamController = null;
1397
+ /**
1398
+ * Trailing-unclosed-syntax policy of the active stream, or `'literal'` when no
1399
+ * stream is open.
1400
+ *
1401
+ * Held here rather than read back off the controller because it is a rendering
1402
+ * concern: `StreamController` owns buffering and pacing and has no view of the
1403
+ * entity tree, while the guess is a transform applied where spans are built.
1404
+ */
1405
+ streamIncompleteMode = "literal";
1406
+ /** End-of-stream callback of the active stream, if it supplied one. */
1407
+ streamOnStable = null;
1408
+ /**
1409
+ * The trailing paragraph entity currently showing an optimistic guess, plus the
1410
+ * token it was rendered from.
1411
+ *
1412
+ * Both halves are needed. The entity is what must be re-rendered to drop the
1413
+ * guess; the token is what it must be re-rendered FROM, and it is the only
1414
+ * copy — `this.tokens` has already moved on by the time an unwind is decided.
1415
+ * `null` means no guess is live, which is the state every `'literal'` stream
1416
+ * and every closed stream stays in.
1417
+ */
1418
+ optimisticTail = null;
1419
+ /** Resolvers waiting for every in-flight worker append to have been applied. */
1420
+ appendSettledWaiters = [];
1421
+ /** True only inside an `onStable` callback, to reject reentrant mutation. */
1422
+ inStableCallback = false;
1423
+ /** Set by {@link destroy} so late settlement work skips a torn-down tree. */
1424
+ isDestroyed = false;
1425
+ /**
1426
+ * This instance's entry in {@link inlineMathRasterWaiters}, or `undefined` if it
1427
+ * has never rendered inline math.
1428
+ *
1429
+ * Subscribed lazily so a document without formulas costs nothing, and held as a
1430
+ * field only so {@link destroy} can remove the exact closure it added.
1431
+ */
1432
+ inlineMathRepaint;
1433
+ /**
1434
+ * True while this document is waiting on the lazy MathJax load.
1435
+ *
1436
+ * Tracked per instance rather than read off the module state because it also
1437
+ * gates settlement: `await close()` and `onStable` must not resolve while a
1438
+ * formula is still showing TeX source, or a caller doing expensive one-time
1439
+ * work on a "final" document would measure and export placeholder boxes.
1440
+ */
1441
+ mathLoadPending = false;
1156
1442
  _userTiming;
1157
1443
  tokens = [];
1158
1444
  // At most one worker lex request in flight at a time. Required for the
@@ -1310,21 +1596,44 @@ var Markdown = class extends import_ui.UIComponent {
1310
1596
  {
1311
1597
  append: (chunk) => this.appendMarkdownCore(chunk),
1312
1598
  release: (released) => {
1313
- if (this.streamController === released) this.streamController = null;
1599
+ if (this.streamController !== released) return;
1600
+ this.streamController = null;
1601
+ this.streamIncompleteMode = "literal";
1602
+ this.streamOnStable = null;
1603
+ this.unwindOptimisticTail();
1604
+ },
1605
+ onClose: async () => {
1606
+ await this.waitForAppendSettled();
1607
+ if (this.isDestroyed) return;
1608
+ this.unwindOptimisticTail();
1609
+ const onStable = this.streamOnStable;
1610
+ if (!onStable) return;
1611
+ this.inStableCallback = true;
1612
+ try {
1613
+ onStable(Array.from(this.content.children));
1614
+ } finally {
1615
+ this.inStableCallback = false;
1616
+ }
1314
1617
  }
1315
1618
  },
1316
1619
  options
1317
1620
  );
1318
- if (controller.state === "open") this.streamController = controller;
1621
+ if (controller.state === "open") {
1622
+ this.streamController = controller;
1623
+ this.streamIncompleteMode = options.incompleteMode ?? "literal";
1624
+ this.streamOnStable = options.onStable ?? null;
1625
+ }
1319
1626
  return controller;
1320
1627
  }
1321
1628
  /** Replace all markdown content (full rebuild). */
1322
1629
  setContent(markdown) {
1630
+ this.assertNotInStableCallback("setContent");
1323
1631
  this.streamController?.abort(new Error("Markdown content was replaced"));
1324
1632
  for (const id of this.pendingWorkerIds) workerCallbacks.delete(id);
1325
1633
  this.pendingWorkerIds.clear();
1326
1634
  this.appendInFlight = false;
1327
1635
  this.appendPending = false;
1636
+ this.flushAppendSettledWaiters();
1328
1637
  this.rawMarkdown = markdown;
1329
1638
  this.workerSourceLen = 0;
1330
1639
  while (this.content.children.length > 0) {
@@ -1340,12 +1649,35 @@ var Markdown = class extends import_ui.UIComponent {
1340
1649
  * the whole subtree alive until the worker replied), then recurse into the
1341
1650
  * content subtree via `super.destroy()` so every block's resources are freed.
1342
1651
  */
1652
+ /**
1653
+ * Repaint this document when an inline formula's raster finishes decoding.
1654
+ *
1655
+ * Idempotent — called on every render of a math-bearing token, and the set holds
1656
+ * one closure per instance.
1657
+ */
1658
+ subscribeInlineMathRepaint() {
1659
+ if (this.inlineMathRepaint || this.isDestroyed) return;
1660
+ const repaint = () => {
1661
+ if (this.isDestroyed) return;
1662
+ this.scene?.markDirty();
1663
+ };
1664
+ this.inlineMathRepaint = repaint;
1665
+ inlineMathRasterWaiters.add(repaint);
1666
+ }
1343
1667
  destroy() {
1668
+ this.isDestroyed = true;
1669
+ this.optimisticTail = null;
1344
1670
  this.streamController?.destroy();
1345
1671
  for (const id of this.pendingWorkerIds) workerCallbacks.delete(id);
1346
1672
  this.pendingWorkerIds.clear();
1347
1673
  this.appendInFlight = false;
1348
1674
  this.appendPending = false;
1675
+ this.mathLoadPending = false;
1676
+ this.flushAppendSettledWaiters();
1677
+ if (this.inlineMathRepaint) {
1678
+ inlineMathRasterWaiters.delete(this.inlineMathRepaint);
1679
+ this.inlineMathRepaint = void 0;
1680
+ }
1349
1681
  markdownWorker?.postMessage({
1350
1682
  instance: this.workerInstanceId,
1351
1683
  dispose: true
@@ -1534,6 +1866,7 @@ var Markdown = class extends import_ui.UIComponent {
1534
1866
  }
1535
1867
  /** Append a markdown chunk incrementally. Reuses unchanged prefix entities. */
1536
1868
  appendMarkdown(chunk) {
1869
+ this.assertNotInStableCallback("appendMarkdown");
1537
1870
  this.streamController?.flush();
1538
1871
  return this.appendMarkdownCore(chunk);
1539
1872
  }
@@ -1602,6 +1935,7 @@ var Markdown = class extends import_ui.UIComponent {
1602
1935
  this.appendPending = false;
1603
1936
  this.dispatchAppend();
1604
1937
  }
1938
+ this.flushAppendSettledWaiters();
1605
1939
  },
1606
1940
  // The worker can't trust what it holds for this request; retry it once with
1607
1941
  // the full text and raws attached. `this.tokens` is untouched (no
@@ -1612,6 +1946,20 @@ var Markdown = class extends import_ui.UIComponent {
1612
1946
  this.workerSourceLen = 0;
1613
1947
  this.dispatchAppend(true);
1614
1948
  },
1949
+ // Neither the worker nor the fallback lexer could produce tokens for this
1950
+ // request, so `this.tokens` stays as it was. Only the in-flight bookkeeping
1951
+ // needs unwinding — including any coalesced chunk waiting behind it, which
1952
+ // still has to be attempted.
1953
+ onDropped: () => {
1954
+ this.pendingWorkerIds.delete(id);
1955
+ this.appendInFlight = false;
1956
+ this.workerSourceLen = 0;
1957
+ if (this.appendPending) {
1958
+ this.appendPending = false;
1959
+ this.dispatchAppend(true);
1960
+ }
1961
+ this.flushAppendSettledWaiters();
1962
+ },
1615
1963
  text: this.rawMarkdown,
1616
1964
  userTiming: this._userTiming
1617
1965
  });
@@ -1633,6 +1981,647 @@ var Markdown = class extends import_ui.UIComponent {
1633
1981
  }
1634
1982
  });
1635
1983
  }
1984
+ /**
1985
+ * Spans for one paragraph token exactly as `marked` produced it.
1986
+ *
1987
+ * The literal baseline: what every release renders, and what an optimistic
1988
+ * guess is unwound back to.
1989
+ */
1990
+ literalParagraphSpans(token) {
1991
+ const spans = [];
1992
+ if (token.tokens && token.tokens.length > 0) {
1993
+ collectSpans(token.tokens, {}, this.theme, spans);
1994
+ }
1995
+ if (spans.length === 0) spans.push({ text: token.text });
1996
+ return spans;
1997
+ }
1998
+ /**
1999
+ * Update a reused blockquote's tail child in place, or report that it cannot be.
2000
+ *
2001
+ * The render arm builds `container[border, innerStack]` where every inner block
2002
+ * sits in its own single-child `wrapper`, so the tail entity is
2003
+ * `innerStack.children.at(-1).children[0]`. Only the LAST inner block may be
2004
+ * updated: the inner token list is prefix-stable exactly like the top level (a
2005
+ * growing quote keeps its earlier blocks byte-identical), so anything before the
2006
+ * tail is untouched and anything more complicated than a changed tail falls back
2007
+ * to the caller's rebuild.
2008
+ *
2009
+ * Returns `false` without mutating anything when the shape is not the simple
2010
+ * grow-the-tail case, which is the signal for the caller to rebuild. Every early
2011
+ * return has to leave the entity untouched, or a rejected reuse would leave a
2012
+ * half-updated quote on screen.
2013
+ */
2014
+ /**
2015
+ * Build one list item's spans: inline content plus its marker.
2016
+ *
2017
+ * Shared by the `list` render arm and the streamed-reuse path below, because
2018
+ * the two must produce byte-identical spans — a reused list that disagreed with
2019
+ * a rebuilt one about its marker or its entity decoding would make a streamed
2020
+ * document differ from the same source pasted at once.
2021
+ */
2022
+ /**
2023
+ * Inline spans for one table cell.
2024
+ *
2025
+ * Always returns at least one span. A cell whose markup collapses to nothing —
2026
+ * an empty cell, but also a bare `<span>`, an image, or an HTML comment, none
2027
+ * of which `collectSpans` emits for — falls back to its decoded source text,
2028
+ * which is what the previous string-returning path rendered. That guarantee is
2029
+ * what lets every cell be a `RichText`: an empty cell would otherwise become a
2030
+ * `Text`, and since `Text` has `setText` while `RichText` has `setSpans` and
2031
+ * nothing converts between them, a cell that starts empty and later gains
2032
+ * content could not be updated in place. A streamed table needs exactly that,
2033
+ * because `marked` materializes a partial row as a full row of empty cells and
2034
+ * then fills them one at a time.
2035
+ */
2036
+ tableCellSpans(cell, t) {
2037
+ const spans = [];
2038
+ collectSpans(cell.tokens, {}, t, spans);
2039
+ if (spans.length === 0) spans.push({ text: decodeEntities(cell.text) });
2040
+ return spans;
2041
+ }
2042
+ /**
2043
+ * Spans for one run of consecutive non-image inline tokens.
2044
+ *
2045
+ * A paragraph holding an image renders as a `Stack` of alternating text runs
2046
+ * and images, and this is one text run. Shared by the render arm and
2047
+ * {@link updateImageParagraph} so a reused run cannot drift from a rebuilt one.
2048
+ *
2049
+ * The empty fallback mirrors `renderInlineToRichText('', …)`, which the render
2050
+ * arm passed for these runs: a run is only created when it has at least one
2051
+ * token, so the fallback is for tokens that emit no spans at all rather than
2052
+ * for an empty run.
2053
+ */
2054
+ inlineRunSpans(tokens, t) {
2055
+ const spans = [];
2056
+ if (tokens.length > 0) collectSpans(tokens, {}, t, spans);
2057
+ if (spans.length === 0) spans.push({ text: "" });
2058
+ return spans;
2059
+ }
2060
+ /** One text run of an image-bearing paragraph, as both paths build it. */
2061
+ inlineRunRichText(tokens, availableWidth, t) {
2062
+ return new import_ui.RichText(this.inlineRunSpans(tokens, t), {
2063
+ font: `${t.fontSize}px ${t.bodyFont}`,
2064
+ color: t.textColor,
2065
+ maxWidth: availableWidth,
2066
+ linkColor: "#38bdf8",
2067
+ selectable: this.selectable,
2068
+ onLinkClick: this.onLinkClick
2069
+ });
2070
+ }
2071
+ /**
2072
+ * One image inside a paragraph, sized by a guess until its bitmap decodes.
2073
+ *
2074
+ * Width and height start at a 16:10 guess because the intrinsic size is not
2075
+ * known until the browser has the bitmap; `onLoad` corrects both from
2076
+ * `naturalWidth`/`naturalHeight`. Extracted from the render arm so the streamed
2077
+ * path reuses this exact entity rather than constructing a second variant.
2078
+ *
2079
+ * `markDirty()` is unconditional, matching the display-math sibling. It used
2080
+ * to sit inside the `naturalWidth && naturalHeight` check, which meant a
2081
+ * source that loads successfully while reporting a zero dimension left the
2082
+ * scene un-notified. `Image` sets `loaded` before invoking this callback, so
2083
+ * its `render()` starts drawing the bitmap either way — the cost was not a
2084
+ * stale placeholder but a box frozen at the guess: measured on Chromium and
2085
+ * Firefox, an `<svg width="0" height="0">` paragraph image kept 800x480 of
2086
+ * reserved layout forever while a normal raster corrected to 80x60. An
2087
+ * `onDemand` scene repaints only when marked, so nothing reclaimed it.
2088
+ *
2089
+ * The box is deliberately left at the guess when the bitmap reports zero.
2090
+ * Collapsing it to 0x0 would make the paragraph reflow correctly but would
2091
+ * also silently delete a reserved region on the strength of one browser
2092
+ * quirk, and `Image.render()` still blits whatever the bitmap holds. Sizing
2093
+ * policy for a zero-dimension source is a separate decision from notifying
2094
+ * the scene, which is the actual defect here.
2095
+ */
2096
+ paragraphImage(imgToken, availableWidth) {
2097
+ const initialWidth = Math.min(800, availableWidth);
2098
+ const initialHeight = Math.round(initialWidth * 0.6);
2099
+ const img = new import_ui.Image(imgToken.href, {
2100
+ width: initialWidth,
2101
+ height: initialHeight,
2102
+ alt: imgToken.text,
2103
+ radius: 8,
2104
+ onLoad: () => {
2105
+ const bmp = img.bitmap;
2106
+ if (bmp && bmp.naturalWidth && bmp.naturalHeight) {
2107
+ const aspect = bmp.naturalHeight / bmp.naturalWidth;
2108
+ img.width = Math.min(bmp.naturalWidth, availableWidth);
2109
+ img.height = Math.round(img.width * aspect);
2110
+ }
2111
+ this.scene?.markDirty();
2112
+ }
2113
+ });
2114
+ return img;
2115
+ }
2116
+ /** One table cell entity, shared by the render arm and the streamed-table path. */
2117
+ tableCellRichText(cell, header, t) {
2118
+ return new import_ui.RichText(this.tableCellSpans(cell, t), {
2119
+ font: `${t.fontSize - 2}px ${t.bodyFont}`,
2120
+ color: header ? t.headingColor : t.textColor,
2121
+ baseStyle: header ? { bold: true } : void 0,
2122
+ linkColor: "#38bdf8",
2123
+ selectable: this.selectable,
2124
+ onLinkClick: this.onLinkClick
2125
+ });
2126
+ }
2127
+ listItemSpans(token, index) {
2128
+ const item = token.items[index];
2129
+ const num = Number(token.start ?? 1) + index;
2130
+ const contentSpans = [];
2131
+ if (item.tokens && item.tokens.length > 0) {
2132
+ for (const inner of item.tokens) {
2133
+ if (inner.type === "text" && "tokens" in inner && inner.tokens?.length) {
2134
+ collectSpans(
2135
+ inner.tokens,
2136
+ {},
2137
+ this.theme,
2138
+ contentSpans
2139
+ );
2140
+ } else if ("tokens" in inner && inner.tokens?.length) {
2141
+ collectSpans(
2142
+ inner.tokens,
2143
+ {},
2144
+ this.theme,
2145
+ contentSpans
2146
+ );
2147
+ } else if ("text" in inner) {
2148
+ contentSpans.push({ text: decodeEntities(inner.text) });
2149
+ }
2150
+ }
2151
+ } else {
2152
+ contentSpans.push({ text: decodeEntities(item.text) });
2153
+ }
2154
+ const itemIsRtl = import_core.BidiResolver.getBaseLevel(contentSpans.map((s) => s.text).join("")) % 2 === 1;
2155
+ return itemIsRtl ? [...contentSpans, { text: token.ordered ? ` .${num}` : " \u2022" }] : [{ text: token.ordered ? `${num}. ` : "\u2022 " }, ...contentSpans];
2156
+ }
2157
+ /** Construct the `RichText` for one list item. */
2158
+ listItemRichText(token, index, availableWidth, t) {
2159
+ return new import_ui.RichText(this.listItemSpans(token, index), {
2160
+ font: `${t.fontSize}px ${t.bodyFont}`,
2161
+ color: t.textColor,
2162
+ maxWidth: availableWidth,
2163
+ linkColor: "#38bdf8",
2164
+ selectable: this.selectable,
2165
+ onLinkClick: this.onLinkClick
2166
+ });
2167
+ }
2168
+ /**
2169
+ * Reuse a streamed list's `Stack` instead of rebuilding every item.
2170
+ *
2171
+ * Returns `false` to mean "rebuild instead", exactly like
2172
+ * {@link updateBlockquoteTail}, and every rejection path leaves the entity
2173
+ * untouched so a refused reuse cannot leave a half-updated list on screen.
2174
+ *
2175
+ * This is the shape a stream actually produces: items are APPENDED, and only
2176
+ * the last one grows. That matters for the ordinal marker, which is
2177
+ * position-derived (`start + index`) — under append an already-rendered item's
2178
+ * index never changes, so its marker stays correct. A mid-list insertion would
2179
+ * shift every later ordinal, but no stream produces one.
2180
+ *
2181
+ * Two traps this guards, both found by probing marked 18.0.7 rather than by
2182
+ * reading:
2183
+ *
2184
+ * - **A retained item's `raw` is NOT stable.** `items[1].raw` goes `"- two"` ->
2185
+ * `"- two\\n"` when item 3 arrives, so a byte-equality guard on `raw` fails on
2186
+ * every chunk and the fast path would never fire. `text` is stable; compare
2187
+ * that.
2188
+ * - **A tight list can become loose.** Adding a blank line flips
2189
+ * `token.loose`, which re-lexes every item's children from `text` to
2190
+ * `paragraph`. Item 0's own `text` is unchanged, so a naive guard would reuse
2191
+ * and keep stale spans. Bail when `loose` flips.
2192
+ */
2193
+ updateStreamedList(stack, oldToken, newToken) {
2194
+ if (!(stack instanceof import_ui.Stack)) return false;
2195
+ if (newToken.items.length < oldToken.items.length || oldToken.items.length === 0) return false;
2196
+ if (oldToken.ordered !== newToken.ordered) return false;
2197
+ if ((oldToken.start ?? 1) !== (newToken.start ?? 1)) return false;
2198
+ if (oldToken.loose !== newToken.loose) return false;
2199
+ if (stack.children.length !== oldToken.items.length) return false;
2200
+ const lastRetained = oldToken.items.length - 1;
2201
+ for (let i = 0; i < lastRetained; i++) {
2202
+ if (oldToken.items[i].text !== newToken.items[i].text) return false;
2203
+ }
2204
+ const availableWidth = this.activeBlockMetrics?.availableWidth ?? this.maxWidth;
2205
+ const t = this.theme;
2206
+ const tailEntity = stack.children[lastRetained];
2207
+ if (oldToken.items[lastRetained].text !== newToken.items[lastRetained].text) {
2208
+ if (!("setSpans" in tailEntity)) return false;
2209
+ tailEntity.setSpans(
2210
+ this.listItemSpans(newToken, lastRetained)
2211
+ );
2212
+ }
2213
+ for (let i = oldToken.items.length; i < newToken.items.length; i++) {
2214
+ stack.add(this.listItemRichText(newToken, i, availableWidth, t));
2215
+ }
2216
+ const last = stack.children.at(-1);
2217
+ if (last) stack.resizeLastChild(last);
2218
+ return true;
2219
+ }
2220
+ /**
2221
+ * Reuse a streamed image-bearing paragraph's `Stack` instead of rebuilding it.
2222
+ *
2223
+ * Returns `false` to mean "rebuild instead", and every rejection happens before
2224
+ * any mutation, so a refused reuse leaves the entity exactly as it was.
2225
+ *
2226
+ * This was the last silent fallthrough in the in-place reuse path. A paragraph
2227
+ * holding an image renders as a `Stack` of alternating text runs and images
2228
+ * rather than one `RichText`, so it has no `setSpans` and failed the ordinary
2229
+ * paragraph gate — with no `else`, which is what made the miss invisible:
2230
+ * `inPlaceUpdates` stayed flat while `entitiesRebuilt` climbed. Measured on a
2231
+ * six-chunk stream, `inPlaceUpdates` 0 / `entitiesRebuilt` 4 with an image
2232
+ * against 4 / 0 for the identical shape without one. Every rebuild also
2233
+ * re-created the `Image`, discarding its decoded bitmap and its corrected
2234
+ * intrinsic size.
2235
+ *
2236
+ * It is *only* a performance path. The obvious worry — that a fresh `Image`
2237
+ * starts at `loaded = false` and so repaints its placeholder slab — was
2238
+ * measured and does not happen: sampling the real canvas pixel at the image
2239
+ * centre in both Chromium and Firefox gives zero placeholder frames after the
2240
+ * first paint, at 60ms and at 0ms between chunks, because a cached bitmap
2241
+ * decodes before the next frame.
2242
+ *
2243
+ * The reuse is deliberately narrow: **only a growing trailing text run**. Probed
2244
+ * against `marked@18.0.7`, that is the shape a stream actually produces once an
2245
+ * image has closed — the image token's `raw` and its index are then stable while
2246
+ * trailing prose grows, and the token list settles at
2247
+ * `[…, image, text]` and stops changing length. Anything else (a new image
2248
+ * arriving, an image token changing, a run appearing before the last image)
2249
+ * falls through to the rebuild, which is correct and rare.
2250
+ *
2251
+ * Note the child list is not one entity per token: consecutive non-image tokens
2252
+ * are merged into one `RichText` by the render arm's `flushText`, so
2253
+ * `[text, text, image]` is two children, not three. The guards therefore compare
2254
+ * *token runs* split at the last image, never token index against child index.
2255
+ */
2256
+ updateImageParagraph(entity, oldToken, newToken) {
2257
+ if (!(entity instanceof import_ui.Stack)) return false;
2258
+ const oldTokens = oldToken.tokens;
2259
+ const newTokens = newToken.tokens;
2260
+ if (!oldTokens || !newTokens) return false;
2261
+ const oldLastImage = lastIndexOfImage(oldTokens);
2262
+ const newLastImage = lastIndexOfImage(newTokens);
2263
+ if (oldLastImage < 0 || newLastImage < 0) return false;
2264
+ if (oldLastImage !== newLastImage) return false;
2265
+ for (let i = 0; i <= newLastImage; i++) {
2266
+ if (oldTokens[i].raw !== newTokens[i].raw) return false;
2267
+ }
2268
+ const oldTail = oldTokens.slice(oldLastImage + 1);
2269
+ const newTail = newTokens.slice(newLastImage + 1);
2270
+ if (newTail.length === 0) return false;
2271
+ const oldTailRaw = oldTail.map((t2) => t2.raw).join("");
2272
+ const newTailRaw = newTail.map((t2) => t2.raw).join("");
2273
+ if (!newTailRaw.startsWith(oldTailRaw)) return false;
2274
+ const expectedOldChildren = expectedImageParagraphChildren(oldTokens);
2275
+ if (entity.children.length !== expectedOldChildren) return false;
2276
+ const t = this.theme;
2277
+ const availableWidth = this.activeBlockMetrics?.availableWidth ?? this.maxWidth;
2278
+ if (oldTail.length === 0) {
2279
+ entity.add(this.inlineRunRichText(newTail, availableWidth, t));
2280
+ } else {
2281
+ const tailEntity = entity.children[entity.children.length - 1];
2282
+ if (!(tailEntity instanceof import_ui.RichText)) return false;
2283
+ tailEntity.setSpans(this.inlineRunSpans(newTail, t));
2284
+ }
2285
+ const last = entity.children[entity.children.length - 1];
2286
+ if (last) entity.resizeLastChild(last);
2287
+ return true;
2288
+ }
2289
+ /**
2290
+ * Reuse a streamed table's `Table` entity instead of rebuilding every cell.
2291
+ *
2292
+ * Returns `false` to mean "rebuild instead", and every rejection happens before
2293
+ * any mutation, so a refused reuse leaves the entity exactly as it was.
2294
+ *
2295
+ * A `table` token carries every row, so the rebuild path costs Θ(C·N²)
2296
+ * `RichText` constructions across a stream — and a further 2×, because
2297
+ * `Table.layout()` re-runs `fitCell` on every cell. This was the last block
2298
+ * type without an in-place path.
2299
+ *
2300
+ * Two shapes have to be handled, because of how `marked` lexes a growing table
2301
+ * (probed against 18.0.7): a partial row is materialized immediately as a FULL
2302
+ * row padded with empty cells, and its cells are then filled one at a time. A
2303
+ * 2×2 table passes through eleven distinct row states, of which only two are
2304
+ * clean row appends. So handling appends alone would reject most chunks and
2305
+ * leave the quadratic cost essentially in place:
2306
+ *
2307
+ * 1. the last row's cells are rewritten in place via `setSpans`, and
2308
+ * 2. genuinely new rows go through `Table.appendRows`.
2309
+ *
2310
+ * Cells are compared by `text`, never `raw` — a table cell has no `raw` at all
2311
+ * (its keys are `text`/`tokens`/`header`/`align`).
2312
+ */
2313
+ updateStreamedTable(entity, oldToken, newToken) {
2314
+ if (!(entity instanceof import_ui.Table)) return false;
2315
+ if (oldToken.header.length !== newToken.header.length) return false;
2316
+ for (let c = 0; c < oldToken.header.length; c++) {
2317
+ if (oldToken.header[c].text !== newToken.header[c].text) return false;
2318
+ }
2319
+ if (newToken.rows.length < oldToken.rows.length) return false;
2320
+ if (entity.rows.length !== oldToken.rows.length) return false;
2321
+ const lastRetained = oldToken.rows.length - 1;
2322
+ for (let r = 0; r < lastRetained; r++) {
2323
+ const oldRow = oldToken.rows[r];
2324
+ const newRow = newToken.rows[r];
2325
+ for (let c = 0; c < oldToken.header.length; c++) {
2326
+ if (oldRow[c]?.text !== newRow[c]?.text) return false;
2327
+ }
2328
+ }
2329
+ if (lastRetained >= 0) {
2330
+ for (let c = 0; c < oldToken.header.length; c++) {
2331
+ const cell = entity.rows[lastRetained]?.[c];
2332
+ if (!(cell instanceof import_ui.RichText)) return false;
2333
+ }
2334
+ }
2335
+ const t = this.theme;
2336
+ let changed = false;
2337
+ if (lastRetained >= 0) {
2338
+ const oldRow = oldToken.rows[lastRetained];
2339
+ const newRow = newToken.rows[lastRetained];
2340
+ for (let c = 0; c < oldToken.header.length; c++) {
2341
+ if (oldRow[c]?.text === newRow[c]?.text) continue;
2342
+ const cell = entity.rows[lastRetained][c];
2343
+ cell.setSpans(this.tableCellSpans(newRow[c], t));
2344
+ changed = true;
2345
+ }
2346
+ }
2347
+ if (newToken.rows.length > oldToken.rows.length) {
2348
+ const added = newToken.rows.slice(oldToken.rows.length).map((row) => row.map((cell) => this.tableCellRichText(cell, false, t)));
2349
+ entity.appendRows(added);
2350
+ } else if (changed) {
2351
+ entity.layout();
2352
+ }
2353
+ return true;
2354
+ }
2355
+ updateBlockquoteTail(container, oldInner, newInner) {
2356
+ if (oldInner.length !== newInner.length || newInner.length === 0) return false;
2357
+ const tail = newInner.length - 1;
2358
+ for (let i = 0; i < tail; i++) {
2359
+ if (oldInner[i].raw !== newInner[i].raw) return false;
2360
+ }
2361
+ const oldTail = oldInner[tail];
2362
+ const newTail = newInner[tail];
2363
+ if (oldTail.type !== newTail.type) return false;
2364
+ const innerStack = container.children[1];
2365
+ if (!(innerStack instanceof import_ui.Stack)) return false;
2366
+ const wrapper = innerStack.children.at(-1);
2367
+ if (!wrapper || wrapper.children.length !== 1) return false;
2368
+ const entity = wrapper.children[0];
2369
+ if (!this.producesEntity(newTail)) return false;
2370
+ if (newTail.type === "paragraph" && "setSpans" in entity) {
2371
+ entity.setSpans(
2372
+ this.literalParagraphSpans(newTail)
2373
+ );
2374
+ } else if (newTail.type === "heading" && "setSpans" in entity) {
2375
+ if (oldTail.depth !== newTail.depth) {
2376
+ return false;
2377
+ }
2378
+ entity.setSpans(
2379
+ this.headingSpans(newTail)
2380
+ );
2381
+ } else if (newTail.type === "code" && entity instanceof CodeBlock && !rendersAsMath(newTail)) {
2382
+ const codeToken = newTail;
2383
+ entity.setCode(codeToken.text, codeToken.lang ?? void 0);
2384
+ } else {
2385
+ return false;
2386
+ }
2387
+ wrapper.width = entity.x + entity.width;
2388
+ wrapper.height = entity.height;
2389
+ innerStack.resizeLastChild(wrapper);
2390
+ const border = container.children[0];
2391
+ if (border instanceof QuoteBorder) border.height = innerStack.height || 20;
2392
+ container.height = Math.max(border?.height ?? 0, innerStack.height);
2393
+ return true;
2394
+ }
2395
+ /**
2396
+ * Spans for a heading being updated in place.
2397
+ *
2398
+ * Kept in lockstep with the `heading` arm of {@link renderToken}, which builds
2399
+ * its `RichText` through `renderInlineToRichText`: same `collectSpans` call and
2400
+ * the same `decodeEntities` fallback when a heading has no inline tokens (`##`
2401
+ * with no text yet, which a stream produces before its first word arrives). A
2402
+ * plain `token.text` fallback here would leave an entity-bearing heading
2403
+ * undecoded on the in-place path but decoded on a fresh render.
2404
+ */
2405
+ headingSpans(token) {
2406
+ const spans = [];
2407
+ if (token.tokens && token.tokens.length > 0) {
2408
+ collectSpans(token.tokens, {}, this.theme, spans);
2409
+ }
2410
+ if (spans.length === 0) spans.push({ text: decodeEntities(token.text) });
2411
+ return spans;
2412
+ }
2413
+ /**
2414
+ * Spans for the trailing paragraph with its last unclosed inline construct
2415
+ * rendered as though it had closed, or `null` when there is nothing to guess.
2416
+ *
2417
+ * `null` is the answer for every `'literal'` stream, every closed or absent
2418
+ * stream, and any trailing paragraph whose syntax is all balanced — so the
2419
+ * caller falls back to {@link literalParagraphSpans} and pays nothing.
2420
+ *
2421
+ * Only the paragraph's LAST inline token is scanned. An unclosed construct can
2422
+ * only be there: anything that closed is already its own `strong`/`em`/
2423
+ * `codespan`/`link` token, so a syntax character surviving into a trailing
2424
+ * plain-text run is one `marked` could not pair. Scanning the whole raw string
2425
+ * instead would re-find the markers of already-closed constructs.
2426
+ */
2427
+ optimisticParagraphSpans(token) {
2428
+ if (this.streamIncompleteMode !== "optimistic") return null;
2429
+ if (this.streamController?.state !== "open") return null;
2430
+ const inline = token.tokens;
2431
+ if (!inline || inline.length === 0) return null;
2432
+ let runLength = 1;
2433
+ let runText;
2434
+ const last = inline[inline.length - 1];
2435
+ const prev = inline.length > 1 ? inline[inline.length - 2] : null;
2436
+ const isFlatText = (token2) => token2.type === "text" && !token2.tokens?.length;
2437
+ if (last.type === "link" && last.raw === last.text && prev !== null && isFlatText(prev) && prev.text.endsWith("](")) {
2438
+ runLength = 2;
2439
+ runText = prev.text + last.raw;
2440
+ } else if (isFlatText(last)) {
2441
+ runText = last.text;
2442
+ } else {
2443
+ return null;
2444
+ }
2445
+ const found = findUnclosedInline(runText);
2446
+ if (!found) return null;
2447
+ const spans = [];
2448
+ if (inline.length > runLength) {
2449
+ collectSpans(inline.slice(0, -runLength), {}, this.theme, spans);
2450
+ }
2451
+ const head = runText.slice(0, found.at);
2452
+ if (head) spans.push({ text: decodeEntities(head) });
2453
+ let content = runText.slice(found.contentAt);
2454
+ if (found.kind === "link") {
2455
+ const close = content.indexOf("](");
2456
+ if (close !== -1) content = content.slice(0, close);
2457
+ }
2458
+ if (!content) return null;
2459
+ const style = this.optimisticStyle(found.kind);
2460
+ spans.push({ text: decodeEntities(content), style });
2461
+ return spans;
2462
+ }
2463
+ /** Display style for a guessed-closed construct. */
2464
+ optimisticStyle(kind) {
2465
+ switch (kind) {
2466
+ case "strong":
2467
+ return { bold: true };
2468
+ case "em":
2469
+ return { italic: true };
2470
+ case "codespan":
2471
+ return { color: this.theme.codeColor, fontFamily: this.theme.codeFont };
2472
+ // A link with no closing paren has no href, so it renders as plain text —
2473
+ // no link color and no click affordance for a destination nobody has yet.
2474
+ case "link":
2475
+ return void 0;
2476
+ }
2477
+ }
2478
+ /**
2479
+ * Re-render the paragraph currently showing a guess from its own tokens, with
2480
+ * no overlay, and forget it.
2481
+ *
2482
+ * Idempotent and free when no guess is live, which is what lets `close()`,
2483
+ * `abort()`, and a mid-stream staleness check all call it unconditionally.
2484
+ */
2485
+ /**
2486
+ * Start the MathJax load, and re-typeset this document once it resolves.
2487
+ *
2488
+ * Called from two places, for two different reasons:
2489
+ *
2490
+ * - When an OPEN math fence is rendered. This is a prefetch, and it is what
2491
+ * makes the lazy load invisible while streaming: the module starts loading
2492
+ * the moment a formula begins arriving, several chunks before its closing
2493
+ * fence, so by the time the fence closes the converter is usually already
2494
+ * installed and the formula typesets synchronously on the normal path.
2495
+ * - When a CLOSED fence could not be typeset because the module is not ready.
2496
+ * That is the case a rebuild actually exists for: a document constructed with
2497
+ * math already complete, or a stream that closed a fence faster than the
2498
+ * module loaded.
2499
+ *
2500
+ * Idempotent per instance. Concurrent callers coalesce onto the one cached
2501
+ * module promise, and `mathLoadPending` keeps a second rebuild from being
2502
+ * queued while the first is outstanding.
2503
+ */
2504
+ ensureMathJax() {
2505
+ if (mathConverter || this.mathLoadPending || this.isDestroyed) return;
2506
+ this.mathLoadPending = true;
2507
+ void preloadMathJax().then(() => {
2508
+ this.mathLoadPending = false;
2509
+ if (this.isDestroyed) return;
2510
+ if (mathConverter) this.retypesetFromTokens();
2511
+ this.flushAppendSettledWaiters();
2512
+ });
2513
+ }
2514
+ /**
2515
+ * Rebuild every block from the tokens already lexed, without re-lexing.
2516
+ *
2517
+ * Used only when MathJax arrives after a formula has already been rendered as
2518
+ * source. Rebuilding wholesale rather than surgically replacing the math blocks
2519
+ * is the deliberate choice: `tokenChildPrefix` maps token indices to child
2520
+ * slots positionally, so swapping one child in place would have to keep that
2521
+ * mapping, the `Stack`'s cached box, and every following sibling's position in
2522
+ * agreement by hand. Re-rendering the same token list in the same order leaves
2523
+ * the mapping trivially correct, and this runs at most once per document — the
2524
+ * same cost as the `setContent` rebuild that already exists.
2525
+ *
2526
+ * The optimistic tail is dropped first. Its `entity` is about to be destroyed,
2527
+ * so the pointer would dangle; unwinding restores literal spans, and if the
2528
+ * stream is still open the next chunk re-applies a guess.
2529
+ */
2530
+ retypesetFromTokens() {
2531
+ this.unwindOptimisticTail();
2532
+ const tokens = this.tokens;
2533
+ while (this.content.children.length > 0) {
2534
+ this.content.children[this.content.children.length - 1].destroy();
2535
+ }
2536
+ for (const token of tokens) {
2537
+ const el = this.renderToken(token);
2538
+ if (el) this.content.add(el);
2539
+ }
2540
+ this.width = this.content.width;
2541
+ this.height = this.content.height;
2542
+ this.scene?.markDirty();
2543
+ }
2544
+ unwindOptimisticTail() {
2545
+ const tail = this.optimisticTail;
2546
+ this.optimisticTail = null;
2547
+ if (!tail || this.isDestroyed) return;
2548
+ const entity = tail.entity;
2549
+ if (!entity.setSpans || entity.parent !== this.content) return;
2550
+ entity.setSpans(this.literalParagraphSpans(tail.token));
2551
+ if (this.content.children.at(-1) === entity) {
2552
+ this.content.resizeLastChild(entity);
2553
+ } else {
2554
+ this.content.layout();
2555
+ }
2556
+ this.width = this.content.width;
2557
+ this.height = this.content.height;
2558
+ this.scene?.markDirty();
2559
+ }
2560
+ /**
2561
+ * Drop a guess that is no longer on the document's trailing paragraph.
2562
+ *
2563
+ * A coalesced append can add a block after the paragraph that owns the guess,
2564
+ * at which point the guess is frozen — the construct can never close, because
2565
+ * no further text lands in that paragraph. Without this the stale styling would
2566
+ * survive until `close()`.
2567
+ *
2568
+ * `writtenThisPass` is the entity whose spans this reconcile already rewrote,
2569
+ * if any: for that one, literal spans are on screen already and re-rendering it
2570
+ * would be wasted layout, so only the bookkeeping is cleared.
2571
+ */
2572
+ dropStaleOptimisticTail(trailing, writtenThisPass) {
2573
+ const tail = this.optimisticTail;
2574
+ if (!tail || tail.entity === trailing) return;
2575
+ if (tail.entity === writtenThisPass) {
2576
+ this.optimisticTail = null;
2577
+ return;
2578
+ }
2579
+ this.unwindOptimisticTail();
2580
+ }
2581
+ /**
2582
+ * Resolve once every in-flight worker append has actually been applied.
2583
+ *
2584
+ * Committing text is not the same as the document reflecting it: `append()`
2585
+ * reaches `dispatchAppend()`, which `postMessage()`s and returns, and the reply
2586
+ * that runs `updateTokens()` lands later. Without waiting here, `close()` could
2587
+ * resolve — and `onStable` fire — against a document missing its last chunk.
2588
+ *
2589
+ * An outstanding lazy MathJax load counts as unsettled for the same reason. A
2590
+ * document whose formulas are still TeX source is not final in any sense a
2591
+ * caller of `onStable` cares about: the boxes are the wrong size, so measuring
2592
+ * or exporting there would capture placeholders.
2593
+ */
2594
+ waitForAppendSettled() {
2595
+ if (!this.appendInFlight && !this.mathLoadPending) return Promise.resolve();
2596
+ return new Promise((resolve) => {
2597
+ this.appendSettledWaiters.push(resolve);
2598
+ });
2599
+ }
2600
+ /**
2601
+ * Release settlement waiters, but only once nothing is outstanding.
2602
+ *
2603
+ * Called at the very END of the worker callback, after its coalesced-re-dispatch
2604
+ * check, rather than wherever `appendInFlight` goes false. Within that callback
2605
+ * `appendInFlight` is cleared and then, if another chunk arrived while the
2606
+ * request was in flight, set straight back to `true` by the re-dispatch — both
2607
+ * synchronously, before anything watching the flag could observe the gap. Only
2608
+ * checking here, after that, waits through the re-dispatch instead of resolving
2609
+ * one chunk early.
2610
+ */
2611
+ flushAppendSettledWaiters() {
2612
+ if (this.appendInFlight || this.mathLoadPending || this.appendSettledWaiters.length === 0) {
2613
+ return;
2614
+ }
2615
+ const waiters = this.appendSettledWaiters;
2616
+ this.appendSettledWaiters = [];
2617
+ for (const resolve of waiters) resolve();
2618
+ }
2619
+ /** Throw if a public mutation is attempted from inside an `onStable` callback. */
2620
+ assertNotInStableCallback(method) {
2621
+ if (this.inStableCallback) {
2622
+ throw new Error(`Markdown.${method}() cannot be called from an onStable callback`);
2623
+ }
2624
+ }
1636
2625
  updateTokens(newTokens, knownMatchLen) {
1637
2626
  const oldTokens = this.tokens;
1638
2627
  const oldChildren = [...this.content.children];
@@ -1652,11 +2641,18 @@ var Markdown = class extends import_ui.UIComponent {
1652
2641
  }
1653
2642
  const oldTokenToChild = this.tokenChildPrefix;
1654
2643
  const rawMatchLen = matchLen;
2644
+ let pendingTail = null;
2645
+ let spansWrittenTo = null;
1655
2646
  const lastTokenSameType = matchLen === oldTokens.length - 1 && matchLen < newTokens.length && oldTokens[matchLen]?.type === newTokens[matchLen]?.type;
1656
2647
  if (lastTokenSameType && newTokens[matchLen]?.type === "code") {
1657
2648
  const existingEntity = oldChildren[oldTokenToChild[matchLen]];
1658
2649
  const codeToken = newTokens[matchLen];
1659
- if (existingEntity instanceof CodeBlock) {
2650
+ const oldCodeToken = oldTokens[matchLen];
2651
+ const isMath = rendersAsMath(codeToken);
2652
+ if (isMath && rendersAsMath(oldCodeToken) && oldCodeToken.text === codeToken.text) {
2653
+ this.streamStats.inPlaceUpdates++;
2654
+ matchLen++;
2655
+ } else if (existingEntity instanceof CodeBlock && !isMath) {
1660
2656
  existingEntity.setCode(codeToken.text, codeToken.lang ?? void 0);
1661
2657
  this.streamStats.inPlaceUpdates++;
1662
2658
  matchLen++;
@@ -1665,17 +2661,63 @@ var Markdown = class extends import_ui.UIComponent {
1665
2661
  } else if (lastTokenSameType && newTokens[matchLen]?.type === "paragraph") {
1666
2662
  const entityIdx = oldTokenToChild[matchLen];
1667
2663
  const existingEntity = oldChildren[entityIdx];
1668
- if (existingEntity && "setSpans" in existingEntity) {
2664
+ if (existingEntity && "setSpans" in existingEntity && !paragraphHasImage(newTokens[matchLen])) {
1669
2665
  const pToken = newTokens[matchLen];
1670
- const t = this.theme;
1671
- const spans = [];
1672
- if (pToken.tokens && pToken.tokens.length > 0) {
1673
- collectSpans(pToken.tokens, {}, t, spans);
1674
- }
1675
- if (spans.length === 0) {
1676
- spans.push({ text: pToken.text });
1677
- }
1678
- existingEntity.setSpans(spans);
2666
+ const isTrailing = matchLen === newTokens.length - 1;
2667
+ const optimistic = isTrailing ? this.optimisticParagraphSpans(pToken) : null;
2668
+ existingEntity.setSpans(optimistic ?? this.literalParagraphSpans(pToken));
2669
+ spansWrittenTo = existingEntity;
2670
+ if (optimistic) pendingTail = { entity: existingEntity, token: pToken };
2671
+ this.streamStats.inPlaceUpdates++;
2672
+ matchLen++;
2673
+ this.content.resizeLastChild(existingEntity);
2674
+ } else if (existingEntity && this.updateImageParagraph(
2675
+ existingEntity,
2676
+ oldTokens[matchLen],
2677
+ newTokens[matchLen]
2678
+ )) {
2679
+ this.streamStats.inPlaceUpdates++;
2680
+ matchLen++;
2681
+ this.content.resizeLastChild(existingEntity);
2682
+ }
2683
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "heading") {
2684
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2685
+ const hToken = newTokens[matchLen];
2686
+ const oldToken = oldTokens[matchLen];
2687
+ if (existingEntity && "setSpans" in existingEntity && oldToken?.depth === hToken.depth) {
2688
+ existingEntity.setSpans(this.headingSpans(hToken));
2689
+ spansWrittenTo = existingEntity;
2690
+ this.streamStats.inPlaceUpdates++;
2691
+ matchLen++;
2692
+ this.content.resizeLastChild(existingEntity);
2693
+ }
2694
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "blockquote") {
2695
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2696
+ const newInner = newTokens[matchLen].tokens;
2697
+ const oldInner = oldTokens[matchLen].tokens;
2698
+ if (existingEntity instanceof MarkdownContainer && newInner && oldInner && this.updateBlockquoteTail(existingEntity, oldInner, newInner)) {
2699
+ this.streamStats.inPlaceUpdates++;
2700
+ matchLen++;
2701
+ this.content.resizeLastChild(existingEntity);
2702
+ }
2703
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "list") {
2704
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2705
+ if (existingEntity && this.updateStreamedList(
2706
+ existingEntity,
2707
+ oldTokens[matchLen],
2708
+ newTokens[matchLen]
2709
+ )) {
2710
+ this.streamStats.inPlaceUpdates++;
2711
+ matchLen++;
2712
+ this.content.resizeLastChild(existingEntity);
2713
+ }
2714
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "table") {
2715
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2716
+ if (existingEntity && this.updateStreamedTable(
2717
+ existingEntity,
2718
+ oldTokens[matchLen],
2719
+ newTokens[matchLen]
2720
+ )) {
1679
2721
  this.streamStats.inPlaceUpdates++;
1680
2722
  matchLen++;
1681
2723
  this.content.resizeLastChild(existingEntity);
@@ -1693,10 +2735,24 @@ var Markdown = class extends import_ui.UIComponent {
1693
2735
  }
1694
2736
  }
1695
2737
  }
2738
+ const lastIndex = newTokens.length - 1;
1696
2739
  for (let i = matchLen; i < newTokens.length; i++) {
1697
2740
  const el = this.renderToken(newTokens[i]);
1698
- if (el) this.content.add(el);
2741
+ if (!el) continue;
2742
+ this.content.add(el);
2743
+ if (i === lastIndex && newTokens[i].type === "paragraph" && "setSpans" in el) {
2744
+ const pToken = newTokens[i];
2745
+ const optimistic = this.optimisticParagraphSpans(pToken);
2746
+ if (optimistic) {
2747
+ el.setSpans(optimistic);
2748
+ this.content.resizeLastChild(el);
2749
+ pendingTail = { entity: el, token: pToken };
2750
+ spansWrittenTo = el;
2751
+ }
2752
+ }
1699
2753
  }
2754
+ this.dropStaleOptimisticTail(pendingTail?.entity ?? null, spansWrittenTo);
2755
+ if (pendingTail) this.optimisticTail = pendingTail;
1700
2756
  this.setTokens(newTokens, rawMatchLen);
1701
2757
  this.width = this.content.width;
1702
2758
  this.height = this.content.height;
@@ -1759,6 +2815,10 @@ var Markdown = class extends import_ui.UIComponent {
1759
2815
  availableWidth: this.maxWidth
1760
2816
  };
1761
2817
  const availableWidth = metrics.availableWidth;
2818
+ if (containsInlineMath(token)) {
2819
+ if (!mathConverter) this.ensureMathJax();
2820
+ this.subscribeInlineMathRepaint();
2821
+ }
1762
2822
  switch (token.type) {
1763
2823
  // ── Headings ─────────────────────────────────────────────────────
1764
2824
  case "heading": {
@@ -1780,7 +2840,7 @@ var Markdown = class extends import_ui.UIComponent {
1780
2840
  // ── Paragraphs ───────────────────────────────────────────────────
1781
2841
  case "paragraph": {
1782
2842
  const pToken = token;
1783
- if (!pToken.tokens || !pToken.tokens.some((t2) => t2.type === "image")) {
2843
+ if (!paragraphHasImage(pToken)) {
1784
2844
  return renderInlineToRichText(
1785
2845
  pToken.tokens,
1786
2846
  pToken.text,
@@ -1800,43 +2860,14 @@ var Markdown = class extends import_ui.UIComponent {
1800
2860
  let currentTokens = [];
1801
2861
  const flushText = () => {
1802
2862
  if (currentTokens.length > 0) {
1803
- stack.add(
1804
- renderInlineToRichText(
1805
- currentTokens,
1806
- "",
1807
- bodyFont,
1808
- t.textColor,
1809
- availableWidth,
1810
- t,
1811
- this.selectable,
1812
- this.onLinkClick
1813
- )
1814
- );
2863
+ stack.add(this.inlineRunRichText(currentTokens, availableWidth, t));
1815
2864
  currentTokens = [];
1816
2865
  }
1817
2866
  };
1818
2867
  for (const child of pToken.tokens) {
1819
2868
  if (child.type === "image") {
1820
2869
  flushText();
1821
- const imgToken = child;
1822
- const initialWidth = Math.min(800, availableWidth);
1823
- const initialHeight = Math.round(initialWidth * 0.6);
1824
- const img = new import_ui.Image(imgToken.href, {
1825
- width: initialWidth,
1826
- height: initialHeight,
1827
- alt: imgToken.text,
1828
- radius: 8,
1829
- onLoad: () => {
1830
- const bmp = img.bitmap;
1831
- if (bmp && bmp.naturalWidth && bmp.naturalHeight) {
1832
- const aspect = bmp.naturalHeight / bmp.naturalWidth;
1833
- img.width = Math.min(bmp.naturalWidth, availableWidth);
1834
- img.height = Math.round(img.width * aspect);
1835
- if (this.scene) this.scene.markDirty();
1836
- }
1837
- }
1838
- });
1839
- stack.add(img);
2870
+ stack.add(this.paragraphImage(child, availableWidth));
1840
2871
  } else {
1841
2872
  currentTokens.push(child);
1842
2873
  }
@@ -1848,13 +2879,22 @@ var Markdown = class extends import_ui.UIComponent {
1848
2879
  case "code": {
1849
2880
  const codeToken = token;
1850
2881
  const lang = (codeToken.lang ?? "").toLowerCase();
1851
- if (lang === "math" || lang === "latex" || lang === "tex") {
2882
+ if (MATH_LANGS.has(lang)) this.ensureMathJax();
2883
+ if (rendersAsMath(codeToken)) {
1852
2884
  const mathData = renderMathToSVGDataURI(codeToken.text, true);
1853
2885
  if (mathData) {
2886
+ const intrinsicW = exToPx(mathData.widthEx, t.fontSize);
2887
+ const intrinsicH = exToPx(mathData.heightEx, t.fontSize);
1854
2888
  const mathImg = new import_ui.Image(mathData.uri, {
1855
- width: Math.min(availableWidth, mathData.width),
1856
- height: mathData.height * Math.min(1, availableWidth / mathData.width),
1857
- alt: codeToken.text
2889
+ width: Math.min(availableWidth, intrinsicW),
2890
+ height: intrinsicH * Math.min(1, availableWidth / intrinsicW),
2891
+ alt: codeToken.text,
2892
+ // The SVG decodes asynchronously and Image paints a placeholder
2893
+ // until it lands. Without this an `onDemand` scene, which repaints
2894
+ // only when marked dirty, leaves the formula a blank slab forever.
2895
+ onLoad: () => {
2896
+ this.scene?.markDirty();
2897
+ }
1858
2898
  });
1859
2899
  const wrapper = new MarkdownContainer();
1860
2900
  mathImg.x = 16;
@@ -1903,62 +2943,22 @@ var Markdown = class extends import_ui.UIComponent {
1903
2943
  container.height = Math.max(border.height, innerStack.height);
1904
2944
  return container;
1905
2945
  }
1906
- // ── Lists ────────────────────────────────────────────────────────
2946
+ // ── Lists ────────────────────────────────────────────────
1907
2947
  case "list": {
1908
2948
  const listToken = token;
1909
2949
  const listStack = new import_ui.Stack({ direction: "vertical", gap: 6 });
1910
2950
  for (let i = 0; i < listToken.items.length; i++) {
1911
- const item = listToken.items[i];
1912
- const num = Number(listToken.start ?? 1) + i;
1913
- const contentSpans = [];
1914
- if (item.tokens && item.tokens.length > 0) {
1915
- for (const inner of item.tokens) {
1916
- if (inner.type === "text" && "tokens" in inner && inner.tokens?.length) {
1917
- collectSpans(inner.tokens, {}, t, contentSpans);
1918
- } else if ("tokens" in inner && inner.tokens?.length) {
1919
- collectSpans(inner.tokens, {}, t, contentSpans);
1920
- } else if ("text" in inner) {
1921
- contentSpans.push({
1922
- text: decodeEntities(inner.text)
1923
- });
1924
- }
1925
- }
1926
- } else {
1927
- contentSpans.push({ text: decodeEntities(item.text) });
1928
- }
1929
- const itemIsRtl = import_core.BidiResolver.getBaseLevel(contentSpans.map((s) => s.text).join("")) % 2 === 1;
1930
- const itemSpans = itemIsRtl ? [...contentSpans, { text: listToken.ordered ? ` .${num}` : " \u2022" }] : [{ text: listToken.ordered ? `${num}. ` : "\u2022 " }, ...contentSpans];
1931
- const itemRt = new import_ui.RichText(itemSpans, {
1932
- font: bodyFont,
1933
- color: t.textColor,
1934
- maxWidth: Math.max(0, availableWidth - 24),
1935
- linkColor: "#38bdf8",
1936
- selectable: this.selectable,
1937
- onLinkClick: this.onLinkClick
1938
- });
1939
- itemRt.x = 12;
1940
- listStack.add(itemRt);
2951
+ listStack.add(this.listItemRichText(listToken, i, availableWidth, t));
1941
2952
  }
1942
2953
  return listStack;
1943
2954
  }
1944
2955
  // ── Table ────────────────────────────────────────────────────────
1945
2956
  case "table": {
1946
2957
  const tblToken = token;
1947
- const buildCell = (cell, header) => {
1948
- const spans = [];
1949
- collectSpans(cell.tokens, {}, t, spans);
1950
- if (spans.length === 0) return decodeEntities(cell.text);
1951
- return new import_ui.RichText(spans, {
1952
- font: `${t.fontSize - 2}px ${t.bodyFont}`,
1953
- color: header ? t.headingColor : t.textColor,
1954
- baseStyle: header ? { bold: true } : void 0,
1955
- linkColor: "#38bdf8",
1956
- selectable: this.selectable,
1957
- onLinkClick: this.onLinkClick
1958
- });
1959
- };
1960
- const headers = tblToken.header.map((cell) => buildCell(cell, true));
1961
- const rows = tblToken.rows.map((row) => row.map((cell) => buildCell(cell, false)));
2958
+ const headers = tblToken.header.map((cell) => this.tableCellRichText(cell, true, t));
2959
+ const rows = tblToken.rows.map(
2960
+ (row) => row.map((cell) => this.tableCellRichText(cell, false, t))
2961
+ );
1962
2962
  return new import_ui.Table({
1963
2963
  headers,
1964
2964
  rows,
@@ -2009,5 +3009,7 @@ var Markdown = class extends import_ui.UIComponent {
2009
3009
  CodeBlock,
2010
3010
  Markdown,
2011
3011
  codeAtlas,
2012
- codeAtlasStats
3012
+ codeAtlasStats,
3013
+ isMathJaxReady,
3014
+ preloadMathJax
2013
3015
  });