@stream-mdx/react 0.4.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 (106) hide show
  1. package/CHANGELOG.md +385 -4
  2. package/README.md +141 -16
  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 +268 -0
  6. package/dist/components/bottom-stick-scroll-area.d.cts +36 -0
  7. package/dist/components/bottom-stick-scroll-area.d.ts +36 -0
  8. package/dist/components/bottom-stick-scroll-area.mjs +249 -0
  9. package/dist/components/diff-renderer.cjs +86 -0
  10. package/dist/components/diff-renderer.d.cts +11 -0
  11. package/dist/components/diff-renderer.d.ts +11 -0
  12. package/dist/components/diff-renderer.mjs +66 -0
  13. package/dist/components/index.cjs +2879 -1295
  14. package/dist/components/index.d.cts +9 -2
  15. package/dist/components/index.d.ts +9 -2
  16. package/dist/components/index.mjs +2842 -1277
  17. package/dist/components/katex-math.cjs +220 -0
  18. package/dist/components/katex-math.d.cts +10 -0
  19. package/dist/components/katex-math.d.ts +10 -0
  20. package/dist/components/katex-math.mjs +188 -0
  21. package/dist/contexts/math-tracker.cjs +240 -521
  22. package/dist/contexts/math-tracker.mjs +235 -513
  23. package/dist/index-Cmne1yUK.d.cts +723 -0
  24. package/dist/index-D7dyyu3q.d.ts +723 -0
  25. package/dist/index.cjs +13180 -5640
  26. package/dist/index.d.cts +72 -40
  27. package/dist/index.d.ts +72 -40
  28. package/dist/index.mjs +12587 -5038
  29. package/dist/math/display-wrapper.cjs +7 -15
  30. package/dist/math/display-wrapper.d.cts +2 -2
  31. package/dist/math/display-wrapper.d.ts +2 -2
  32. package/dist/math/display-wrapper.mjs +2 -6
  33. package/dist/node-views-Bpc6Gkgl.d.cts +13 -0
  34. package/dist/node-views-DpnYdaAS.d.ts +13 -0
  35. package/dist/renderer/hooks.cjs +35 -20
  36. package/dist/renderer/hooks.d.cts +22 -1
  37. package/dist/renderer/hooks.d.ts +22 -1
  38. package/dist/renderer/hooks.mjs +27 -12
  39. package/dist/renderer/patch-batching.cjs +7 -8
  40. package/dist/renderer/patch-batching.d.cts +1 -1
  41. package/dist/renderer/patch-batching.d.ts +1 -1
  42. package/dist/renderer/patch-batching.mjs +2 -1
  43. package/dist/renderer/patch-coalescing.cjs +5 -8
  44. package/dist/renderer/patch-commit-scheduler.cjs +160 -326
  45. package/dist/renderer/patch-commit-scheduler.d.cts +28 -4
  46. package/dist/renderer/patch-commit-scheduler.d.ts +28 -4
  47. package/dist/renderer/patch-commit-scheduler.mjs +157 -318
  48. package/dist/renderer/store.cjs +3847 -1099
  49. package/dist/renderer/store.d.cts +111 -3
  50. package/dist/renderer/store.d.ts +111 -3
  51. package/dist/renderer/store.mjs +3847 -1085
  52. package/dist/renderer/virtualized-code.cjs +415 -71
  53. package/dist/renderer/virtualized-code.d.cts +24 -23
  54. package/dist/renderer/virtualized-code.d.ts +24 -23
  55. package/dist/renderer/virtualized-code.mjs +409 -62
  56. package/dist/renderer.cjs +10939 -3974
  57. package/dist/renderer.d.cts +100 -29
  58. package/dist/renderer.d.ts +100 -29
  59. package/dist/renderer.mjs +10711 -3697
  60. package/dist/server-regions-CPLHGli0.d.cts +32 -0
  61. package/dist/server-regions-mUhyoKi7.d.ts +32 -0
  62. package/dist/server.cjs +10286 -3365
  63. package/dist/server.d.cts +17 -247
  64. package/dist/server.d.ts +17 -247
  65. package/dist/server.mjs +10565 -3619
  66. package/dist/{streaming-markdown-DOc2uLiP.d.ts → streaming-markdown-yELbJxyH.d.ts} +51 -55
  67. package/dist/{streaming-markdown-D-JcByd9.d.cts → streaming-markdown-zVwFuaJG.d.cts} +51 -55
  68. package/dist/streaming-markdown.cjs +11828 -4879
  69. package/dist/streaming-markdown.d.cts +9 -2
  70. package/dist/streaming-markdown.d.ts +9 -2
  71. package/dist/streaming-markdown.mjs +11820 -4821
  72. package/dist/trusted-mdx/index.cjs +833 -0
  73. package/dist/trusted-mdx/index.d.cts +11 -0
  74. package/dist/trusted-mdx/index.d.ts +11 -0
  75. package/dist/trusted-mdx/index.mjs +807 -0
  76. package/dist/trusted-mdx/native-children-slot.cjs +45 -0
  77. package/dist/trusted-mdx/native-children-slot.d.cts +11 -0
  78. package/dist/trusted-mdx/native-children-slot.d.ts +11 -0
  79. package/dist/trusted-mdx/native-children-slot.mjs +24 -0
  80. package/dist/trusted-mdx/server.cjs +752 -0
  81. package/dist/trusted-mdx/server.d.cts +24 -0
  82. package/dist/trusted-mdx/server.d.ts +24 -0
  83. package/dist/trusted-mdx/server.mjs +724 -0
  84. package/dist/trusted-mdx-contract-ElKpkDI5.d.cts +113 -0
  85. package/dist/trusted-mdx-contract-ElKpkDI5.d.ts +113 -0
  86. package/dist/utils/inline-html.cjs +246 -147
  87. package/dist/utils/inline-html.d.cts +39 -6
  88. package/dist/utils/inline-html.d.ts +39 -6
  89. package/dist/utils/inline-html.mjs +237 -134
  90. package/package.json +52 -18
  91. package/shadcn/README.md +28 -0
  92. package/shadcn/bottom-stick-scroll-area.tsx +358 -0
  93. package/dist/index-D2MYusAM.d.cts +0 -248
  94. package/dist/index-D2MYusAM.d.ts +0 -248
  95. package/dist/mdx-client.cjs +0 -408
  96. package/dist/mdx-client.d.cts +0 -113
  97. package/dist/mdx-client.d.ts +0 -113
  98. package/dist/mdx-client.mjs +0 -369
  99. package/dist/mdx-coordinator.cjs +0 -563
  100. package/dist/mdx-coordinator.d.cts +0 -21
  101. package/dist/mdx-coordinator.d.ts +0 -21
  102. package/dist/mdx-coordinator.mjs +0 -529
  103. package/dist/renderer/node-views.cjs +0 -1642
  104. package/dist/renderer/node-views.d.cts +0 -12
  105. package/dist/renderer/node-views.d.ts +0 -12
  106. package/dist/renderer/node-views.mjs +0 -1616
