@stream-mdx/react 0.5.0 → 1.0.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.
Files changed (99) hide show
  1. package/CHANGELOG.md +371 -0
  2. package/README.md +79 -4
  3. package/dist/blocks-renderer-DAOBFBfi.d.ts +29 -0
  4. package/dist/blocks-renderer-DQEL1kJW.d.cts +29 -0
  5. package/dist/components/bottom-stick-scroll-area.cjs +117 -193
  6. package/dist/components/bottom-stick-scroll-area.mjs +112 -183
  7. package/dist/components/diff-renderer.cjs +86 -0
  8. package/dist/components/diff-renderer.d.cts +11 -0
  9. package/dist/components/diff-renderer.d.ts +11 -0
  10. package/dist/components/diff-renderer.mjs +66 -0
  11. package/dist/components/index.cjs +2761 -1508
  12. package/dist/components/index.d.cts +7 -2
  13. package/dist/components/index.d.ts +7 -2
  14. package/dist/components/index.mjs +2730 -1493
  15. package/dist/components/katex-math.cjs +220 -0
  16. package/dist/components/katex-math.d.cts +10 -0
  17. package/dist/components/katex-math.d.ts +10 -0
  18. package/dist/components/katex-math.mjs +188 -0
  19. package/dist/contexts/math-tracker.cjs +240 -521
  20. package/dist/contexts/math-tracker.mjs +235 -513
  21. package/dist/index-Cmne1yUK.d.cts +723 -0
  22. package/dist/index-D7dyyu3q.d.ts +723 -0
  23. package/dist/index.cjs +13029 -6475
  24. package/dist/index.d.cts +69 -39
  25. package/dist/index.d.ts +69 -39
  26. package/dist/index.mjs +13007 -6442
  27. package/dist/math/display-wrapper.cjs +7 -15
  28. package/dist/math/display-wrapper.d.cts +2 -2
  29. package/dist/math/display-wrapper.d.ts +2 -2
  30. package/dist/math/display-wrapper.mjs +2 -6
  31. package/dist/node-views-Bpc6Gkgl.d.cts +13 -0
  32. package/dist/node-views-DpnYdaAS.d.ts +13 -0
  33. package/dist/renderer/hooks.cjs +35 -20
  34. package/dist/renderer/hooks.d.cts +22 -1
  35. package/dist/renderer/hooks.d.ts +22 -1
  36. package/dist/renderer/hooks.mjs +27 -12
  37. package/dist/renderer/patch-batching.cjs +5 -8
  38. package/dist/renderer/patch-coalescing.cjs +5 -8
  39. package/dist/renderer/patch-commit-scheduler.cjs +138 -356
  40. package/dist/renderer/patch-commit-scheduler.d.cts +13 -1
  41. package/dist/renderer/patch-commit-scheduler.d.ts +13 -1
  42. package/dist/renderer/patch-commit-scheduler.mjs +133 -348
  43. package/dist/renderer/store.cjs +3775 -1373
  44. package/dist/renderer/store.d.cts +108 -3
  45. package/dist/renderer/store.d.ts +108 -3
  46. package/dist/renderer/store.mjs +3778 -1362
  47. package/dist/renderer/virtualized-code.cjs +415 -71
  48. package/dist/renderer/virtualized-code.d.cts +24 -23
  49. package/dist/renderer/virtualized-code.d.ts +24 -23
  50. package/dist/renderer/virtualized-code.mjs +409 -62
  51. package/dist/renderer.cjs +10655 -4334
  52. package/dist/renderer.d.cts +98 -29
  53. package/dist/renderer.d.ts +98 -29
  54. package/dist/renderer.mjs +10582 -4212
  55. package/dist/server-regions-CPLHGli0.d.cts +32 -0
  56. package/dist/server-regions-mUhyoKi7.d.ts +32 -0
  57. package/dist/server.cjs +10195 -3872
  58. package/dist/server.d.cts +17 -252
  59. package/dist/server.d.ts +17 -252
  60. package/dist/server.mjs +9997 -3649
  61. package/dist/{streaming-markdown-CEI9eDZm.d.ts → streaming-markdown-yELbJxyH.d.ts} +49 -55
  62. package/dist/{streaming-markdown-DRisClXb.d.cts → streaming-markdown-zVwFuaJG.d.cts} +49 -55
  63. package/dist/streaming-markdown.cjs +11660 -5378
  64. package/dist/streaming-markdown.d.cts +7 -2
  65. package/dist/streaming-markdown.d.ts +7 -2
  66. package/dist/streaming-markdown.mjs +11679 -5347
  67. package/dist/trusted-mdx/index.cjs +833 -0
  68. package/dist/trusted-mdx/index.d.cts +11 -0
  69. package/dist/trusted-mdx/index.d.ts +11 -0
  70. package/dist/trusted-mdx/index.mjs +807 -0
  71. package/dist/trusted-mdx/native-children-slot.cjs +45 -0
  72. package/dist/trusted-mdx/native-children-slot.d.cts +11 -0
  73. package/dist/trusted-mdx/native-children-slot.d.ts +11 -0
  74. package/dist/trusted-mdx/native-children-slot.mjs +24 -0
  75. package/dist/trusted-mdx/server.cjs +752 -0
  76. package/dist/trusted-mdx/server.d.cts +24 -0
  77. package/dist/trusted-mdx/server.d.ts +24 -0
  78. package/dist/trusted-mdx/server.mjs +724 -0
  79. package/dist/trusted-mdx-contract-ElKpkDI5.d.cts +113 -0
  80. package/dist/trusted-mdx-contract-ElKpkDI5.d.ts +113 -0
  81. package/dist/utils/inline-html.cjs +246 -147
  82. package/dist/utils/inline-html.d.cts +37 -6
  83. package/dist/utils/inline-html.d.ts +37 -6
  84. package/dist/utils/inline-html.mjs +237 -134
  85. package/package.json +41 -18
  86. package/dist/index-BVhp_pcF.d.ts +0 -251
  87. package/dist/index-EaeouYp2.d.cts +0 -251
  88. package/dist/mdx-client.cjs +0 -408
  89. package/dist/mdx-client.d.cts +0 -113
  90. package/dist/mdx-client.d.ts +0 -113
  91. package/dist/mdx-client.mjs +0 -369
  92. package/dist/mdx-coordinator.cjs +0 -584
  93. package/dist/mdx-coordinator.d.cts +0 -21
  94. package/dist/mdx-coordinator.d.ts +0 -21
  95. package/dist/mdx-coordinator.mjs +0 -550
  96. package/dist/renderer/node-views.cjs +0 -1887
  97. package/dist/renderer/node-views.d.cts +0 -14
  98. package/dist/renderer/node-views.d.ts +0 -14
  99. package/dist/renderer/node-views.mjs +0 -1861
