@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/README.md +119 -4
- package/dist/Markdown.d.ts +350 -0
- package/dist/StreamController.d.ts +53 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1131 -129
- package/dist/index.mjs +1119 -128
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
BidiResolver,
|
|
4
4
|
Entity,
|
|
5
5
|
GlyphRasterAtlas,
|
|
6
|
+
OBJECT_REPLACEMENT,
|
|
6
7
|
prepareContentGrid,
|
|
7
8
|
SVGEntity,
|
|
8
9
|
beginVectoUserTiming,
|
|
@@ -38,7 +39,10 @@ var StreamControllerImpl = class {
|
|
|
38
39
|
this.signal = options.signal;
|
|
39
40
|
this.onSignalAbort = () => this.abort(this.signal?.reason);
|
|
40
41
|
if (this.signal?.aborted) this.abort(this.signal.reason);
|
|
41
|
-
else
|
|
42
|
+
else
|
|
43
|
+
this.signal?.addEventListener("abort", this.onSignalAbort, {
|
|
44
|
+
once: true
|
|
45
|
+
});
|
|
42
46
|
}
|
|
43
47
|
host;
|
|
44
48
|
maxBufferedChars;
|
|
@@ -126,10 +130,33 @@ var StreamControllerImpl = class {
|
|
|
126
130
|
return closePromise;
|
|
127
131
|
}
|
|
128
132
|
this.currentState = "closed";
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
+
let settled;
|
|
134
|
+
try {
|
|
135
|
+
settled = this.host.onClose?.();
|
|
136
|
+
} catch (error) {
|
|
137
|
+
this.cleanup();
|
|
138
|
+
this.rejectPendingClose(error);
|
|
139
|
+
return closePromise;
|
|
140
|
+
}
|
|
141
|
+
if (settled === void 0) {
|
|
142
|
+
this.cleanup();
|
|
143
|
+
this.resolveClose?.();
|
|
144
|
+
this.resolveClose = null;
|
|
145
|
+
this.rejectClose = null;
|
|
146
|
+
return closePromise;
|
|
147
|
+
}
|
|
148
|
+
void Promise.resolve(settled).then(
|
|
149
|
+
() => {
|
|
150
|
+
this.cleanup();
|
|
151
|
+
this.resolveClose?.();
|
|
152
|
+
this.resolveClose = null;
|
|
153
|
+
this.rejectClose = null;
|
|
154
|
+
},
|
|
155
|
+
(error) => {
|
|
156
|
+
this.cleanup();
|
|
157
|
+
this.rejectPendingClose(error);
|
|
158
|
+
}
|
|
159
|
+
);
|
|
133
160
|
return closePromise;
|
|
134
161
|
}
|
|
135
162
|
abort(reason) {
|
|
@@ -395,12 +422,6 @@ function createStreamController(host, options = {}) {
|
|
|
395
422
|
}
|
|
396
423
|
|
|
397
424
|
// src/Markdown.ts
|
|
398
|
-
import { mathjax } from "mathjax-full/js/mathjax.js";
|
|
399
|
-
import { TeX } from "mathjax-full/js/input/tex.js";
|
|
400
|
-
import { SVG } from "mathjax-full/js/output/svg.js";
|
|
401
|
-
import { liteAdaptor } from "mathjax-full/js/adaptors/liteAdaptor.js";
|
|
402
|
-
import { RegisterHTMLHandler } from "mathjax-full/js/handlers/html.js";
|
|
403
|
-
import { AllPackages } from "mathjax-full/js/input/tex/AllPackages.js";
|
|
404
425
|
import { measureText, RichText, Stack, Table, Text, Image, UIComponent } from "@vectojs/ui";
|
|
405
426
|
|
|
406
427
|
// src/MarkdownWorkerSource.ts
|
|
@@ -442,23 +463,183 @@ marked.use({
|
|
|
442
463
|
}
|
|
443
464
|
]
|
|
444
465
|
});
|
|
445
|
-
var
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
466
|
+
var mathConverter = null;
|
|
467
|
+
var mathLoad = null;
|
|
468
|
+
function interop(mod, key) {
|
|
469
|
+
const ns = mod;
|
|
470
|
+
if (typeof ns?.[key] !== "undefined") return ns;
|
|
471
|
+
const fallback = ns?.default;
|
|
472
|
+
if (fallback && typeof fallback[key] !== "undefined") return fallback;
|
|
473
|
+
throw new Error(`mathjax-full module is missing export "${key}"`);
|
|
474
|
+
}
|
|
475
|
+
function preloadMathJax() {
|
|
476
|
+
if (mathLoad) return mathLoad;
|
|
477
|
+
mathLoad = (async () => {
|
|
478
|
+
const [mathjaxMod, texMod, svgMod, adaptorMod, handlerMod, packagesMod] = await Promise.all([
|
|
479
|
+
import("mathjax-full/js/mathjax.js"),
|
|
480
|
+
import("mathjax-full/js/input/tex.js"),
|
|
481
|
+
import("mathjax-full/js/output/svg.js"),
|
|
482
|
+
import("mathjax-full/js/adaptors/liteAdaptor.js"),
|
|
483
|
+
import("mathjax-full/js/handlers/html.js"),
|
|
484
|
+
import("mathjax-full/js/input/tex/AllPackages.js")
|
|
485
|
+
]);
|
|
486
|
+
const { mathjax } = interop(mathjaxMod, "mathjax");
|
|
487
|
+
const { TeX } = interop(texMod, "TeX");
|
|
488
|
+
const { SVG } = interop(svgMod, "SVG");
|
|
489
|
+
const { liteAdaptor } = interop(adaptorMod, "liteAdaptor");
|
|
490
|
+
const { RegisterHTMLHandler } = interop(handlerMod, "RegisterHTMLHandler");
|
|
491
|
+
const { AllPackages } = interop(packagesMod, "AllPackages");
|
|
492
|
+
const adaptor = liteAdaptor();
|
|
493
|
+
RegisterHTMLHandler(adaptor);
|
|
494
|
+
const tex = new TeX({ packages: AllPackages });
|
|
495
|
+
const svg = new SVG({ fontCache: "local" });
|
|
496
|
+
const htmlMathJax = mathjax.document("", { InputJax: tex, OutputJax: svg });
|
|
497
|
+
mathConverter = (formula, displayMode) => convertMathToSVGDataURI(
|
|
498
|
+
formula,
|
|
499
|
+
displayMode,
|
|
500
|
+
(f, d) => adaptor.innerHTML(htmlMathJax.convert(f, { display: d }))
|
|
501
|
+
);
|
|
502
|
+
})().catch((e) => {
|
|
503
|
+
console.error("MathJax failed to load; formulas will render as TeX source", e);
|
|
504
|
+
});
|
|
505
|
+
return mathLoad;
|
|
506
|
+
}
|
|
507
|
+
function isMathJaxReady() {
|
|
508
|
+
return mathConverter !== null;
|
|
509
|
+
}
|
|
510
|
+
var EX_PER_EM = 0.4421;
|
|
511
|
+
function exToPx(ex, fontSize) {
|
|
512
|
+
return ex * fontSize * EX_PER_EM;
|
|
513
|
+
}
|
|
514
|
+
function fontSizeFromFont(font) {
|
|
515
|
+
const pxIndex = font.indexOf("px");
|
|
516
|
+
if (pxIndex <= 0) return void 0;
|
|
517
|
+
let start = pxIndex;
|
|
518
|
+
while (start > 0) {
|
|
519
|
+
const ch = font[start - 1];
|
|
520
|
+
if (ch >= "0" && ch <= "9" || ch === ".") start--;
|
|
521
|
+
else break;
|
|
522
|
+
}
|
|
523
|
+
if (start === pxIndex) return void 0;
|
|
524
|
+
const size = parseFloat(font.slice(start, pxIndex));
|
|
525
|
+
return Number.isFinite(size) ? size : void 0;
|
|
526
|
+
}
|
|
527
|
+
var mathCache = /* @__PURE__ */ new Map();
|
|
528
|
+
var MATH_CACHE_LIMIT = 256;
|
|
529
|
+
var inlineMathRasters = /* @__PURE__ */ new Map();
|
|
530
|
+
var inlineMathRasterWaiters = /* @__PURE__ */ new Set();
|
|
531
|
+
function ensureInlineMathRaster(uri) {
|
|
532
|
+
const existing = inlineMathRasters.get(uri);
|
|
533
|
+
if (existing) return existing;
|
|
534
|
+
const entry = { decoded: false };
|
|
535
|
+
inlineMathRasters.set(uri, entry);
|
|
536
|
+
if (typeof globalThis.Image !== "undefined") {
|
|
537
|
+
const bitmap = new globalThis.Image();
|
|
538
|
+
bitmap.onload = () => {
|
|
539
|
+
entry.decoded = true;
|
|
540
|
+
for (const notify of inlineMathRasterWaiters) notify();
|
|
541
|
+
};
|
|
542
|
+
bitmap.src = uri;
|
|
543
|
+
entry.bitmap = bitmap;
|
|
544
|
+
}
|
|
545
|
+
return entry;
|
|
546
|
+
}
|
|
547
|
+
function paintInlineMath(uri, surface, box) {
|
|
548
|
+
const raster = ensureInlineMathRaster(uri);
|
|
549
|
+
if (!raster.decoded || !raster.bitmap) return;
|
|
550
|
+
surface.drawImage(raster.bitmap, box.x, box.y, box.width, box.height);
|
|
551
|
+
}
|
|
552
|
+
var MATH_LANGS = /* @__PURE__ */ new Set(["math", "latex", "tex"]);
|
|
553
|
+
function containsInlineMath(token) {
|
|
554
|
+
if (token.type === "inlineMath") return true;
|
|
555
|
+
const anyToken = token;
|
|
556
|
+
if (Array.isArray(anyToken.tokens) && anyToken.tokens.some(containsInlineMath)) {
|
|
557
|
+
return true;
|
|
558
|
+
}
|
|
559
|
+
if (Array.isArray(anyToken.items) && anyToken.items.some(containsInlineMath)) {
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
if (Array.isArray(anyToken.header) && anyToken.header.some(containsInlineMath)) {
|
|
563
|
+
return true;
|
|
564
|
+
}
|
|
565
|
+
if (Array.isArray(anyToken.rows)) {
|
|
566
|
+
for (const row of anyToken.rows) {
|
|
567
|
+
if (Array.isArray(row) && row.some(containsInlineMath)) return true;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return false;
|
|
571
|
+
}
|
|
572
|
+
var FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})/;
|
|
573
|
+
var FENCE_CLOSE_RE = /^ {0,3}(`+|~+)[ \t]*$/;
|
|
574
|
+
function isFenceClosed(raw) {
|
|
575
|
+
const lines = raw.split("\n");
|
|
576
|
+
const open = FENCE_OPEN_RE.exec(lines[0]);
|
|
577
|
+
if (!open) return false;
|
|
578
|
+
const marker = open[1][0];
|
|
579
|
+
const minLen = open[1].length;
|
|
580
|
+
for (let i = 1; i < lines.length; i++) {
|
|
581
|
+
const close = FENCE_CLOSE_RE.exec(lines[i]);
|
|
582
|
+
if (close && close[1][0] === marker && close[1].length >= minLen) return true;
|
|
583
|
+
}
|
|
584
|
+
return false;
|
|
585
|
+
}
|
|
586
|
+
function paragraphHasImage(token) {
|
|
587
|
+
return token.tokens?.some((child) => child.type === "image") === true;
|
|
588
|
+
}
|
|
589
|
+
function lastIndexOfImage(tokens) {
|
|
590
|
+
for (let i = tokens.length - 1; i >= 0; i--) {
|
|
591
|
+
if (tokens[i].type === "image") return i;
|
|
592
|
+
}
|
|
593
|
+
return -1;
|
|
594
|
+
}
|
|
595
|
+
function expectedImageParagraphChildren(tokens) {
|
|
596
|
+
let children = 0;
|
|
597
|
+
let inTextRun = false;
|
|
598
|
+
for (const token of tokens) {
|
|
599
|
+
if (token.type === "image") {
|
|
600
|
+
children++;
|
|
601
|
+
inTextRun = false;
|
|
602
|
+
} else if (!inTextRun) {
|
|
603
|
+
children++;
|
|
604
|
+
inTextRun = true;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return children;
|
|
608
|
+
}
|
|
609
|
+
function rendersAsMath(token) {
|
|
610
|
+
return MATH_LANGS.has((token.lang ?? "").toLowerCase()) && token.text.trim() !== "" && isFenceClosed(token.raw);
|
|
611
|
+
}
|
|
450
612
|
function renderMathToSVGDataURI(formula, displayMode) {
|
|
613
|
+
const key = `${displayMode ? 1 : 0}\0${formula}`;
|
|
614
|
+
const hit = mathCache.get(key);
|
|
615
|
+
if (hit) return hit;
|
|
616
|
+
if (!mathConverter) return null;
|
|
617
|
+
const converted = mathConverter(formula, displayMode);
|
|
618
|
+
if (converted) {
|
|
619
|
+
if (mathCache.size >= MATH_CACHE_LIMIT) {
|
|
620
|
+
const oldest = mathCache.keys().next().value;
|
|
621
|
+
if (oldest !== void 0) mathCache.delete(oldest);
|
|
622
|
+
}
|
|
623
|
+
mathCache.set(key, converted);
|
|
624
|
+
}
|
|
625
|
+
return converted;
|
|
626
|
+
}
|
|
627
|
+
function convertMathToSVGDataURI(formula, displayMode, typeset) {
|
|
451
628
|
try {
|
|
452
|
-
const
|
|
453
|
-
const svgString = adaptor.innerHTML(node);
|
|
629
|
+
const svgString = typeset(formula, displayMode);
|
|
454
630
|
const wMatch = svgString.match(/width="([^"]+)ex"/);
|
|
455
631
|
const hMatch = svgString.match(/height="([^"]+)ex"/);
|
|
456
632
|
const wEx = wMatch ? parseFloat(wMatch[1]) : 10;
|
|
457
633
|
const hEx = hMatch ? parseFloat(hMatch[1]) : 2;
|
|
458
|
-
const
|
|
459
|
-
const
|
|
634
|
+
const vMatch = svgString.match(/vertical-align:\s*(-?[\d.]+)ex/);
|
|
635
|
+
const depthEx = vMatch ? Math.max(0, -parseFloat(vMatch[1])) : 0;
|
|
460
636
|
const base64 = btoa(unescape(encodeURIComponent(svgString)));
|
|
461
|
-
return {
|
|
637
|
+
return {
|
|
638
|
+
uri: `data:image/svg+xml;base64,${base64}`,
|
|
639
|
+
widthEx: wEx,
|
|
640
|
+
heightEx: hEx,
|
|
641
|
+
depthEx
|
|
642
|
+
};
|
|
462
643
|
} catch (e) {
|
|
463
644
|
console.error("MathJax error", e);
|
|
464
645
|
return null;
|
|
@@ -473,6 +654,7 @@ function runSyncFallback(entry) {
|
|
|
473
654
|
entry.cb(0, lexMarkdown(entry.text, entry.userTiming), true);
|
|
474
655
|
} catch (err) {
|
|
475
656
|
console.warn("Markdown sync fallback parse failed", err);
|
|
657
|
+
entry.onDropped?.();
|
|
476
658
|
}
|
|
477
659
|
}
|
|
478
660
|
if (typeof Worker !== "undefined") {
|
|
@@ -998,13 +1180,13 @@ function codeAtlas() {
|
|
|
998
1180
|
function decodeEntities(text) {
|
|
999
1181
|
return text.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
1000
1182
|
}
|
|
1001
|
-
function collectSpans(tokens, inherited, theme, out) {
|
|
1183
|
+
function collectSpans(tokens, inherited, theme, out, blockFontSize) {
|
|
1002
1184
|
for (const token of tokens) {
|
|
1003
1185
|
switch (token.type) {
|
|
1004
1186
|
case "strong": {
|
|
1005
1187
|
const t = token;
|
|
1006
1188
|
if (t.tokens) {
|
|
1007
|
-
collectSpans(t.tokens, { ...inherited, bold: true }, theme, out);
|
|
1189
|
+
collectSpans(t.tokens, { ...inherited, bold: true }, theme, out, blockFontSize);
|
|
1008
1190
|
} else {
|
|
1009
1191
|
out.push({
|
|
1010
1192
|
text: decodeEntities(t.text),
|
|
@@ -1016,7 +1198,7 @@ function collectSpans(tokens, inherited, theme, out) {
|
|
|
1016
1198
|
case "em": {
|
|
1017
1199
|
const t = token;
|
|
1018
1200
|
if (t.tokens) {
|
|
1019
|
-
collectSpans(t.tokens, { ...inherited, italic: true }, theme, out);
|
|
1201
|
+
collectSpans(t.tokens, { ...inherited, italic: true }, theme, out, blockFontSize);
|
|
1020
1202
|
} else {
|
|
1021
1203
|
out.push({
|
|
1022
1204
|
text: decodeEntities(t.text),
|
|
@@ -1052,10 +1234,31 @@ function collectSpans(tokens, inherited, theme, out) {
|
|
|
1052
1234
|
}
|
|
1053
1235
|
case "inlineMath": {
|
|
1054
1236
|
const t = token;
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1237
|
+
const runSize = inherited.fontSize ?? blockFontSize ?? theme.fontSize;
|
|
1238
|
+
const rendered = renderMathToSVGDataURI(t.text, false);
|
|
1239
|
+
if (rendered) {
|
|
1240
|
+
const uri = rendered.uri;
|
|
1241
|
+
out.push({
|
|
1242
|
+
text: OBJECT_REPLACEMENT,
|
|
1243
|
+
style: inherited,
|
|
1244
|
+
object: {
|
|
1245
|
+
width: exToPx(rendered.widthEx, runSize),
|
|
1246
|
+
height: exToPx(rendered.heightEx, runSize),
|
|
1247
|
+
depth: exToPx(rendered.depthEx, runSize),
|
|
1248
|
+
// The TeX source is the accessible name: without it a screen reader
|
|
1249
|
+
// receives only the invisible U+FFFC sentinel.
|
|
1250
|
+
alt: t.text,
|
|
1251
|
+
// Without this the box is reserved and stays empty. The engine does
|
|
1252
|
+
// not draw objects, and nothing else in the tree holds the raster.
|
|
1253
|
+
paint: (surface, box) => paintInlineMath(uri, surface, box)
|
|
1254
|
+
}
|
|
1255
|
+
});
|
|
1256
|
+
} else {
|
|
1257
|
+
out.push({
|
|
1258
|
+
text: decodeEntities(t.raw),
|
|
1259
|
+
style: { ...inherited, color: "#fcd34d" }
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1059
1262
|
break;
|
|
1060
1263
|
}
|
|
1061
1264
|
case "link": {
|
|
@@ -1066,7 +1269,7 @@ function collectSpans(tokens, inherited, theme, out) {
|
|
|
1066
1269
|
color: "#38bdf8"
|
|
1067
1270
|
};
|
|
1068
1271
|
if (t.tokens && t.tokens.length > 0) {
|
|
1069
|
-
collectSpans(t.tokens, linkStyle, theme, out);
|
|
1272
|
+
collectSpans(t.tokens, linkStyle, theme, out, blockFontSize);
|
|
1070
1273
|
} else {
|
|
1071
1274
|
out.push({ text: decodeEntities(t.text), style: linkStyle });
|
|
1072
1275
|
}
|
|
@@ -1075,7 +1278,7 @@ function collectSpans(tokens, inherited, theme, out) {
|
|
|
1075
1278
|
case "text": {
|
|
1076
1279
|
const t = token;
|
|
1077
1280
|
if ("tokens" in t && t.tokens?.length) {
|
|
1078
|
-
collectSpans(t.tokens, inherited, theme, out);
|
|
1281
|
+
collectSpans(t.tokens, inherited, theme, out, blockFontSize);
|
|
1079
1282
|
} else {
|
|
1080
1283
|
const decoded = decodeEntities(t.text);
|
|
1081
1284
|
if (decoded) {
|
|
@@ -1098,10 +1301,37 @@ function collectSpans(tokens, inherited, theme, out) {
|
|
|
1098
1301
|
}
|
|
1099
1302
|
}
|
|
1100
1303
|
}
|
|
1304
|
+
function findUnclosedInline(text) {
|
|
1305
|
+
let best = null;
|
|
1306
|
+
const tick = text.lastIndexOf("`");
|
|
1307
|
+
if (tick !== -1 && tick < text.length - 1) {
|
|
1308
|
+
return { kind: "codespan", at: tick, contentAt: tick + 1 };
|
|
1309
|
+
}
|
|
1310
|
+
if (tick !== -1) return null;
|
|
1311
|
+
const emphasis = /(\*{1,2}(?!\*)|_{1,2}(?!_))(?=[^\s])/g;
|
|
1312
|
+
for (let match = emphasis.exec(text); match !== null; match = emphasis.exec(text)) {
|
|
1313
|
+
const marker = match[1];
|
|
1314
|
+
const at = match.index;
|
|
1315
|
+
if (marker[0] === "_" && at > 0 && /[\w]/.test(text[at - 1])) continue;
|
|
1316
|
+
best = {
|
|
1317
|
+
kind: marker.length === 2 ? "strong" : "em",
|
|
1318
|
+
at,
|
|
1319
|
+
contentAt: at + marker.length
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
const bracket = text.lastIndexOf("[");
|
|
1323
|
+
if (bracket !== -1 && bracket < text.length - 1 && (best === null || bracket > best.at)) {
|
|
1324
|
+
const closed = /\]\([^)]*\)/.test(text.slice(bracket));
|
|
1325
|
+
if (!closed) {
|
|
1326
|
+
best = { kind: "link", at: bracket, contentAt: bracket + 1 };
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
return best;
|
|
1330
|
+
}
|
|
1101
1331
|
function renderInlineToRichText(tokens, fallbackText, font, color, maxWidth, theme, selectable, onLinkClick) {
|
|
1102
1332
|
const spans = [];
|
|
1103
1333
|
if (tokens && tokens.length > 0) {
|
|
1104
|
-
collectSpans(tokens, {}, theme, spans);
|
|
1334
|
+
collectSpans(tokens, {}, theme, spans, fontSizeFromFont(font));
|
|
1105
1335
|
}
|
|
1106
1336
|
if (spans.length === 0) {
|
|
1107
1337
|
spans.push({ text: decodeEntities(fallbackText) });
|
|
@@ -1133,6 +1363,51 @@ var Markdown = class extends UIComponent {
|
|
|
1133
1363
|
onLayoutUpdated;
|
|
1134
1364
|
rawMarkdown;
|
|
1135
1365
|
streamController = null;
|
|
1366
|
+
/**
|
|
1367
|
+
* Trailing-unclosed-syntax policy of the active stream, or `'literal'` when no
|
|
1368
|
+
* stream is open.
|
|
1369
|
+
*
|
|
1370
|
+
* Held here rather than read back off the controller because it is a rendering
|
|
1371
|
+
* concern: `StreamController` owns buffering and pacing and has no view of the
|
|
1372
|
+
* entity tree, while the guess is a transform applied where spans are built.
|
|
1373
|
+
*/
|
|
1374
|
+
streamIncompleteMode = "literal";
|
|
1375
|
+
/** End-of-stream callback of the active stream, if it supplied one. */
|
|
1376
|
+
streamOnStable = null;
|
|
1377
|
+
/**
|
|
1378
|
+
* The trailing paragraph entity currently showing an optimistic guess, plus the
|
|
1379
|
+
* token it was rendered from.
|
|
1380
|
+
*
|
|
1381
|
+
* Both halves are needed. The entity is what must be re-rendered to drop the
|
|
1382
|
+
* guess; the token is what it must be re-rendered FROM, and it is the only
|
|
1383
|
+
* copy — `this.tokens` has already moved on by the time an unwind is decided.
|
|
1384
|
+
* `null` means no guess is live, which is the state every `'literal'` stream
|
|
1385
|
+
* and every closed stream stays in.
|
|
1386
|
+
*/
|
|
1387
|
+
optimisticTail = null;
|
|
1388
|
+
/** Resolvers waiting for every in-flight worker append to have been applied. */
|
|
1389
|
+
appendSettledWaiters = [];
|
|
1390
|
+
/** True only inside an `onStable` callback, to reject reentrant mutation. */
|
|
1391
|
+
inStableCallback = false;
|
|
1392
|
+
/** Set by {@link destroy} so late settlement work skips a torn-down tree. */
|
|
1393
|
+
isDestroyed = false;
|
|
1394
|
+
/**
|
|
1395
|
+
* This instance's entry in {@link inlineMathRasterWaiters}, or `undefined` if it
|
|
1396
|
+
* has never rendered inline math.
|
|
1397
|
+
*
|
|
1398
|
+
* Subscribed lazily so a document without formulas costs nothing, and held as a
|
|
1399
|
+
* field only so {@link destroy} can remove the exact closure it added.
|
|
1400
|
+
*/
|
|
1401
|
+
inlineMathRepaint;
|
|
1402
|
+
/**
|
|
1403
|
+
* True while this document is waiting on the lazy MathJax load.
|
|
1404
|
+
*
|
|
1405
|
+
* Tracked per instance rather than read off the module state because it also
|
|
1406
|
+
* gates settlement: `await close()` and `onStable` must not resolve while a
|
|
1407
|
+
* formula is still showing TeX source, or a caller doing expensive one-time
|
|
1408
|
+
* work on a "final" document would measure and export placeholder boxes.
|
|
1409
|
+
*/
|
|
1410
|
+
mathLoadPending = false;
|
|
1136
1411
|
_userTiming;
|
|
1137
1412
|
tokens = [];
|
|
1138
1413
|
// At most one worker lex request in flight at a time. Required for the
|
|
@@ -1290,21 +1565,44 @@ var Markdown = class extends UIComponent {
|
|
|
1290
1565
|
{
|
|
1291
1566
|
append: (chunk) => this.appendMarkdownCore(chunk),
|
|
1292
1567
|
release: (released) => {
|
|
1293
|
-
if (this.streamController
|
|
1568
|
+
if (this.streamController !== released) return;
|
|
1569
|
+
this.streamController = null;
|
|
1570
|
+
this.streamIncompleteMode = "literal";
|
|
1571
|
+
this.streamOnStable = null;
|
|
1572
|
+
this.unwindOptimisticTail();
|
|
1573
|
+
},
|
|
1574
|
+
onClose: async () => {
|
|
1575
|
+
await this.waitForAppendSettled();
|
|
1576
|
+
if (this.isDestroyed) return;
|
|
1577
|
+
this.unwindOptimisticTail();
|
|
1578
|
+
const onStable = this.streamOnStable;
|
|
1579
|
+
if (!onStable) return;
|
|
1580
|
+
this.inStableCallback = true;
|
|
1581
|
+
try {
|
|
1582
|
+
onStable(Array.from(this.content.children));
|
|
1583
|
+
} finally {
|
|
1584
|
+
this.inStableCallback = false;
|
|
1585
|
+
}
|
|
1294
1586
|
}
|
|
1295
1587
|
},
|
|
1296
1588
|
options
|
|
1297
1589
|
);
|
|
1298
|
-
if (controller.state === "open")
|
|
1590
|
+
if (controller.state === "open") {
|
|
1591
|
+
this.streamController = controller;
|
|
1592
|
+
this.streamIncompleteMode = options.incompleteMode ?? "literal";
|
|
1593
|
+
this.streamOnStable = options.onStable ?? null;
|
|
1594
|
+
}
|
|
1299
1595
|
return controller;
|
|
1300
1596
|
}
|
|
1301
1597
|
/** Replace all markdown content (full rebuild). */
|
|
1302
1598
|
setContent(markdown) {
|
|
1599
|
+
this.assertNotInStableCallback("setContent");
|
|
1303
1600
|
this.streamController?.abort(new Error("Markdown content was replaced"));
|
|
1304
1601
|
for (const id of this.pendingWorkerIds) workerCallbacks.delete(id);
|
|
1305
1602
|
this.pendingWorkerIds.clear();
|
|
1306
1603
|
this.appendInFlight = false;
|
|
1307
1604
|
this.appendPending = false;
|
|
1605
|
+
this.flushAppendSettledWaiters();
|
|
1308
1606
|
this.rawMarkdown = markdown;
|
|
1309
1607
|
this.workerSourceLen = 0;
|
|
1310
1608
|
while (this.content.children.length > 0) {
|
|
@@ -1320,12 +1618,35 @@ var Markdown = class extends UIComponent {
|
|
|
1320
1618
|
* the whole subtree alive until the worker replied), then recurse into the
|
|
1321
1619
|
* content subtree via `super.destroy()` so every block's resources are freed.
|
|
1322
1620
|
*/
|
|
1621
|
+
/**
|
|
1622
|
+
* Repaint this document when an inline formula's raster finishes decoding.
|
|
1623
|
+
*
|
|
1624
|
+
* Idempotent — called on every render of a math-bearing token, and the set holds
|
|
1625
|
+
* one closure per instance.
|
|
1626
|
+
*/
|
|
1627
|
+
subscribeInlineMathRepaint() {
|
|
1628
|
+
if (this.inlineMathRepaint || this.isDestroyed) return;
|
|
1629
|
+
const repaint = () => {
|
|
1630
|
+
if (this.isDestroyed) return;
|
|
1631
|
+
this.scene?.markDirty();
|
|
1632
|
+
};
|
|
1633
|
+
this.inlineMathRepaint = repaint;
|
|
1634
|
+
inlineMathRasterWaiters.add(repaint);
|
|
1635
|
+
}
|
|
1323
1636
|
destroy() {
|
|
1637
|
+
this.isDestroyed = true;
|
|
1638
|
+
this.optimisticTail = null;
|
|
1324
1639
|
this.streamController?.destroy();
|
|
1325
1640
|
for (const id of this.pendingWorkerIds) workerCallbacks.delete(id);
|
|
1326
1641
|
this.pendingWorkerIds.clear();
|
|
1327
1642
|
this.appendInFlight = false;
|
|
1328
1643
|
this.appendPending = false;
|
|
1644
|
+
this.mathLoadPending = false;
|
|
1645
|
+
this.flushAppendSettledWaiters();
|
|
1646
|
+
if (this.inlineMathRepaint) {
|
|
1647
|
+
inlineMathRasterWaiters.delete(this.inlineMathRepaint);
|
|
1648
|
+
this.inlineMathRepaint = void 0;
|
|
1649
|
+
}
|
|
1329
1650
|
markdownWorker?.postMessage({
|
|
1330
1651
|
instance: this.workerInstanceId,
|
|
1331
1652
|
dispose: true
|
|
@@ -1514,6 +1835,7 @@ var Markdown = class extends UIComponent {
|
|
|
1514
1835
|
}
|
|
1515
1836
|
/** Append a markdown chunk incrementally. Reuses unchanged prefix entities. */
|
|
1516
1837
|
appendMarkdown(chunk) {
|
|
1838
|
+
this.assertNotInStableCallback("appendMarkdown");
|
|
1517
1839
|
this.streamController?.flush();
|
|
1518
1840
|
return this.appendMarkdownCore(chunk);
|
|
1519
1841
|
}
|
|
@@ -1582,6 +1904,7 @@ var Markdown = class extends UIComponent {
|
|
|
1582
1904
|
this.appendPending = false;
|
|
1583
1905
|
this.dispatchAppend();
|
|
1584
1906
|
}
|
|
1907
|
+
this.flushAppendSettledWaiters();
|
|
1585
1908
|
},
|
|
1586
1909
|
// The worker can't trust what it holds for this request; retry it once with
|
|
1587
1910
|
// the full text and raws attached. `this.tokens` is untouched (no
|
|
@@ -1592,6 +1915,20 @@ var Markdown = class extends UIComponent {
|
|
|
1592
1915
|
this.workerSourceLen = 0;
|
|
1593
1916
|
this.dispatchAppend(true);
|
|
1594
1917
|
},
|
|
1918
|
+
// Neither the worker nor the fallback lexer could produce tokens for this
|
|
1919
|
+
// request, so `this.tokens` stays as it was. Only the in-flight bookkeeping
|
|
1920
|
+
// needs unwinding — including any coalesced chunk waiting behind it, which
|
|
1921
|
+
// still has to be attempted.
|
|
1922
|
+
onDropped: () => {
|
|
1923
|
+
this.pendingWorkerIds.delete(id);
|
|
1924
|
+
this.appendInFlight = false;
|
|
1925
|
+
this.workerSourceLen = 0;
|
|
1926
|
+
if (this.appendPending) {
|
|
1927
|
+
this.appendPending = false;
|
|
1928
|
+
this.dispatchAppend(true);
|
|
1929
|
+
}
|
|
1930
|
+
this.flushAppendSettledWaiters();
|
|
1931
|
+
},
|
|
1595
1932
|
text: this.rawMarkdown,
|
|
1596
1933
|
userTiming: this._userTiming
|
|
1597
1934
|
});
|
|
@@ -1613,6 +1950,647 @@ var Markdown = class extends UIComponent {
|
|
|
1613
1950
|
}
|
|
1614
1951
|
});
|
|
1615
1952
|
}
|
|
1953
|
+
/**
|
|
1954
|
+
* Spans for one paragraph token exactly as `marked` produced it.
|
|
1955
|
+
*
|
|
1956
|
+
* The literal baseline: what every release renders, and what an optimistic
|
|
1957
|
+
* guess is unwound back to.
|
|
1958
|
+
*/
|
|
1959
|
+
literalParagraphSpans(token) {
|
|
1960
|
+
const spans = [];
|
|
1961
|
+
if (token.tokens && token.tokens.length > 0) {
|
|
1962
|
+
collectSpans(token.tokens, {}, this.theme, spans);
|
|
1963
|
+
}
|
|
1964
|
+
if (spans.length === 0) spans.push({ text: token.text });
|
|
1965
|
+
return spans;
|
|
1966
|
+
}
|
|
1967
|
+
/**
|
|
1968
|
+
* Update a reused blockquote's tail child in place, or report that it cannot be.
|
|
1969
|
+
*
|
|
1970
|
+
* The render arm builds `container[border, innerStack]` where every inner block
|
|
1971
|
+
* sits in its own single-child `wrapper`, so the tail entity is
|
|
1972
|
+
* `innerStack.children.at(-1).children[0]`. Only the LAST inner block may be
|
|
1973
|
+
* updated: the inner token list is prefix-stable exactly like the top level (a
|
|
1974
|
+
* growing quote keeps its earlier blocks byte-identical), so anything before the
|
|
1975
|
+
* tail is untouched and anything more complicated than a changed tail falls back
|
|
1976
|
+
* to the caller's rebuild.
|
|
1977
|
+
*
|
|
1978
|
+
* Returns `false` without mutating anything when the shape is not the simple
|
|
1979
|
+
* grow-the-tail case, which is the signal for the caller to rebuild. Every early
|
|
1980
|
+
* return has to leave the entity untouched, or a rejected reuse would leave a
|
|
1981
|
+
* half-updated quote on screen.
|
|
1982
|
+
*/
|
|
1983
|
+
/**
|
|
1984
|
+
* Build one list item's spans: inline content plus its marker.
|
|
1985
|
+
*
|
|
1986
|
+
* Shared by the `list` render arm and the streamed-reuse path below, because
|
|
1987
|
+
* the two must produce byte-identical spans — a reused list that disagreed with
|
|
1988
|
+
* a rebuilt one about its marker or its entity decoding would make a streamed
|
|
1989
|
+
* document differ from the same source pasted at once.
|
|
1990
|
+
*/
|
|
1991
|
+
/**
|
|
1992
|
+
* Inline spans for one table cell.
|
|
1993
|
+
*
|
|
1994
|
+
* Always returns at least one span. A cell whose markup collapses to nothing —
|
|
1995
|
+
* an empty cell, but also a bare `<span>`, an image, or an HTML comment, none
|
|
1996
|
+
* of which `collectSpans` emits for — falls back to its decoded source text,
|
|
1997
|
+
* which is what the previous string-returning path rendered. That guarantee is
|
|
1998
|
+
* what lets every cell be a `RichText`: an empty cell would otherwise become a
|
|
1999
|
+
* `Text`, and since `Text` has `setText` while `RichText` has `setSpans` and
|
|
2000
|
+
* nothing converts between them, a cell that starts empty and later gains
|
|
2001
|
+
* content could not be updated in place. A streamed table needs exactly that,
|
|
2002
|
+
* because `marked` materializes a partial row as a full row of empty cells and
|
|
2003
|
+
* then fills them one at a time.
|
|
2004
|
+
*/
|
|
2005
|
+
tableCellSpans(cell, t) {
|
|
2006
|
+
const spans = [];
|
|
2007
|
+
collectSpans(cell.tokens, {}, t, spans);
|
|
2008
|
+
if (spans.length === 0) spans.push({ text: decodeEntities(cell.text) });
|
|
2009
|
+
return spans;
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* Spans for one run of consecutive non-image inline tokens.
|
|
2013
|
+
*
|
|
2014
|
+
* A paragraph holding an image renders as a `Stack` of alternating text runs
|
|
2015
|
+
* and images, and this is one text run. Shared by the render arm and
|
|
2016
|
+
* {@link updateImageParagraph} so a reused run cannot drift from a rebuilt one.
|
|
2017
|
+
*
|
|
2018
|
+
* The empty fallback mirrors `renderInlineToRichText('', …)`, which the render
|
|
2019
|
+
* arm passed for these runs: a run is only created when it has at least one
|
|
2020
|
+
* token, so the fallback is for tokens that emit no spans at all rather than
|
|
2021
|
+
* for an empty run.
|
|
2022
|
+
*/
|
|
2023
|
+
inlineRunSpans(tokens, t) {
|
|
2024
|
+
const spans = [];
|
|
2025
|
+
if (tokens.length > 0) collectSpans(tokens, {}, t, spans);
|
|
2026
|
+
if (spans.length === 0) spans.push({ text: "" });
|
|
2027
|
+
return spans;
|
|
2028
|
+
}
|
|
2029
|
+
/** One text run of an image-bearing paragraph, as both paths build it. */
|
|
2030
|
+
inlineRunRichText(tokens, availableWidth, t) {
|
|
2031
|
+
return new RichText(this.inlineRunSpans(tokens, t), {
|
|
2032
|
+
font: `${t.fontSize}px ${t.bodyFont}`,
|
|
2033
|
+
color: t.textColor,
|
|
2034
|
+
maxWidth: availableWidth,
|
|
2035
|
+
linkColor: "#38bdf8",
|
|
2036
|
+
selectable: this.selectable,
|
|
2037
|
+
onLinkClick: this.onLinkClick
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
/**
|
|
2041
|
+
* One image inside a paragraph, sized by a guess until its bitmap decodes.
|
|
2042
|
+
*
|
|
2043
|
+
* Width and height start at a 16:10 guess because the intrinsic size is not
|
|
2044
|
+
* known until the browser has the bitmap; `onLoad` corrects both from
|
|
2045
|
+
* `naturalWidth`/`naturalHeight`. Extracted from the render arm so the streamed
|
|
2046
|
+
* path reuses this exact entity rather than constructing a second variant.
|
|
2047
|
+
*
|
|
2048
|
+
* `markDirty()` is unconditional, matching the display-math sibling. It used
|
|
2049
|
+
* to sit inside the `naturalWidth && naturalHeight` check, which meant a
|
|
2050
|
+
* source that loads successfully while reporting a zero dimension left the
|
|
2051
|
+
* scene un-notified. `Image` sets `loaded` before invoking this callback, so
|
|
2052
|
+
* its `render()` starts drawing the bitmap either way — the cost was not a
|
|
2053
|
+
* stale placeholder but a box frozen at the guess: measured on Chromium and
|
|
2054
|
+
* Firefox, an `<svg width="0" height="0">` paragraph image kept 800x480 of
|
|
2055
|
+
* reserved layout forever while a normal raster corrected to 80x60. An
|
|
2056
|
+
* `onDemand` scene repaints only when marked, so nothing reclaimed it.
|
|
2057
|
+
*
|
|
2058
|
+
* The box is deliberately left at the guess when the bitmap reports zero.
|
|
2059
|
+
* Collapsing it to 0x0 would make the paragraph reflow correctly but would
|
|
2060
|
+
* also silently delete a reserved region on the strength of one browser
|
|
2061
|
+
* quirk, and `Image.render()` still blits whatever the bitmap holds. Sizing
|
|
2062
|
+
* policy for a zero-dimension source is a separate decision from notifying
|
|
2063
|
+
* the scene, which is the actual defect here.
|
|
2064
|
+
*/
|
|
2065
|
+
paragraphImage(imgToken, availableWidth) {
|
|
2066
|
+
const initialWidth = Math.min(800, availableWidth);
|
|
2067
|
+
const initialHeight = Math.round(initialWidth * 0.6);
|
|
2068
|
+
const img = new Image(imgToken.href, {
|
|
2069
|
+
width: initialWidth,
|
|
2070
|
+
height: initialHeight,
|
|
2071
|
+
alt: imgToken.text,
|
|
2072
|
+
radius: 8,
|
|
2073
|
+
onLoad: () => {
|
|
2074
|
+
const bmp = img.bitmap;
|
|
2075
|
+
if (bmp && bmp.naturalWidth && bmp.naturalHeight) {
|
|
2076
|
+
const aspect = bmp.naturalHeight / bmp.naturalWidth;
|
|
2077
|
+
img.width = Math.min(bmp.naturalWidth, availableWidth);
|
|
2078
|
+
img.height = Math.round(img.width * aspect);
|
|
2079
|
+
}
|
|
2080
|
+
this.scene?.markDirty();
|
|
2081
|
+
}
|
|
2082
|
+
});
|
|
2083
|
+
return img;
|
|
2084
|
+
}
|
|
2085
|
+
/** One table cell entity, shared by the render arm and the streamed-table path. */
|
|
2086
|
+
tableCellRichText(cell, header, t) {
|
|
2087
|
+
return new RichText(this.tableCellSpans(cell, t), {
|
|
2088
|
+
font: `${t.fontSize - 2}px ${t.bodyFont}`,
|
|
2089
|
+
color: header ? t.headingColor : t.textColor,
|
|
2090
|
+
baseStyle: header ? { bold: true } : void 0,
|
|
2091
|
+
linkColor: "#38bdf8",
|
|
2092
|
+
selectable: this.selectable,
|
|
2093
|
+
onLinkClick: this.onLinkClick
|
|
2094
|
+
});
|
|
2095
|
+
}
|
|
2096
|
+
listItemSpans(token, index) {
|
|
2097
|
+
const item = token.items[index];
|
|
2098
|
+
const num = Number(token.start ?? 1) + index;
|
|
2099
|
+
const contentSpans = [];
|
|
2100
|
+
if (item.tokens && item.tokens.length > 0) {
|
|
2101
|
+
for (const inner of item.tokens) {
|
|
2102
|
+
if (inner.type === "text" && "tokens" in inner && inner.tokens?.length) {
|
|
2103
|
+
collectSpans(
|
|
2104
|
+
inner.tokens,
|
|
2105
|
+
{},
|
|
2106
|
+
this.theme,
|
|
2107
|
+
contentSpans
|
|
2108
|
+
);
|
|
2109
|
+
} else if ("tokens" in inner && inner.tokens?.length) {
|
|
2110
|
+
collectSpans(
|
|
2111
|
+
inner.tokens,
|
|
2112
|
+
{},
|
|
2113
|
+
this.theme,
|
|
2114
|
+
contentSpans
|
|
2115
|
+
);
|
|
2116
|
+
} else if ("text" in inner) {
|
|
2117
|
+
contentSpans.push({ text: decodeEntities(inner.text) });
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
} else {
|
|
2121
|
+
contentSpans.push({ text: decodeEntities(item.text) });
|
|
2122
|
+
}
|
|
2123
|
+
const itemIsRtl = BidiResolver.getBaseLevel(contentSpans.map((s) => s.text).join("")) % 2 === 1;
|
|
2124
|
+
return itemIsRtl ? [...contentSpans, { text: token.ordered ? ` .${num}` : " \u2022" }] : [{ text: token.ordered ? `${num}. ` : "\u2022 " }, ...contentSpans];
|
|
2125
|
+
}
|
|
2126
|
+
/** Construct the `RichText` for one list item. */
|
|
2127
|
+
listItemRichText(token, index, availableWidth, t) {
|
|
2128
|
+
return new RichText(this.listItemSpans(token, index), {
|
|
2129
|
+
font: `${t.fontSize}px ${t.bodyFont}`,
|
|
2130
|
+
color: t.textColor,
|
|
2131
|
+
maxWidth: availableWidth,
|
|
2132
|
+
linkColor: "#38bdf8",
|
|
2133
|
+
selectable: this.selectable,
|
|
2134
|
+
onLinkClick: this.onLinkClick
|
|
2135
|
+
});
|
|
2136
|
+
}
|
|
2137
|
+
/**
|
|
2138
|
+
* Reuse a streamed list's `Stack` instead of rebuilding every item.
|
|
2139
|
+
*
|
|
2140
|
+
* Returns `false` to mean "rebuild instead", exactly like
|
|
2141
|
+
* {@link updateBlockquoteTail}, and every rejection path leaves the entity
|
|
2142
|
+
* untouched so a refused reuse cannot leave a half-updated list on screen.
|
|
2143
|
+
*
|
|
2144
|
+
* This is the shape a stream actually produces: items are APPENDED, and only
|
|
2145
|
+
* the last one grows. That matters for the ordinal marker, which is
|
|
2146
|
+
* position-derived (`start + index`) — under append an already-rendered item's
|
|
2147
|
+
* index never changes, so its marker stays correct. A mid-list insertion would
|
|
2148
|
+
* shift every later ordinal, but no stream produces one.
|
|
2149
|
+
*
|
|
2150
|
+
* Two traps this guards, both found by probing marked 18.0.7 rather than by
|
|
2151
|
+
* reading:
|
|
2152
|
+
*
|
|
2153
|
+
* - **A retained item's `raw` is NOT stable.** `items[1].raw` goes `"- two"` ->
|
|
2154
|
+
* `"- two\\n"` when item 3 arrives, so a byte-equality guard on `raw` fails on
|
|
2155
|
+
* every chunk and the fast path would never fire. `text` is stable; compare
|
|
2156
|
+
* that.
|
|
2157
|
+
* - **A tight list can become loose.** Adding a blank line flips
|
|
2158
|
+
* `token.loose`, which re-lexes every item's children from `text` to
|
|
2159
|
+
* `paragraph`. Item 0's own `text` is unchanged, so a naive guard would reuse
|
|
2160
|
+
* and keep stale spans. Bail when `loose` flips.
|
|
2161
|
+
*/
|
|
2162
|
+
updateStreamedList(stack, oldToken, newToken) {
|
|
2163
|
+
if (!(stack instanceof Stack)) return false;
|
|
2164
|
+
if (newToken.items.length < oldToken.items.length || oldToken.items.length === 0) return false;
|
|
2165
|
+
if (oldToken.ordered !== newToken.ordered) return false;
|
|
2166
|
+
if ((oldToken.start ?? 1) !== (newToken.start ?? 1)) return false;
|
|
2167
|
+
if (oldToken.loose !== newToken.loose) return false;
|
|
2168
|
+
if (stack.children.length !== oldToken.items.length) return false;
|
|
2169
|
+
const lastRetained = oldToken.items.length - 1;
|
|
2170
|
+
for (let i = 0; i < lastRetained; i++) {
|
|
2171
|
+
if (oldToken.items[i].text !== newToken.items[i].text) return false;
|
|
2172
|
+
}
|
|
2173
|
+
const availableWidth = this.activeBlockMetrics?.availableWidth ?? this.maxWidth;
|
|
2174
|
+
const t = this.theme;
|
|
2175
|
+
const tailEntity = stack.children[lastRetained];
|
|
2176
|
+
if (oldToken.items[lastRetained].text !== newToken.items[lastRetained].text) {
|
|
2177
|
+
if (!("setSpans" in tailEntity)) return false;
|
|
2178
|
+
tailEntity.setSpans(
|
|
2179
|
+
this.listItemSpans(newToken, lastRetained)
|
|
2180
|
+
);
|
|
2181
|
+
}
|
|
2182
|
+
for (let i = oldToken.items.length; i < newToken.items.length; i++) {
|
|
2183
|
+
stack.add(this.listItemRichText(newToken, i, availableWidth, t));
|
|
2184
|
+
}
|
|
2185
|
+
const last = stack.children.at(-1);
|
|
2186
|
+
if (last) stack.resizeLastChild(last);
|
|
2187
|
+
return true;
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Reuse a streamed image-bearing paragraph's `Stack` instead of rebuilding it.
|
|
2191
|
+
*
|
|
2192
|
+
* Returns `false` to mean "rebuild instead", and every rejection happens before
|
|
2193
|
+
* any mutation, so a refused reuse leaves the entity exactly as it was.
|
|
2194
|
+
*
|
|
2195
|
+
* This was the last silent fallthrough in the in-place reuse path. A paragraph
|
|
2196
|
+
* holding an image renders as a `Stack` of alternating text runs and images
|
|
2197
|
+
* rather than one `RichText`, so it has no `setSpans` and failed the ordinary
|
|
2198
|
+
* paragraph gate — with no `else`, which is what made the miss invisible:
|
|
2199
|
+
* `inPlaceUpdates` stayed flat while `entitiesRebuilt` climbed. Measured on a
|
|
2200
|
+
* six-chunk stream, `inPlaceUpdates` 0 / `entitiesRebuilt` 4 with an image
|
|
2201
|
+
* against 4 / 0 for the identical shape without one. Every rebuild also
|
|
2202
|
+
* re-created the `Image`, discarding its decoded bitmap and its corrected
|
|
2203
|
+
* intrinsic size.
|
|
2204
|
+
*
|
|
2205
|
+
* It is *only* a performance path. The obvious worry — that a fresh `Image`
|
|
2206
|
+
* starts at `loaded = false` and so repaints its placeholder slab — was
|
|
2207
|
+
* measured and does not happen: sampling the real canvas pixel at the image
|
|
2208
|
+
* centre in both Chromium and Firefox gives zero placeholder frames after the
|
|
2209
|
+
* first paint, at 60ms and at 0ms between chunks, because a cached bitmap
|
|
2210
|
+
* decodes before the next frame.
|
|
2211
|
+
*
|
|
2212
|
+
* The reuse is deliberately narrow: **only a growing trailing text run**. Probed
|
|
2213
|
+
* against `marked@18.0.7`, that is the shape a stream actually produces once an
|
|
2214
|
+
* image has closed — the image token's `raw` and its index are then stable while
|
|
2215
|
+
* trailing prose grows, and the token list settles at
|
|
2216
|
+
* `[…, image, text]` and stops changing length. Anything else (a new image
|
|
2217
|
+
* arriving, an image token changing, a run appearing before the last image)
|
|
2218
|
+
* falls through to the rebuild, which is correct and rare.
|
|
2219
|
+
*
|
|
2220
|
+
* Note the child list is not one entity per token: consecutive non-image tokens
|
|
2221
|
+
* are merged into one `RichText` by the render arm's `flushText`, so
|
|
2222
|
+
* `[text, text, image]` is two children, not three. The guards therefore compare
|
|
2223
|
+
* *token runs* split at the last image, never token index against child index.
|
|
2224
|
+
*/
|
|
2225
|
+
updateImageParagraph(entity, oldToken, newToken) {
|
|
2226
|
+
if (!(entity instanceof Stack)) return false;
|
|
2227
|
+
const oldTokens = oldToken.tokens;
|
|
2228
|
+
const newTokens = newToken.tokens;
|
|
2229
|
+
if (!oldTokens || !newTokens) return false;
|
|
2230
|
+
const oldLastImage = lastIndexOfImage(oldTokens);
|
|
2231
|
+
const newLastImage = lastIndexOfImage(newTokens);
|
|
2232
|
+
if (oldLastImage < 0 || newLastImage < 0) return false;
|
|
2233
|
+
if (oldLastImage !== newLastImage) return false;
|
|
2234
|
+
for (let i = 0; i <= newLastImage; i++) {
|
|
2235
|
+
if (oldTokens[i].raw !== newTokens[i].raw) return false;
|
|
2236
|
+
}
|
|
2237
|
+
const oldTail = oldTokens.slice(oldLastImage + 1);
|
|
2238
|
+
const newTail = newTokens.slice(newLastImage + 1);
|
|
2239
|
+
if (newTail.length === 0) return false;
|
|
2240
|
+
const oldTailRaw = oldTail.map((t2) => t2.raw).join("");
|
|
2241
|
+
const newTailRaw = newTail.map((t2) => t2.raw).join("");
|
|
2242
|
+
if (!newTailRaw.startsWith(oldTailRaw)) return false;
|
|
2243
|
+
const expectedOldChildren = expectedImageParagraphChildren(oldTokens);
|
|
2244
|
+
if (entity.children.length !== expectedOldChildren) return false;
|
|
2245
|
+
const t = this.theme;
|
|
2246
|
+
const availableWidth = this.activeBlockMetrics?.availableWidth ?? this.maxWidth;
|
|
2247
|
+
if (oldTail.length === 0) {
|
|
2248
|
+
entity.add(this.inlineRunRichText(newTail, availableWidth, t));
|
|
2249
|
+
} else {
|
|
2250
|
+
const tailEntity = entity.children[entity.children.length - 1];
|
|
2251
|
+
if (!(tailEntity instanceof RichText)) return false;
|
|
2252
|
+
tailEntity.setSpans(this.inlineRunSpans(newTail, t));
|
|
2253
|
+
}
|
|
2254
|
+
const last = entity.children[entity.children.length - 1];
|
|
2255
|
+
if (last) entity.resizeLastChild(last);
|
|
2256
|
+
return true;
|
|
2257
|
+
}
|
|
2258
|
+
/**
|
|
2259
|
+
* Reuse a streamed table's `Table` entity instead of rebuilding every cell.
|
|
2260
|
+
*
|
|
2261
|
+
* Returns `false` to mean "rebuild instead", and every rejection happens before
|
|
2262
|
+
* any mutation, so a refused reuse leaves the entity exactly as it was.
|
|
2263
|
+
*
|
|
2264
|
+
* A `table` token carries every row, so the rebuild path costs Θ(C·N²)
|
|
2265
|
+
* `RichText` constructions across a stream — and a further 2×, because
|
|
2266
|
+
* `Table.layout()` re-runs `fitCell` on every cell. This was the last block
|
|
2267
|
+
* type without an in-place path.
|
|
2268
|
+
*
|
|
2269
|
+
* Two shapes have to be handled, because of how `marked` lexes a growing table
|
|
2270
|
+
* (probed against 18.0.7): a partial row is materialized immediately as a FULL
|
|
2271
|
+
* row padded with empty cells, and its cells are then filled one at a time. A
|
|
2272
|
+
* 2×2 table passes through eleven distinct row states, of which only two are
|
|
2273
|
+
* clean row appends. So handling appends alone would reject most chunks and
|
|
2274
|
+
* leave the quadratic cost essentially in place:
|
|
2275
|
+
*
|
|
2276
|
+
* 1. the last row's cells are rewritten in place via `setSpans`, and
|
|
2277
|
+
* 2. genuinely new rows go through `Table.appendRows`.
|
|
2278
|
+
*
|
|
2279
|
+
* Cells are compared by `text`, never `raw` — a table cell has no `raw` at all
|
|
2280
|
+
* (its keys are `text`/`tokens`/`header`/`align`).
|
|
2281
|
+
*/
|
|
2282
|
+
updateStreamedTable(entity, oldToken, newToken) {
|
|
2283
|
+
if (!(entity instanceof Table)) return false;
|
|
2284
|
+
if (oldToken.header.length !== newToken.header.length) return false;
|
|
2285
|
+
for (let c = 0; c < oldToken.header.length; c++) {
|
|
2286
|
+
if (oldToken.header[c].text !== newToken.header[c].text) return false;
|
|
2287
|
+
}
|
|
2288
|
+
if (newToken.rows.length < oldToken.rows.length) return false;
|
|
2289
|
+
if (entity.rows.length !== oldToken.rows.length) return false;
|
|
2290
|
+
const lastRetained = oldToken.rows.length - 1;
|
|
2291
|
+
for (let r = 0; r < lastRetained; r++) {
|
|
2292
|
+
const oldRow = oldToken.rows[r];
|
|
2293
|
+
const newRow = newToken.rows[r];
|
|
2294
|
+
for (let c = 0; c < oldToken.header.length; c++) {
|
|
2295
|
+
if (oldRow[c]?.text !== newRow[c]?.text) return false;
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
if (lastRetained >= 0) {
|
|
2299
|
+
for (let c = 0; c < oldToken.header.length; c++) {
|
|
2300
|
+
const cell = entity.rows[lastRetained]?.[c];
|
|
2301
|
+
if (!(cell instanceof RichText)) return false;
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
const t = this.theme;
|
|
2305
|
+
let changed = false;
|
|
2306
|
+
if (lastRetained >= 0) {
|
|
2307
|
+
const oldRow = oldToken.rows[lastRetained];
|
|
2308
|
+
const newRow = newToken.rows[lastRetained];
|
|
2309
|
+
for (let c = 0; c < oldToken.header.length; c++) {
|
|
2310
|
+
if (oldRow[c]?.text === newRow[c]?.text) continue;
|
|
2311
|
+
const cell = entity.rows[lastRetained][c];
|
|
2312
|
+
cell.setSpans(this.tableCellSpans(newRow[c], t));
|
|
2313
|
+
changed = true;
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
if (newToken.rows.length > oldToken.rows.length) {
|
|
2317
|
+
const added = newToken.rows.slice(oldToken.rows.length).map((row) => row.map((cell) => this.tableCellRichText(cell, false, t)));
|
|
2318
|
+
entity.appendRows(added);
|
|
2319
|
+
} else if (changed) {
|
|
2320
|
+
entity.layout();
|
|
2321
|
+
}
|
|
2322
|
+
return true;
|
|
2323
|
+
}
|
|
2324
|
+
updateBlockquoteTail(container, oldInner, newInner) {
|
|
2325
|
+
if (oldInner.length !== newInner.length || newInner.length === 0) return false;
|
|
2326
|
+
const tail = newInner.length - 1;
|
|
2327
|
+
for (let i = 0; i < tail; i++) {
|
|
2328
|
+
if (oldInner[i].raw !== newInner[i].raw) return false;
|
|
2329
|
+
}
|
|
2330
|
+
const oldTail = oldInner[tail];
|
|
2331
|
+
const newTail = newInner[tail];
|
|
2332
|
+
if (oldTail.type !== newTail.type) return false;
|
|
2333
|
+
const innerStack = container.children[1];
|
|
2334
|
+
if (!(innerStack instanceof Stack)) return false;
|
|
2335
|
+
const wrapper = innerStack.children.at(-1);
|
|
2336
|
+
if (!wrapper || wrapper.children.length !== 1) return false;
|
|
2337
|
+
const entity = wrapper.children[0];
|
|
2338
|
+
if (!this.producesEntity(newTail)) return false;
|
|
2339
|
+
if (newTail.type === "paragraph" && "setSpans" in entity) {
|
|
2340
|
+
entity.setSpans(
|
|
2341
|
+
this.literalParagraphSpans(newTail)
|
|
2342
|
+
);
|
|
2343
|
+
} else if (newTail.type === "heading" && "setSpans" in entity) {
|
|
2344
|
+
if (oldTail.depth !== newTail.depth) {
|
|
2345
|
+
return false;
|
|
2346
|
+
}
|
|
2347
|
+
entity.setSpans(
|
|
2348
|
+
this.headingSpans(newTail)
|
|
2349
|
+
);
|
|
2350
|
+
} else if (newTail.type === "code" && entity instanceof CodeBlock && !rendersAsMath(newTail)) {
|
|
2351
|
+
const codeToken = newTail;
|
|
2352
|
+
entity.setCode(codeToken.text, codeToken.lang ?? void 0);
|
|
2353
|
+
} else {
|
|
2354
|
+
return false;
|
|
2355
|
+
}
|
|
2356
|
+
wrapper.width = entity.x + entity.width;
|
|
2357
|
+
wrapper.height = entity.height;
|
|
2358
|
+
innerStack.resizeLastChild(wrapper);
|
|
2359
|
+
const border = container.children[0];
|
|
2360
|
+
if (border instanceof QuoteBorder) border.height = innerStack.height || 20;
|
|
2361
|
+
container.height = Math.max(border?.height ?? 0, innerStack.height);
|
|
2362
|
+
return true;
|
|
2363
|
+
}
|
|
2364
|
+
/**
|
|
2365
|
+
* Spans for a heading being updated in place.
|
|
2366
|
+
*
|
|
2367
|
+
* Kept in lockstep with the `heading` arm of {@link renderToken}, which builds
|
|
2368
|
+
* its `RichText` through `renderInlineToRichText`: same `collectSpans` call and
|
|
2369
|
+
* the same `decodeEntities` fallback when a heading has no inline tokens (`##`
|
|
2370
|
+
* with no text yet, which a stream produces before its first word arrives). A
|
|
2371
|
+
* plain `token.text` fallback here would leave an entity-bearing heading
|
|
2372
|
+
* undecoded on the in-place path but decoded on a fresh render.
|
|
2373
|
+
*/
|
|
2374
|
+
headingSpans(token) {
|
|
2375
|
+
const spans = [];
|
|
2376
|
+
if (token.tokens && token.tokens.length > 0) {
|
|
2377
|
+
collectSpans(token.tokens, {}, this.theme, spans);
|
|
2378
|
+
}
|
|
2379
|
+
if (spans.length === 0) spans.push({ text: decodeEntities(token.text) });
|
|
2380
|
+
return spans;
|
|
2381
|
+
}
|
|
2382
|
+
/**
|
|
2383
|
+
* Spans for the trailing paragraph with its last unclosed inline construct
|
|
2384
|
+
* rendered as though it had closed, or `null` when there is nothing to guess.
|
|
2385
|
+
*
|
|
2386
|
+
* `null` is the answer for every `'literal'` stream, every closed or absent
|
|
2387
|
+
* stream, and any trailing paragraph whose syntax is all balanced — so the
|
|
2388
|
+
* caller falls back to {@link literalParagraphSpans} and pays nothing.
|
|
2389
|
+
*
|
|
2390
|
+
* Only the paragraph's LAST inline token is scanned. An unclosed construct can
|
|
2391
|
+
* only be there: anything that closed is already its own `strong`/`em`/
|
|
2392
|
+
* `codespan`/`link` token, so a syntax character surviving into a trailing
|
|
2393
|
+
* plain-text run is one `marked` could not pair. Scanning the whole raw string
|
|
2394
|
+
* instead would re-find the markers of already-closed constructs.
|
|
2395
|
+
*/
|
|
2396
|
+
optimisticParagraphSpans(token) {
|
|
2397
|
+
if (this.streamIncompleteMode !== "optimistic") return null;
|
|
2398
|
+
if (this.streamController?.state !== "open") return null;
|
|
2399
|
+
const inline = token.tokens;
|
|
2400
|
+
if (!inline || inline.length === 0) return null;
|
|
2401
|
+
let runLength = 1;
|
|
2402
|
+
let runText;
|
|
2403
|
+
const last = inline[inline.length - 1];
|
|
2404
|
+
const prev = inline.length > 1 ? inline[inline.length - 2] : null;
|
|
2405
|
+
const isFlatText = (token2) => token2.type === "text" && !token2.tokens?.length;
|
|
2406
|
+
if (last.type === "link" && last.raw === last.text && prev !== null && isFlatText(prev) && prev.text.endsWith("](")) {
|
|
2407
|
+
runLength = 2;
|
|
2408
|
+
runText = prev.text + last.raw;
|
|
2409
|
+
} else if (isFlatText(last)) {
|
|
2410
|
+
runText = last.text;
|
|
2411
|
+
} else {
|
|
2412
|
+
return null;
|
|
2413
|
+
}
|
|
2414
|
+
const found = findUnclosedInline(runText);
|
|
2415
|
+
if (!found) return null;
|
|
2416
|
+
const spans = [];
|
|
2417
|
+
if (inline.length > runLength) {
|
|
2418
|
+
collectSpans(inline.slice(0, -runLength), {}, this.theme, spans);
|
|
2419
|
+
}
|
|
2420
|
+
const head = runText.slice(0, found.at);
|
|
2421
|
+
if (head) spans.push({ text: decodeEntities(head) });
|
|
2422
|
+
let content = runText.slice(found.contentAt);
|
|
2423
|
+
if (found.kind === "link") {
|
|
2424
|
+
const close = content.indexOf("](");
|
|
2425
|
+
if (close !== -1) content = content.slice(0, close);
|
|
2426
|
+
}
|
|
2427
|
+
if (!content) return null;
|
|
2428
|
+
const style = this.optimisticStyle(found.kind);
|
|
2429
|
+
spans.push({ text: decodeEntities(content), style });
|
|
2430
|
+
return spans;
|
|
2431
|
+
}
|
|
2432
|
+
/** Display style for a guessed-closed construct. */
|
|
2433
|
+
optimisticStyle(kind) {
|
|
2434
|
+
switch (kind) {
|
|
2435
|
+
case "strong":
|
|
2436
|
+
return { bold: true };
|
|
2437
|
+
case "em":
|
|
2438
|
+
return { italic: true };
|
|
2439
|
+
case "codespan":
|
|
2440
|
+
return { color: this.theme.codeColor, fontFamily: this.theme.codeFont };
|
|
2441
|
+
// A link with no closing paren has no href, so it renders as plain text —
|
|
2442
|
+
// no link color and no click affordance for a destination nobody has yet.
|
|
2443
|
+
case "link":
|
|
2444
|
+
return void 0;
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
/**
|
|
2448
|
+
* Re-render the paragraph currently showing a guess from its own tokens, with
|
|
2449
|
+
* no overlay, and forget it.
|
|
2450
|
+
*
|
|
2451
|
+
* Idempotent and free when no guess is live, which is what lets `close()`,
|
|
2452
|
+
* `abort()`, and a mid-stream staleness check all call it unconditionally.
|
|
2453
|
+
*/
|
|
2454
|
+
/**
|
|
2455
|
+
* Start the MathJax load, and re-typeset this document once it resolves.
|
|
2456
|
+
*
|
|
2457
|
+
* Called from two places, for two different reasons:
|
|
2458
|
+
*
|
|
2459
|
+
* - When an OPEN math fence is rendered. This is a prefetch, and it is what
|
|
2460
|
+
* makes the lazy load invisible while streaming: the module starts loading
|
|
2461
|
+
* the moment a formula begins arriving, several chunks before its closing
|
|
2462
|
+
* fence, so by the time the fence closes the converter is usually already
|
|
2463
|
+
* installed and the formula typesets synchronously on the normal path.
|
|
2464
|
+
* - When a CLOSED fence could not be typeset because the module is not ready.
|
|
2465
|
+
* That is the case a rebuild actually exists for: a document constructed with
|
|
2466
|
+
* math already complete, or a stream that closed a fence faster than the
|
|
2467
|
+
* module loaded.
|
|
2468
|
+
*
|
|
2469
|
+
* Idempotent per instance. Concurrent callers coalesce onto the one cached
|
|
2470
|
+
* module promise, and `mathLoadPending` keeps a second rebuild from being
|
|
2471
|
+
* queued while the first is outstanding.
|
|
2472
|
+
*/
|
|
2473
|
+
ensureMathJax() {
|
|
2474
|
+
if (mathConverter || this.mathLoadPending || this.isDestroyed) return;
|
|
2475
|
+
this.mathLoadPending = true;
|
|
2476
|
+
void preloadMathJax().then(() => {
|
|
2477
|
+
this.mathLoadPending = false;
|
|
2478
|
+
if (this.isDestroyed) return;
|
|
2479
|
+
if (mathConverter) this.retypesetFromTokens();
|
|
2480
|
+
this.flushAppendSettledWaiters();
|
|
2481
|
+
});
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Rebuild every block from the tokens already lexed, without re-lexing.
|
|
2485
|
+
*
|
|
2486
|
+
* Used only when MathJax arrives after a formula has already been rendered as
|
|
2487
|
+
* source. Rebuilding wholesale rather than surgically replacing the math blocks
|
|
2488
|
+
* is the deliberate choice: `tokenChildPrefix` maps token indices to child
|
|
2489
|
+
* slots positionally, so swapping one child in place would have to keep that
|
|
2490
|
+
* mapping, the `Stack`'s cached box, and every following sibling's position in
|
|
2491
|
+
* agreement by hand. Re-rendering the same token list in the same order leaves
|
|
2492
|
+
* the mapping trivially correct, and this runs at most once per document — the
|
|
2493
|
+
* same cost as the `setContent` rebuild that already exists.
|
|
2494
|
+
*
|
|
2495
|
+
* The optimistic tail is dropped first. Its `entity` is about to be destroyed,
|
|
2496
|
+
* so the pointer would dangle; unwinding restores literal spans, and if the
|
|
2497
|
+
* stream is still open the next chunk re-applies a guess.
|
|
2498
|
+
*/
|
|
2499
|
+
retypesetFromTokens() {
|
|
2500
|
+
this.unwindOptimisticTail();
|
|
2501
|
+
const tokens = this.tokens;
|
|
2502
|
+
while (this.content.children.length > 0) {
|
|
2503
|
+
this.content.children[this.content.children.length - 1].destroy();
|
|
2504
|
+
}
|
|
2505
|
+
for (const token of tokens) {
|
|
2506
|
+
const el = this.renderToken(token);
|
|
2507
|
+
if (el) this.content.add(el);
|
|
2508
|
+
}
|
|
2509
|
+
this.width = this.content.width;
|
|
2510
|
+
this.height = this.content.height;
|
|
2511
|
+
this.scene?.markDirty();
|
|
2512
|
+
}
|
|
2513
|
+
unwindOptimisticTail() {
|
|
2514
|
+
const tail = this.optimisticTail;
|
|
2515
|
+
this.optimisticTail = null;
|
|
2516
|
+
if (!tail || this.isDestroyed) return;
|
|
2517
|
+
const entity = tail.entity;
|
|
2518
|
+
if (!entity.setSpans || entity.parent !== this.content) return;
|
|
2519
|
+
entity.setSpans(this.literalParagraphSpans(tail.token));
|
|
2520
|
+
if (this.content.children.at(-1) === entity) {
|
|
2521
|
+
this.content.resizeLastChild(entity);
|
|
2522
|
+
} else {
|
|
2523
|
+
this.content.layout();
|
|
2524
|
+
}
|
|
2525
|
+
this.width = this.content.width;
|
|
2526
|
+
this.height = this.content.height;
|
|
2527
|
+
this.scene?.markDirty();
|
|
2528
|
+
}
|
|
2529
|
+
/**
|
|
2530
|
+
* Drop a guess that is no longer on the document's trailing paragraph.
|
|
2531
|
+
*
|
|
2532
|
+
* A coalesced append can add a block after the paragraph that owns the guess,
|
|
2533
|
+
* at which point the guess is frozen — the construct can never close, because
|
|
2534
|
+
* no further text lands in that paragraph. Without this the stale styling would
|
|
2535
|
+
* survive until `close()`.
|
|
2536
|
+
*
|
|
2537
|
+
* `writtenThisPass` is the entity whose spans this reconcile already rewrote,
|
|
2538
|
+
* if any: for that one, literal spans are on screen already and re-rendering it
|
|
2539
|
+
* would be wasted layout, so only the bookkeeping is cleared.
|
|
2540
|
+
*/
|
|
2541
|
+
dropStaleOptimisticTail(trailing, writtenThisPass) {
|
|
2542
|
+
const tail = this.optimisticTail;
|
|
2543
|
+
if (!tail || tail.entity === trailing) return;
|
|
2544
|
+
if (tail.entity === writtenThisPass) {
|
|
2545
|
+
this.optimisticTail = null;
|
|
2546
|
+
return;
|
|
2547
|
+
}
|
|
2548
|
+
this.unwindOptimisticTail();
|
|
2549
|
+
}
|
|
2550
|
+
/**
|
|
2551
|
+
* Resolve once every in-flight worker append has actually been applied.
|
|
2552
|
+
*
|
|
2553
|
+
* Committing text is not the same as the document reflecting it: `append()`
|
|
2554
|
+
* reaches `dispatchAppend()`, which `postMessage()`s and returns, and the reply
|
|
2555
|
+
* that runs `updateTokens()` lands later. Without waiting here, `close()` could
|
|
2556
|
+
* resolve — and `onStable` fire — against a document missing its last chunk.
|
|
2557
|
+
*
|
|
2558
|
+
* An outstanding lazy MathJax load counts as unsettled for the same reason. A
|
|
2559
|
+
* document whose formulas are still TeX source is not final in any sense a
|
|
2560
|
+
* caller of `onStable` cares about: the boxes are the wrong size, so measuring
|
|
2561
|
+
* or exporting there would capture placeholders.
|
|
2562
|
+
*/
|
|
2563
|
+
waitForAppendSettled() {
|
|
2564
|
+
if (!this.appendInFlight && !this.mathLoadPending) return Promise.resolve();
|
|
2565
|
+
return new Promise((resolve) => {
|
|
2566
|
+
this.appendSettledWaiters.push(resolve);
|
|
2567
|
+
});
|
|
2568
|
+
}
|
|
2569
|
+
/**
|
|
2570
|
+
* Release settlement waiters, but only once nothing is outstanding.
|
|
2571
|
+
*
|
|
2572
|
+
* Called at the very END of the worker callback, after its coalesced-re-dispatch
|
|
2573
|
+
* check, rather than wherever `appendInFlight` goes false. Within that callback
|
|
2574
|
+
* `appendInFlight` is cleared and then, if another chunk arrived while the
|
|
2575
|
+
* request was in flight, set straight back to `true` by the re-dispatch — both
|
|
2576
|
+
* synchronously, before anything watching the flag could observe the gap. Only
|
|
2577
|
+
* checking here, after that, waits through the re-dispatch instead of resolving
|
|
2578
|
+
* one chunk early.
|
|
2579
|
+
*/
|
|
2580
|
+
flushAppendSettledWaiters() {
|
|
2581
|
+
if (this.appendInFlight || this.mathLoadPending || this.appendSettledWaiters.length === 0) {
|
|
2582
|
+
return;
|
|
2583
|
+
}
|
|
2584
|
+
const waiters = this.appendSettledWaiters;
|
|
2585
|
+
this.appendSettledWaiters = [];
|
|
2586
|
+
for (const resolve of waiters) resolve();
|
|
2587
|
+
}
|
|
2588
|
+
/** Throw if a public mutation is attempted from inside an `onStable` callback. */
|
|
2589
|
+
assertNotInStableCallback(method) {
|
|
2590
|
+
if (this.inStableCallback) {
|
|
2591
|
+
throw new Error(`Markdown.${method}() cannot be called from an onStable callback`);
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
1616
2594
|
updateTokens(newTokens, knownMatchLen) {
|
|
1617
2595
|
const oldTokens = this.tokens;
|
|
1618
2596
|
const oldChildren = [...this.content.children];
|
|
@@ -1632,11 +2610,18 @@ var Markdown = class extends UIComponent {
|
|
|
1632
2610
|
}
|
|
1633
2611
|
const oldTokenToChild = this.tokenChildPrefix;
|
|
1634
2612
|
const rawMatchLen = matchLen;
|
|
2613
|
+
let pendingTail = null;
|
|
2614
|
+
let spansWrittenTo = null;
|
|
1635
2615
|
const lastTokenSameType = matchLen === oldTokens.length - 1 && matchLen < newTokens.length && oldTokens[matchLen]?.type === newTokens[matchLen]?.type;
|
|
1636
2616
|
if (lastTokenSameType && newTokens[matchLen]?.type === "code") {
|
|
1637
2617
|
const existingEntity = oldChildren[oldTokenToChild[matchLen]];
|
|
1638
2618
|
const codeToken = newTokens[matchLen];
|
|
1639
|
-
|
|
2619
|
+
const oldCodeToken = oldTokens[matchLen];
|
|
2620
|
+
const isMath = rendersAsMath(codeToken);
|
|
2621
|
+
if (isMath && rendersAsMath(oldCodeToken) && oldCodeToken.text === codeToken.text) {
|
|
2622
|
+
this.streamStats.inPlaceUpdates++;
|
|
2623
|
+
matchLen++;
|
|
2624
|
+
} else if (existingEntity instanceof CodeBlock && !isMath) {
|
|
1640
2625
|
existingEntity.setCode(codeToken.text, codeToken.lang ?? void 0);
|
|
1641
2626
|
this.streamStats.inPlaceUpdates++;
|
|
1642
2627
|
matchLen++;
|
|
@@ -1645,17 +2630,63 @@ var Markdown = class extends UIComponent {
|
|
|
1645
2630
|
} else if (lastTokenSameType && newTokens[matchLen]?.type === "paragraph") {
|
|
1646
2631
|
const entityIdx = oldTokenToChild[matchLen];
|
|
1647
2632
|
const existingEntity = oldChildren[entityIdx];
|
|
1648
|
-
if (existingEntity && "setSpans" in existingEntity) {
|
|
2633
|
+
if (existingEntity && "setSpans" in existingEntity && !paragraphHasImage(newTokens[matchLen])) {
|
|
1649
2634
|
const pToken = newTokens[matchLen];
|
|
1650
|
-
const
|
|
1651
|
-
const
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
}
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
2635
|
+
const isTrailing = matchLen === newTokens.length - 1;
|
|
2636
|
+
const optimistic = isTrailing ? this.optimisticParagraphSpans(pToken) : null;
|
|
2637
|
+
existingEntity.setSpans(optimistic ?? this.literalParagraphSpans(pToken));
|
|
2638
|
+
spansWrittenTo = existingEntity;
|
|
2639
|
+
if (optimistic) pendingTail = { entity: existingEntity, token: pToken };
|
|
2640
|
+
this.streamStats.inPlaceUpdates++;
|
|
2641
|
+
matchLen++;
|
|
2642
|
+
this.content.resizeLastChild(existingEntity);
|
|
2643
|
+
} else if (existingEntity && this.updateImageParagraph(
|
|
2644
|
+
existingEntity,
|
|
2645
|
+
oldTokens[matchLen],
|
|
2646
|
+
newTokens[matchLen]
|
|
2647
|
+
)) {
|
|
2648
|
+
this.streamStats.inPlaceUpdates++;
|
|
2649
|
+
matchLen++;
|
|
2650
|
+
this.content.resizeLastChild(existingEntity);
|
|
2651
|
+
}
|
|
2652
|
+
} else if (lastTokenSameType && newTokens[matchLen]?.type === "heading") {
|
|
2653
|
+
const existingEntity = oldChildren[oldTokenToChild[matchLen]];
|
|
2654
|
+
const hToken = newTokens[matchLen];
|
|
2655
|
+
const oldToken = oldTokens[matchLen];
|
|
2656
|
+
if (existingEntity && "setSpans" in existingEntity && oldToken?.depth === hToken.depth) {
|
|
2657
|
+
existingEntity.setSpans(this.headingSpans(hToken));
|
|
2658
|
+
spansWrittenTo = existingEntity;
|
|
2659
|
+
this.streamStats.inPlaceUpdates++;
|
|
2660
|
+
matchLen++;
|
|
2661
|
+
this.content.resizeLastChild(existingEntity);
|
|
2662
|
+
}
|
|
2663
|
+
} else if (lastTokenSameType && newTokens[matchLen]?.type === "blockquote") {
|
|
2664
|
+
const existingEntity = oldChildren[oldTokenToChild[matchLen]];
|
|
2665
|
+
const newInner = newTokens[matchLen].tokens;
|
|
2666
|
+
const oldInner = oldTokens[matchLen].tokens;
|
|
2667
|
+
if (existingEntity instanceof MarkdownContainer && newInner && oldInner && this.updateBlockquoteTail(existingEntity, oldInner, newInner)) {
|
|
2668
|
+
this.streamStats.inPlaceUpdates++;
|
|
2669
|
+
matchLen++;
|
|
2670
|
+
this.content.resizeLastChild(existingEntity);
|
|
2671
|
+
}
|
|
2672
|
+
} else if (lastTokenSameType && newTokens[matchLen]?.type === "list") {
|
|
2673
|
+
const existingEntity = oldChildren[oldTokenToChild[matchLen]];
|
|
2674
|
+
if (existingEntity && this.updateStreamedList(
|
|
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 === "table") {
|
|
2684
|
+
const existingEntity = oldChildren[oldTokenToChild[matchLen]];
|
|
2685
|
+
if (existingEntity && this.updateStreamedTable(
|
|
2686
|
+
existingEntity,
|
|
2687
|
+
oldTokens[matchLen],
|
|
2688
|
+
newTokens[matchLen]
|
|
2689
|
+
)) {
|
|
1659
2690
|
this.streamStats.inPlaceUpdates++;
|
|
1660
2691
|
matchLen++;
|
|
1661
2692
|
this.content.resizeLastChild(existingEntity);
|
|
@@ -1673,10 +2704,24 @@ var Markdown = class extends UIComponent {
|
|
|
1673
2704
|
}
|
|
1674
2705
|
}
|
|
1675
2706
|
}
|
|
2707
|
+
const lastIndex = newTokens.length - 1;
|
|
1676
2708
|
for (let i = matchLen; i < newTokens.length; i++) {
|
|
1677
2709
|
const el = this.renderToken(newTokens[i]);
|
|
1678
|
-
if (el)
|
|
2710
|
+
if (!el) continue;
|
|
2711
|
+
this.content.add(el);
|
|
2712
|
+
if (i === lastIndex && newTokens[i].type === "paragraph" && "setSpans" in el) {
|
|
2713
|
+
const pToken = newTokens[i];
|
|
2714
|
+
const optimistic = this.optimisticParagraphSpans(pToken);
|
|
2715
|
+
if (optimistic) {
|
|
2716
|
+
el.setSpans(optimistic);
|
|
2717
|
+
this.content.resizeLastChild(el);
|
|
2718
|
+
pendingTail = { entity: el, token: pToken };
|
|
2719
|
+
spansWrittenTo = el;
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
1679
2722
|
}
|
|
2723
|
+
this.dropStaleOptimisticTail(pendingTail?.entity ?? null, spansWrittenTo);
|
|
2724
|
+
if (pendingTail) this.optimisticTail = pendingTail;
|
|
1680
2725
|
this.setTokens(newTokens, rawMatchLen);
|
|
1681
2726
|
this.width = this.content.width;
|
|
1682
2727
|
this.height = this.content.height;
|
|
@@ -1739,6 +2784,10 @@ var Markdown = class extends UIComponent {
|
|
|
1739
2784
|
availableWidth: this.maxWidth
|
|
1740
2785
|
};
|
|
1741
2786
|
const availableWidth = metrics.availableWidth;
|
|
2787
|
+
if (containsInlineMath(token)) {
|
|
2788
|
+
if (!mathConverter) this.ensureMathJax();
|
|
2789
|
+
this.subscribeInlineMathRepaint();
|
|
2790
|
+
}
|
|
1742
2791
|
switch (token.type) {
|
|
1743
2792
|
// ── Headings ─────────────────────────────────────────────────────
|
|
1744
2793
|
case "heading": {
|
|
@@ -1760,7 +2809,7 @@ var Markdown = class extends UIComponent {
|
|
|
1760
2809
|
// ── Paragraphs ───────────────────────────────────────────────────
|
|
1761
2810
|
case "paragraph": {
|
|
1762
2811
|
const pToken = token;
|
|
1763
|
-
if (!pToken
|
|
2812
|
+
if (!paragraphHasImage(pToken)) {
|
|
1764
2813
|
return renderInlineToRichText(
|
|
1765
2814
|
pToken.tokens,
|
|
1766
2815
|
pToken.text,
|
|
@@ -1780,43 +2829,14 @@ var Markdown = class extends UIComponent {
|
|
|
1780
2829
|
let currentTokens = [];
|
|
1781
2830
|
const flushText = () => {
|
|
1782
2831
|
if (currentTokens.length > 0) {
|
|
1783
|
-
stack.add(
|
|
1784
|
-
renderInlineToRichText(
|
|
1785
|
-
currentTokens,
|
|
1786
|
-
"",
|
|
1787
|
-
bodyFont,
|
|
1788
|
-
t.textColor,
|
|
1789
|
-
availableWidth,
|
|
1790
|
-
t,
|
|
1791
|
-
this.selectable,
|
|
1792
|
-
this.onLinkClick
|
|
1793
|
-
)
|
|
1794
|
-
);
|
|
2832
|
+
stack.add(this.inlineRunRichText(currentTokens, availableWidth, t));
|
|
1795
2833
|
currentTokens = [];
|
|
1796
2834
|
}
|
|
1797
2835
|
};
|
|
1798
2836
|
for (const child of pToken.tokens) {
|
|
1799
2837
|
if (child.type === "image") {
|
|
1800
2838
|
flushText();
|
|
1801
|
-
|
|
1802
|
-
const initialWidth = Math.min(800, availableWidth);
|
|
1803
|
-
const initialHeight = Math.round(initialWidth * 0.6);
|
|
1804
|
-
const img = new Image(imgToken.href, {
|
|
1805
|
-
width: initialWidth,
|
|
1806
|
-
height: initialHeight,
|
|
1807
|
-
alt: imgToken.text,
|
|
1808
|
-
radius: 8,
|
|
1809
|
-
onLoad: () => {
|
|
1810
|
-
const bmp = img.bitmap;
|
|
1811
|
-
if (bmp && bmp.naturalWidth && bmp.naturalHeight) {
|
|
1812
|
-
const aspect = bmp.naturalHeight / bmp.naturalWidth;
|
|
1813
|
-
img.width = Math.min(bmp.naturalWidth, availableWidth);
|
|
1814
|
-
img.height = Math.round(img.width * aspect);
|
|
1815
|
-
if (this.scene) this.scene.markDirty();
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
});
|
|
1819
|
-
stack.add(img);
|
|
2839
|
+
stack.add(this.paragraphImage(child, availableWidth));
|
|
1820
2840
|
} else {
|
|
1821
2841
|
currentTokens.push(child);
|
|
1822
2842
|
}
|
|
@@ -1828,13 +2848,22 @@ var Markdown = class extends UIComponent {
|
|
|
1828
2848
|
case "code": {
|
|
1829
2849
|
const codeToken = token;
|
|
1830
2850
|
const lang = (codeToken.lang ?? "").toLowerCase();
|
|
1831
|
-
if (lang
|
|
2851
|
+
if (MATH_LANGS.has(lang)) this.ensureMathJax();
|
|
2852
|
+
if (rendersAsMath(codeToken)) {
|
|
1832
2853
|
const mathData = renderMathToSVGDataURI(codeToken.text, true);
|
|
1833
2854
|
if (mathData) {
|
|
2855
|
+
const intrinsicW = exToPx(mathData.widthEx, t.fontSize);
|
|
2856
|
+
const intrinsicH = exToPx(mathData.heightEx, t.fontSize);
|
|
1834
2857
|
const mathImg = new Image(mathData.uri, {
|
|
1835
|
-
width: Math.min(availableWidth,
|
|
1836
|
-
height:
|
|
1837
|
-
alt: codeToken.text
|
|
2858
|
+
width: Math.min(availableWidth, intrinsicW),
|
|
2859
|
+
height: intrinsicH * Math.min(1, availableWidth / intrinsicW),
|
|
2860
|
+
alt: codeToken.text,
|
|
2861
|
+
// The SVG decodes asynchronously and Image paints a placeholder
|
|
2862
|
+
// until it lands. Without this an `onDemand` scene, which repaints
|
|
2863
|
+
// only when marked dirty, leaves the formula a blank slab forever.
|
|
2864
|
+
onLoad: () => {
|
|
2865
|
+
this.scene?.markDirty();
|
|
2866
|
+
}
|
|
1838
2867
|
});
|
|
1839
2868
|
const wrapper = new MarkdownContainer();
|
|
1840
2869
|
mathImg.x = 16;
|
|
@@ -1883,62 +2912,22 @@ var Markdown = class extends UIComponent {
|
|
|
1883
2912
|
container.height = Math.max(border.height, innerStack.height);
|
|
1884
2913
|
return container;
|
|
1885
2914
|
}
|
|
1886
|
-
// ── Lists
|
|
2915
|
+
// ── Lists ────────────────────────────────────────────────
|
|
1887
2916
|
case "list": {
|
|
1888
2917
|
const listToken = token;
|
|
1889
2918
|
const listStack = new Stack({ direction: "vertical", gap: 6 });
|
|
1890
2919
|
for (let i = 0; i < listToken.items.length; i++) {
|
|
1891
|
-
|
|
1892
|
-
const num = Number(listToken.start ?? 1) + i;
|
|
1893
|
-
const contentSpans = [];
|
|
1894
|
-
if (item.tokens && item.tokens.length > 0) {
|
|
1895
|
-
for (const inner of item.tokens) {
|
|
1896
|
-
if (inner.type === "text" && "tokens" in inner && inner.tokens?.length) {
|
|
1897
|
-
collectSpans(inner.tokens, {}, t, contentSpans);
|
|
1898
|
-
} else if ("tokens" in inner && inner.tokens?.length) {
|
|
1899
|
-
collectSpans(inner.tokens, {}, t, contentSpans);
|
|
1900
|
-
} else if ("text" in inner) {
|
|
1901
|
-
contentSpans.push({
|
|
1902
|
-
text: decodeEntities(inner.text)
|
|
1903
|
-
});
|
|
1904
|
-
}
|
|
1905
|
-
}
|
|
1906
|
-
} else {
|
|
1907
|
-
contentSpans.push({ text: decodeEntities(item.text) });
|
|
1908
|
-
}
|
|
1909
|
-
const itemIsRtl = BidiResolver.getBaseLevel(contentSpans.map((s) => s.text).join("")) % 2 === 1;
|
|
1910
|
-
const itemSpans = itemIsRtl ? [...contentSpans, { text: listToken.ordered ? ` .${num}` : " \u2022" }] : [{ text: listToken.ordered ? `${num}. ` : "\u2022 " }, ...contentSpans];
|
|
1911
|
-
const itemRt = new RichText(itemSpans, {
|
|
1912
|
-
font: bodyFont,
|
|
1913
|
-
color: t.textColor,
|
|
1914
|
-
maxWidth: Math.max(0, availableWidth - 24),
|
|
1915
|
-
linkColor: "#38bdf8",
|
|
1916
|
-
selectable: this.selectable,
|
|
1917
|
-
onLinkClick: this.onLinkClick
|
|
1918
|
-
});
|
|
1919
|
-
itemRt.x = 12;
|
|
1920
|
-
listStack.add(itemRt);
|
|
2920
|
+
listStack.add(this.listItemRichText(listToken, i, availableWidth, t));
|
|
1921
2921
|
}
|
|
1922
2922
|
return listStack;
|
|
1923
2923
|
}
|
|
1924
2924
|
// ── Table ────────────────────────────────────────────────────────
|
|
1925
2925
|
case "table": {
|
|
1926
2926
|
const tblToken = token;
|
|
1927
|
-
const
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
return new RichText(spans, {
|
|
1932
|
-
font: `${t.fontSize - 2}px ${t.bodyFont}`,
|
|
1933
|
-
color: header ? t.headingColor : t.textColor,
|
|
1934
|
-
baseStyle: header ? { bold: true } : void 0,
|
|
1935
|
-
linkColor: "#38bdf8",
|
|
1936
|
-
selectable: this.selectable,
|
|
1937
|
-
onLinkClick: this.onLinkClick
|
|
1938
|
-
});
|
|
1939
|
-
};
|
|
1940
|
-
const headers = tblToken.header.map((cell) => buildCell(cell, true));
|
|
1941
|
-
const rows = tblToken.rows.map((row) => row.map((cell) => buildCell(cell, false)));
|
|
2927
|
+
const headers = tblToken.header.map((cell) => this.tableCellRichText(cell, true, t));
|
|
2928
|
+
const rows = tblToken.rows.map(
|
|
2929
|
+
(row) => row.map((cell) => this.tableCellRichText(cell, false, t))
|
|
2930
|
+
);
|
|
1942
2931
|
return new Table({
|
|
1943
2932
|
headers,
|
|
1944
2933
|
rows,
|
|
@@ -1988,5 +2977,7 @@ export {
|
|
|
1988
2977
|
CodeBlock,
|
|
1989
2978
|
Markdown,
|
|
1990
2979
|
codeAtlas,
|
|
1991
|
-
codeAtlasStats
|
|
2980
|
+
codeAtlasStats,
|
|
2981
|
+
isMathJaxReady,
|
|
2982
|
+
preloadMathJax
|
|
1992
2983
|
};
|