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