@@ -1,1861 +0,0 @@
1
- "use client";
2
-
3
- // src/renderer/node-views.tsx
4
- import { getDefaultCodeWrapperAttributes as getDefaultCodeWrapperAttributes2, stripCodeFence } from "@stream-mdx/core";
5
- import React5 from "react";
6
-
7
- // src/components/index.ts
8
- import { createTrustedHTML, sanitizeHTML } from "@stream-mdx/core";
9
-
10
- // src/renderer/use-deferred-render.ts
11
- import { useEffect, useState } from "react";
12
- function useDeferredRender(ref, options) {
13
- const enabled = options?.enabled ?? true;
14
- const [shouldRender, setShouldRender] = useState(!enabled);
15
- useEffect(() => {
16
- if (!enabled) {
17
- setShouldRender(true);
18
- return;
19
- }
20
- const target = ref.current;
21
- if (!target) {
22
- return;
23
- }
24
- let cancelled = false;
25
- let idleId = null;
26
- let timerId = null;
27
- const scheduleRender = () => {
28
- if (cancelled) return;
29
- setShouldRender(true);
30
- };
31
- const runWithIdle = () => {
32
- if (typeof globalThis.requestIdleCallback === "function") {
33
- idleId = globalThis.requestIdleCallback(scheduleRender, { timeout: options?.idleTimeoutMs ?? 200 });
34
- } else {
35
- timerId = window.setTimeout(scheduleRender, options?.idleTimeoutMs ?? 200);
36
- }
37
- };
38
- const observer = new IntersectionObserver(
39
- (entries) => {
40
- for (const entry of entries) {
41
- if (entry.isIntersecting || entry.intersectionRatio > 0) {
42
- observer.disconnect();
43
- const debounceMs = options?.debounceMs ?? 80;
44
- timerId = window.setTimeout(runWithIdle, debounceMs);
45
- return;
46
- }
47
- }
48
- },
49
- { rootMargin: options?.rootMargin ?? "200px 0px" }
50
- );
51
- observer.observe(target);
52
- return () => {
53
- cancelled = true;
54
- observer.disconnect();
55
- if (idleId !== null && typeof globalThis.cancelIdleCallback === "function") {
56
- globalThis.cancelIdleCallback(idleId);
57
- }
58
- if (timerId !== null) {
59
- window.clearTimeout(timerId);
60
- }
61
- };
62
- }, [enabled, options?.debounceMs, options?.idleTimeoutMs, options?.rootMargin, ref]);
63
- return shouldRender;
64
- }
65
-
66
- // src/components/index.ts
67
- import { removeHeadingMarkers } from "@stream-mdx/core";
68
- import React2 from "react";
69
-
70
- // src/utils/inline-html.ts
71
- import React from "react";
72
- var BACKTICK_CONTENT = /^`([\s\S]+)`$/;
73
- var DEFAULT_INLINE_HTML_RENDERERS = {
74
- kbd: (descriptor, ctx) => {
75
- const trimmed = descriptor.rawInner.trim();
76
- const match = BACKTICK_CONTENT.exec(trimmed);
77
- if (match) {
78
- const codeText = decodeHtmlEntities(match[1]);
79
- const props = mapAttributesToProps(descriptor.attributes);
80
- if (ctx.key !== void 0 && ctx.key !== null) {
81
- props.key = ctx.key;
82
- }
83
- return React.createElement("kbd", props, React.createElement("code", { className: "inline-code" }, codeText));
84
- }
85
- return ctx.defaultRender();
86
- }
87
- };
88
- function renderInlineHtmlSegment(raw, sanitized, options = {}) {
89
- const descriptor = parseInlineHtmlDescriptor(raw, sanitized);
90
- if (!descriptor) {
91
- return null;
92
- }
93
- const className = options.className ?? "markdown-inline-html";
94
- const isInlineTag = INLINE_ELEMENTS.has(descriptor.tagName);
95
- const defaultRender = () => {
96
- if (!descriptor.sanitized || descriptor.sanitized.length === 0) {
97
- if (!descriptor.text) {
98
- return null;
99
- }
100
- if (options.key !== void 0 && options.key !== null) {
101
- return React.createElement(React.Fragment, { key: options.key }, descriptor.text);
102
- }
103
- return React.createElement(React.Fragment, {}, descriptor.text);
104
- }
105
- if (isInlineTag) {
106
- const parsedElement = renderSanitizedHtmlTree(descriptor.sanitized, options.key);
107
- if (parsedElement) {
108
- return parsedElement;
109
- }
110
- }
111
- const props = {
112
- className,
113
- dangerouslySetInnerHTML: { __html: descriptor.sanitized }
114
- };
115
- if (options.key !== void 0 && options.key !== null) {
116
- props.key = options.key;
117
- }
118
- return React.createElement("span", props);
119
- };
120
- const allRenderers = options.renderers ? { ...DEFAULT_INLINE_HTML_RENDERERS, ...options.renderers } : DEFAULT_INLINE_HTML_RENDERERS;
121
- const renderer = allRenderers[descriptor.tagName];
122
- if (renderer) {
123
- const rendered = renderer(descriptor, { key: options.key, defaultRender });
124
- if (rendered) {
125
- if (options.key !== void 0 && options.key !== null && React.isValidElement(rendered) && rendered.key === null) {
126
- return React.cloneElement(rendered, { key: options.key });
127
- }
128
- return rendered;
129
- }
130
- }
131
- return defaultRender();
132
- }
133
- function parseInlineHtmlDescriptor(raw, sanitized) {
134
- const normalizedRaw = typeof raw === "string" ? raw.trim() : "";
135
- const normalizedSanitized = typeof sanitized === "string" && sanitized.length > 0 ? sanitized.trim() : normalizedRaw;
136
- if (!normalizedSanitized) {
137
- return null;
138
- }
139
- const match = normalizedSanitized.match(/^<([A-Za-z][\w:-]*)(\s[^>]*)?>([\s\S]*)<\/\1>$/);
140
- if (!match) {
141
- return null;
142
- }
143
- const [, tagNameRaw, attrString = "", sanitizedInner = ""] = match;
144
- const tagName = tagNameRaw.toLowerCase();
145
- const attributes = parseAttributes(attrString);
146
- let rawInner = "";
147
- if (normalizedRaw) {
148
- const rawMatch = normalizedRaw.match(/^<([A-Za-z][\w:-]*)(\s[^>]*)?>([\s\S]*)<\/\1>$/);
149
- rawInner = rawMatch ? rawMatch[3] ?? "" : normalizedRaw;
150
- }
151
- const text = extractPlainText(rawInner || sanitizedInner);
152
- return {
153
- tagName,
154
- attributes,
155
- raw: normalizedRaw || normalizedSanitized,
156
- sanitized: normalizedSanitized,
157
- rawInner,
158
- sanitizedInner,
159
- text
160
- };
161
- }
162
- function parseAttributes(input) {
163
- const attrs = {};
164
- if (!input) return attrs;
165
- const attrPattern = /([A-Za-z_:][\w:.\-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
166
- let match = attrPattern.exec(input);
167
- while (match !== null) {
168
- const name = match[1];
169
- if (!name) continue;
170
- const value = match[2] ?? match[3] ?? match[4] ?? "";
171
- attrs[name] = value;
172
- match = attrPattern.exec(input);
173
- }
174
- return attrs;
175
- }
176
- function mapAttributesToProps(attrs) {
177
- const props = {};
178
- for (const [key, value] of Object.entries(attrs)) {
179
- if (key === "class") {
180
- props.className = value;
181
- } else if (key === "style") {
182
- props.style = parseStyleAttribute(value);
183
- } else if (key === "tabindex" || key === "tabIndex") {
184
- const normalized = normalizeTabIndex(value);
185
- if (normalized !== void 0) {
186
- props.tabIndex = normalized;
187
- }
188
- } else {
189
- props[key] = value;
190
- }
191
- }
192
- return props;
193
- }
194
- function parseStyleAttribute(value) {
195
- const style = {};
196
- if (!value) return style;
197
- const pairs = value.split(";");
198
- for (const pair of pairs) {
199
- if (!pair.trim()) continue;
200
- const [property, rawVal] = pair.split(":");
201
- if (!property || rawVal === void 0) continue;
202
- const camelProp = property.trim().replace(/-([a-z])/g, (_, char) => char.toUpperCase());
203
- style[camelProp] = rawVal.trim();
204
- }
205
- return style;
206
- }
207
- function normalizeTabIndex(value) {
208
- const numeric = Number(value);
209
- return Number.isNaN(numeric) ? void 0 : numeric;
210
- }
211
- function decodeHtmlEntities(value) {
212
- return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
213
- }
214
- function extractPlainText(value) {
215
- if (!value) return "";
216
- const withoutTags = value.replace(/<\/?[^>]+>/g, "");
217
- return decodeHtmlEntities(withoutTags);
218
- }
219
- function renderSanitizedHtmlTree(html, key) {
220
- if (typeof DOMParser === "undefined") {
221
- return null;
222
- }
223
- try {
224
- const parser = new DOMParser();
225
- const doc = parser.parseFromString(html, "text/html");
226
- const body = doc.body;
227
- const nodes = Array.from(body.childNodes);
228
- if (nodes.length === 0) {
229
- return null;
230
- }
231
- const baseKey = typeof key === "string" || typeof key === "number" ? String(key) : "inline-html";
232
- const children = nodes.map((node, index) => convertDomNode(node, `${baseKey}-${index}`)).filter((child) => child !== null && child !== void 0);
233
- if (children.length === 0) {
234
- return null;
235
- }
236
- if (children.length === 1) {
237
- const [child] = children;
238
- if (React.isValidElement(child)) {
239
- if (key !== void 0 && key !== null) {
240
- return React.cloneElement(child, { key });
241
- }
242
- return child;
243
- }
244
- if (typeof child === "string" || typeof child === "number") {
245
- if (key !== void 0 && key !== null) {
246
- return React.createElement(React.Fragment, { key }, child);
247
- }
248
- return React.createElement(React.Fragment, {}, child);
249
- }
250
- return React.createElement(React.Fragment, { key }, child);
251
- }
252
- return React.createElement(React.Fragment, { key }, ...children);
253
- } catch {
254
- return null;
255
- }
256
- }
257
- function convertDomNode(node, key) {
258
- if (node.nodeType === Node.TEXT_NODE) {
259
- return node.textContent ?? "";
260
- }
261
- if (node.nodeType !== Node.ELEMENT_NODE) {
262
- return null;
263
- }
264
- const element = node;
265
- const tagName = element.tagName.toLowerCase();
266
- const attrs = getElementAttributes(element);
267
- const props = mapAttributesToProps(attrs);
268
- props.key = key;
269
- const children = [];
270
- element.childNodes.forEach((child, index) => {
271
- const converted = convertDomNode(child, `${key}-${index}`);
272
- if (converted !== null && converted !== void 0) {
273
- children.push(converted);
274
- }
275
- });
276
- if (children.length === 0) {
277
- return React.createElement(tagName, props);
278
- }
279
- return React.createElement(tagName, props, ...children);
280
- }
281
- function getElementAttributes(element) {
282
- const attrs = {};
283
- for (const attr of Array.from(element.attributes)) {
284
- attrs[attr.name] = attr.value;
285
- }
286
- return attrs;
287
- }
288
- var INLINE_ELEMENTS = /* @__PURE__ */ new Set([
289
- "a",
290
- "abbr",
291
- "b",
292
- "bdi",
293
- "bdo",
294
- "br",
295
- "cite",
296
- "code",
297
- "data",
298
- "dfn",
299
- "em",
300
- "i",
301
- "kbd",
302
- "mark",
303
- "q",
304
- "rp",
305
- "rt",
306
- "ruby",
307
- "s",
308
- "samp",
309
- "small",
310
- "span",
311
- "strong",
312
- "sub",
313
- "sup",
314
- "time",
315
- "u",
316
- "var",
317
- // MathML inline elements commonly emitted by KaTeX
318
- "annotation",
319
- "semantics",
320
- "mtext",
321
- "mn",
322
- "mo",
323
- "mi",
324
- "mspace",
325
- "mrow",
326
- "msup",
327
- "msub",
328
- "msubsup",
329
- "munder",
330
- "mover",
331
- "munderover",
332
- "msqrt",
333
- "mroot",
334
- "mtable",
335
- "mtr",
336
- "mtd"
337
- ]);
338
-
339
- // src/components/index.ts
340
- var MdxRuntimeBoundary = class extends React2.Component {
341
- constructor() {
342
- super(...arguments);
343
- this.state = { hasError: false };
344
- }
345
- static getDerivedStateFromError() {
346
- return { hasError: true };
347
- }
348
- componentDidCatch(error) {
349
- this.props.onError(error);
350
- }
351
- componentDidUpdate(prevProps) {
352
- if (prevProps.resetKey !== this.props.resetKey && this.state.hasError) {
353
- this.setState({ hasError: false });
354
- }
355
- }
356
- render() {
357
- if (this.state.hasError) {
358
- return null;
359
- }
360
- return this.props.children;
361
- }
362
- };
363
- function renderInlineNodes(nodes, components) {
364
- return nodes.map((node, index) => {
365
- const key = `${node.kind}-${index}`;
366
- switch (node.kind) {
367
- case "text": {
368
- const textComponent = components.text;
369
- if (textComponent && textComponent !== defaultInlineComponents.text) {
370
- return React2.createElement(textComponent, { key, text: node.text });
371
- }
372
- return React2.createElement(React2.Fragment, { key, children: node.text });
373
- }
374
- case "strong":
375
- return React2.createElement(components.strong, {
376
- key,
377
- children: renderInlineNodes(node.children, components)
378
- });
379
- case "em":
380
- return React2.createElement(components.em, {
381
- key,
382
- children: renderInlineNodes(node.children, components)
383
- });
384
- case "strike": {
385
- const StrikeComponent = components.strike ?? ((props) => React2.createElement("del", {}, props.children));
386
- return React2.createElement(StrikeComponent, {
387
- key,
388
- children: renderInlineNodes(node.children, components)
389
- });
390
- }
391
- case "code":
392
- return React2.createElement(components.code, { key, text: node.text });
393
- case "link":
394
- return React2.createElement(
395
- components.link,
396
- {
397
- key,
398
- href: node.href,
399
- title: node.title,
400
- children: renderInlineNodes(node.children, components)
401
- }
402
- );
403
- case "image":
404
- return React2.createElement(components.image, {
405
- key,
406
- src: node.src,
407
- alt: node.alt,
408
- title: node.title
409
- });
410
- case "br":
411
- return React2.createElement(React2.Fragment, { key }, React2.createElement(components.br, {}));
412
- default: {
413
- const component = components[node.kind];
414
- if (component) {
415
- return React2.createElement(component, { key, ...node });
416
- }
417
- return null;
418
- }
419
- }
420
- });
421
- }
422
- var defaultInlineComponents = {
423
- text: ({ text }) => React2.createElement(React2.Fragment, {}, text),
424
- strong: ({ children }) => React2.createElement("strong", {}, children),
425
- em: ({ children }) => React2.createElement("em", {}, children),
426
- strike: ({ children }) => React2.createElement("del", {}, children),
427
- code: ({ text }) => React2.createElement(
428
- "code",
429
- {
430
- className: "inline-code"
431
- },
432
- text
433
- ),
434
- link: ({ href, title, children }) => React2.createElement(
435
- "a",
436
- {
437
- href,
438
- title,
439
- className: "markdown-link",
440
- target: href?.startsWith("http") ? "_blank" : void 0,
441
- rel: href?.startsWith("http") ? "noopener noreferrer" : void 0
442
- },
443
- children
444
- ),
445
- image: ({ src, alt, title }) => React2.createElement("img", {
446
- src,
447
- alt,
448
- title,
449
- className: "markdown-image"
450
- }),
451
- br: () => React2.createElement("br"),
452
- // Custom extensible components
453
- mention: ({ handle }) => React2.createElement(
454
- "span",
455
- {
456
- className: "mention",
457
- "data-handle": handle
458
- },
459
- `@${handle}`
460
- ),
461
- citation: ({ id }) => React2.createElement(
462
- "span",
463
- {
464
- className: "citation",
465
- "data-citation-id": id
466
- },
467
- `[${id}]`
468
- ),
469
- "math-inline": ({ tex }) => React2.createElement(
470
- "span",
471
- {
472
- className: "math-inline",
473
- "data-tex": tex
474
- },
475
- `$${tex}$`
476
- ),
477
- "math-display": ({ tex }) => React2.createElement(
478
- "div",
479
- {
480
- className: "math-display markdown-math-display",
481
- "data-tex": tex,
482
- style: { overflowX: "auto" }
483
- },
484
- React2.createElement("span", { className: "math-display-content" }, `$$${tex}$$`)
485
- ),
486
- // Footnote inline reference (superscript anchor)
487
- "footnote-ref": ({ label, number }) => {
488
- const n = number ?? "?";
489
- const href = number ? `#fn:${n}` : void 0;
490
- const id = number ? `fnref:${n}` : void 0;
491
- return React2.createElement(
492
- "sup",
493
- { className: "footnote-ref" },
494
- React2.createElement("a", { href, id, "data-label": label, style: { color: "var(--foreground)", textDecoration: "underline" } }, String(n))
495
- );
496
- }
497
- };
498
- function renderParagraphMixedSegments(segments, inlineComponents, inlineHtmlRenderers) {
499
- const result = [];
500
- let inlineBuffer = [];
501
- let inlineGroupIndex = 0;
502
- const pushRenderedNodes = (nodes, target, baseKey) => {
503
- nodes.forEach((node, idx) => {
504
- if (node === null || node === void 0) return;
505
- const key = `${baseKey}-${idx}`;
506
- if (React2.isValidElement(node)) {
507
- target.push(node.key === key ? node : React2.cloneElement(node, { key }));
508
- } else if (typeof node === "string" || typeof node === "number") {
509
- target.push(React2.createElement(React2.Fragment, { key }, node));
510
- } else {
511
- target.push(React2.createElement(React2.Fragment, { key }, node));
512
- }
513
- });
514
- };
515
- const ensureArray = (value) => {
516
- if (value === null || value === void 0) {
517
- return [];
518
- }
519
- return Array.isArray(value) ? value : [value];
520
- };
521
- const flushInline = () => {
522
- if (inlineBuffer.length === 0) {
523
- return;
524
- }
525
- const key = `paragraph-inline-group-${inlineGroupIndex++}`;
526
- result.push(
527
- React2.createElement(
528
- "p",
529
- {
530
- key,
531
- className: "markdown-paragraph"
532
- },
533
- inlineBuffer
534
- )
535
- );
536
- inlineBuffer = [];
537
- };
538
- segments.forEach((segment, index) => {
539
- const key = `paragraph-segment-${index}`;
540
- switch (segment.kind) {
541
- case "text": {
542
- const inlineNodes = Array.isArray(segment.inline) ? segment.inline : [];
543
- if (inlineNodes.length === 0) {
544
- if (segment.value) {
545
- inlineBuffer.push(React2.createElement(React2.Fragment, { key }, segment.value));
546
- }
547
- break;
548
- }
549
- let chunk = [];
550
- const pushChunk = (chunkNodes, chunkKey) => {
551
- if (chunkNodes.length === 0) return;
552
- const rendered = renderInlineNodes(chunkNodes, inlineComponents);
553
- pushRenderedNodes(ensureArray(rendered), inlineBuffer, chunkKey);
554
- };
555
- inlineNodes.forEach((inlineNode, inlineIdx) => {
556
- if (inlineNode.kind === "math-display") {
557
- pushChunk(chunk, `${key}-chunk-${inlineIdx}`);
558
- chunk = [];
559
- flushInline();
560
- const rendered = renderInlineNodes([inlineNode], inlineComponents);
561
- pushRenderedNodes(ensureArray(rendered), result, `${key}-math-${inlineIdx}`);
562
- } else {
563
- chunk.push(inlineNode);
564
- }
565
- });
566
- pushChunk(chunk, `${key}-chunk-tail`);
567
- break;
568
- }
569
- case "mdx": {
570
- const status = segment.status ?? "pending";
571
- let element;
572
- if (status === "compiled") {
573
- element = React2.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
574
- } else if (status === "error") {
575
- const message = segment.value || "MDX error";
576
- element = React2.createElement("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error" }, message);
577
- } else {
578
- element = React2.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": status }, segment.value);
579
- }
580
- inlineBuffer.push(React2.createElement(React2.Fragment, { key }, element));
581
- break;
582
- }
583
- case "html": {
584
- const html = segment.sanitized ?? segment.value;
585
- const isBlockLevel = isBlockLevelHtml(html);
586
- const element = renderInlineHtmlSegment(segment.value, segment.sanitized, {
587
- key,
588
- renderers: inlineHtmlRenderers
589
- });
590
- if (isBlockLevel) {
591
- flushInline();
592
- if (element) {
593
- result.push(element);
594
- } else if (html) {
595
- result.push(
596
- React2.createElement("div", {
597
- key,
598
- className: "markdown-inline-html-block",
599
- dangerouslySetInnerHTML: { __html: html }
600
- })
601
- );
602
- }
603
- } else if (element) {
604
- inlineBuffer.push(element);
605
- }
606
- break;
607
- }
608
- default:
609
- break;
610
- }
611
- });
612
- flushInline();
613
- if (result.length === 0) {
614
- return [
615
- React2.createElement(
616
- "p",
617
- {
618
- key: "paragraph-inline-group-0",
619
- className: "markdown-paragraph"
620
- },
621
- inlineBuffer
622
- )
623
- ];
624
- }
625
- return result;
626
- }
627
- function isBlockLevelHtml(html) {
628
- if (!html) return false;
629
- const trimmed = html.trim();
630
- if (!trimmed.startsWith("<")) {
631
- return false;
632
- }
633
- const match = trimmed.match(/^<([A-Za-z][\w:-]*)\b/);
634
- if (!match) {
635
- return false;
636
- }
637
- const tag = match[1].toLowerCase();
638
- return BLOCK_LEVEL_TAGS.has(tag);
639
- }
640
- var BLOCK_LEVEL_TAGS = /* @__PURE__ */ new Set([
641
- "address",
642
- "article",
643
- "aside",
644
- "blockquote",
645
- "canvas",
646
- "div",
647
- "dl",
648
- "fieldset",
649
- "figcaption",
650
- "figure",
651
- "footer",
652
- "form",
653
- "h1",
654
- "h2",
655
- "h3",
656
- "h4",
657
- "h5",
658
- "h6",
659
- "header",
660
- "hr",
661
- "li",
662
- "main",
663
- "nav",
664
- "ol",
665
- "p",
666
- "pre",
667
- "section",
668
- "table",
669
- "ul",
670
- "math"
671
- ]);
672
-
673
- // src/renderer/hooks.ts
674
- import { useMemo, useSyncExternalStore } from "react";
675
- function useRendererNode(store, id) {
676
- const selector = useMemo(() => {
677
- return () => store.getNodeWithVersion(id);
678
- }, [store, id]);
679
- const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
680
- return snapshot.node;
681
- }
682
- function useRendererChildren(store, id) {
683
- const selector = useMemo(() => {
684
- return () => store.getChildrenWithVersion(id);
685
- }, [store, id]);
686
- const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
687
- return snapshot.children;
688
- }
689
-
690
- // src/renderer/code-highlight-context.tsx
691
- import React3 from "react";
692
- var CodeHighlightRequestContext = React3.createContext(null);
693
- function useCodeHighlightRequester() {
694
- return React3.useContext(CodeHighlightRequestContext);
695
- }
696
-
697
- // src/renderer/deferred-render-context.tsx
698
- import React4 from "react";
699
- var DeferredRenderContext = React4.createContext(null);
700
-
701
- // src/renderer/store.ts
702
- import {
703
- cloneBlock,
704
- createBlockSnapshot,
705
- extractCodeWrapperAttributes,
706
- getDefaultCodeWrapperAttributes,
707
- sanitizeCodeHTML,
708
- sanitizeHTML as sanitizeHTML2,
709
- PATCH_ROOT_ID
710
- } from "@stream-mdx/core";
711
- import { getPatchKind } from "@stream-mdx/core/perf/patch-batching";
712
- var NODE_SNAPSHOT_CACHE_LIMIT = 5e4;
713
- var CHILDREN_SNAPSHOT_CACHE_LIMIT = 5e4;
714
- var NODE_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(NODE_SNAPSHOT_CACHE_LIMIT * 0.1));
715
- var CHILDREN_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(CHILDREN_SNAPSHOT_CACHE_LIMIT * 0.1));
716
- var EMPTY_CHILDREN = Object.freeze([]);
717
- var EMPTY_NODE_SNAPSHOT = Object.freeze({ version: -1, node: void 0 });
718
- var EMPTY_CHILDREN_SNAPSHOT = Object.freeze({
719
- version: -1,
720
- children: EMPTY_CHILDREN
721
- });
722
- function isListPatchDebugEnabled() {
723
- if (typeof globalThis !== "undefined") {
724
- const flag = globalThis.__STREAMING_LIST_DEBUG__;
725
- if (flag === true) return true;
726
- }
727
- if (typeof process !== "undefined" && process.env.NEXT_PUBLIC_STREAMING_LIST_DEBUG === "true") {
728
- return true;
729
- }
730
- return false;
731
- }
732
- var CODE_BLOCK_DEBUG_ENABLED = (() => {
733
- try {
734
- if (typeof process !== "undefined" && process.env && process.env.NEXT_PUBLIC_STREAMING_DEBUG_CODELINES === "1") {
735
- return true;
736
- }
737
- if (typeof globalThis !== "undefined") {
738
- const debug = globalThis?.__STREAMING_DEBUG__;
739
- if (debug?.codeLines) {
740
- return true;
741
- }
742
- }
743
- } catch {
744
- }
745
- return false;
746
- })() || false;
747
- var CODE_BLOCK_VALIDATION_ENABLED = typeof process !== "undefined" && process.env ? process.env.NODE_ENV !== "production" : true;
748
- var getPerfNow = (() => {
749
- if (typeof performance !== "undefined" && typeof performance.now === "function") {
750
- return () => performance.now();
751
- }
752
- return () => Date.now();
753
- })();
754
-
755
- // src/renderer/virtualized-code.tsx
756
- import { useCallback, useEffect as useEffect2, useMemo as useMemo2, useRef, useState as useState2 } from "react";
757
- var DEFAULT_VIRTUALIZED_CODE_CONFIG = {
758
- enabled: true,
759
- windowSize: 100,
760
- // Render 100 lines at a time
761
- bufferSize: 50,
762
- // +50 lines buffer above/below
763
- virtualizeThreshold: 200
764
- // Only virtualize if 200+ lines
765
- };
766
- function calculateCodeWindow(lines, scrollTop, containerHeight, lineHeight, config) {
767
- const totalLines = lines.length;
768
- if (!config.enabled || totalLines < config.virtualizeThreshold) {
769
- return {
770
- startIndex: 0,
771
- endIndex: totalLines,
772
- visibleStart: 0,
773
- visibleEnd: totalLines,
774
- visibleLines: lines,
775
- totalLines,
776
- mountedLines: totalLines
777
- };
778
- }
779
- const firstVisibleLine = Math.floor(scrollTop / lineHeight);
780
- const lastVisibleLine = Math.ceil((scrollTop + containerHeight) / lineHeight);
781
- const visibleStart = Math.max(0, firstVisibleLine);
782
- const visibleEnd = Math.min(totalLines, Math.max(visibleStart, lastVisibleLine));
783
- const startIndex = Math.max(0, visibleStart - config.bufferSize);
784
- const endIndex = Math.min(totalLines, visibleEnd + config.bufferSize);
785
- return {
786
- startIndex,
787
- endIndex,
788
- visibleStart,
789
- visibleEnd,
790
- visibleLines: lines.slice(startIndex, endIndex),
791
- totalLines,
792
- mountedLines: endIndex - startIndex
793
- };
794
- }
795
- function useVirtualizedCode(lines, config = DEFAULT_VIRTUALIZED_CODE_CONFIG) {
796
- const containerRef = useRef(null);
797
- const [scrollTop, setScrollTop] = useState2(0);
798
- const [containerHeight, setContainerHeight] = useState2(0);
799
- const lineHeightRef = useRef(20);
800
- useEffect2(() => {
801
- if (!containerRef.current || lines.length === 0) return;
802
- const timeoutId = setTimeout(() => {
803
- if (!containerRef.current) return;
804
- const firstLine = containerRef.current.querySelector(".line");
805
- if (firstLine) {
806
- const measuredHeight = firstLine.offsetHeight || 20;
807
- if (measuredHeight !== lineHeightRef.current) {
808
- lineHeightRef.current = measuredHeight;
809
- }
810
- }
811
- }, 0);
812
- return () => clearTimeout(timeoutId);
813
- }, [lines.length]);
814
- const handleScroll = useCallback((e) => {
815
- const target = e.currentTarget;
816
- setScrollTop(target.scrollTop);
817
- setContainerHeight(target.clientHeight);
818
- }, []);
819
- useEffect2(() => {
820
- if (!containerRef.current) return;
821
- const resizeObserver = new ResizeObserver((entries) => {
822
- for (const entry of entries) {
823
- setContainerHeight(entry.contentRect.height);
824
- }
825
- });
826
- resizeObserver.observe(containerRef.current);
827
- return () => resizeObserver.disconnect();
828
- }, []);
829
- const window2 = useMemo2(() => {
830
- return calculateCodeWindow(lines, scrollTop, containerHeight, lineHeightRef.current, config);
831
- }, [lines, scrollTop, containerHeight, config]);
832
- const scrollToLine = useCallback((lineIndex) => {
833
- if (!containerRef.current) return;
834
- const targetScrollTop = lineIndex * lineHeightRef.current;
835
- containerRef.current.scrollTop = targetScrollTop;
836
- setScrollTop(targetScrollTop);
837
- }, []);
838
- return {
839
- containerRef,
840
- window: window2,
841
- handleScroll,
842
- scrollToLine,
843
- lineHeight: lineHeightRef.current,
844
- config
845
- };
846
- }
847
-
848
- // src/renderer/node-views.tsx
849
- import { jsx, jsxs } from "react/jsx-runtime";
850
- var BlockNodeRenderer = ({ store, blockId, registry }) => {
851
- const node = useRendererNode(store, blockId);
852
- const block = node?.block;
853
- if (!node || !block) return null;
854
- switch (block.type) {
855
- case "paragraph":
856
- return /* @__PURE__ */ jsx(ParagraphBlockView, { store, blockId: block.id, registry });
857
- case "blockquote":
858
- return /* @__PURE__ */ jsx(BlockquoteBlockView, { store, blockId: block.id, registry });
859
- case "list":
860
- return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: block.id, registry, depth: 0 });
861
- case "table":
862
- return /* @__PURE__ */ jsx(TableBlockView, { store, blockId: block.id, registry });
863
- case "code":
864
- return /* @__PURE__ */ jsx(CodeBlockView, { store, blockId: block.id, registry });
865
- case "html":
866
- return /* @__PURE__ */ jsx(HtmlBlockView, { store, blockId: block.id, registry });
867
- case "mdx":
868
- return /* @__PURE__ */ jsx(MdxBlockView, { store, blockId: block.id, registry });
869
- default:
870
- return registry.renderBlock(block);
871
- }
872
- };
873
- var ParagraphBlockView = React5.memo(({ store, blockId, registry }) => {
874
- const node = useRendererNode(store, blockId);
875
- const block = node?.block;
876
- const childIds = useRendererChildren(store, blockId);
877
- if (!node || !block) {
878
- return null;
879
- }
880
- const inlineComponents = registry.getInlineComponents();
881
- if (!block.isFinalized) {
882
- const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
883
- const meta = block.payload.meta ?? {};
884
- const segments2 = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
885
- if (segments2.length > 0) {
886
- const allowMixedStreaming = Boolean(meta.allowMixedStreaming);
887
- if (!allowMixedStreaming) {
888
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
889
- }
890
- const structured = renderParagraphMixedSegments(segments2, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
891
- if (structured.length === 1) {
892
- const [single] = structured;
893
- return React5.isValidElement(single) ? single : single;
894
- }
895
- return structured;
896
- }
897
- if (meta.inlineStatus === "complete" || meta.inlineStatus === "anticipated") {
898
- const inlineNodes2 = block.payload.inline ?? [];
899
- const containsDisplayMath2 = inlineNodes2.some((node2) => node2.kind === "math-display");
900
- if (containsDisplayMath2) {
901
- const derivedSegments = [
902
- {
903
- kind: "text",
904
- value: raw,
905
- inline: inlineNodes2
906
- }
907
- ];
908
- const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
909
- if (structured.length === 1) {
910
- const [single] = structured;
911
- return React5.isValidElement(single) ? single : single;
912
- }
913
- return structured;
914
- }
915
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: renderInlineNodes(inlineNodes2, inlineComponents) });
916
- }
917
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
918
- }
919
- const propsBlock = node.props?.block;
920
- const inlineStatus = propsBlock?.payload?.meta?.inlineStatus ?? block.payload.meta?.inlineStatus ?? node.props?.inlineStatus;
921
- if (inlineStatus && inlineStatus !== "complete") {
922
- const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
923
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: raw });
924
- }
925
- const segments = Array.isArray(block.payload.meta?.mixedSegments) ? block.payload.meta.mixedSegments : void 0;
926
- if (segments && segments.length > 0) {
927
- const structured = renderParagraphMixedSegments(segments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
928
- if (structured.length === 1) {
929
- const [single] = structured;
930
- return React5.isValidElement(single) ? single : single;
931
- }
932
- return structured;
933
- }
934
- const inlineNodes = block.payload.inline ?? [];
935
- const containsDisplayMath = inlineNodes.some((node2) => node2.kind === "math-display");
936
- if (containsDisplayMath) {
937
- const derivedSegments = [
938
- {
939
- kind: "text",
940
- value: typeof block.payload.raw === "string" ? block.payload.raw : "",
941
- inline: inlineNodes
942
- }
943
- ];
944
- const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
945
- if (structured.length === 1) {
946
- const [single] = structured;
947
- return React5.isValidElement(single) ? single : single;
948
- }
949
- return structured;
950
- }
951
- const ParagraphComponent = registry.getBlockComponent("paragraph");
952
- const baseElement = React5.createElement(ParagraphComponent, {
953
- inlines: block.payload.inline ?? [],
954
- raw: block.payload.raw,
955
- meta: block.payload.meta
956
- });
957
- if (childIds.length > 0) {
958
- const renderedChildren = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
959
- if (React5.isValidElement(baseElement)) {
960
- const { children: _ignored, className = "markdown-paragraph", inlines: _inlines, raw: _raw, meta: _meta, ...rest } = baseElement.props ?? {};
961
- return React5.createElement("p", { ...rest, className }, renderedChildren);
962
- }
963
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderedChildren });
964
- }
965
- if (React5.isValidElement(baseElement)) {
966
- return baseElement;
967
- }
968
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderInlineNodes(block.payload.inline ?? [], inlineComponents) });
969
- });
970
- ParagraphBlockView.displayName = "ParagraphBlockView";
971
- var BlockquoteBlockView = React5.memo(({ store, blockId, registry }) => {
972
- const node = useRendererNode(store, blockId);
973
- const block = node?.block;
974
- const childIds = useRendererChildren(store, blockId);
975
- if (!node || !block) {
976
- return null;
977
- }
978
- const meta = block.payload.meta ?? {};
979
- const mixedSegments = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
980
- const normalizedText = typeof meta.normalizedText === "string" && meta.normalizedText.length > 0 ? meta.normalizedText : typeof block.payload.raw === "string" ? block.payload.raw : "";
981
- const inlineComponents = registry.getInlineComponents();
982
- const renderTextWithBreaks = (text, keyPrefix) => {
983
- const lines = text.split("\n");
984
- const lastIndex = lines.length - 1;
985
- let offset = 0;
986
- return lines.map((line, idx) => {
987
- const key = `${keyPrefix}${offset}`;
988
- offset += line.length + 1;
989
- return /* @__PURE__ */ jsxs("span", { className: "markdown-blockquote-line", children: [
990
- line,
991
- idx < lastIndex ? /* @__PURE__ */ jsx("br", {}) : null
992
- ] }, key);
993
- });
994
- };
995
- const renderInlineContent = (inline, keyPrefix) => {
996
- if (inline && inline.length > 0) {
997
- return renderInlineNodes(inline, inlineComponents);
998
- }
999
- return null;
1000
- };
1001
- const renderMixedSegments = () => {
1002
- if (!mixedSegments.length) {
1003
- return [];
1004
- }
1005
- const elements = [];
1006
- mixedSegments.forEach((segment, segmentIndex) => {
1007
- switch (segment.kind) {
1008
- case "html": {
1009
- const htmlNode = renderInlineHtmlSegment(segment.value, segment.sanitized ?? segment.value, {
1010
- key: `blockquote-html-${block.id}-${segmentIndex}`,
1011
- renderers: DEFAULT_INLINE_HTML_RENDERERS
1012
- });
1013
- if (htmlNode) {
1014
- elements.push(htmlNode);
1015
- } else {
1016
- elements.push(
1017
- React5.createElement("span", {
1018
- key: `blockquote-html-${block.id}-${segmentIndex}`,
1019
- className: "markdown-inline-html",
1020
- /* biome-ignore lint/security/noDangerouslySetInnerHtml: segment content is sanitized by the worker before streaming */
1021
- dangerouslySetInnerHTML: { __html: segment.sanitized ?? segment.value }
1022
- })
1023
- );
1024
- }
1025
- break;
1026
- }
1027
- case "mdx":
1028
- elements.push(
1029
- /* @__PURE__ */ jsx("span", { "data-mdx-status": segment.status ?? "pending", children: segment.value }, `blockquote-mdx-${block.id}-${segmentIndex}`)
1030
- );
1031
- break;
1032
- default: {
1033
- const inline = renderInlineContent(segment.inline, `blockquote-text-inline-${block.id}-${segmentIndex}-`);
1034
- if (inline) {
1035
- elements.push(/* @__PURE__ */ jsx(React5.Fragment, { children: inline }, `blockquote-inline-${block.id}-${segmentIndex}`));
1036
- } else {
1037
- elements.push(
1038
- /* @__PURE__ */ jsx(React5.Fragment, { children: renderTextWithBreaks(segment.value, `blockquote-text-${block.id}-${segmentIndex}-`) }, `blockquote-text-${block.id}-${segmentIndex}`)
1039
- );
1040
- }
1041
- break;
1042
- }
1043
- }
1044
- });
1045
- return elements;
1046
- };
1047
- const mixedSegmentElements = renderMixedSegments();
1048
- const fallbackElements = normalizedText ? renderTextWithBreaks(normalizedText, `blockquote-fallback-${block.id}-`) : null;
1049
- const inlineNodes = block.payload.inline ?? [];
1050
- const inlineElements = inlineNodes.length > 0 ? renderInlineNodes(inlineNodes, inlineComponents) : null;
1051
- if (!block.isFinalized) {
1052
- const streamingContent = mixedSegmentElements.length ? mixedSegmentElements : inlineElements ? inlineElements : fallbackElements;
1053
- const shouldShowStreaming = !block.isFinalized && (!streamingContent || Array.isArray(streamingContent) && streamingContent.length === 0);
1054
- const className = shouldShowStreaming ? "markdown-blockquote streaming-partial" : "markdown-blockquote";
1055
- return /* @__PURE__ */ jsx("blockquote", { className, children: streamingContent });
1056
- }
1057
- const childContent = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
1058
- const renderedContent = (() => {
1059
- if (mixedSegmentElements.length > 0) {
1060
- return mixedSegmentElements;
1061
- }
1062
- if (childIds.length > 0) {
1063
- const resolved = childContent.filter((child) => child !== null);
1064
- if (resolved.length > 0) {
1065
- return resolved;
1066
- }
1067
- }
1068
- if (inlineElements) {
1069
- return inlineElements;
1070
- }
1071
- if (fallbackElements && fallbackElements.length > 0) {
1072
- return fallbackElements;
1073
- }
1074
- return null;
1075
- })();
1076
- const BlockquoteComponent = registry.getBlockComponent("blockquote");
1077
- const baseElement = React5.createElement(
1078
- BlockquoteComponent,
1079
- {
1080
- inlines: block.payload.inline ?? [],
1081
- renderedContent
1082
- },
1083
- renderedContent
1084
- );
1085
- if (React5.isValidElement(baseElement)) {
1086
- return baseElement;
1087
- }
1088
- return /* @__PURE__ */ jsx("blockquote", { className: "markdown-blockquote", children: renderedContent });
1089
- });
1090
- BlockquoteBlockView.displayName = "BlockquoteBlockView";
1091
- var MixedSegmentView = React5.memo(({ store, nodeId, inlineComponents }) => {
1092
- const node = useRendererNode(store, nodeId);
1093
- if (!node) return null;
1094
- switch (node.type) {
1095
- case "paragraph-text":
1096
- case "blockquote-text":
1097
- case "list-item-text": {
1098
- const inline = node.props?.inline ?? [];
1099
- if (inline.length > 0) {
1100
- return renderInlineNodes(inline, inlineComponents);
1101
- }
1102
- const text = typeof node.props?.text === "string" ? node.props?.text : "";
1103
- if (!text) return null;
1104
- return text;
1105
- }
1106
- case "paragraph-html":
1107
- case "blockquote-html":
1108
- case "list-item-html": {
1109
- const raw = typeof node.props?.raw === "string" ? node.props.raw : void 0;
1110
- const html = typeof node.props?.html === "string" ? node.props?.html : "";
1111
- const rendered = renderInlineHtmlSegment(raw, html, {
1112
- key: node.id,
1113
- renderers: DEFAULT_INLINE_HTML_RENDERERS
1114
- });
1115
- if (rendered) {
1116
- return rendered;
1117
- }
1118
- if (!html) return null;
1119
- return React5.createElement("span", {
1120
- className: "markdown-inline-html",
1121
- /* biome-ignore lint/security/noDangerouslySetInnerHtml: html is sanitized upstream before reaching the renderer */
1122
- dangerouslySetInnerHTML: { __html: html }
1123
- });
1124
- }
1125
- case "paragraph-mdx":
1126
- case "blockquote-mdx":
1127
- case "list-item-mdx": {
1128
- const status = node.props?.status ?? "pending";
1129
- const raw = typeof node.props?.raw === "string" ? node.props?.raw : "";
1130
- if (status === "compiled") {
1131
- return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
1132
- }
1133
- if (status === "error") {
1134
- const message = raw || "MDX error";
1135
- return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error", children: message });
1136
- }
1137
- return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": status, children: status === "compiled" ? "" : raw });
1138
- }
1139
- default:
1140
- return null;
1141
- }
1142
- });
1143
- MixedSegmentView.displayName = "MixedSegmentView";
1144
- var HtmlBlockView = React5.memo(({ store, blockId, registry }) => {
1145
- const node = useRendererNode(store, blockId);
1146
- if (!node || !node.block) return null;
1147
- return registry.renderBlock(node.block);
1148
- });
1149
- HtmlBlockView.displayName = "HtmlBlockView";
1150
- var MdxBlockView = React5.memo(({ store, blockId, registry }) => {
1151
- const node = useRendererNode(store, blockId);
1152
- if (!node || !node.block) return null;
1153
- return registry.renderBlock(node.block);
1154
- });
1155
- MdxBlockView.displayName = "MdxBlockView";
1156
- var ListBlockView = React5.memo(
1157
- ({ store, blockId, registry, depth = 0 }) => {
1158
- const node = useRendererNode(store, blockId);
1159
- const block = node?.block;
1160
- const childIds = useRendererChildren(store, blockId);
1161
- const inlineComponents = registry.getInlineComponents();
1162
- const ordered = Boolean(node?.props?.ordered ?? block?.payload.meta?.ordered);
1163
- const Tag = ordered ? "ol" : "ul";
1164
- const listDebugEnabled = isListPatchDebugEnabled();
1165
- const listItemIds = React5.useMemo(() => {
1166
- const ids = [];
1167
- for (const childId of childIds) {
1168
- const childNode = store.getNode(childId);
1169
- if (childNode?.type === "list-item") {
1170
- ids.push(childId);
1171
- }
1172
- }
1173
- return ids;
1174
- }, [childIds, store]);
1175
- React5.useEffect(() => {
1176
- if (!listDebugEnabled) return;
1177
- const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
1178
- console.info("[stream-mdx:list-render]", {
1179
- listId: blockId,
1180
- depth,
1181
- ordered,
1182
- childIds,
1183
- childTypes,
1184
- listItemIds,
1185
- listItems: listItemIds.length,
1186
- totalChildren: childIds.length,
1187
- isFinalized: block?.isFinalized ?? false
1188
- });
1189
- }, [listDebugEnabled, blockId, depth, ordered, childIds, listItemIds, store, block?.isFinalized]);
1190
- const { listStyle, markerDigits } = React5.useMemo(() => {
1191
- if (!ordered || listItemIds.length === 0) {
1192
- return { listStyle: void 0, markerDigits: 1 };
1193
- }
1194
- let maxDigits = 1;
1195
- listItemIds.forEach((childId, index) => {
1196
- const childNode = store.getNode(childId);
1197
- const raw = typeof childNode?.block?.payload?.raw === "string" ? childNode.block.payload.raw : void 0;
1198
- const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
1199
- const marker = markerMatch?.[1]?.trim();
1200
- const text = marker ?? `${index + 1}.`;
1201
- const digitMatch = text.match(/\d/g);
1202
- const digits = digitMatch ? digitMatch.length : text.length;
1203
- if (digits > maxDigits) maxDigits = digits;
1204
- });
1205
- const baseIndent = depth === 0 ? "2rem" : depth === 1 ? "1.75rem" : "1.5rem";
1206
- const extraDigits = Math.max(0, maxDigits - 1);
1207
- return {
1208
- markerDigits: maxDigits,
1209
- listStyle: {
1210
- ["--list-indent"]: extraDigits > 0 ? `calc(${baseIndent} + ${extraDigits}ch)` : baseIndent,
1211
- ["--list-marker-digits"]: String(maxDigits)
1212
- }
1213
- };
1214
- }, [ordered, listItemIds, store, depth]);
1215
- if (listItemIds.length === 0) return null;
1216
- return /* @__PURE__ */ jsx(
1217
- Tag,
1218
- {
1219
- className: `markdown-list ${ordered ? "ordered" : "unordered"}`,
1220
- "data-list-depth": depth,
1221
- "data-marker-digits": ordered ? markerDigits : void 0,
1222
- "data-list-id": listDebugEnabled ? blockId : void 0,
1223
- style: listStyle,
1224
- children: listItemIds.map((childId, index) => /* @__PURE__ */ jsx(
1225
- ListItemView,
1226
- {
1227
- store,
1228
- nodeId: childId,
1229
- inlineComponents,
1230
- registry,
1231
- ordered,
1232
- index,
1233
- depth
1234
- },
1235
- childId
1236
- ))
1237
- }
1238
- );
1239
- }
1240
- );
1241
- ListBlockView.displayName = "ListBlockView";
1242
- var ListItemView = React5.memo(({ store, nodeId, inlineComponents, registry, ordered, index, depth }) => {
1243
- const node = useRendererNode(store, nodeId);
1244
- const childIds = useRendererChildren(store, nodeId);
1245
- const inline = node?.props?.inline ?? [];
1246
- const isTask = Boolean(node?.props?.task);
1247
- const isChecked = Boolean(node?.props?.checked);
1248
- const block = node?.block;
1249
- const raw = typeof block?.payload?.raw === "string" ? block.payload.raw : void 0;
1250
- const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
1251
- const marker = markerMatch?.[1]?.trim();
1252
- const inferredIndex = typeof node?.props?.index === "number" ? Number(node?.props?.index) : index;
1253
- const isOrdered = Boolean(node?.props?.ordered ?? ordered);
1254
- const counterText = !isTask ? isOrdered ? marker ? marker : `${inferredIndex + 1}.` : "\u2022" : void 0;
1255
- const listDebugEnabled = isListPatchDebugEnabled();
1256
- const inlineLength = inline.length;
1257
- const [segmentChildIds, contentChildIds] = React5.useMemo(() => {
1258
- const segments = [];
1259
- const structural = [];
1260
- for (const childId of childIds) {
1261
- const childNode = store.getNode(childId);
1262
- if (!childNode) continue;
1263
- if (childNode.type?.startsWith("list-item-")) {
1264
- segments.push(childId);
1265
- } else {
1266
- structural.push(childId);
1267
- }
1268
- }
1269
- return [segments, structural];
1270
- }, [childIds, store]);
1271
- const segmentElements = React5.useMemo(() => {
1272
- return segmentChildIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
1273
- }, [segmentChildIds, store, inlineComponents]);
1274
- const primaryContent = React5.useMemo(() => {
1275
- if (segmentChildIds.length > 0) {
1276
- return segmentElements;
1277
- }
1278
- return renderInlineNodes(inline, inlineComponents);
1279
- }, [segmentChildIds, segmentElements, inline, inlineComponents]);
1280
- const trailingChildren = React5.useMemo(() => {
1281
- return contentChildIds.map((childId) => {
1282
- const childNode = store.getNode(childId);
1283
- if (!childNode) return null;
1284
- switch (childNode.type) {
1285
- case "paragraph": {
1286
- const childInline = childNode.props?.inline ?? [];
1287
- return /* @__PURE__ */ jsx("p", { className: "markdown-list-item-paragraph", children: renderInlineNodes(childInline, inlineComponents) }, childId);
1288
- }
1289
- case "list":
1290
- return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: childId, registry, depth: depth + 1 }, childId);
1291
- default:
1292
- return /* @__PURE__ */ jsx(BlockNodeRenderer, { store, blockId: childId, registry }, childId);
1293
- }
1294
- });
1295
- }, [contentChildIds, store, inlineComponents, registry, depth]);
1296
- const filteredChildren = trailingChildren.filter((child) => Boolean(child));
1297
- const hasChildren = filteredChildren.length > 0;
1298
- React5.useEffect(() => {
1299
- if (!listDebugEnabled) return;
1300
- const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
1301
- console.info("[stream-mdx:list-item-render]", {
1302
- itemId: nodeId,
1303
- depth,
1304
- ordered: isOrdered,
1305
- inferredIndex,
1306
- marker,
1307
- isTask,
1308
- isChecked,
1309
- childIds,
1310
- childTypes,
1311
- segmentChildIds,
1312
- contentChildIds,
1313
- inlineLength,
1314
- hasChildren,
1315
- isFinalized: block?.isFinalized ?? false
1316
- });
1317
- }, [
1318
- listDebugEnabled,
1319
- nodeId,
1320
- depth,
1321
- isOrdered,
1322
- inferredIndex,
1323
- marker,
1324
- isTask,
1325
- isChecked,
1326
- childIds,
1327
- segmentChildIds,
1328
- contentChildIds,
1329
- inlineLength,
1330
- hasChildren,
1331
- store,
1332
- block?.isFinalized
1333
- ]);
1334
- return /* @__PURE__ */ jsxs(
1335
- "li",
1336
- {
1337
- className: `markdown-list-item${isTask ? " markdown-list-item-task" : ""}`,
1338
- "data-counter-text": counterText,
1339
- "data-list-depth": depth,
1340
- "data-list-item-id": listDebugEnabled ? nodeId : void 0,
1341
- children: [
1342
- isTask ? /* @__PURE__ */ jsxs("div", { className: "markdown-task", children: [
1343
- /* @__PURE__ */ jsx("input", { type: "checkbox", className: "markdown-task-checkbox", checked: isChecked, readOnly: true, disabled: true, tabIndex: -1, "aria-checked": isChecked }),
1344
- /* @__PURE__ */ jsx("span", { className: "markdown-task-content", children: primaryContent })
1345
- ] }) : primaryContent,
1346
- hasChildren ? /* @__PURE__ */ jsx("div", { className: "markdown-list-item-children", children: filteredChildren }) : null
1347
- ]
1348
- }
1349
- );
1350
- });
1351
- ListItemView.displayName = "ListItemView";
1352
- var TableBlockView = React5.memo(({ store, blockId, registry }) => {
1353
- const tableElements = registry.getTableElements();
1354
- const childIds = useRendererChildren(store, blockId);
1355
- return /* @__PURE__ */ jsx(tableElements.Table, { className: "markdown-table w-full caption-bottom text-base", children: childIds.map((sectionId) => /* @__PURE__ */ jsx(TableSectionView, { store, nodeId: sectionId, registry }, sectionId)) });
1356
- });
1357
- TableBlockView.displayName = "TableBlockView";
1358
- var TableSectionView = React5.memo(({ store, nodeId, registry }) => {
1359
- const node = useRendererNode(store, nodeId);
1360
- if (!node) return null;
1361
- const tableElements = registry.getTableElements();
1362
- if (node.type === "table-header") {
1363
- const childIds = useRendererChildren(store, nodeId);
1364
- return /* @__PURE__ */ jsx(tableElements.Thead, { children: /* @__PURE__ */ jsx(tableElements.Tr, { children: childIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) }) });
1365
- }
1366
- if (node.type === "table-body") {
1367
- const rowIds = useRendererChildren(store, nodeId);
1368
- return /* @__PURE__ */ jsx(tableElements.Tbody, { children: rowIds.map((rowId) => /* @__PURE__ */ jsx(TableRowView, { store, nodeId: rowId, registry }, rowId)) });
1369
- }
1370
- return null;
1371
- });
1372
- TableSectionView.displayName = "TableSectionView";
1373
- var TableRowView = React5.memo(({ store, nodeId, registry }) => {
1374
- const tableElements = registry.getTableElements();
1375
- const cellIds = useRendererChildren(store, nodeId);
1376
- return /* @__PURE__ */ jsx(tableElements.Tr, { children: cellIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) });
1377
- });
1378
- TableRowView.displayName = "TableRowView";
1379
- var TableCellView = React5.memo(({ store, nodeId, registry }) => {
1380
- const node = useRendererNode(store, nodeId);
1381
- const inlineComponents = registry.getInlineComponents();
1382
- const tableElements = registry.getTableElements();
1383
- if (!node) return null;
1384
- const Tag = node.type === "table-header-cell" ? tableElements.Th : tableElements.Td;
1385
- const inline = node.props?.inline ?? [];
1386
- const align = node.props?.align;
1387
- const content = renderInlineNodes(inline, inlineComponents);
1388
- const alignProps = align ? { align } : void 0;
1389
- return /* @__PURE__ */ jsx(Tag, { ...alignProps, children: content });
1390
- });
1391
- TableCellView.displayName = "TableCellView";
1392
- var CodeBlockView = React5.memo(({ store, blockId, registry }) => {
1393
- const node = useRendererNode(store, blockId);
1394
- const childIds = useRendererChildren(store, blockId);
1395
- const CodeComponent = registry.getBlockComponent("code");
1396
- const deferredConfig = React5.useContext(DeferredRenderContext);
1397
- const deferredRef = React5.useRef(null);
1398
- const shouldRenderDeferred = useDeferredRender(
1399
- deferredRef,
1400
- deferredConfig ? { ...deferredConfig, enabled: true } : { enabled: false }
1401
- );
1402
- if (!node || !node.block) return null;
1403
- const blockIsFinalized = node.block.isFinalized;
1404
- const nodeVersion = node.version;
1405
- const lines = React5.useMemo(() => {
1406
- const seenIds = /* @__PURE__ */ new Set();
1407
- const seenIndices = /* @__PURE__ */ new Set();
1408
- const deduped = [];
1409
- for (const childId of childIds) {
1410
- const child = store.getNode(childId);
1411
- if (!child) continue;
1412
- const index = typeof child.props?.index === "number" ? child.props?.index : deduped.length;
1413
- const text = typeof child.props?.text === "string" ? child.props?.text : "";
1414
- const html = typeof child.props?.html === "string" ? child.props?.html : null;
1415
- const tokens = Object.prototype.hasOwnProperty.call(child.props ?? {}, "tokens") ? child.props?.tokens : void 0;
1416
- if (seenIds.has(child.id) || seenIndices.has(index)) {
1417
- console.warn("[renderer-view] duplicate code line detected", {
1418
- blockId,
1419
- childId: child.id,
1420
- index
1421
- });
1422
- continue;
1423
- }
1424
- seenIds.add(child.id);
1425
- seenIndices.add(index);
1426
- deduped.push({ id: child.id, index, text, html, tokens });
1427
- }
1428
- deduped.sort((a, b) => a.index - b.index);
1429
- return deduped;
1430
- }, [childIds, store, blockId, nodeVersion]);
1431
- const lang = typeof node.props?.lang === "string" ? node.props?.lang : node.block.payload.meta?.lang;
1432
- const preAttrs = node.props?.preAttrs ?? void 0;
1433
- const codeAttrs = node.props?.codeAttrs ?? void 0;
1434
- const blockMeta = node.block.payload.meta ?? void 0;
1435
- const lazyEnabled = Boolean(blockMeta?.lazyTokenization);
1436
- const lazyTokenizedUntil = typeof blockMeta?.lazyTokenizedUntil === "number" ? blockMeta.lazyTokenizedUntil : 0;
1437
- const lazyHighlightedLines = Array.isArray(blockMeta?.highlightedLines) ? blockMeta.highlightedLines.length : 0;
1438
- const lazyTokenLines = Array.isArray(blockMeta?.tokenLines) ? blockMeta.tokenLines.length : 0;
1439
- const lazySourceTextLineCount = React5.useMemo(() => {
1440
- const raw = typeof node.block?.payload.raw === "string" ? node.block.payload.raw : "";
1441
- const metaCode = typeof blockMeta?.code === "string" ? blockMeta.code : null;
1442
- const sourceText = resolveCodeSourceText(raw, metaCode);
1443
- if (sourceText.length === 0) return 0;
1444
- return sourceText.split("\n").length;
1445
- }, [blockMeta, node.block?.payload.raw]);
1446
- const totalLazyLineCount = Math.max(lines.length, lazyHighlightedLines, lazyTokenLines, lazySourceTextLineCount);
1447
- const virtualizationConfig = DEFAULT_VIRTUALIZED_CODE_CONFIG;
1448
- const virtualizationDisabled = typeof process !== "undefined" && typeof process.env === "object" && process.env.STREAM_MDX_DISABLE_VIRTUALIZED_CODE === "true";
1449
- const canVirtualize = node.block.isFinalized && !lazyEnabled;
1450
- const shouldVirtualize = canVirtualize && !virtualizationDisabled && virtualizationConfig.enabled && lines.length >= virtualizationConfig.virtualizeThreshold;
1451
- const virtualization = useVirtualizedCode(lines, shouldVirtualize ? virtualizationConfig : { ...virtualizationConfig, enabled: false });
1452
- const highlightRequester = useCodeHighlightRequester();
1453
- const lastRangeRef = React5.useRef(null);
1454
- const rafRef = React5.useRef(null);
1455
- const idleRef = React5.useRef(null);
1456
- React5.useEffect(() => {
1457
- if (!shouldVirtualize || !lazyEnabled || !highlightRequester) return;
1458
- const { visibleStart, visibleEnd, startIndex, endIndex } = virtualization.window;
1459
- if (endIndex <= lazyTokenizedUntil) return;
1460
- const nextRange = {
1461
- visibleStart,
1462
- visibleEnd,
1463
- prefetchStart: startIndex,
1464
- prefetchEnd: endIndex,
1465
- tokenizedUntil: lazyTokenizedUntil
1466
- };
1467
- const last = lastRangeRef.current;
1468
- if (last && last.visibleStart === nextRange.visibleStart && last.visibleEnd === nextRange.visibleEnd && last.prefetchStart === nextRange.prefetchStart && last.prefetchEnd === nextRange.prefetchEnd && last.tokenizedUntil === nextRange.tokenizedUntil) {
1469
- return;
1470
- }
1471
- lastRangeRef.current = nextRange;
1472
- if (rafRef.current !== null && typeof cancelAnimationFrame === "function") {
1473
- cancelAnimationFrame(rafRef.current);
1474
- }
1475
- if (typeof requestAnimationFrame === "function") {
1476
- rafRef.current = requestAnimationFrame(() => {
1477
- highlightRequester({
1478
- blockId,
1479
- startLine: visibleStart,
1480
- endLine: visibleEnd,
1481
- priority: "visible",
1482
- reason: "scroll"
1483
- });
1484
- rafRef.current = null;
1485
- });
1486
- } else {
1487
- highlightRequester({
1488
- blockId,
1489
- startLine: visibleStart,
1490
- endLine: visibleEnd,
1491
- priority: "visible",
1492
- reason: "scroll"
1493
- });
1494
- }
1495
- const prefetchNeeded = startIndex < visibleStart || endIndex > visibleEnd;
1496
- if (prefetchNeeded) {
1497
- const idleCallback = globalThis.requestIdleCallback;
1498
- const cancelIdle = globalThis.cancelIdleCallback;
1499
- if (idleRef.current !== null) {
1500
- if (typeof cancelIdle === "function") {
1501
- cancelIdle(idleRef.current);
1502
- } else if (typeof clearTimeout === "function") {
1503
- clearTimeout(idleRef.current);
1504
- }
1505
- }
1506
- const schedule = () => {
1507
- highlightRequester({
1508
- blockId,
1509
- startLine: startIndex,
1510
- endLine: endIndex,
1511
- priority: "prefetch",
1512
- reason: "buffer"
1513
- });
1514
- idleRef.current = null;
1515
- };
1516
- if (typeof idleCallback === "function") {
1517
- idleRef.current = idleCallback(() => schedule());
1518
- } else if (typeof setTimeout === "function") {
1519
- idleRef.current = setTimeout(schedule, 80);
1520
- }
1521
- }
1522
- }, [
1523
- blockId,
1524
- highlightRequester,
1525
- lazyEnabled,
1526
- lazyTokenizedUntil,
1527
- shouldVirtualize,
1528
- virtualization.window.visibleStart,
1529
- virtualization.window.visibleEnd,
1530
- virtualization.window.startIndex,
1531
- virtualization.window.endIndex
1532
- ]);
1533
- React5.useEffect(() => {
1534
- if (shouldVirtualize || !blockIsFinalized || !lazyEnabled || !highlightRequester) return;
1535
- if (totalLazyLineCount <= 0 || lazyTokenizedUntil >= totalLazyLineCount) return;
1536
- const nextRange = {
1537
- visibleStart: 0,
1538
- visibleEnd: totalLazyLineCount,
1539
- prefetchStart: 0,
1540
- prefetchEnd: totalLazyLineCount,
1541
- tokenizedUntil: lazyTokenizedUntil
1542
- };
1543
- const last = lastRangeRef.current;
1544
- if (last && last.visibleStart === nextRange.visibleStart && last.visibleEnd === nextRange.visibleEnd && last.prefetchStart === nextRange.prefetchStart && last.prefetchEnd === nextRange.prefetchEnd && last.tokenizedUntil === nextRange.tokenizedUntil) {
1545
- return;
1546
- }
1547
- lastRangeRef.current = nextRange;
1548
- if (rafRef.current !== null && typeof cancelAnimationFrame === "function") {
1549
- cancelAnimationFrame(rafRef.current);
1550
- }
1551
- const requestFullHighlight = () => {
1552
- highlightRequester({
1553
- blockId,
1554
- startLine: 0,
1555
- endLine: totalLazyLineCount,
1556
- priority: "visible",
1557
- reason: "finalize-full"
1558
- });
1559
- rafRef.current = null;
1560
- };
1561
- if (typeof requestAnimationFrame === "function") {
1562
- rafRef.current = requestAnimationFrame(requestFullHighlight);
1563
- } else {
1564
- requestFullHighlight();
1565
- }
1566
- }, [blockId, blockIsFinalized, highlightRequester, lazyEnabled, lazyTokenizedUntil, shouldVirtualize, totalLazyLineCount]);
1567
- const highlightedHtml = React5.useMemo(() => {
1568
- const blockHtml = node.block?.payload.highlightedHtml ?? "";
1569
- const raw = typeof node.block?.payload.raw === "string" ? node.block.payload.raw : "";
1570
- const metaCode = typeof node.block?.payload.meta?.code === "string" ? (node.block?.payload.meta).code : null;
1571
- const sourceText = resolveCodeSourceText(raw, metaCode);
1572
- const sourceEndsWithNewline = sourceText.endsWith("\n");
1573
- const sourceLines = sourceText.length > 0 ? sourceText.split("\n") : [];
1574
- const rawFallbackLines = buildCodeFallbackLines(raw);
1575
- const deterministicWrapperAttrs = getDefaultCodeWrapperAttributes2(lang);
1576
- const composedPreAttrs = deterministicWrapperAttrs.preAttrs;
1577
- const composedCodeAttrs = deterministicWrapperAttrs.codeAttrs;
1578
- const shouldAppendTerminalNewline = (renderedLines) => {
1579
- if (!sourceEndsWithNewline || renderedLines.length === 0 || lines.length === 0) {
1580
- return false;
1581
- }
1582
- const lastRendered = renderedLines[renderedLines.length - 1];
1583
- const lastKnown = lines[lines.length - 1];
1584
- if (!lastRendered || !lastKnown || lastRendered.index !== lastKnown.index || lastRendered.text === "") {
1585
- return false;
1586
- }
1587
- const expectedRenderedLineCount = Math.max(0, sourceLines.length - 1);
1588
- const expectedLastRenderedLine = sourceLines.length >= 2 ? sourceLines[sourceLines.length - 2] ?? "" : "";
1589
- return renderedLines.length === expectedRenderedLineCount && lastRendered.text === expectedLastRenderedLine;
1590
- };
1591
- if (lines.length > 0) {
1592
- const hasLineHtml = lines.some((line) => typeof line.html === "string" && line.html.length > 0);
1593
- if (!hasLineHtml && blockHtml) {
1594
- return blockHtml;
1595
- }
1596
- if (shouldVirtualize) {
1597
- return composeHighlightedHtml(
1598
- virtualization.window.visibleLines,
1599
- composedPreAttrs,
1600
- composedCodeAttrs,
1601
- shouldAppendTerminalNewline(virtualization.window.visibleLines)
1602
- );
1603
- }
1604
- return composeHighlightedHtml(lines, composedPreAttrs, composedCodeAttrs, shouldAppendTerminalNewline(lines));
1605
- }
1606
- if (!shouldVirtualize && blockHtml) {
1607
- const hasHighlightedLines = blockHtml.includes('class="line"');
1608
- if (!hasHighlightedLines && rawFallbackLines.length > 0) {
1609
- return composeHighlightedHtml(
1610
- rawFallbackLines,
1611
- composedPreAttrs,
1612
- composedCodeAttrs,
1613
- sourceEndsWithNewline && rawFallbackLines[rawFallbackLines.length - 1]?.text !== ""
1614
- );
1615
- }
1616
- return blockHtml;
1617
- }
1618
- if (blockHtml?.trim().match(/^```[\w-]*\s*$/)) {
1619
- if (rawFallbackLines.length > 0) {
1620
- return composeHighlightedHtml(
1621
- rawFallbackLines,
1622
- composedPreAttrs,
1623
- composedCodeAttrs,
1624
- sourceEndsWithNewline && rawFallbackLines[rawFallbackLines.length - 1]?.text !== ""
1625
- );
1626
- }
1627
- }
1628
- if (!blockHtml && rawFallbackLines.length > 0) {
1629
- return composeHighlightedHtml(
1630
- rawFallbackLines,
1631
- composedPreAttrs,
1632
- composedCodeAttrs,
1633
- sourceEndsWithNewline && rawFallbackLines[rawFallbackLines.length - 1]?.text !== ""
1634
- );
1635
- }
1636
- return blockHtml;
1637
- }, [blockIsFinalized, shouldVirtualize, node.block?.payload.highlightedHtml, node.block?.payload.meta, lines, lang, virtualization.window.visibleLines, node.block?.payload.raw]);
1638
- const rendered = /* @__PURE__ */ jsx(
1639
- CodeComponent,
1640
- {
1641
- html: highlightedHtml,
1642
- meta: node.block.payload.meta,
1643
- lines: shouldVirtualize ? virtualization.window.visibleLines : lines,
1644
- lang,
1645
- preAttrs,
1646
- codeAttrs
1647
- }
1648
- );
1649
- const effectiveLineCount = React5.useMemo(() => {
1650
- if (lines.length > 0) {
1651
- return lines.length;
1652
- }
1653
- return 1;
1654
- }, [lines.length]);
1655
- const codeFrameClass = "not-prose flex flex-col rounded-lg border border-input pt-1 font-mono text-sm";
1656
- const codeMetricsAttrs = {
1657
- "data-code-block": "true",
1658
- "data-block-id": blockId,
1659
- "data-code-virtualized": shouldVirtualize ? "true" : "false",
1660
- "data-code-total-lines": String(effectiveLineCount),
1661
- "data-code-mounted-lines": String(shouldVirtualize ? virtualization.window.mountedLines : effectiveLineCount),
1662
- "data-code-window-size": String(virtualization.config.windowSize)
1663
- };
1664
- const codeView = shouldVirtualize ? (() => {
1665
- const { containerRef, window: window2, handleScroll, lineHeight } = virtualization;
1666
- const spacerTop = window2.startIndex * lineHeight;
1667
- const spacerBottom = (window2.totalLines - window2.endIndex) * lineHeight;
1668
- return /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: /* @__PURE__ */ jsxs(
1669
- "div",
1670
- {
1671
- ref: containerRef,
1672
- className: "markdown-code-block-container relative",
1673
- style: { overflowY: "auto", overflowX: "hidden", maxHeight: "600px" },
1674
- onScroll: handleScroll,
1675
- children: [
1676
- /* @__PURE__ */ jsx("div", { style: { height: spacerTop }, "aria-hidden": "true" }),
1677
- rendered,
1678
- /* @__PURE__ */ jsx("div", { style: { height: spacerBottom }, "aria-hidden": "true" })
1679
- ]
1680
- }
1681
- ) });
1682
- })() : /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: rendered });
1683
- const blockComponentMap = registry.getBlockComponentMap();
1684
- const MermaidComponent = Object.prototype.hasOwnProperty.call(blockComponentMap, "mermaid") ? blockComponentMap.mermaid : null;
1685
- if ((lang ?? "").toLowerCase() === "mermaid" && MermaidComponent) {
1686
- const raw = typeof node.block.payload.raw === "string" ? node.block.payload.raw : "";
1687
- const fenced = stripCodeFence(raw);
1688
- const code = fenced.hadFence ? fenced.code : raw;
1689
- if (deferredConfig) {
1690
- return /* @__PURE__ */ jsx("div", { ref: deferredRef, children: shouldRenderDeferred ? React5.createElement(MermaidComponent, {
1691
- code,
1692
- renderCode: codeView,
1693
- meta: node.block.payload.meta,
1694
- isFinalized: node.block.isFinalized
1695
- }) : codeView });
1696
- }
1697
- return React5.createElement(MermaidComponent, {
1698
- code,
1699
- renderCode: codeView,
1700
- meta: node.block.payload.meta,
1701
- isFinalized: node.block.isFinalized
1702
- });
1703
- }
1704
- return codeView;
1705
- });
1706
- CodeBlockView.displayName = "CodeBlockView";
1707
- function composeHighlightedHtml(lines, preAttrs, codeAttrs, appendTerminalNewline = false) {
1708
- const lineMarkup = lines.map((line) => {
1709
- const content = line.html ?? renderTokenLineHtml(line.tokens) ?? escapeHtml(line.text);
1710
- const dataLine = Number.isFinite(line.index) ? ` data-line="${line.index + 1}"` : "";
1711
- return `<span class="line"${dataLine}>${content}</span>`;
1712
- }).join("\n");
1713
- const preAttr = attrsToString(preAttrs);
1714
- const codeAttr = attrsToString(codeAttrs);
1715
- return `<pre${preAttr}><code${codeAttr}>${lineMarkup}${appendTerminalNewline ? "\n" : ""}</code></pre>`;
1716
- }
1717
- var TOKEN_FONT_STYLE_ITALIC = 1;
1718
- var TOKEN_FONT_STYLE_BOLD = 2;
1719
- var TOKEN_FONT_STYLE_UNDERLINE = 4;
1720
- var TOKEN_FONT_STYLE_STRIKETHROUGH = 8;
1721
- function renderTokenLineHtml(tokens) {
1722
- if (!tokens || !Array.isArray(tokens.spans)) {
1723
- return null;
1724
- }
1725
- return mergeRenderableTokenSpans(tokens.spans).map((span) => renderTokenSpanHtml(span)).join("");
1726
- }
1727
- function renderTokenSpanHtml(span) {
1728
- const dark = span.v?.dark;
1729
- const light = span.v?.light;
1730
- const single = span.s;
1731
- const styles = [];
1732
- if (dark?.fg) {
1733
- styles.push(`--shiki-dark:${dark.fg}`);
1734
- }
1735
- if (light?.fg) {
1736
- styles.push(`--shiki-light:${light.fg}`);
1737
- }
1738
- if (!light?.fg && !dark?.fg && single?.fg) {
1739
- styles.push(`color:${single.fg}`);
1740
- }
1741
- const fontStyle = light?.fs ?? dark?.fs ?? single?.fs;
1742
- if (typeof fontStyle === "number" && fontStyle > 0) {
1743
- if (fontStyle & TOKEN_FONT_STYLE_ITALIC) {
1744
- styles.push("font-style: italic");
1745
- }
1746
- if (fontStyle & TOKEN_FONT_STYLE_BOLD) {
1747
- styles.push("font-weight: bold");
1748
- }
1749
- const decorations = [];
1750
- if (fontStyle & TOKEN_FONT_STYLE_UNDERLINE) {
1751
- decorations.push("underline");
1752
- }
1753
- if (fontStyle & TOKEN_FONT_STYLE_STRIKETHROUGH) {
1754
- decorations.push("line-through");
1755
- }
1756
- if (decorations.length > 0) {
1757
- styles.push(`text-decoration: ${decorations.join(" ")}`);
1758
- }
1759
- }
1760
- const content = escapeHtml(span.t ?? "");
1761
- if (styles.length === 0) {
1762
- return content;
1763
- }
1764
- return `<span style="${styles.join(";")}">${content}</span>`;
1765
- }
1766
- function mergeRenderableTokenSpans(spans) {
1767
- if (spans.length <= 1) {
1768
- return spans.slice();
1769
- }
1770
- const merged = [];
1771
- let pendingWhitespace = "";
1772
- for (const span of spans) {
1773
- const text = typeof span.t === "string" ? span.t : "";
1774
- if (/^[\t ]+$/.test(text)) {
1775
- pendingWhitespace += text;
1776
- continue;
1777
- }
1778
- const nextSpan = pendingWhitespace ? { ...span, t: `${pendingWhitespace}${text}` } : span;
1779
- pendingWhitespace = "";
1780
- const previous = merged[merged.length - 1];
1781
- if (previous && sameTokenSpanStyle(previous, nextSpan)) {
1782
- previous.t += nextSpan.t;
1783
- } else {
1784
- merged.push({ ...nextSpan });
1785
- }
1786
- }
1787
- if (pendingWhitespace) {
1788
- const previous = merged[merged.length - 1];
1789
- if (previous) {
1790
- previous.t += pendingWhitespace;
1791
- } else {
1792
- merged.push({ t: pendingWhitespace });
1793
- }
1794
- }
1795
- return merged;
1796
- }
1797
- function sameTokenSpanStyle(a, b) {
1798
- const variantKeys = /* @__PURE__ */ new Set([
1799
- ...Object.keys(a.v ?? {}),
1800
- ...Object.keys(b.v ?? {})
1801
- ]);
1802
- for (const key of variantKeys) {
1803
- const aStyle = a.v?.[key];
1804
- const bStyle = b.v?.[key];
1805
- if ((aStyle?.fg ?? null) !== (bStyle?.fg ?? null)) return false;
1806
- if ((aStyle?.bg ?? null) !== (bStyle?.bg ?? null)) return false;
1807
- if ((aStyle?.fs ?? null) !== (bStyle?.fs ?? null)) return false;
1808
- }
1809
- if ((a.s?.fg ?? null) !== (b.s?.fg ?? null)) return false;
1810
- if ((a.s?.bg ?? null) !== (b.s?.bg ?? null)) return false;
1811
- if ((a.s?.fs ?? null) !== (b.s?.fs ?? null)) return false;
1812
- return true;
1813
- }
1814
- function resolveCodeSourceText(raw, metaCode) {
1815
- if (metaCode !== null) {
1816
- return metaCode.replace(/\r\n?/g, "\n");
1817
- }
1818
- if (!raw) return "";
1819
- const normalized = raw.replace(/\r\n?/g, "\n");
1820
- const fenced = stripCodeFence(normalized);
1821
- return fenced.hadFence ? fenced.code : normalized;
1822
- }
1823
- function attrsToString(attrs) {
1824
- if (!attrs) return "";
1825
- return Object.entries(attrs).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("");
1826
- }
1827
- function buildCodeFallbackLines(raw) {
1828
- const normalized = normalizeCodeFallbackRaw(raw);
1829
- if (normalized.length === 0) {
1830
- if (/^\s*```[^\n]*\n?\s*$/.test(raw)) {
1831
- return [{ id: "temp-0", index: 0, text: "", html: null }];
1832
- }
1833
- return [];
1834
- }
1835
- return normalized.split("\n").map((line, index) => ({
1836
- id: `temp-${index}`,
1837
- index,
1838
- text: line,
1839
- html: null
1840
- }));
1841
- }
1842
- function normalizeCodeFallbackRaw(raw) {
1843
- if (!raw) return "";
1844
- const normalized = raw.replace(/\r\n?/g, "\n");
1845
- const fenced = stripCodeFence(normalized);
1846
- if (!fenced.hadFence) {
1847
- return normalized.replace(/\n+$/, "");
1848
- }
1849
- let code = fenced.code;
1850
- code = code.replace(/\n+$/, "");
1851
- return code;
1852
- }
1853
- function escapeHtml(value) {
1854
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1855
- }
1856
- function escapeAttribute(value) {
1857
- return value.replace(/"/g, "&quot;");
1858
- }
1859
- export {
1860
- BlockNodeRenderer
1861
- };