@@ -1,1616 +0,0 @@
1
- "use client";
2
-
3
- // src/renderer/node-views.tsx
4
- import { 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("sup", { className: "footnote-ref" }, React2.createElement("a", { href, id, "data-label": label }, String(n)));
492
- }
493
- };
494
- function renderParagraphMixedSegments(segments, inlineComponents, inlineHtmlRenderers) {
495
- const result = [];
496
- let inlineBuffer = [];
497
- let inlineGroupIndex = 0;
498
- const pushRenderedNodes = (nodes, target, baseKey) => {
499
- nodes.forEach((node, idx) => {
500
- if (node === null || node === void 0) return;
501
- const key = `${baseKey}-${idx}`;
502
- if (React2.isValidElement(node)) {
503
- target.push(node.key === key ? node : React2.cloneElement(node, { key }));
504
- } else if (typeof node === "string" || typeof node === "number") {
505
- target.push(React2.createElement(React2.Fragment, { key }, node));
506
- } else {
507
- target.push(React2.createElement(React2.Fragment, { key }, node));
508
- }
509
- });
510
- };
511
- const ensureArray = (value) => {
512
- if (value === null || value === void 0) {
513
- return [];
514
- }
515
- return Array.isArray(value) ? value : [value];
516
- };
517
- const flushInline = () => {
518
- if (inlineBuffer.length === 0) {
519
- return;
520
- }
521
- const key = `paragraph-inline-group-${inlineGroupIndex++}`;
522
- result.push(
523
- React2.createElement(
524
- "p",
525
- {
526
- key,
527
- className: "markdown-paragraph"
528
- },
529
- inlineBuffer
530
- )
531
- );
532
- inlineBuffer = [];
533
- };
534
- segments.forEach((segment, index) => {
535
- const key = `paragraph-segment-${index}`;
536
- switch (segment.kind) {
537
- case "text": {
538
- const inlineNodes = Array.isArray(segment.inline) ? segment.inline : [];
539
- if (inlineNodes.length === 0) {
540
- if (segment.value) {
541
- inlineBuffer.push(React2.createElement(React2.Fragment, { key }, segment.value));
542
- }
543
- break;
544
- }
545
- let chunk = [];
546
- const pushChunk = (chunkNodes, chunkKey) => {
547
- if (chunkNodes.length === 0) return;
548
- const rendered = renderInlineNodes(chunkNodes, inlineComponents);
549
- pushRenderedNodes(ensureArray(rendered), inlineBuffer, chunkKey);
550
- };
551
- inlineNodes.forEach((inlineNode, inlineIdx) => {
552
- if (inlineNode.kind === "math-display") {
553
- pushChunk(chunk, `${key}-chunk-${inlineIdx}`);
554
- chunk = [];
555
- flushInline();
556
- const rendered = renderInlineNodes([inlineNode], inlineComponents);
557
- pushRenderedNodes(ensureArray(rendered), result, `${key}-math-${inlineIdx}`);
558
- } else {
559
- chunk.push(inlineNode);
560
- }
561
- });
562
- pushChunk(chunk, `${key}-chunk-tail`);
563
- break;
564
- }
565
- case "mdx": {
566
- const status = segment.status ?? "pending";
567
- let element;
568
- if (status === "compiled") {
569
- element = React2.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
570
- } else if (status === "error") {
571
- const message = segment.value || "MDX error";
572
- element = React2.createElement("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error" }, message);
573
- } else {
574
- element = React2.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": status }, segment.value);
575
- }
576
- inlineBuffer.push(React2.createElement(React2.Fragment, { key }, element));
577
- break;
578
- }
579
- case "html": {
580
- const html = segment.sanitized ?? segment.value;
581
- const isBlockLevel = isBlockLevelHtml(html);
582
- const element = renderInlineHtmlSegment(segment.value, segment.sanitized, {
583
- key,
584
- renderers: inlineHtmlRenderers
585
- });
586
- if (isBlockLevel) {
587
- flushInline();
588
- if (element) {
589
- result.push(element);
590
- } else if (html) {
591
- result.push(
592
- React2.createElement("div", {
593
- key,
594
- className: "markdown-inline-html-block",
595
- dangerouslySetInnerHTML: { __html: html }
596
- })
597
- );
598
- }
599
- } else if (element) {
600
- inlineBuffer.push(element);
601
- }
602
- break;
603
- }
604
- default:
605
- break;
606
- }
607
- });
608
- flushInline();
609
- if (result.length === 0) {
610
- return [
611
- React2.createElement(
612
- "p",
613
- {
614
- key: "paragraph-inline-group-0",
615
- className: "markdown-paragraph"
616
- },
617
- inlineBuffer
618
- )
619
- ];
620
- }
621
- return result;
622
- }
623
- function isBlockLevelHtml(html) {
624
- if (!html) return false;
625
- const trimmed = html.trim();
626
- if (!trimmed.startsWith("<")) {
627
- return false;
628
- }
629
- const match = trimmed.match(/^<([A-Za-z][\w:-]*)\b/);
630
- if (!match) {
631
- return false;
632
- }
633
- const tag = match[1].toLowerCase();
634
- return BLOCK_LEVEL_TAGS.has(tag);
635
- }
636
- var BLOCK_LEVEL_TAGS = /* @__PURE__ */ new Set([
637
- "address",
638
- "article",
639
- "aside",
640
- "blockquote",
641
- "canvas",
642
- "div",
643
- "dl",
644
- "fieldset",
645
- "figcaption",
646
- "figure",
647
- "footer",
648
- "form",
649
- "h1",
650
- "h2",
651
- "h3",
652
- "h4",
653
- "h5",
654
- "h6",
655
- "header",
656
- "hr",
657
- "li",
658
- "main",
659
- "nav",
660
- "ol",
661
- "p",
662
- "pre",
663
- "section",
664
- "table",
665
- "ul",
666
- "math"
667
- ]);
668
-
669
- // src/renderer/hooks.ts
670
- import { useMemo, useSyncExternalStore } from "react";
671
- function useRendererNode(store, id) {
672
- const selector = useMemo(() => {
673
- return () => store.getNodeWithVersion(id);
674
- }, [store, id]);
675
- const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
676
- return snapshot.node;
677
- }
678
- function useRendererChildren(store, id) {
679
- const selector = useMemo(() => {
680
- return () => store.getChildrenWithVersion(id);
681
- }, [store, id]);
682
- const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
683
- return snapshot.children;
684
- }
685
-
686
- // src/renderer/code-highlight-context.tsx
687
- import React3 from "react";
688
- var CodeHighlightRequestContext = React3.createContext(null);
689
- function useCodeHighlightRequester() {
690
- return React3.useContext(CodeHighlightRequestContext);
691
- }
692
-
693
- // src/renderer/deferred-render-context.tsx
694
- import React4 from "react";
695
- var DeferredRenderContext = React4.createContext(null);
696
-
697
- // src/renderer/store.ts
698
- import {
699
- cloneBlock,
700
- createBlockSnapshot,
701
- extractCodeWrapperAttributes,
702
- getDefaultCodeWrapperAttributes,
703
- sanitizeCodeHTML,
704
- sanitizeHTML as sanitizeHTML2,
705
- PATCH_ROOT_ID
706
- } from "@stream-mdx/core";
707
- var NODE_SNAPSHOT_CACHE_LIMIT = 5e4;
708
- var CHILDREN_SNAPSHOT_CACHE_LIMIT = 5e4;
709
- var NODE_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(NODE_SNAPSHOT_CACHE_LIMIT * 0.1));
710
- var CHILDREN_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(CHILDREN_SNAPSHOT_CACHE_LIMIT * 0.1));
711
- var EMPTY_CHILDREN = Object.freeze([]);
712
- var EMPTY_NODE_SNAPSHOT = Object.freeze({ version: -1, node: void 0 });
713
- var EMPTY_CHILDREN_SNAPSHOT = Object.freeze({
714
- version: -1,
715
- children: EMPTY_CHILDREN
716
- });
717
- function isListPatchDebugEnabled() {
718
- if (typeof globalThis !== "undefined") {
719
- const flag = globalThis.__STREAMING_LIST_DEBUG__;
720
- if (flag === true) return true;
721
- }
722
- if (typeof process !== "undefined" && process.env.NEXT_PUBLIC_STREAMING_LIST_DEBUG === "true") {
723
- return true;
724
- }
725
- return false;
726
- }
727
- var CODE_BLOCK_DEBUG_ENABLED = (() => {
728
- try {
729
- if (typeof process !== "undefined" && process.env && process.env.NEXT_PUBLIC_STREAMING_DEBUG_CODELINES === "1") {
730
- return true;
731
- }
732
- if (typeof globalThis !== "undefined") {
733
- const debug = globalThis?.__STREAMING_DEBUG__;
734
- if (debug?.codeLines) {
735
- return true;
736
- }
737
- }
738
- } catch {
739
- }
740
- return false;
741
- })() || false;
742
- var CODE_BLOCK_VALIDATION_ENABLED = typeof process !== "undefined" && process.env ? process.env.NODE_ENV !== "production" : true;
743
- var getPerfNow = (() => {
744
- if (typeof performance !== "undefined" && typeof performance.now === "function") {
745
- return () => performance.now();
746
- }
747
- return () => Date.now();
748
- })();
749
-
750
- // src/renderer/virtualized-code.tsx
751
- import { useCallback, useEffect as useEffect2, useMemo as useMemo2, useRef, useState as useState2 } from "react";
752
- var DEFAULT_VIRTUALIZED_CODE_CONFIG = {
753
- enabled: true,
754
- windowSize: 100,
755
- // Render 100 lines at a time
756
- bufferSize: 50,
757
- // +50 lines buffer above/below
758
- virtualizeThreshold: 200
759
- // Only virtualize if 200+ lines
760
- };
761
- function calculateCodeWindow(lines, scrollTop, containerHeight, lineHeight, config) {
762
- const totalLines = lines.length;
763
- if (!config.enabled || totalLines < config.virtualizeThreshold) {
764
- return {
765
- startIndex: 0,
766
- endIndex: totalLines,
767
- visibleStart: 0,
768
- visibleEnd: totalLines,
769
- visibleLines: lines,
770
- totalLines,
771
- mountedLines: totalLines
772
- };
773
- }
774
- const firstVisibleLine = Math.floor(scrollTop / lineHeight);
775
- const lastVisibleLine = Math.ceil((scrollTop + containerHeight) / lineHeight);
776
- const visibleStart = Math.max(0, firstVisibleLine);
777
- const visibleEnd = Math.min(totalLines, Math.max(visibleStart, lastVisibleLine));
778
- const startIndex = Math.max(0, visibleStart - config.bufferSize);
779
- const endIndex = Math.min(totalLines, visibleEnd + config.bufferSize);
780
- return {
781
- startIndex,
782
- endIndex,
783
- visibleStart,
784
- visibleEnd,
785
- visibleLines: lines.slice(startIndex, endIndex),
786
- totalLines,
787
- mountedLines: endIndex - startIndex
788
- };
789
- }
790
- function useVirtualizedCode(lines, config = DEFAULT_VIRTUALIZED_CODE_CONFIG) {
791
- const containerRef = useRef(null);
792
- const [scrollTop, setScrollTop] = useState2(0);
793
- const [containerHeight, setContainerHeight] = useState2(0);
794
- const lineHeightRef = useRef(20);
795
- useEffect2(() => {
796
- if (!containerRef.current || lines.length === 0) return;
797
- const timeoutId = setTimeout(() => {
798
- if (!containerRef.current) return;
799
- const firstLine = containerRef.current.querySelector(".line");
800
- if (firstLine) {
801
- const measuredHeight = firstLine.offsetHeight || 20;
802
- if (measuredHeight !== lineHeightRef.current) {
803
- lineHeightRef.current = measuredHeight;
804
- }
805
- }
806
- }, 0);
807
- return () => clearTimeout(timeoutId);
808
- }, [lines.length]);
809
- const handleScroll = useCallback((e) => {
810
- const target = e.currentTarget;
811
- setScrollTop(target.scrollTop);
812
- setContainerHeight(target.clientHeight);
813
- }, []);
814
- useEffect2(() => {
815
- if (!containerRef.current) return;
816
- const resizeObserver = new ResizeObserver((entries) => {
817
- for (const entry of entries) {
818
- setContainerHeight(entry.contentRect.height);
819
- }
820
- });
821
- resizeObserver.observe(containerRef.current);
822
- return () => resizeObserver.disconnect();
823
- }, []);
824
- const window2 = useMemo2(() => {
825
- return calculateCodeWindow(lines, scrollTop, containerHeight, lineHeightRef.current, config);
826
- }, [lines, scrollTop, containerHeight, config]);
827
- const scrollToLine = useCallback((lineIndex) => {
828
- if (!containerRef.current) return;
829
- const targetScrollTop = lineIndex * lineHeightRef.current;
830
- containerRef.current.scrollTop = targetScrollTop;
831
- setScrollTop(targetScrollTop);
832
- }, []);
833
- return {
834
- containerRef,
835
- window: window2,
836
- handleScroll,
837
- scrollToLine,
838
- lineHeight: lineHeightRef.current,
839
- config
840
- };
841
- }
842
-
843
- // src/renderer/node-views.tsx
844
- import { jsx, jsxs } from "react/jsx-runtime";
845
- var BlockNodeRenderer = ({ store, blockId, registry }) => {
846
- const node = useRendererNode(store, blockId);
847
- const block = node?.block;
848
- if (!node || !block) return null;
849
- switch (block.type) {
850
- case "paragraph":
851
- return /* @__PURE__ */ jsx(ParagraphBlockView, { store, blockId: block.id, registry });
852
- case "blockquote":
853
- return /* @__PURE__ */ jsx(BlockquoteBlockView, { store, blockId: block.id, registry });
854
- case "list":
855
- return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: block.id, registry, depth: 0 });
856
- case "table":
857
- return /* @__PURE__ */ jsx(TableBlockView, { store, blockId: block.id, registry });
858
- case "code":
859
- return /* @__PURE__ */ jsx(CodeBlockView, { store, blockId: block.id, registry });
860
- case "html":
861
- return /* @__PURE__ */ jsx(HtmlBlockView, { store, blockId: block.id, registry });
862
- case "mdx":
863
- return /* @__PURE__ */ jsx(MdxBlockView, { store, blockId: block.id, registry });
864
- default:
865
- return registry.renderBlock(block);
866
- }
867
- };
868
- var ParagraphBlockView = React5.memo(({ store, blockId, registry }) => {
869
- const node = useRendererNode(store, blockId);
870
- const block = node?.block;
871
- const childIds = useRendererChildren(store, blockId);
872
- if (!node || !block) {
873
- return null;
874
- }
875
- const inlineComponents = registry.getInlineComponents();
876
- if (!block.isFinalized) {
877
- const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
878
- const meta = block.payload.meta ?? {};
879
- const segments2 = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
880
- if (segments2.length > 0) {
881
- const allowMixedStreaming = Boolean(meta.allowMixedStreaming);
882
- if (!allowMixedStreaming) {
883
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
884
- }
885
- const structured = renderParagraphMixedSegments(segments2, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
886
- if (structured.length === 1) {
887
- const [single] = structured;
888
- return React5.isValidElement(single) ? single : single;
889
- }
890
- return structured;
891
- }
892
- if (meta.inlineStatus === "complete" || meta.inlineStatus === "anticipated") {
893
- const inlineNodes2 = block.payload.inline ?? [];
894
- const containsDisplayMath2 = inlineNodes2.some((node2) => node2.kind === "math-display");
895
- if (containsDisplayMath2) {
896
- const derivedSegments = [
897
- {
898
- kind: "text",
899
- value: raw,
900
- inline: inlineNodes2
901
- }
902
- ];
903
- const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
904
- if (structured.length === 1) {
905
- const [single] = structured;
906
- return React5.isValidElement(single) ? single : single;
907
- }
908
- return structured;
909
- }
910
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: renderInlineNodes(inlineNodes2, inlineComponents) });
911
- }
912
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
913
- }
914
- const propsBlock = node.props?.block;
915
- const inlineStatus = propsBlock?.payload?.meta?.inlineStatus ?? block.payload.meta?.inlineStatus ?? node.props?.inlineStatus;
916
- if (inlineStatus && inlineStatus !== "complete") {
917
- const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
918
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: raw });
919
- }
920
- const segments = Array.isArray(block.payload.meta?.mixedSegments) ? block.payload.meta.mixedSegments : void 0;
921
- if (segments && segments.length > 0) {
922
- const structured = renderParagraphMixedSegments(segments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
923
- if (structured.length === 1) {
924
- const [single] = structured;
925
- return React5.isValidElement(single) ? single : single;
926
- }
927
- return structured;
928
- }
929
- const inlineNodes = block.payload.inline ?? [];
930
- const containsDisplayMath = inlineNodes.some((node2) => node2.kind === "math-display");
931
- if (containsDisplayMath) {
932
- const derivedSegments = [
933
- {
934
- kind: "text",
935
- value: typeof block.payload.raw === "string" ? block.payload.raw : "",
936
- inline: inlineNodes
937
- }
938
- ];
939
- const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
940
- if (structured.length === 1) {
941
- const [single] = structured;
942
- return React5.isValidElement(single) ? single : single;
943
- }
944
- return structured;
945
- }
946
- const ParagraphComponent = registry.getBlockComponent("paragraph");
947
- const baseElement = React5.createElement(ParagraphComponent, {
948
- inlines: block.payload.inline ?? [],
949
- raw: block.payload.raw,
950
- meta: block.payload.meta
951
- });
952
- if (childIds.length > 0) {
953
- const renderedChildren = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
954
- if (React5.isValidElement(baseElement)) {
955
- const { children: _ignored, className = "markdown-paragraph", inlines: _inlines, raw: _raw, meta: _meta, ...rest } = baseElement.props ?? {};
956
- return React5.createElement("p", { ...rest, className }, renderedChildren);
957
- }
958
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderedChildren });
959
- }
960
- if (React5.isValidElement(baseElement)) {
961
- return baseElement;
962
- }
963
- return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderInlineNodes(block.payload.inline ?? [], inlineComponents) });
964
- });
965
- ParagraphBlockView.displayName = "ParagraphBlockView";
966
- var BlockquoteBlockView = React5.memo(({ store, blockId, registry }) => {
967
- const node = useRendererNode(store, blockId);
968
- const block = node?.block;
969
- const childIds = useRendererChildren(store, blockId);
970
- if (!node || !block) {
971
- return null;
972
- }
973
- const meta = block.payload.meta ?? {};
974
- const mixedSegments = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
975
- const normalizedText = typeof meta.normalizedText === "string" && meta.normalizedText.length > 0 ? meta.normalizedText : typeof block.payload.raw === "string" ? block.payload.raw : "";
976
- const inlineComponents = registry.getInlineComponents();
977
- const renderTextWithBreaks = (text, keyPrefix) => {
978
- const lines = text.split("\n");
979
- const lastIndex = lines.length - 1;
980
- let offset = 0;
981
- return lines.map((line, idx) => {
982
- const key = `${keyPrefix}${offset}`;
983
- offset += line.length + 1;
984
- return /* @__PURE__ */ jsxs("span", { className: "markdown-blockquote-line", children: [
985
- line,
986
- idx < lastIndex ? /* @__PURE__ */ jsx("br", {}) : null
987
- ] }, key);
988
- });
989
- };
990
- const renderInlineContent = (inline, keyPrefix) => {
991
- if (inline && inline.length > 0) {
992
- return renderInlineNodes(inline, inlineComponents);
993
- }
994
- return null;
995
- };
996
- const renderMixedSegments = () => {
997
- if (!mixedSegments.length) {
998
- return [];
999
- }
1000
- const elements = [];
1001
- mixedSegments.forEach((segment, segmentIndex) => {
1002
- switch (segment.kind) {
1003
- case "html": {
1004
- const htmlNode = renderInlineHtmlSegment(segment.value, segment.sanitized ?? segment.value, {
1005
- key: `blockquote-html-${block.id}-${segmentIndex}`,
1006
- renderers: DEFAULT_INLINE_HTML_RENDERERS
1007
- });
1008
- if (htmlNode) {
1009
- elements.push(htmlNode);
1010
- } else {
1011
- elements.push(
1012
- React5.createElement("span", {
1013
- key: `blockquote-html-${block.id}-${segmentIndex}`,
1014
- className: "markdown-inline-html",
1015
- /* biome-ignore lint/security/noDangerouslySetInnerHtml: segment content is sanitized by the worker before streaming */
1016
- dangerouslySetInnerHTML: { __html: segment.sanitized ?? segment.value }
1017
- })
1018
- );
1019
- }
1020
- break;
1021
- }
1022
- case "mdx":
1023
- elements.push(
1024
- /* @__PURE__ */ jsx("span", { "data-mdx-status": segment.status ?? "pending", children: segment.value }, `blockquote-mdx-${block.id}-${segmentIndex}`)
1025
- );
1026
- break;
1027
- default: {
1028
- const inline = renderInlineContent(segment.inline, `blockquote-text-inline-${block.id}-${segmentIndex}-`);
1029
- if (inline) {
1030
- elements.push(/* @__PURE__ */ jsx(React5.Fragment, { children: inline }, `blockquote-inline-${block.id}-${segmentIndex}`));
1031
- } else {
1032
- elements.push(
1033
- /* @__PURE__ */ jsx(React5.Fragment, { children: renderTextWithBreaks(segment.value, `blockquote-text-${block.id}-${segmentIndex}-`) }, `blockquote-text-${block.id}-${segmentIndex}`)
1034
- );
1035
- }
1036
- break;
1037
- }
1038
- }
1039
- });
1040
- return elements;
1041
- };
1042
- const mixedSegmentElements = renderMixedSegments();
1043
- const fallbackElements = normalizedText ? renderTextWithBreaks(normalizedText, `blockquote-fallback-${block.id}-`) : null;
1044
- const inlineNodes = block.payload.inline ?? [];
1045
- const inlineElements = inlineNodes.length > 0 ? renderInlineNodes(inlineNodes, inlineComponents) : null;
1046
- if (!block.isFinalized) {
1047
- const streamingContent = mixedSegmentElements.length ? mixedSegmentElements : inlineElements ? inlineElements : fallbackElements;
1048
- const shouldShowStreaming = !block.isFinalized && (!streamingContent || Array.isArray(streamingContent) && streamingContent.length === 0);
1049
- const className = shouldShowStreaming ? "markdown-blockquote streaming-partial" : "markdown-blockquote";
1050
- return /* @__PURE__ */ jsx("blockquote", { className, children: streamingContent });
1051
- }
1052
- const childContent = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
1053
- const renderedContent = (() => {
1054
- if (mixedSegmentElements.length > 0) {
1055
- return mixedSegmentElements;
1056
- }
1057
- if (childIds.length > 0) {
1058
- const resolved = childContent.filter((child) => child !== null);
1059
- if (resolved.length > 0) {
1060
- return resolved;
1061
- }
1062
- }
1063
- if (inlineElements) {
1064
- return inlineElements;
1065
- }
1066
- if (fallbackElements && fallbackElements.length > 0) {
1067
- return fallbackElements;
1068
- }
1069
- return null;
1070
- })();
1071
- const BlockquoteComponent = registry.getBlockComponent("blockquote");
1072
- const baseElement = React5.createElement(
1073
- BlockquoteComponent,
1074
- {
1075
- inlines: block.payload.inline ?? [],
1076
- renderedContent
1077
- },
1078
- renderedContent
1079
- );
1080
- if (React5.isValidElement(baseElement)) {
1081
- return baseElement;
1082
- }
1083
- return /* @__PURE__ */ jsx("blockquote", { className: "markdown-blockquote", children: renderedContent });
1084
- });
1085
- BlockquoteBlockView.displayName = "BlockquoteBlockView";
1086
- var MixedSegmentView = React5.memo(({ store, nodeId, inlineComponents }) => {
1087
- const node = useRendererNode(store, nodeId);
1088
- if (!node) return null;
1089
- switch (node.type) {
1090
- case "paragraph-text":
1091
- case "blockquote-text":
1092
- case "list-item-text": {
1093
- const inline = node.props?.inline ?? [];
1094
- if (inline.length > 0) {
1095
- return renderInlineNodes(inline, inlineComponents);
1096
- }
1097
- const text = typeof node.props?.text === "string" ? node.props?.text : "";
1098
- if (!text) return null;
1099
- return text;
1100
- }
1101
- case "paragraph-html":
1102
- case "blockquote-html":
1103
- case "list-item-html": {
1104
- const raw = typeof node.props?.raw === "string" ? node.props.raw : void 0;
1105
- const html = typeof node.props?.html === "string" ? node.props?.html : "";
1106
- const rendered = renderInlineHtmlSegment(raw, html, {
1107
- key: node.id,
1108
- renderers: DEFAULT_INLINE_HTML_RENDERERS
1109
- });
1110
- if (rendered) {
1111
- return rendered;
1112
- }
1113
- if (!html) return null;
1114
- return React5.createElement("span", {
1115
- className: "markdown-inline-html",
1116
- /* biome-ignore lint/security/noDangerouslySetInnerHtml: html is sanitized upstream before reaching the renderer */
1117
- dangerouslySetInnerHTML: { __html: html }
1118
- });
1119
- }
1120
- case "paragraph-mdx":
1121
- case "blockquote-mdx":
1122
- case "list-item-mdx": {
1123
- const status = node.props?.status ?? "pending";
1124
- const raw = typeof node.props?.raw === "string" ? node.props?.raw : "";
1125
- if (status === "compiled") {
1126
- return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
1127
- }
1128
- if (status === "error") {
1129
- const message = raw || "MDX error";
1130
- return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error", children: message });
1131
- }
1132
- return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": status, children: status === "compiled" ? "" : raw });
1133
- }
1134
- default:
1135
- return null;
1136
- }
1137
- });
1138
- MixedSegmentView.displayName = "MixedSegmentView";
1139
- var HtmlBlockView = React5.memo(({ store, blockId, registry }) => {
1140
- const node = useRendererNode(store, blockId);
1141
- if (!node || !node.block) return null;
1142
- return registry.renderBlock(node.block);
1143
- });
1144
- HtmlBlockView.displayName = "HtmlBlockView";
1145
- var MdxBlockView = React5.memo(({ store, blockId, registry }) => {
1146
- const node = useRendererNode(store, blockId);
1147
- if (!node || !node.block) return null;
1148
- return registry.renderBlock(node.block);
1149
- });
1150
- MdxBlockView.displayName = "MdxBlockView";
1151
- var ListBlockView = React5.memo(
1152
- ({ store, blockId, registry, depth = 0 }) => {
1153
- const node = useRendererNode(store, blockId);
1154
- const block = node?.block;
1155
- const childIds = useRendererChildren(store, blockId);
1156
- const inlineComponents = registry.getInlineComponents();
1157
- const ordered = Boolean(node?.props?.ordered ?? block?.payload.meta?.ordered);
1158
- const Tag = ordered ? "ol" : "ul";
1159
- const listDebugEnabled = isListPatchDebugEnabled();
1160
- const listItemIds = React5.useMemo(() => {
1161
- const ids = [];
1162
- for (const childId of childIds) {
1163
- const childNode = store.getNode(childId);
1164
- if (childNode?.type === "list-item") {
1165
- ids.push(childId);
1166
- }
1167
- }
1168
- return ids;
1169
- }, [childIds, store]);
1170
- React5.useEffect(() => {
1171
- if (!listDebugEnabled) return;
1172
- const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
1173
- console.info("[stream-mdx:list-render]", {
1174
- listId: blockId,
1175
- depth,
1176
- ordered,
1177
- childIds,
1178
- childTypes,
1179
- listItemIds,
1180
- listItems: listItemIds.length,
1181
- totalChildren: childIds.length,
1182
- isFinalized: block?.isFinalized ?? false
1183
- });
1184
- }, [listDebugEnabled, blockId, depth, ordered, childIds, listItemIds, store, block?.isFinalized]);
1185
- const listStyle = React5.useMemo(() => {
1186
- if (!ordered || listItemIds.length === 0) return void 0;
1187
- let maxDigits = 1;
1188
- listItemIds.forEach((childId, index) => {
1189
- const childNode = store.getNode(childId);
1190
- const raw = typeof childNode?.block?.payload?.raw === "string" ? childNode.block.payload.raw : void 0;
1191
- const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
1192
- const marker = markerMatch?.[1]?.trim();
1193
- const text = marker ?? `${index + 1}.`;
1194
- const digitMatch = text.match(/\d/g);
1195
- const digits = digitMatch ? digitMatch.length : text.length;
1196
- if (digits > maxDigits) maxDigits = digits;
1197
- });
1198
- const baseIndent = depth === 0 ? "2.5rem" : depth === 1 ? "2rem" : "1.5rem";
1199
- return {
1200
- ["--list-indent"]: `calc(${baseIndent} + ${maxDigits}ch)`
1201
- };
1202
- }, [ordered, listItemIds, store, depth]);
1203
- if (listItemIds.length === 0) return null;
1204
- return /* @__PURE__ */ jsx(
1205
- Tag,
1206
- {
1207
- className: `markdown-list ${ordered ? "ordered" : "unordered"}`,
1208
- "data-list-depth": depth,
1209
- "data-list-id": listDebugEnabled ? blockId : void 0,
1210
- style: listStyle,
1211
- children: listItemIds.map((childId, index) => /* @__PURE__ */ jsx(
1212
- ListItemView,
1213
- {
1214
- store,
1215
- nodeId: childId,
1216
- inlineComponents,
1217
- registry,
1218
- ordered,
1219
- index,
1220
- depth
1221
- },
1222
- childId
1223
- ))
1224
- }
1225
- );
1226
- }
1227
- );
1228
- ListBlockView.displayName = "ListBlockView";
1229
- var ListItemView = React5.memo(({ store, nodeId, inlineComponents, registry, ordered, index, depth }) => {
1230
- const node = useRendererNode(store, nodeId);
1231
- const childIds = useRendererChildren(store, nodeId);
1232
- const inline = node?.props?.inline ?? [];
1233
- const isTask = Boolean(node?.props?.task);
1234
- const isChecked = Boolean(node?.props?.checked);
1235
- const block = node?.block;
1236
- const raw = typeof block?.payload?.raw === "string" ? block.payload.raw : void 0;
1237
- const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
1238
- const marker = markerMatch?.[1]?.trim();
1239
- const inferredIndex = typeof node?.props?.index === "number" ? Number(node?.props?.index) : index;
1240
- const isOrdered = Boolean(node?.props?.ordered ?? ordered);
1241
- const counterText = !isTask ? isOrdered ? marker ? marker : `${inferredIndex + 1}.` : "\u2022" : void 0;
1242
- const listDebugEnabled = isListPatchDebugEnabled();
1243
- const inlineLength = inline.length;
1244
- const [segmentChildIds, contentChildIds] = React5.useMemo(() => {
1245
- const segments = [];
1246
- const structural = [];
1247
- for (const childId of childIds) {
1248
- const childNode = store.getNode(childId);
1249
- if (!childNode) continue;
1250
- if (childNode.type?.startsWith("list-item-")) {
1251
- segments.push(childId);
1252
- } else {
1253
- structural.push(childId);
1254
- }
1255
- }
1256
- return [segments, structural];
1257
- }, [childIds, store]);
1258
- const segmentElements = React5.useMemo(() => {
1259
- return segmentChildIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
1260
- }, [segmentChildIds, store, inlineComponents]);
1261
- const primaryContent = React5.useMemo(() => {
1262
- if (segmentChildIds.length > 0) {
1263
- return segmentElements;
1264
- }
1265
- return renderInlineNodes(inline, inlineComponents);
1266
- }, [segmentChildIds, segmentElements, inline, inlineComponents]);
1267
- const trailingChildren = React5.useMemo(() => {
1268
- return contentChildIds.map((childId) => {
1269
- const childNode = store.getNode(childId);
1270
- if (!childNode) return null;
1271
- switch (childNode.type) {
1272
- case "paragraph": {
1273
- const childInline = childNode.props?.inline ?? [];
1274
- return /* @__PURE__ */ jsx("p", { className: "markdown-list-item-paragraph", children: renderInlineNodes(childInline, inlineComponents) }, childId);
1275
- }
1276
- case "list":
1277
- return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: childId, registry, depth: depth + 1 }, childId);
1278
- default:
1279
- return /* @__PURE__ */ jsx(BlockNodeRenderer, { store, blockId: childId, registry }, childId);
1280
- }
1281
- });
1282
- }, [contentChildIds, store, inlineComponents, registry, depth]);
1283
- const filteredChildren = trailingChildren.filter((child) => Boolean(child));
1284
- const hasChildren = filteredChildren.length > 0;
1285
- React5.useEffect(() => {
1286
- if (!listDebugEnabled) return;
1287
- const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
1288
- console.info("[stream-mdx:list-item-render]", {
1289
- itemId: nodeId,
1290
- depth,
1291
- ordered: isOrdered,
1292
- inferredIndex,
1293
- marker,
1294
- isTask,
1295
- isChecked,
1296
- childIds,
1297
- childTypes,
1298
- segmentChildIds,
1299
- contentChildIds,
1300
- inlineLength,
1301
- hasChildren,
1302
- isFinalized: block?.isFinalized ?? false
1303
- });
1304
- }, [
1305
- listDebugEnabled,
1306
- nodeId,
1307
- depth,
1308
- isOrdered,
1309
- inferredIndex,
1310
- marker,
1311
- isTask,
1312
- isChecked,
1313
- childIds,
1314
- segmentChildIds,
1315
- contentChildIds,
1316
- inlineLength,
1317
- hasChildren,
1318
- store,
1319
- block?.isFinalized
1320
- ]);
1321
- return /* @__PURE__ */ jsxs(
1322
- "li",
1323
- {
1324
- className: `markdown-list-item${isTask ? " markdown-list-item-task" : ""}`,
1325
- "data-counter-text": counterText,
1326
- "data-list-depth": depth,
1327
- "data-list-item-id": listDebugEnabled ? nodeId : void 0,
1328
- children: [
1329
- isTask ? /* @__PURE__ */ jsxs("div", { className: "markdown-task", children: [
1330
- /* @__PURE__ */ jsx("input", { type: "checkbox", className: "markdown-task-checkbox", checked: isChecked, readOnly: true, disabled: true, tabIndex: -1, "aria-checked": isChecked }),
1331
- /* @__PURE__ */ jsx("span", { className: "markdown-task-content", children: primaryContent })
1332
- ] }) : primaryContent,
1333
- hasChildren ? /* @__PURE__ */ jsx("div", { className: "markdown-list-item-children", children: filteredChildren }) : null
1334
- ]
1335
- }
1336
- );
1337
- });
1338
- ListItemView.displayName = "ListItemView";
1339
- var TableBlockView = React5.memo(({ store, blockId, registry }) => {
1340
- const tableElements = registry.getTableElements();
1341
- const childIds = useRendererChildren(store, blockId);
1342
- 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)) });
1343
- });
1344
- TableBlockView.displayName = "TableBlockView";
1345
- var TableSectionView = React5.memo(({ store, nodeId, registry }) => {
1346
- const node = useRendererNode(store, nodeId);
1347
- if (!node) return null;
1348
- const tableElements = registry.getTableElements();
1349
- if (node.type === "table-header") {
1350
- const childIds = useRendererChildren(store, nodeId);
1351
- return /* @__PURE__ */ jsx(tableElements.Thead, { children: /* @__PURE__ */ jsx(tableElements.Tr, { children: childIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) }) });
1352
- }
1353
- if (node.type === "table-body") {
1354
- const rowIds = useRendererChildren(store, nodeId);
1355
- return /* @__PURE__ */ jsx(tableElements.Tbody, { children: rowIds.map((rowId) => /* @__PURE__ */ jsx(TableRowView, { store, nodeId: rowId, registry }, rowId)) });
1356
- }
1357
- return null;
1358
- });
1359
- TableSectionView.displayName = "TableSectionView";
1360
- var TableRowView = React5.memo(({ store, nodeId, registry }) => {
1361
- const tableElements = registry.getTableElements();
1362
- const cellIds = useRendererChildren(store, nodeId);
1363
- return /* @__PURE__ */ jsx(tableElements.Tr, { children: cellIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) });
1364
- });
1365
- TableRowView.displayName = "TableRowView";
1366
- var TableCellView = React5.memo(({ store, nodeId, registry }) => {
1367
- const node = useRendererNode(store, nodeId);
1368
- const inlineComponents = registry.getInlineComponents();
1369
- const tableElements = registry.getTableElements();
1370
- if (!node) return null;
1371
- const Tag = node.type === "table-header-cell" ? tableElements.Th : tableElements.Td;
1372
- const inline = node.props?.inline ?? [];
1373
- const align = node.props?.align;
1374
- const content = renderInlineNodes(inline, inlineComponents);
1375
- const alignProps = align ? { align } : void 0;
1376
- return /* @__PURE__ */ jsx(Tag, { ...alignProps, children: content });
1377
- });
1378
- TableCellView.displayName = "TableCellView";
1379
- var CodeBlockView = React5.memo(({ store, blockId, registry }) => {
1380
- const node = useRendererNode(store, blockId);
1381
- const childIds = useRendererChildren(store, blockId);
1382
- const CodeComponent = registry.getBlockComponent("code");
1383
- const deferredConfig = React5.useContext(DeferredRenderContext);
1384
- const deferredRef = React5.useRef(null);
1385
- const shouldRenderDeferred = useDeferredRender(
1386
- deferredRef,
1387
- deferredConfig ? { ...deferredConfig, enabled: true } : { enabled: false }
1388
- );
1389
- if (!node || !node.block) return null;
1390
- const nodeVersion = node.version;
1391
- const lines = React5.useMemo(() => {
1392
- const seenIds = /* @__PURE__ */ new Set();
1393
- const seenIndices = /* @__PURE__ */ new Set();
1394
- const deduped = [];
1395
- for (const childId of childIds) {
1396
- const child = store.getNode(childId);
1397
- if (!child) continue;
1398
- const index = typeof child.props?.index === "number" ? child.props?.index : deduped.length;
1399
- const text = typeof child.props?.text === "string" ? child.props?.text : "";
1400
- const html = typeof child.props?.html === "string" ? child.props?.html : null;
1401
- const tokens = Object.prototype.hasOwnProperty.call(child.props ?? {}, "tokens") ? child.props?.tokens : void 0;
1402
- if (seenIds.has(child.id) || seenIndices.has(index)) {
1403
- console.warn("[renderer-view] duplicate code line detected", {
1404
- blockId,
1405
- childId: child.id,
1406
- index
1407
- });
1408
- continue;
1409
- }
1410
- seenIds.add(child.id);
1411
- seenIndices.add(index);
1412
- deduped.push({ id: child.id, index, text, html, tokens });
1413
- }
1414
- deduped.sort((a, b) => a.index - b.index);
1415
- return deduped;
1416
- }, [childIds, store, blockId, nodeVersion]);
1417
- const lang = typeof node.props?.lang === "string" ? node.props?.lang : node.block.payload.meta?.lang;
1418
- const preAttrs = node.props?.preAttrs ?? void 0;
1419
- const codeAttrs = node.props?.codeAttrs ?? void 0;
1420
- const virtualizationConfig = DEFAULT_VIRTUALIZED_CODE_CONFIG;
1421
- const virtualizationDisabled = typeof process !== "undefined" && typeof process.env === "object" && process.env.STREAM_MDX_DISABLE_VIRTUALIZED_CODE === "true";
1422
- const shouldVirtualize = !virtualizationDisabled && virtualizationConfig.enabled && lines.length >= virtualizationConfig.virtualizeThreshold;
1423
- const virtualization = useVirtualizedCode(lines, shouldVirtualize ? virtualizationConfig : { ...virtualizationConfig, enabled: false });
1424
- const highlightRequester = useCodeHighlightRequester();
1425
- const lazyEnabled = Boolean(node.block.payload.meta?.lazyTokenization);
1426
- const lazyTokenizedUntil = typeof node.block.payload.meta?.lazyTokenizedUntil === "number" ? node.block.payload.meta.lazyTokenizedUntil : 0;
1427
- const lastRangeRef = React5.useRef(null);
1428
- const rafRef = React5.useRef(null);
1429
- const idleRef = React5.useRef(null);
1430
- React5.useEffect(() => {
1431
- if (!shouldVirtualize || !lazyEnabled || !highlightRequester) return;
1432
- const { visibleStart, visibleEnd, startIndex, endIndex } = virtualization.window;
1433
- if (endIndex <= lazyTokenizedUntil) return;
1434
- const nextRange = {
1435
- visibleStart,
1436
- visibleEnd,
1437
- prefetchStart: startIndex,
1438
- prefetchEnd: endIndex,
1439
- tokenizedUntil: lazyTokenizedUntil
1440
- };
1441
- const last = lastRangeRef.current;
1442
- if (last && last.visibleStart === nextRange.visibleStart && last.visibleEnd === nextRange.visibleEnd && last.prefetchStart === nextRange.prefetchStart && last.prefetchEnd === nextRange.prefetchEnd && last.tokenizedUntil === nextRange.tokenizedUntil) {
1443
- return;
1444
- }
1445
- lastRangeRef.current = nextRange;
1446
- if (rafRef.current !== null && typeof cancelAnimationFrame === "function") {
1447
- cancelAnimationFrame(rafRef.current);
1448
- }
1449
- if (typeof requestAnimationFrame === "function") {
1450
- rafRef.current = requestAnimationFrame(() => {
1451
- highlightRequester({
1452
- blockId,
1453
- startLine: visibleStart,
1454
- endLine: visibleEnd,
1455
- priority: "visible",
1456
- reason: "scroll"
1457
- });
1458
- rafRef.current = null;
1459
- });
1460
- } else {
1461
- highlightRequester({
1462
- blockId,
1463
- startLine: visibleStart,
1464
- endLine: visibleEnd,
1465
- priority: "visible",
1466
- reason: "scroll"
1467
- });
1468
- }
1469
- const prefetchNeeded = startIndex < visibleStart || endIndex > visibleEnd;
1470
- if (prefetchNeeded) {
1471
- const idleCallback = globalThis.requestIdleCallback;
1472
- const cancelIdle = globalThis.cancelIdleCallback;
1473
- if (idleRef.current !== null) {
1474
- if (typeof cancelIdle === "function") {
1475
- cancelIdle(idleRef.current);
1476
- } else if (typeof clearTimeout === "function") {
1477
- clearTimeout(idleRef.current);
1478
- }
1479
- }
1480
- const schedule = () => {
1481
- highlightRequester({
1482
- blockId,
1483
- startLine: startIndex,
1484
- endLine: endIndex,
1485
- priority: "prefetch",
1486
- reason: "buffer"
1487
- });
1488
- idleRef.current = null;
1489
- };
1490
- if (typeof idleCallback === "function") {
1491
- idleRef.current = idleCallback(() => schedule());
1492
- } else if (typeof setTimeout === "function") {
1493
- idleRef.current = setTimeout(schedule, 80);
1494
- }
1495
- }
1496
- }, [
1497
- blockId,
1498
- highlightRequester,
1499
- lazyEnabled,
1500
- lazyTokenizedUntil,
1501
- shouldVirtualize,
1502
- virtualization.window.visibleStart,
1503
- virtualization.window.visibleEnd,
1504
- virtualization.window.startIndex,
1505
- virtualization.window.endIndex
1506
- ]);
1507
- const highlightedHtml = React5.useMemo(() => {
1508
- if (!shouldVirtualize && node.block?.payload.highlightedHtml) {
1509
- return node.block.payload.highlightedHtml;
1510
- }
1511
- if (lines.length > 0) {
1512
- const hasLineHtml = lines.some((line) => typeof line.html === "string" && line.html.length > 0);
1513
- if (!hasLineHtml && node.block?.payload.highlightedHtml) {
1514
- return node.block.payload.highlightedHtml;
1515
- }
1516
- if (shouldVirtualize) {
1517
- return composeHighlightedHtml(virtualization.window.visibleLines, preAttrs, codeAttrs);
1518
- }
1519
- return composeHighlightedHtml(lines, preAttrs, codeAttrs);
1520
- }
1521
- const blockHtml = node.block?.payload.highlightedHtml ?? "";
1522
- if (blockHtml?.trim().match(/^```[\w-]*\s*$/)) {
1523
- const raw = node.block?.payload.raw ?? "";
1524
- if (raw.trim().length > 0) {
1525
- return composeHighlightedHtml([{ index: 0, text: raw, html: null, id: "temp" }], preAttrs, codeAttrs);
1526
- }
1527
- }
1528
- return blockHtml;
1529
- }, [shouldVirtualize, node.block?.payload.highlightedHtml, lines, preAttrs, codeAttrs, virtualization.window.visibleLines, node.block?.payload.raw]);
1530
- const rendered = /* @__PURE__ */ jsx(
1531
- CodeComponent,
1532
- {
1533
- html: highlightedHtml,
1534
- meta: node.block.payload.meta,
1535
- lines: shouldVirtualize ? virtualization.window.visibleLines : lines,
1536
- lang,
1537
- preAttrs,
1538
- codeAttrs
1539
- }
1540
- );
1541
- const codeFrameClass = "not-prose flex flex-col rounded-lg border border-input pt-1 font-mono text-sm";
1542
- const codeMetricsAttrs = {
1543
- "data-code-block": "true",
1544
- "data-block-id": blockId,
1545
- "data-code-virtualized": shouldVirtualize ? "true" : "false",
1546
- "data-code-total-lines": String(lines.length),
1547
- "data-code-mounted-lines": String(shouldVirtualize ? virtualization.window.mountedLines : lines.length),
1548
- "data-code-window-size": String(virtualization.config.windowSize)
1549
- };
1550
- const codeView = shouldVirtualize ? (() => {
1551
- const { containerRef, window: window2, handleScroll, lineHeight } = virtualization;
1552
- const spacerTop = window2.startIndex * lineHeight;
1553
- const spacerBottom = (window2.totalLines - window2.endIndex) * lineHeight;
1554
- return /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: /* @__PURE__ */ jsxs(
1555
- "div",
1556
- {
1557
- ref: containerRef,
1558
- className: "markdown-code-block-container relative",
1559
- style: { overflowY: "auto", overflowX: "hidden", maxHeight: "600px" },
1560
- onScroll: handleScroll,
1561
- children: [
1562
- /* @__PURE__ */ jsx("div", { style: { height: spacerTop }, "aria-hidden": "true" }),
1563
- rendered,
1564
- /* @__PURE__ */ jsx("div", { style: { height: spacerBottom }, "aria-hidden": "true" })
1565
- ]
1566
- }
1567
- ) });
1568
- })() : /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: rendered });
1569
- const blockComponentMap = registry.getBlockComponentMap();
1570
- const MermaidComponent = Object.prototype.hasOwnProperty.call(blockComponentMap, "mermaid") ? blockComponentMap.mermaid : null;
1571
- if ((lang ?? "").toLowerCase() === "mermaid" && MermaidComponent) {
1572
- const raw = typeof node.block.payload.raw === "string" ? node.block.payload.raw : "";
1573
- const fenced = stripCodeFence(raw);
1574
- const code = fenced.hadFence ? fenced.code : raw;
1575
- if (deferredConfig) {
1576
- return /* @__PURE__ */ jsx("div", { ref: deferredRef, children: shouldRenderDeferred ? React5.createElement(MermaidComponent, {
1577
- code,
1578
- renderCode: codeView,
1579
- meta: node.block.payload.meta,
1580
- isFinalized: node.block.isFinalized
1581
- }) : codeView });
1582
- }
1583
- return React5.createElement(MermaidComponent, {
1584
- code,
1585
- renderCode: codeView,
1586
- meta: node.block.payload.meta,
1587
- isFinalized: node.block.isFinalized
1588
- });
1589
- }
1590
- return codeView;
1591
- });
1592
- CodeBlockView.displayName = "CodeBlockView";
1593
- function composeHighlightedHtml(lines, preAttrs, codeAttrs) {
1594
- const lineMarkup = lines.map((line) => {
1595
- const content = line.html ?? escapeHtml(line.text);
1596
- const dataLine = Number.isFinite(line.index) ? ` data-line="${line.index + 1}"` : "";
1597
- return `<span class="line"${dataLine}>${content}</span>`;
1598
- }).join("\n");
1599
- const preAttr = attrsToString(preAttrs);
1600
- const codeAttr = attrsToString(codeAttrs);
1601
- return `<pre${preAttr}><code${codeAttr}>${lineMarkup}
1602
- </code></pre>`;
1603
- }
1604
- function attrsToString(attrs) {
1605
- if (!attrs) return "";
1606
- return Object.entries(attrs).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("");
1607
- }
1608
- function escapeHtml(value) {
1609
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1610
- }
1611
- function escapeAttribute(value) {
1612
- return value.replace(/"/g, "&quot;");
1613
- }
1614
- export {
1615
- BlockNodeRenderer
1616
- };