@stream-mdx/react 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -4
- package/README.md +65 -14
- package/dist/components/bottom-stick-scroll-area.cjs +344 -0
- package/dist/components/bottom-stick-scroll-area.d.cts +36 -0
- package/dist/components/bottom-stick-scroll-area.d.ts +36 -0
- package/dist/components/bottom-stick-scroll-area.mjs +320 -0
- package/dist/components/index.cjs +511 -176
- package/dist/components/index.d.cts +3 -1
- package/dist/components/index.d.ts +3 -1
- package/dist/components/index.mjs +358 -26
- package/dist/{index-D7px9jug.d.cts → index-BVhp_pcF.d.ts} +4 -1
- package/dist/{index-D7px9jug.d.ts → index-EaeouYp2.d.cts} +4 -1
- package/dist/index.cjs +2146 -1145
- package/dist/index.d.cts +6 -4
- package/dist/index.d.ts +6 -4
- package/dist/index.mjs +3835 -2836
- package/dist/mdx-client.cjs +1 -1
- package/dist/mdx-client.mjs +1 -1
- package/dist/mdx-coordinator.cjs +28 -7
- package/dist/mdx-coordinator.d.cts +2 -2
- package/dist/mdx-coordinator.d.ts +2 -2
- package/dist/mdx-coordinator.mjs +28 -7
- package/dist/renderer/node-views.cjs +273 -24
- package/dist/renderer/node-views.d.cts +3 -1
- package/dist/renderer/node-views.d.ts +3 -1
- package/dist/renderer/node-views.mjs +274 -25
- package/dist/renderer/patch-batching.cjs +2 -0
- package/dist/renderer/patch-batching.d.cts +1 -1
- package/dist/renderer/patch-batching.d.ts +1 -1
- package/dist/renderer/patch-batching.mjs +2 -1
- package/dist/renderer/patch-commit-scheduler.cjs +82 -30
- package/dist/renderer/patch-commit-scheduler.d.cts +15 -3
- package/dist/renderer/patch-commit-scheduler.d.ts +15 -3
- package/dist/renderer/patch-commit-scheduler.mjs +84 -30
- package/dist/renderer/store.cjs +382 -36
- package/dist/renderer/store.d.cts +3 -0
- package/dist/renderer/store.d.ts +3 -0
- package/dist/renderer/store.mjs +382 -36
- package/dist/renderer.cjs +3386 -2727
- package/dist/renderer.d.cts +15 -12
- package/dist/renderer.d.ts +15 -12
- package/dist/renderer.mjs +3410 -2751
- package/dist/server.cjs +4842 -0
- package/dist/server.d.cts +254 -0
- package/dist/server.d.ts +254 -0
- package/dist/server.mjs +4824 -0
- package/dist/{streaming-markdown-Dp1IDgMT.d.ts → streaming-markdown-CEI9eDZm.d.ts} +3 -1
- package/dist/{streaming-markdown-DSC4L0xR.d.cts → streaming-markdown-DRisClXb.d.cts} +3 -1
- package/dist/streaming-markdown.cjs +3476 -2794
- package/dist/streaming-markdown.d.cts +4 -2
- package/dist/streaming-markdown.d.ts +4 -2
- package/dist/streaming-markdown.mjs +3436 -2754
- package/dist/utils/inline-html.d.cts +3 -1
- package/dist/utils/inline-html.d.ts +3 -1
- package/package.json +19 -3
- package/shadcn/README.md +28 -0
- package/shadcn/bottom-stick-scroll-area.tsx +358 -0
package/dist/server.mjs
ADDED
|
@@ -0,0 +1,4824 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __esm = (fn, res) => function __init() {
|
|
4
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
5
|
+
};
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// src/mdx-client.ts
|
|
12
|
+
var mdx_client_exports = {};
|
|
13
|
+
__export(mdx_client_exports, {
|
|
14
|
+
MDXClient: () => MDXClient,
|
|
15
|
+
MDXComponentFactory: () => MDXComponentFactory,
|
|
16
|
+
getMDXClient: () => getMDXClient,
|
|
17
|
+
getMDXComponentFactory: () => getMDXComponentFactory,
|
|
18
|
+
registerInlineMdxModule: () => registerInlineMdxModule,
|
|
19
|
+
registerMDXComponents: () => registerMDXComponents
|
|
20
|
+
});
|
|
21
|
+
import React2 from "react";
|
|
22
|
+
import * as ReactJsxRuntime from "react/jsx-runtime";
|
|
23
|
+
function assignMdxChildKey(child, index) {
|
|
24
|
+
if (child == null) return child;
|
|
25
|
+
if (Array.isArray(child)) {
|
|
26
|
+
return child.map((entry, subIndex) => assignMdxChildKey(entry, `${index}-${subIndex}`));
|
|
27
|
+
}
|
|
28
|
+
if (React2.isValidElement(child)) {
|
|
29
|
+
if (child.key !== null && child.key !== void 0) {
|
|
30
|
+
return child;
|
|
31
|
+
}
|
|
32
|
+
return React2.cloneElement(child, { key: index });
|
|
33
|
+
}
|
|
34
|
+
return child;
|
|
35
|
+
}
|
|
36
|
+
function getMDXClient(compileEndpoint) {
|
|
37
|
+
if (!globalMDXClient) {
|
|
38
|
+
globalMDXClient = new MDXClient(compileEndpoint);
|
|
39
|
+
}
|
|
40
|
+
return globalMDXClient;
|
|
41
|
+
}
|
|
42
|
+
function getMDXComponentFactory(compileEndpoint) {
|
|
43
|
+
if (!globalComponentFactory) {
|
|
44
|
+
const client = getMDXClient(compileEndpoint);
|
|
45
|
+
globalComponentFactory = new MDXComponentFactory(client);
|
|
46
|
+
}
|
|
47
|
+
return globalComponentFactory;
|
|
48
|
+
}
|
|
49
|
+
function registerMDXComponents(components, options) {
|
|
50
|
+
const factory = getMDXComponentFactory();
|
|
51
|
+
factory.registerComponents(components, options);
|
|
52
|
+
}
|
|
53
|
+
function registerInlineMdxModule(compiled) {
|
|
54
|
+
const factory = getMDXComponentFactory();
|
|
55
|
+
factory.registerInlineModule({
|
|
56
|
+
id: compiled.id,
|
|
57
|
+
code: compiled.code,
|
|
58
|
+
dependencies: compiled.dependencies ?? []
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
var withClassName, MDXClient, MDXComponentFactory, globalMDXClient, globalComponentFactory;
|
|
62
|
+
var init_mdx_client = __esm({
|
|
63
|
+
"src/mdx-client.ts"() {
|
|
64
|
+
"use strict";
|
|
65
|
+
withClassName = (tag, className) => {
|
|
66
|
+
return (props) => React2.createElement(tag, { className, ...props });
|
|
67
|
+
};
|
|
68
|
+
MDXClient = class {
|
|
69
|
+
constructor(compileEndpoint = "/api/mdx-compile-v2") {
|
|
70
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
71
|
+
this.inlineModules = /* @__PURE__ */ new Map();
|
|
72
|
+
this.compiledCache = /* @__PURE__ */ new Map();
|
|
73
|
+
this.compiledInflight = /* @__PURE__ */ new Map();
|
|
74
|
+
this.compileEndpoint = compileEndpoint;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Compile MDX block on server
|
|
78
|
+
*/
|
|
79
|
+
async compile(block) {
|
|
80
|
+
if (block.type !== "mdx") {
|
|
81
|
+
throw new Error("Block is not MDX type");
|
|
82
|
+
}
|
|
83
|
+
const cacheKey = `${block.id}\0${block.payload.raw ?? ""}`;
|
|
84
|
+
const cachedPromise = this.cache.get(cacheKey);
|
|
85
|
+
if (cachedPromise) {
|
|
86
|
+
return cachedPromise;
|
|
87
|
+
}
|
|
88
|
+
const compilationPromise = this.doCompile(block);
|
|
89
|
+
this.cache.set(cacheKey, compilationPromise);
|
|
90
|
+
try {
|
|
91
|
+
const result = await compilationPromise;
|
|
92
|
+
return result;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
this.cache.delete(cacheKey);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async getCompiledInternal(ref) {
|
|
99
|
+
const inline = this.inlineModules.get(ref.id);
|
|
100
|
+
if (inline) {
|
|
101
|
+
return this.cloneCompiled(inline);
|
|
102
|
+
}
|
|
103
|
+
const cached = this.compiledCache.get(ref.id);
|
|
104
|
+
if (cached) {
|
|
105
|
+
return this.cloneCompiled(cached);
|
|
106
|
+
}
|
|
107
|
+
const inflight = this.compiledInflight.get(ref.id);
|
|
108
|
+
if (inflight) {
|
|
109
|
+
const resolved = await inflight;
|
|
110
|
+
return this.cloneCompiled(resolved);
|
|
111
|
+
}
|
|
112
|
+
const fetchPromise = this.fetchCompiled(ref);
|
|
113
|
+
this.compiledInflight.set(ref.id, fetchPromise);
|
|
114
|
+
try {
|
|
115
|
+
const data = await fetchPromise;
|
|
116
|
+
this.compiledCache.set(ref.id, data);
|
|
117
|
+
return this.cloneCompiled(data);
|
|
118
|
+
} finally {
|
|
119
|
+
this.compiledInflight.delete(ref.id);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async getCompiled(ref, options) {
|
|
123
|
+
if (options?.signal) {
|
|
124
|
+
const inline = this.inlineModules.get(ref.id);
|
|
125
|
+
if (inline) {
|
|
126
|
+
return this.cloneCompiled(inline);
|
|
127
|
+
}
|
|
128
|
+
const cached = this.compiledCache.get(ref.id);
|
|
129
|
+
if (cached) {
|
|
130
|
+
return this.cloneCompiled(cached);
|
|
131
|
+
}
|
|
132
|
+
const data = await this.fetchCompiled(ref, options);
|
|
133
|
+
this.compiledCache.set(ref.id, data);
|
|
134
|
+
return this.cloneCompiled(data);
|
|
135
|
+
}
|
|
136
|
+
return this.getCompiledInternal(ref);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Clear compilation cache
|
|
140
|
+
*/
|
|
141
|
+
clearCache() {
|
|
142
|
+
this.cache.clear();
|
|
143
|
+
this.compiledCache.clear();
|
|
144
|
+
this.compiledInflight.clear();
|
|
145
|
+
}
|
|
146
|
+
registerInlineModule(compiled) {
|
|
147
|
+
this.inlineModules.set(compiled.id, {
|
|
148
|
+
...compiled,
|
|
149
|
+
dependencies: Array.isArray(compiled.dependencies) ? [...compiled.dependencies] : []
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
clearInlineModules() {
|
|
153
|
+
this.inlineModules.clear();
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Actual compilation implementation
|
|
157
|
+
*/
|
|
158
|
+
async doCompile(block) {
|
|
159
|
+
const response = await fetch(this.compileEndpoint, {
|
|
160
|
+
method: "POST",
|
|
161
|
+
headers: {
|
|
162
|
+
"Content-Type": "application/json"
|
|
163
|
+
},
|
|
164
|
+
body: JSON.stringify({
|
|
165
|
+
content: block.payload.raw,
|
|
166
|
+
blockId: block.id
|
|
167
|
+
})
|
|
168
|
+
});
|
|
169
|
+
if (!response.ok) {
|
|
170
|
+
const error = await response.json().catch(() => ({ error: "Unknown error" }));
|
|
171
|
+
throw new Error(`MDX compilation failed: ${error.error || response.statusText}`);
|
|
172
|
+
}
|
|
173
|
+
const data = await response.json();
|
|
174
|
+
return {
|
|
175
|
+
id: data.id,
|
|
176
|
+
code: data.code,
|
|
177
|
+
dependencies: data.dependencies || [],
|
|
178
|
+
cached: data.cached || false
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
async fetchCompiled(ref, options) {
|
|
182
|
+
const response = await fetch(`${this.compileEndpoint}?id=${ref.id}`, {
|
|
183
|
+
signal: options?.signal
|
|
184
|
+
});
|
|
185
|
+
if (!response.ok) {
|
|
186
|
+
throw new Error(`Failed to get compiled MDX: ${response.statusText}`);
|
|
187
|
+
}
|
|
188
|
+
const data = await response.json();
|
|
189
|
+
return {
|
|
190
|
+
id: data.id,
|
|
191
|
+
code: data.code,
|
|
192
|
+
dependencies: data.dependencies || [],
|
|
193
|
+
timestamp: data.timestamp
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
cloneCompiled(compiled) {
|
|
197
|
+
return {
|
|
198
|
+
...compiled,
|
|
199
|
+
dependencies: Array.isArray(compiled.dependencies) ? [...compiled.dependencies] : []
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
MDXComponentFactory = class {
|
|
204
|
+
constructor(mdxClient) {
|
|
205
|
+
this.components = /* @__PURE__ */ new Map();
|
|
206
|
+
this.customComponents = /* @__PURE__ */ new Map();
|
|
207
|
+
this.mdxClient = mdxClient;
|
|
208
|
+
this.baseComponents = this.createBaseComponents();
|
|
209
|
+
}
|
|
210
|
+
registerInlineModule(module) {
|
|
211
|
+
this.mdxClient.registerInlineModule(module);
|
|
212
|
+
this.components.delete(module.id);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Create React component from compiled MDX
|
|
216
|
+
*/
|
|
217
|
+
async createComponent(ref) {
|
|
218
|
+
const cached = this.components.get(ref.id);
|
|
219
|
+
if (cached) {
|
|
220
|
+
return cached;
|
|
221
|
+
}
|
|
222
|
+
const compiled = await this.mdxClient.getCompiled(ref);
|
|
223
|
+
const component = this.evaluateCompiledMDX(compiled);
|
|
224
|
+
this.components.set(ref.id, component);
|
|
225
|
+
return component;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Safely evaluate compiled MDX code
|
|
229
|
+
*/
|
|
230
|
+
evaluateCompiledMDX(compiled) {
|
|
231
|
+
try {
|
|
232
|
+
const context = this.createEvaluationContext();
|
|
233
|
+
const argNames = Object.keys(context);
|
|
234
|
+
const argValues = Object.values(context);
|
|
235
|
+
const moduleExports = new Function(...argNames, compiled.code)(...argValues);
|
|
236
|
+
const MDXComponent = this.resolveEvaluatedModule(moduleExports);
|
|
237
|
+
return (props) => {
|
|
238
|
+
const registryComponents = this.getComponents();
|
|
239
|
+
const incomingComponents = props?.components;
|
|
240
|
+
const mergedComponents = incomingComponents ? { ...registryComponents, ...incomingComponents } : registryComponents;
|
|
241
|
+
return React2.createElement(MDXComponent, {
|
|
242
|
+
...props,
|
|
243
|
+
components: mergedComponents
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
} catch (error) {
|
|
247
|
+
console.error("Failed to evaluate MDX:", error);
|
|
248
|
+
return () => React2.createElement(
|
|
249
|
+
"div",
|
|
250
|
+
{
|
|
251
|
+
className: "mdx-error"
|
|
252
|
+
},
|
|
253
|
+
`MDX Error: ${error instanceof Error ? error.message : "Unknown error"}`
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Create safe evaluation context for MDX
|
|
259
|
+
*/
|
|
260
|
+
createEvaluationContext() {
|
|
261
|
+
const runtime = ReactJsxRuntime;
|
|
262
|
+
const createElementWithChildren = (type, props, key) => {
|
|
263
|
+
const baseProps = props ?? {};
|
|
264
|
+
const finalProps = key === void 0 || key === null ? baseProps : { ...baseProps, key };
|
|
265
|
+
if (Array.isArray(finalProps.children)) {
|
|
266
|
+
finalProps.children = finalProps.children.map((child, index) => assignMdxChildKey(child, index));
|
|
267
|
+
}
|
|
268
|
+
return React2.createElement(type, finalProps);
|
|
269
|
+
};
|
|
270
|
+
const runtimeJsx = typeof runtime.jsx === "function" ? runtime.jsx.bind(runtime) : createElementWithChildren;
|
|
271
|
+
const runtimeJsxs = typeof runtime.jsxs === "function" ? runtime.jsxs.bind(runtime) : createElementWithChildren;
|
|
272
|
+
const runtimeJsxDEV = typeof runtime.jsxDEV === "function" ? runtime.jsxDEV.bind(runtime) : (type, props, key, ..._rest) => createElementWithChildren(type, props, key);
|
|
273
|
+
const jsxRuntime = {
|
|
274
|
+
jsx: runtimeJsx,
|
|
275
|
+
jsxs: runtimeJsxs,
|
|
276
|
+
jsxDEV: runtimeJsxDEV,
|
|
277
|
+
Fragment: runtime.Fragment ?? React2.Fragment
|
|
278
|
+
};
|
|
279
|
+
return {
|
|
280
|
+
__mdx_runtime: jsxRuntime,
|
|
281
|
+
React: React2,
|
|
282
|
+
Fragment: React2.Fragment,
|
|
283
|
+
useState: React2.useState,
|
|
284
|
+
useEffect: React2.useEffect,
|
|
285
|
+
useMemo: React2.useMemo,
|
|
286
|
+
useCallback: React2.useCallback,
|
|
287
|
+
useRef: React2.useRef,
|
|
288
|
+
useContext: React2.useContext,
|
|
289
|
+
useReducer: React2.useReducer,
|
|
290
|
+
useLayoutEffect: React2.useLayoutEffect,
|
|
291
|
+
console: {
|
|
292
|
+
log: console.log,
|
|
293
|
+
warn: console.warn,
|
|
294
|
+
error: console.error
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
resolveEvaluatedModule(output) {
|
|
299
|
+
if (!output) {
|
|
300
|
+
throw new Error("Compiled MDX module returned no exports");
|
|
301
|
+
}
|
|
302
|
+
if (typeof output === "function") {
|
|
303
|
+
return output;
|
|
304
|
+
}
|
|
305
|
+
if (typeof output.default === "function") {
|
|
306
|
+
return output.default;
|
|
307
|
+
}
|
|
308
|
+
if (typeof output.MDXContent === "function") {
|
|
309
|
+
return output.MDXContent;
|
|
310
|
+
}
|
|
311
|
+
throw new Error("Compiled MDX module did not export a component");
|
|
312
|
+
}
|
|
313
|
+
getComponents() {
|
|
314
|
+
if (this.customComponents.size === 0) {
|
|
315
|
+
return { ...this.baseComponents };
|
|
316
|
+
}
|
|
317
|
+
const merged = { ...this.baseComponents };
|
|
318
|
+
for (const [key, component] of this.customComponents) {
|
|
319
|
+
merged[key] = component;
|
|
320
|
+
}
|
|
321
|
+
return merged;
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Register or replace custom MDX components
|
|
325
|
+
*/
|
|
326
|
+
registerComponents(components, options) {
|
|
327
|
+
if (options?.replace) {
|
|
328
|
+
this.customComponents.clear();
|
|
329
|
+
}
|
|
330
|
+
for (const [key, component] of Object.entries(components)) {
|
|
331
|
+
if (!component) continue;
|
|
332
|
+
this.customComponents.set(key, component);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Get base MDX components
|
|
337
|
+
*/
|
|
338
|
+
createBaseComponents() {
|
|
339
|
+
return {
|
|
340
|
+
// Standard HTML elements
|
|
341
|
+
h1: withClassName("h1", "mdx-h1"),
|
|
342
|
+
h2: withClassName("h2", "mdx-h2"),
|
|
343
|
+
h3: withClassName("h3", "mdx-h3"),
|
|
344
|
+
h4: withClassName("h4", "mdx-h4"),
|
|
345
|
+
h5: withClassName("h5", "mdx-h5"),
|
|
346
|
+
h6: withClassName("h6", "mdx-h6"),
|
|
347
|
+
p: withClassName("p", "mdx-p"),
|
|
348
|
+
strong: withClassName("strong", "mdx-strong"),
|
|
349
|
+
em: withClassName("em", "mdx-em"),
|
|
350
|
+
code: withClassName("code", "mdx-code"),
|
|
351
|
+
pre: withClassName("pre", "mdx-pre"),
|
|
352
|
+
ul: withClassName("ul", "mdx-ul"),
|
|
353
|
+
ol: withClassName("ol", "mdx-ol"),
|
|
354
|
+
li: withClassName("li", "mdx-li"),
|
|
355
|
+
blockquote: withClassName("blockquote", "mdx-blockquote"),
|
|
356
|
+
a: (props) => React2.createElement("a", {
|
|
357
|
+
className: "mdx-link",
|
|
358
|
+
target: props.href?.startsWith("http") ? "_blank" : void 0,
|
|
359
|
+
rel: props.href?.startsWith("http") ? "noopener noreferrer" : void 0,
|
|
360
|
+
...props
|
|
361
|
+
}),
|
|
362
|
+
img: (props) => React2.createElement("img", { className: "mdx-img", ...props }),
|
|
363
|
+
table: withClassName("table", "mdx-table"),
|
|
364
|
+
thead: withClassName("thead", "mdx-thead"),
|
|
365
|
+
tbody: withClassName("tbody", "mdx-tbody"),
|
|
366
|
+
tr: withClassName("tr", "mdx-tr"),
|
|
367
|
+
th: withClassName("th", "mdx-th"),
|
|
368
|
+
td: withClassName("td", "mdx-td")
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Clear component cache
|
|
373
|
+
*/
|
|
374
|
+
clearCache() {
|
|
375
|
+
this.components.clear();
|
|
376
|
+
}
|
|
377
|
+
clearCustomComponents() {
|
|
378
|
+
this.customComponents.clear();
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
globalMDXClient = null;
|
|
382
|
+
globalComponentFactory = null;
|
|
383
|
+
}
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
// src/renderer/blocks-renderer.tsx
|
|
387
|
+
import React8, { useMemo as useMemo3 } from "react";
|
|
388
|
+
import { getBlockKey, PATCH_ROOT_ID as PATCH_ROOT_ID2 } from "@stream-mdx/core";
|
|
389
|
+
|
|
390
|
+
// src/renderer/hooks.ts
|
|
391
|
+
import { useMemo, useSyncExternalStore } from "react";
|
|
392
|
+
function useRendererNode(store, id) {
|
|
393
|
+
const selector = useMemo(() => {
|
|
394
|
+
return () => store.getNodeWithVersion(id);
|
|
395
|
+
}, [store, id]);
|
|
396
|
+
const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
|
|
397
|
+
return snapshot.node;
|
|
398
|
+
}
|
|
399
|
+
function useRendererChildren(store, id) {
|
|
400
|
+
const selector = useMemo(() => {
|
|
401
|
+
return () => store.getChildrenWithVersion(id);
|
|
402
|
+
}, [store, id]);
|
|
403
|
+
const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
|
|
404
|
+
return snapshot.children;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// src/renderer/node-views.tsx
|
|
408
|
+
import { getDefaultCodeWrapperAttributes as getDefaultCodeWrapperAttributes2, stripCodeFence } from "@stream-mdx/core";
|
|
409
|
+
import React7 from "react";
|
|
410
|
+
|
|
411
|
+
// src/components/index.ts
|
|
412
|
+
import { createTrustedHTML, sanitizeHTML } from "@stream-mdx/core";
|
|
413
|
+
|
|
414
|
+
// src/mdx-hydration-metrics.ts
|
|
415
|
+
var entries = /* @__PURE__ */ new Map();
|
|
416
|
+
var lastHydrationMs = null;
|
|
417
|
+
function now() {
|
|
418
|
+
if (typeof performance !== "undefined" && typeof performance.now === "function") {
|
|
419
|
+
return performance.now();
|
|
420
|
+
}
|
|
421
|
+
return Date.now();
|
|
422
|
+
}
|
|
423
|
+
function markMdxHydrationStart(id) {
|
|
424
|
+
if (!id) return;
|
|
425
|
+
const entry = entries.get(id) ?? { status: "compiled" };
|
|
426
|
+
if (entry.startedAt === void 0) {
|
|
427
|
+
entry.startedAt = now();
|
|
428
|
+
}
|
|
429
|
+
entry.status = "compiled";
|
|
430
|
+
entries.set(id, entry);
|
|
431
|
+
}
|
|
432
|
+
function markMdxHydrated(id) {
|
|
433
|
+
if (!id) return;
|
|
434
|
+
const entry = entries.get(id) ?? { status: "hydrated" };
|
|
435
|
+
if (entry.startedAt === void 0) {
|
|
436
|
+
entry.startedAt = now();
|
|
437
|
+
}
|
|
438
|
+
entry.hydratedAt = now();
|
|
439
|
+
entry.status = "hydrated";
|
|
440
|
+
entries.set(id, entry);
|
|
441
|
+
lastHydrationMs = entry.startedAt ? entry.hydratedAt - entry.startedAt : null;
|
|
442
|
+
}
|
|
443
|
+
function markMdxHydrationError(id) {
|
|
444
|
+
if (!id) return;
|
|
445
|
+
const entry = entries.get(id) ?? { status: "error" };
|
|
446
|
+
entry.status = "error";
|
|
447
|
+
entries.set(id, entry);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// src/mdx-hydration-context.ts
|
|
451
|
+
import React from "react";
|
|
452
|
+
var MdxHydrationContext = React.createContext({ controller: null });
|
|
453
|
+
|
|
454
|
+
// src/mdx-runtime.ts
|
|
455
|
+
var mdxRuntimePromise = null;
|
|
456
|
+
function loadMdxRuntime() {
|
|
457
|
+
if (!mdxRuntimePromise) {
|
|
458
|
+
mdxRuntimePromise = Promise.resolve().then(() => (init_mdx_client(), mdx_client_exports));
|
|
459
|
+
}
|
|
460
|
+
return mdxRuntimePromise;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// src/renderer/use-deferred-render.ts
|
|
464
|
+
import { useEffect, useState } from "react";
|
|
465
|
+
function useDeferredRender(ref, options) {
|
|
466
|
+
const enabled = options?.enabled ?? true;
|
|
467
|
+
const [shouldRender, setShouldRender] = useState(!enabled);
|
|
468
|
+
useEffect(() => {
|
|
469
|
+
if (!enabled) {
|
|
470
|
+
setShouldRender(true);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
const target = ref.current;
|
|
474
|
+
if (!target) {
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
let cancelled = false;
|
|
478
|
+
let idleId = null;
|
|
479
|
+
let timerId = null;
|
|
480
|
+
const scheduleRender = () => {
|
|
481
|
+
if (cancelled) return;
|
|
482
|
+
setShouldRender(true);
|
|
483
|
+
};
|
|
484
|
+
const runWithIdle = () => {
|
|
485
|
+
if (typeof globalThis.requestIdleCallback === "function") {
|
|
486
|
+
idleId = globalThis.requestIdleCallback(scheduleRender, { timeout: options?.idleTimeoutMs ?? 200 });
|
|
487
|
+
} else {
|
|
488
|
+
timerId = window.setTimeout(scheduleRender, options?.idleTimeoutMs ?? 200);
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
const observer = new IntersectionObserver(
|
|
492
|
+
(entries2) => {
|
|
493
|
+
for (const entry of entries2) {
|
|
494
|
+
if (entry.isIntersecting || entry.intersectionRatio > 0) {
|
|
495
|
+
observer.disconnect();
|
|
496
|
+
const debounceMs = options?.debounceMs ?? 80;
|
|
497
|
+
timerId = window.setTimeout(runWithIdle, debounceMs);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
},
|
|
502
|
+
{ rootMargin: options?.rootMargin ?? "200px 0px" }
|
|
503
|
+
);
|
|
504
|
+
observer.observe(target);
|
|
505
|
+
return () => {
|
|
506
|
+
cancelled = true;
|
|
507
|
+
observer.disconnect();
|
|
508
|
+
if (idleId !== null && typeof globalThis.cancelIdleCallback === "function") {
|
|
509
|
+
globalThis.cancelIdleCallback(idleId);
|
|
510
|
+
}
|
|
511
|
+
if (timerId !== null) {
|
|
512
|
+
window.clearTimeout(timerId);
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
}, [enabled, options?.debounceMs, options?.idleTimeoutMs, options?.rootMargin, ref]);
|
|
516
|
+
return shouldRender;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// src/components/index.ts
|
|
520
|
+
import { removeHeadingMarkers } from "@stream-mdx/core";
|
|
521
|
+
import React4 from "react";
|
|
522
|
+
|
|
523
|
+
// src/utils/inline-html.ts
|
|
524
|
+
import React3 from "react";
|
|
525
|
+
var BACKTICK_CONTENT = /^`([\s\S]+)`$/;
|
|
526
|
+
var DEFAULT_INLINE_HTML_RENDERERS = {
|
|
527
|
+
kbd: (descriptor, ctx) => {
|
|
528
|
+
const trimmed = descriptor.rawInner.trim();
|
|
529
|
+
const match = BACKTICK_CONTENT.exec(trimmed);
|
|
530
|
+
if (match) {
|
|
531
|
+
const codeText = decodeHtmlEntities(match[1]);
|
|
532
|
+
const props = mapAttributesToProps(descriptor.attributes);
|
|
533
|
+
if (ctx.key !== void 0 && ctx.key !== null) {
|
|
534
|
+
props.key = ctx.key;
|
|
535
|
+
}
|
|
536
|
+
return React3.createElement("kbd", props, React3.createElement("code", { className: "inline-code" }, codeText));
|
|
537
|
+
}
|
|
538
|
+
return ctx.defaultRender();
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
function renderInlineHtmlSegment(raw, sanitized, options = {}) {
|
|
542
|
+
const descriptor = parseInlineHtmlDescriptor(raw, sanitized);
|
|
543
|
+
if (!descriptor) {
|
|
544
|
+
return null;
|
|
545
|
+
}
|
|
546
|
+
const className = options.className ?? "markdown-inline-html";
|
|
547
|
+
const isInlineTag = INLINE_ELEMENTS.has(descriptor.tagName);
|
|
548
|
+
const defaultRender = () => {
|
|
549
|
+
if (!descriptor.sanitized || descriptor.sanitized.length === 0) {
|
|
550
|
+
if (!descriptor.text) {
|
|
551
|
+
return null;
|
|
552
|
+
}
|
|
553
|
+
if (options.key !== void 0 && options.key !== null) {
|
|
554
|
+
return React3.createElement(React3.Fragment, { key: options.key }, descriptor.text);
|
|
555
|
+
}
|
|
556
|
+
return React3.createElement(React3.Fragment, {}, descriptor.text);
|
|
557
|
+
}
|
|
558
|
+
if (isInlineTag) {
|
|
559
|
+
const parsedElement = renderSanitizedHtmlTree(descriptor.sanitized, options.key);
|
|
560
|
+
if (parsedElement) {
|
|
561
|
+
return parsedElement;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const props = {
|
|
565
|
+
className,
|
|
566
|
+
dangerouslySetInnerHTML: { __html: descriptor.sanitized }
|
|
567
|
+
};
|
|
568
|
+
if (options.key !== void 0 && options.key !== null) {
|
|
569
|
+
props.key = options.key;
|
|
570
|
+
}
|
|
571
|
+
return React3.createElement("span", props);
|
|
572
|
+
};
|
|
573
|
+
const allRenderers = options.renderers ? { ...DEFAULT_INLINE_HTML_RENDERERS, ...options.renderers } : DEFAULT_INLINE_HTML_RENDERERS;
|
|
574
|
+
const renderer = allRenderers[descriptor.tagName];
|
|
575
|
+
if (renderer) {
|
|
576
|
+
const rendered = renderer(descriptor, { key: options.key, defaultRender });
|
|
577
|
+
if (rendered) {
|
|
578
|
+
if (options.key !== void 0 && options.key !== null && React3.isValidElement(rendered) && rendered.key === null) {
|
|
579
|
+
return React3.cloneElement(rendered, { key: options.key });
|
|
580
|
+
}
|
|
581
|
+
return rendered;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
return defaultRender();
|
|
585
|
+
}
|
|
586
|
+
function parseInlineHtmlDescriptor(raw, sanitized) {
|
|
587
|
+
const normalizedRaw = typeof raw === "string" ? raw.trim() : "";
|
|
588
|
+
const normalizedSanitized = typeof sanitized === "string" && sanitized.length > 0 ? sanitized.trim() : normalizedRaw;
|
|
589
|
+
if (!normalizedSanitized) {
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
const match = normalizedSanitized.match(/^<([A-Za-z][\w:-]*)(\s[^>]*)?>([\s\S]*)<\/\1>$/);
|
|
593
|
+
if (!match) {
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
const [, tagNameRaw, attrString = "", sanitizedInner = ""] = match;
|
|
597
|
+
const tagName = tagNameRaw.toLowerCase();
|
|
598
|
+
const attributes = parseAttributes(attrString);
|
|
599
|
+
let rawInner = "";
|
|
600
|
+
if (normalizedRaw) {
|
|
601
|
+
const rawMatch = normalizedRaw.match(/^<([A-Za-z][\w:-]*)(\s[^>]*)?>([\s\S]*)<\/\1>$/);
|
|
602
|
+
rawInner = rawMatch ? rawMatch[3] ?? "" : normalizedRaw;
|
|
603
|
+
}
|
|
604
|
+
const text = extractPlainText(rawInner || sanitizedInner);
|
|
605
|
+
return {
|
|
606
|
+
tagName,
|
|
607
|
+
attributes,
|
|
608
|
+
raw: normalizedRaw || normalizedSanitized,
|
|
609
|
+
sanitized: normalizedSanitized,
|
|
610
|
+
rawInner,
|
|
611
|
+
sanitizedInner,
|
|
612
|
+
text
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function parseAttributes(input) {
|
|
616
|
+
const attrs = {};
|
|
617
|
+
if (!input) return attrs;
|
|
618
|
+
const attrPattern = /([A-Za-z_:][\w:.\-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
619
|
+
let match = attrPattern.exec(input);
|
|
620
|
+
while (match !== null) {
|
|
621
|
+
const name = match[1];
|
|
622
|
+
if (!name) continue;
|
|
623
|
+
const value = match[2] ?? match[3] ?? match[4] ?? "";
|
|
624
|
+
attrs[name] = value;
|
|
625
|
+
match = attrPattern.exec(input);
|
|
626
|
+
}
|
|
627
|
+
return attrs;
|
|
628
|
+
}
|
|
629
|
+
function mapAttributesToProps(attrs) {
|
|
630
|
+
const props = {};
|
|
631
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
632
|
+
if (key === "class") {
|
|
633
|
+
props.className = value;
|
|
634
|
+
} else if (key === "style") {
|
|
635
|
+
props.style = parseStyleAttribute(value);
|
|
636
|
+
} else if (key === "tabindex" || key === "tabIndex") {
|
|
637
|
+
const normalized = normalizeTabIndex(value);
|
|
638
|
+
if (normalized !== void 0) {
|
|
639
|
+
props.tabIndex = normalized;
|
|
640
|
+
}
|
|
641
|
+
} else {
|
|
642
|
+
props[key] = value;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
return props;
|
|
646
|
+
}
|
|
647
|
+
function parseStyleAttribute(value) {
|
|
648
|
+
const style = {};
|
|
649
|
+
if (!value) return style;
|
|
650
|
+
const pairs = value.split(";");
|
|
651
|
+
for (const pair of pairs) {
|
|
652
|
+
if (!pair.trim()) continue;
|
|
653
|
+
const [property, rawVal] = pair.split(":");
|
|
654
|
+
if (!property || rawVal === void 0) continue;
|
|
655
|
+
const camelProp = property.trim().replace(/-([a-z])/g, (_, char) => char.toUpperCase());
|
|
656
|
+
style[camelProp] = rawVal.trim();
|
|
657
|
+
}
|
|
658
|
+
return style;
|
|
659
|
+
}
|
|
660
|
+
function normalizeTabIndex(value) {
|
|
661
|
+
const numeric = Number(value);
|
|
662
|
+
return Number.isNaN(numeric) ? void 0 : numeric;
|
|
663
|
+
}
|
|
664
|
+
function decodeHtmlEntities(value) {
|
|
665
|
+
return value.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'");
|
|
666
|
+
}
|
|
667
|
+
function extractPlainText(value) {
|
|
668
|
+
if (!value) return "";
|
|
669
|
+
const withoutTags = value.replace(/<\/?[^>]+>/g, "");
|
|
670
|
+
return decodeHtmlEntities(withoutTags);
|
|
671
|
+
}
|
|
672
|
+
function renderSanitizedHtmlTree(html, key) {
|
|
673
|
+
if (typeof DOMParser === "undefined") {
|
|
674
|
+
return null;
|
|
675
|
+
}
|
|
676
|
+
try {
|
|
677
|
+
const parser = new DOMParser();
|
|
678
|
+
const doc = parser.parseFromString(html, "text/html");
|
|
679
|
+
const body = doc.body;
|
|
680
|
+
const nodes = Array.from(body.childNodes);
|
|
681
|
+
if (nodes.length === 0) {
|
|
682
|
+
return null;
|
|
683
|
+
}
|
|
684
|
+
const baseKey = typeof key === "string" || typeof key === "number" ? String(key) : "inline-html";
|
|
685
|
+
const children = nodes.map((node, index) => convertDomNode(node, `${baseKey}-${index}`)).filter((child) => child !== null && child !== void 0);
|
|
686
|
+
if (children.length === 0) {
|
|
687
|
+
return null;
|
|
688
|
+
}
|
|
689
|
+
if (children.length === 1) {
|
|
690
|
+
const [child] = children;
|
|
691
|
+
if (React3.isValidElement(child)) {
|
|
692
|
+
if (key !== void 0 && key !== null) {
|
|
693
|
+
return React3.cloneElement(child, { key });
|
|
694
|
+
}
|
|
695
|
+
return child;
|
|
696
|
+
}
|
|
697
|
+
if (typeof child === "string" || typeof child === "number") {
|
|
698
|
+
if (key !== void 0 && key !== null) {
|
|
699
|
+
return React3.createElement(React3.Fragment, { key }, child);
|
|
700
|
+
}
|
|
701
|
+
return React3.createElement(React3.Fragment, {}, child);
|
|
702
|
+
}
|
|
703
|
+
return React3.createElement(React3.Fragment, { key }, child);
|
|
704
|
+
}
|
|
705
|
+
return React3.createElement(React3.Fragment, { key }, ...children);
|
|
706
|
+
} catch {
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
function convertDomNode(node, key) {
|
|
711
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
712
|
+
return node.textContent ?? "";
|
|
713
|
+
}
|
|
714
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
715
|
+
return null;
|
|
716
|
+
}
|
|
717
|
+
const element = node;
|
|
718
|
+
const tagName = element.tagName.toLowerCase();
|
|
719
|
+
const attrs = getElementAttributes(element);
|
|
720
|
+
const props = mapAttributesToProps(attrs);
|
|
721
|
+
props.key = key;
|
|
722
|
+
const children = [];
|
|
723
|
+
element.childNodes.forEach((child, index) => {
|
|
724
|
+
const converted = convertDomNode(child, `${key}-${index}`);
|
|
725
|
+
if (converted !== null && converted !== void 0) {
|
|
726
|
+
children.push(converted);
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
if (children.length === 0) {
|
|
730
|
+
return React3.createElement(tagName, props);
|
|
731
|
+
}
|
|
732
|
+
return React3.createElement(tagName, props, ...children);
|
|
733
|
+
}
|
|
734
|
+
function getElementAttributes(element) {
|
|
735
|
+
const attrs = {};
|
|
736
|
+
for (const attr of Array.from(element.attributes)) {
|
|
737
|
+
attrs[attr.name] = attr.value;
|
|
738
|
+
}
|
|
739
|
+
return attrs;
|
|
740
|
+
}
|
|
741
|
+
var INLINE_ELEMENTS = /* @__PURE__ */ new Set([
|
|
742
|
+
"a",
|
|
743
|
+
"abbr",
|
|
744
|
+
"b",
|
|
745
|
+
"bdi",
|
|
746
|
+
"bdo",
|
|
747
|
+
"br",
|
|
748
|
+
"cite",
|
|
749
|
+
"code",
|
|
750
|
+
"data",
|
|
751
|
+
"dfn",
|
|
752
|
+
"em",
|
|
753
|
+
"i",
|
|
754
|
+
"kbd",
|
|
755
|
+
"mark",
|
|
756
|
+
"q",
|
|
757
|
+
"rp",
|
|
758
|
+
"rt",
|
|
759
|
+
"ruby",
|
|
760
|
+
"s",
|
|
761
|
+
"samp",
|
|
762
|
+
"small",
|
|
763
|
+
"span",
|
|
764
|
+
"strong",
|
|
765
|
+
"sub",
|
|
766
|
+
"sup",
|
|
767
|
+
"time",
|
|
768
|
+
"u",
|
|
769
|
+
"var",
|
|
770
|
+
// MathML inline elements commonly emitted by KaTeX
|
|
771
|
+
"annotation",
|
|
772
|
+
"semantics",
|
|
773
|
+
"mtext",
|
|
774
|
+
"mn",
|
|
775
|
+
"mo",
|
|
776
|
+
"mi",
|
|
777
|
+
"mspace",
|
|
778
|
+
"mrow",
|
|
779
|
+
"msup",
|
|
780
|
+
"msub",
|
|
781
|
+
"msubsup",
|
|
782
|
+
"munder",
|
|
783
|
+
"mover",
|
|
784
|
+
"munderover",
|
|
785
|
+
"msqrt",
|
|
786
|
+
"mroot",
|
|
787
|
+
"mtable",
|
|
788
|
+
"mtr",
|
|
789
|
+
"mtd"
|
|
790
|
+
]);
|
|
791
|
+
|
|
792
|
+
// src/components/index.ts
|
|
793
|
+
var MdxRuntimeBoundary = class extends React4.Component {
|
|
794
|
+
constructor() {
|
|
795
|
+
super(...arguments);
|
|
796
|
+
this.state = { hasError: false };
|
|
797
|
+
}
|
|
798
|
+
static getDerivedStateFromError() {
|
|
799
|
+
return { hasError: true };
|
|
800
|
+
}
|
|
801
|
+
componentDidCatch(error) {
|
|
802
|
+
this.props.onError(error);
|
|
803
|
+
}
|
|
804
|
+
componentDidUpdate(prevProps) {
|
|
805
|
+
if (prevProps.resetKey !== this.props.resetKey && this.state.hasError) {
|
|
806
|
+
this.setState({ hasError: false });
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
render() {
|
|
810
|
+
if (this.state.hasError) {
|
|
811
|
+
return null;
|
|
812
|
+
}
|
|
813
|
+
return this.props.children;
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
function renderInlineNodes(nodes, components) {
|
|
817
|
+
return nodes.map((node, index) => {
|
|
818
|
+
const key = `${node.kind}-${index}`;
|
|
819
|
+
switch (node.kind) {
|
|
820
|
+
case "text": {
|
|
821
|
+
const textComponent = components.text;
|
|
822
|
+
if (textComponent && textComponent !== defaultInlineComponents.text) {
|
|
823
|
+
return React4.createElement(textComponent, { key, text: node.text });
|
|
824
|
+
}
|
|
825
|
+
return React4.createElement(React4.Fragment, { key, children: node.text });
|
|
826
|
+
}
|
|
827
|
+
case "strong":
|
|
828
|
+
return React4.createElement(components.strong, {
|
|
829
|
+
key,
|
|
830
|
+
children: renderInlineNodes(node.children, components)
|
|
831
|
+
});
|
|
832
|
+
case "em":
|
|
833
|
+
return React4.createElement(components.em, {
|
|
834
|
+
key,
|
|
835
|
+
children: renderInlineNodes(node.children, components)
|
|
836
|
+
});
|
|
837
|
+
case "strike": {
|
|
838
|
+
const StrikeComponent = components.strike ?? ((props) => React4.createElement("del", {}, props.children));
|
|
839
|
+
return React4.createElement(StrikeComponent, {
|
|
840
|
+
key,
|
|
841
|
+
children: renderInlineNodes(node.children, components)
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
case "code":
|
|
845
|
+
return React4.createElement(components.code, { key, text: node.text });
|
|
846
|
+
case "link":
|
|
847
|
+
return React4.createElement(
|
|
848
|
+
components.link,
|
|
849
|
+
{
|
|
850
|
+
key,
|
|
851
|
+
href: node.href,
|
|
852
|
+
title: node.title,
|
|
853
|
+
children: renderInlineNodes(node.children, components)
|
|
854
|
+
}
|
|
855
|
+
);
|
|
856
|
+
case "image":
|
|
857
|
+
return React4.createElement(components.image, {
|
|
858
|
+
key,
|
|
859
|
+
src: node.src,
|
|
860
|
+
alt: node.alt,
|
|
861
|
+
title: node.title
|
|
862
|
+
});
|
|
863
|
+
case "br":
|
|
864
|
+
return React4.createElement(React4.Fragment, { key }, React4.createElement(components.br, {}));
|
|
865
|
+
default: {
|
|
866
|
+
const component = components[node.kind];
|
|
867
|
+
if (component) {
|
|
868
|
+
return React4.createElement(component, { key, ...node });
|
|
869
|
+
}
|
|
870
|
+
return null;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
var defaultInlineComponents = {
|
|
876
|
+
text: ({ text }) => React4.createElement(React4.Fragment, {}, text),
|
|
877
|
+
strong: ({ children }) => React4.createElement("strong", {}, children),
|
|
878
|
+
em: ({ children }) => React4.createElement("em", {}, children),
|
|
879
|
+
strike: ({ children }) => React4.createElement("del", {}, children),
|
|
880
|
+
code: ({ text }) => React4.createElement(
|
|
881
|
+
"code",
|
|
882
|
+
{
|
|
883
|
+
className: "inline-code"
|
|
884
|
+
},
|
|
885
|
+
text
|
|
886
|
+
),
|
|
887
|
+
link: ({ href, title, children }) => React4.createElement(
|
|
888
|
+
"a",
|
|
889
|
+
{
|
|
890
|
+
href,
|
|
891
|
+
title,
|
|
892
|
+
className: "markdown-link",
|
|
893
|
+
target: href?.startsWith("http") ? "_blank" : void 0,
|
|
894
|
+
rel: href?.startsWith("http") ? "noopener noreferrer" : void 0
|
|
895
|
+
},
|
|
896
|
+
children
|
|
897
|
+
),
|
|
898
|
+
image: ({ src, alt, title }) => React4.createElement("img", {
|
|
899
|
+
src,
|
|
900
|
+
alt,
|
|
901
|
+
title,
|
|
902
|
+
className: "markdown-image"
|
|
903
|
+
}),
|
|
904
|
+
br: () => React4.createElement("br"),
|
|
905
|
+
// Custom extensible components
|
|
906
|
+
mention: ({ handle }) => React4.createElement(
|
|
907
|
+
"span",
|
|
908
|
+
{
|
|
909
|
+
className: "mention",
|
|
910
|
+
"data-handle": handle
|
|
911
|
+
},
|
|
912
|
+
`@${handle}`
|
|
913
|
+
),
|
|
914
|
+
citation: ({ id }) => React4.createElement(
|
|
915
|
+
"span",
|
|
916
|
+
{
|
|
917
|
+
className: "citation",
|
|
918
|
+
"data-citation-id": id
|
|
919
|
+
},
|
|
920
|
+
`[${id}]`
|
|
921
|
+
),
|
|
922
|
+
"math-inline": ({ tex }) => React4.createElement(
|
|
923
|
+
"span",
|
|
924
|
+
{
|
|
925
|
+
className: "math-inline",
|
|
926
|
+
"data-tex": tex
|
|
927
|
+
},
|
|
928
|
+
`$${tex}$`
|
|
929
|
+
),
|
|
930
|
+
"math-display": ({ tex }) => React4.createElement(
|
|
931
|
+
"div",
|
|
932
|
+
{
|
|
933
|
+
className: "math-display markdown-math-display",
|
|
934
|
+
"data-tex": tex,
|
|
935
|
+
style: { overflowX: "auto" }
|
|
936
|
+
},
|
|
937
|
+
React4.createElement("span", { className: "math-display-content" }, `$$${tex}$$`)
|
|
938
|
+
),
|
|
939
|
+
// Footnote inline reference (superscript anchor)
|
|
940
|
+
"footnote-ref": ({ label, number }) => {
|
|
941
|
+
const n = number ?? "?";
|
|
942
|
+
const href = number ? `#fn:${n}` : void 0;
|
|
943
|
+
const id = number ? `fnref:${n}` : void 0;
|
|
944
|
+
return React4.createElement(
|
|
945
|
+
"sup",
|
|
946
|
+
{ className: "footnote-ref" },
|
|
947
|
+
React4.createElement("a", { href, id, "data-label": label, style: { color: "var(--foreground)", textDecoration: "underline" } }, String(n))
|
|
948
|
+
);
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
var defaultBlockComponents = {
|
|
952
|
+
paragraph: ({ inlines, raw, meta, children }) => {
|
|
953
|
+
if (children !== void 0) {
|
|
954
|
+
return React4.createElement(
|
|
955
|
+
"p",
|
|
956
|
+
{
|
|
957
|
+
className: "markdown-paragraph"
|
|
958
|
+
},
|
|
959
|
+
children
|
|
960
|
+
);
|
|
961
|
+
}
|
|
962
|
+
const segments = Array.isArray(meta?.mixedSegments) ? meta?.mixedSegments : void 0;
|
|
963
|
+
if (segments && segments.length > 0) {
|
|
964
|
+
const structured = renderParagraphMixedSegments(segments, defaultInlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
|
|
965
|
+
if (structured.length === 1) {
|
|
966
|
+
return structured[0];
|
|
967
|
+
}
|
|
968
|
+
return React4.createElement(React4.Fragment, {}, ...structured);
|
|
969
|
+
}
|
|
970
|
+
const filteredInlines = inlines && raw && inlines.length > 0 ? inlines.filter((node) => !(node.kind === "text" && node.text === raw)) : inlines ?? [];
|
|
971
|
+
const effectiveInlines = filteredInlines.length > 0 ? filteredInlines : raw ? [
|
|
972
|
+
{
|
|
973
|
+
kind: "text",
|
|
974
|
+
text: raw
|
|
975
|
+
}
|
|
976
|
+
] : [];
|
|
977
|
+
return React4.createElement(
|
|
978
|
+
"p",
|
|
979
|
+
{
|
|
980
|
+
className: "markdown-paragraph"
|
|
981
|
+
},
|
|
982
|
+
effectiveInlines.length > 0 ? renderInlineNodes(effectiveInlines, defaultInlineComponents) : raw ?? ""
|
|
983
|
+
);
|
|
984
|
+
},
|
|
985
|
+
heading: ({ level, inlines, text, meta }) => {
|
|
986
|
+
const tag = `h${level}`;
|
|
987
|
+
const onlyPlainText = Array.isArray(inlines) && inlines.length > 0 && inlines.every((node) => node.kind === "text");
|
|
988
|
+
const children = onlyPlainText ? inlines.map((node) => node.kind === "text" ? node.text : "").join("") : renderInlineNodes(inlines, defaultInlineComponents);
|
|
989
|
+
const headingId = typeof meta?.headingId === "string" && meta.headingId.length > 0 ? meta.headingId : void 0;
|
|
990
|
+
return React4.createElement(
|
|
991
|
+
tag,
|
|
992
|
+
{
|
|
993
|
+
className: `markdown-heading markdown-h${level}`,
|
|
994
|
+
...text ? { "data-heading-text": text } : {},
|
|
995
|
+
...headingId ? { id: headingId, "data-heading-id": headingId } : {}
|
|
996
|
+
},
|
|
997
|
+
children
|
|
998
|
+
);
|
|
999
|
+
},
|
|
1000
|
+
code: ({ html, meta, lines, lang, preAttrs, codeAttrs }) => {
|
|
1001
|
+
const language = typeof lang === "string" ? lang : typeof meta?.lang === "string" ? String(meta.lang) : "text";
|
|
1002
|
+
if (html) {
|
|
1003
|
+
return React4.createElement("div", {
|
|
1004
|
+
className: `markdown-code-block language-${language || "text"}`,
|
|
1005
|
+
/* biome-ignore lint/security/noDangerouslySetInnerHtml: highlighted HTML is generated by our sanitizer */
|
|
1006
|
+
dangerouslySetInnerHTML: { __html: html }
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
const code = meta?.code || "";
|
|
1010
|
+
if (lines && lines.length > 0) {
|
|
1011
|
+
const preAttributes = attrsToProps(preAttrs);
|
|
1012
|
+
const codeAttributes = attrsToProps(codeAttrs);
|
|
1013
|
+
return React4.createElement(
|
|
1014
|
+
"pre",
|
|
1015
|
+
{
|
|
1016
|
+
...preAttributes,
|
|
1017
|
+
className: preAttributes.className ? `${preAttributes.className} markdown-code-block language-${language || "text"}` : `markdown-code-block language-${language || "text"}`
|
|
1018
|
+
},
|
|
1019
|
+
React4.createElement(
|
|
1020
|
+
"code",
|
|
1021
|
+
{
|
|
1022
|
+
...codeAttributes,
|
|
1023
|
+
className: codeAttributes.className ? `${codeAttributes.className} language-${language || "text"}` : `language-${language || "text"}`
|
|
1024
|
+
},
|
|
1025
|
+
lines.map(
|
|
1026
|
+
(line) => React4.createElement("span", {
|
|
1027
|
+
key: line.id,
|
|
1028
|
+
className: "line",
|
|
1029
|
+
/* biome-ignore lint/security/noDangerouslySetInnerHtml: line HTML is sanitized server-side */
|
|
1030
|
+
dangerouslySetInnerHTML: { __html: line.html ?? escapeHtml(line.text) }
|
|
1031
|
+
})
|
|
1032
|
+
)
|
|
1033
|
+
)
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
return React4.createElement("pre", {
|
|
1037
|
+
className: `markdown-code-block language-${language || "text"}`,
|
|
1038
|
+
children: code
|
|
1039
|
+
});
|
|
1040
|
+
},
|
|
1041
|
+
blockquote: ({ inlines, renderedContent }) => React4.createElement(
|
|
1042
|
+
"blockquote",
|
|
1043
|
+
{
|
|
1044
|
+
className: "markdown-blockquote"
|
|
1045
|
+
},
|
|
1046
|
+
renderedContent ?? renderInlineNodes(inlines, defaultInlineComponents)
|
|
1047
|
+
),
|
|
1048
|
+
hr: (props) => React4.createElement("hr", props),
|
|
1049
|
+
list: ({ ordered, items }) => {
|
|
1050
|
+
if (items.length === 0) {
|
|
1051
|
+
return null;
|
|
1052
|
+
}
|
|
1053
|
+
const tag = ordered ? "ol" : "ul";
|
|
1054
|
+
const listStyle = ordered ? {
|
|
1055
|
+
["--list-indent"]: `calc(2.5rem + ${String(items.length).length}ch)`
|
|
1056
|
+
} : void 0;
|
|
1057
|
+
const listItems = items.map(
|
|
1058
|
+
(item, index) => React4.createElement(
|
|
1059
|
+
"li",
|
|
1060
|
+
{
|
|
1061
|
+
key: index,
|
|
1062
|
+
className: "markdown-list-item",
|
|
1063
|
+
"data-counter-text": ordered ? `${index + 1}.` : void 0,
|
|
1064
|
+
"data-list-depth": 0
|
|
1065
|
+
},
|
|
1066
|
+
renderInlineNodes(item, defaultInlineComponents)
|
|
1067
|
+
)
|
|
1068
|
+
);
|
|
1069
|
+
return React4.createElement(
|
|
1070
|
+
tag,
|
|
1071
|
+
{
|
|
1072
|
+
className: `markdown-list ${ordered ? "ordered" : "unordered"}`,
|
|
1073
|
+
style: listStyle
|
|
1074
|
+
},
|
|
1075
|
+
listItems
|
|
1076
|
+
);
|
|
1077
|
+
},
|
|
1078
|
+
html: ({ __trustedHtml, elements }) => {
|
|
1079
|
+
const raw = typeof __trustedHtml === "string" ? __trustedHtml : __trustedHtml.toString();
|
|
1080
|
+
const htmlString = typeof window === "undefined" ? raw : sanitizeHTML(raw);
|
|
1081
|
+
if (typeof window !== "undefined" && elements) {
|
|
1082
|
+
const content = mapHtmlToReact(htmlString, elements);
|
|
1083
|
+
return React4.createElement("div", { className: "markdown-html" }, content);
|
|
1084
|
+
}
|
|
1085
|
+
return React4.createElement("div", {
|
|
1086
|
+
className: "markdown-html",
|
|
1087
|
+
/* biome-ignore lint/security/noDangerouslySetInnerHtml: htmlString is sanitized before injection */
|
|
1088
|
+
dangerouslySetInnerHTML: { __html: htmlString }
|
|
1089
|
+
});
|
|
1090
|
+
},
|
|
1091
|
+
mdx: ({ compiledRef, compiledModule, status, errorMessage }) => {
|
|
1092
|
+
const [Comp, setComp] = React4.useState(null);
|
|
1093
|
+
const [internalError, setInternalError] = React4.useState(null);
|
|
1094
|
+
const [renderError, setRenderError] = React4.useState(null);
|
|
1095
|
+
const [retryKey, setRetryKey] = React4.useState(0);
|
|
1096
|
+
const hydrationContext = React4.useContext(MdxHydrationContext);
|
|
1097
|
+
const hydrationController = hydrationContext?.controller ?? null;
|
|
1098
|
+
const hydrationOptions = hydrationContext?.options;
|
|
1099
|
+
const containerRef = React4.useRef(null);
|
|
1100
|
+
const deferHydration = hydrationOptions?.strategy === "visible";
|
|
1101
|
+
const shouldHydrate = useDeferredRender(
|
|
1102
|
+
containerRef,
|
|
1103
|
+
deferHydration ? {
|
|
1104
|
+
enabled: true,
|
|
1105
|
+
rootMargin: hydrationOptions?.rootMargin,
|
|
1106
|
+
idleTimeoutMs: hydrationOptions?.idleTimeoutMs,
|
|
1107
|
+
debounceMs: hydrationOptions?.debounceMs
|
|
1108
|
+
} : { enabled: false }
|
|
1109
|
+
);
|
|
1110
|
+
const resolvedId = compiledModule?.id ?? (compiledRef?.id && compiledRef.id !== "pending" ? compiledRef.id : void 0);
|
|
1111
|
+
const handleRetry = React4.useCallback(() => {
|
|
1112
|
+
setInternalError(null);
|
|
1113
|
+
setRenderError(null);
|
|
1114
|
+
setComp(null);
|
|
1115
|
+
setRetryKey((prev) => prev + 1);
|
|
1116
|
+
}, []);
|
|
1117
|
+
const handleRuntimeError = React4.useCallback(
|
|
1118
|
+
(error) => {
|
|
1119
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
1120
|
+
setRenderError(message2);
|
|
1121
|
+
markMdxHydrationError(resolvedId ?? compiledRef?.id);
|
|
1122
|
+
},
|
|
1123
|
+
[resolvedId, compiledRef?.id]
|
|
1124
|
+
);
|
|
1125
|
+
const effectiveStatus = status ? status : resolvedId ? "compiled" : "pending";
|
|
1126
|
+
const failureMessage = errorMessage ?? internalError ?? renderError ?? null;
|
|
1127
|
+
const moduleDependencies = compiledModule?.dependencies;
|
|
1128
|
+
React4.useEffect(() => {
|
|
1129
|
+
if (!shouldHydrate) {
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
if (status === "error") {
|
|
1133
|
+
markMdxHydrationError(resolvedId ?? compiledRef?.id);
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
let cancelled = false;
|
|
1137
|
+
async function ensure() {
|
|
1138
|
+
let permit = null;
|
|
1139
|
+
try {
|
|
1140
|
+
if (status === "error" || !resolvedId || resolvedId === "pending") {
|
|
1141
|
+
if (!cancelled) {
|
|
1142
|
+
setComp(null);
|
|
1143
|
+
setInternalError(null);
|
|
1144
|
+
}
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
if (hydrationController) {
|
|
1148
|
+
permit = await hydrationController.acquire();
|
|
1149
|
+
if (cancelled) {
|
|
1150
|
+
permit.release();
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
setInternalError(null);
|
|
1155
|
+
setRenderError(null);
|
|
1156
|
+
markMdxHydrationStart(resolvedId);
|
|
1157
|
+
const { getMDXComponentFactory: getMDXComponentFactory2, registerInlineMdxModule: registerInlineMdxModule2 } = await loadMdxRuntime();
|
|
1158
|
+
if (compiledModule?.code) {
|
|
1159
|
+
registerInlineMdxModule2({
|
|
1160
|
+
id: compiledModule.id,
|
|
1161
|
+
code: compiledModule.code,
|
|
1162
|
+
dependencies: moduleDependencies ?? []
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
const factory = getMDXComponentFactory2();
|
|
1166
|
+
const C = await factory.createComponent({ id: resolvedId });
|
|
1167
|
+
if (!cancelled) {
|
|
1168
|
+
setComp(() => C);
|
|
1169
|
+
setInternalError(null);
|
|
1170
|
+
markMdxHydrated(resolvedId);
|
|
1171
|
+
}
|
|
1172
|
+
} catch (error) {
|
|
1173
|
+
if (!cancelled) {
|
|
1174
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
1175
|
+
setInternalError(message2);
|
|
1176
|
+
markMdxHydrationError(resolvedId);
|
|
1177
|
+
}
|
|
1178
|
+
} finally {
|
|
1179
|
+
permit?.release();
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
ensure();
|
|
1183
|
+
return () => {
|
|
1184
|
+
cancelled = true;
|
|
1185
|
+
};
|
|
1186
|
+
}, [compiledModule?.id, compiledModule?.code, moduleDependencies, resolvedId, status, shouldHydrate, retryKey]);
|
|
1187
|
+
const compileMode = compiledModule?.source === "worker" || compiledRef?.id?.startsWith("worker:") ? "worker" : "server";
|
|
1188
|
+
const pendingId = resolvedId && resolvedId !== "pending" ? resolvedId : compiledRef?.id ?? "pending";
|
|
1189
|
+
const waitingForVisibility = deferHydration && !shouldHydrate && Boolean(resolvedId);
|
|
1190
|
+
const pendingLabel = waitingForVisibility ? "MDX ready (hydrate on view)\u2026" : compileMode === "worker" ? "Compiling MDX (client)\u2026" : "Compiling MDX (server)\u2026";
|
|
1191
|
+
const message = failureMessage ?? (compileMode === "worker" ? "MDX compilation failed in client mode. Try switching back to server rendering or restarting the stream." : "MDX compilation failed. Try restarting the stream.");
|
|
1192
|
+
const allowRetry = Boolean(internalError || renderError);
|
|
1193
|
+
const retryButton = allowRetry ? React4.createElement(
|
|
1194
|
+
"button",
|
|
1195
|
+
{
|
|
1196
|
+
type: "button",
|
|
1197
|
+
className: "markdown-mdx-retry",
|
|
1198
|
+
onClick: handleRetry
|
|
1199
|
+
},
|
|
1200
|
+
"Retry hydration"
|
|
1201
|
+
) : null;
|
|
1202
|
+
const errorPanel = React4.createElement(
|
|
1203
|
+
React4.Fragment,
|
|
1204
|
+
null,
|
|
1205
|
+
React4.createElement("strong", null, "MDX failed"),
|
|
1206
|
+
React4.createElement("div", null, message)
|
|
1207
|
+
);
|
|
1208
|
+
if (Comp && !failureMessage) {
|
|
1209
|
+
return React4.createElement(
|
|
1210
|
+
"div",
|
|
1211
|
+
{
|
|
1212
|
+
className: "markdown-mdx",
|
|
1213
|
+
ref: containerRef,
|
|
1214
|
+
"data-mdx-ref": resolvedId ?? compiledRef?.id ?? "compiled",
|
|
1215
|
+
"data-mdx-status": failureMessage ? "error" : "compiled",
|
|
1216
|
+
"data-mdx-mode": compileMode
|
|
1217
|
+
},
|
|
1218
|
+
React4.createElement(
|
|
1219
|
+
MdxRuntimeBoundary,
|
|
1220
|
+
{ resetKey: retryKey, onError: handleRuntimeError },
|
|
1221
|
+
React4.createElement(Comp, {})
|
|
1222
|
+
)
|
|
1223
|
+
);
|
|
1224
|
+
}
|
|
1225
|
+
if (failureMessage) {
|
|
1226
|
+
return React4.createElement(
|
|
1227
|
+
"div",
|
|
1228
|
+
{
|
|
1229
|
+
className: "markdown-mdx error",
|
|
1230
|
+
ref: containerRef,
|
|
1231
|
+
"data-mdx-ref": pendingId,
|
|
1232
|
+
"data-mdx-status": "error",
|
|
1233
|
+
"data-mdx-mode": compileMode
|
|
1234
|
+
},
|
|
1235
|
+
errorPanel,
|
|
1236
|
+
retryButton
|
|
1237
|
+
);
|
|
1238
|
+
}
|
|
1239
|
+
if (!Comp) {
|
|
1240
|
+
return React4.createElement(
|
|
1241
|
+
"div",
|
|
1242
|
+
{
|
|
1243
|
+
className: "markdown-mdx",
|
|
1244
|
+
ref: containerRef,
|
|
1245
|
+
"data-mdx-ref": pendingId,
|
|
1246
|
+
"data-mdx-status": "pending",
|
|
1247
|
+
"data-mdx-mode": compileMode
|
|
1248
|
+
},
|
|
1249
|
+
pendingLabel
|
|
1250
|
+
);
|
|
1251
|
+
}
|
|
1252
|
+
},
|
|
1253
|
+
// Footnotes block rendered at page end
|
|
1254
|
+
footnotes: ({ items }) => {
|
|
1255
|
+
if (!items || items.length === 0) return React4.createElement(React4.Fragment, null);
|
|
1256
|
+
const listItems = items.map(
|
|
1257
|
+
(item) => React4.createElement(
|
|
1258
|
+
"li",
|
|
1259
|
+
{ key: item.number, id: `fn:${item.number}` },
|
|
1260
|
+
renderInlineNodes(item.inlines, defaultInlineComponents),
|
|
1261
|
+
" ",
|
|
1262
|
+
React4.createElement(
|
|
1263
|
+
"a",
|
|
1264
|
+
{
|
|
1265
|
+
href: `#fnref:${item.number}`,
|
|
1266
|
+
className: "footnote-backref",
|
|
1267
|
+
"aria-label": "Back to content",
|
|
1268
|
+
style: { color: "var(--foreground)", textDecoration: "underline" }
|
|
1269
|
+
},
|
|
1270
|
+
"\u21A9"
|
|
1271
|
+
)
|
|
1272
|
+
)
|
|
1273
|
+
);
|
|
1274
|
+
return React4.createElement("section", { className: "footnotes" }, React4.createElement("hr", {}), React4.createElement("ol", {}, listItems));
|
|
1275
|
+
},
|
|
1276
|
+
// Footnote definition placeholders (render nothing)
|
|
1277
|
+
"footnote-def": () => React4.createElement(React4.Fragment, null),
|
|
1278
|
+
// Callouts block
|
|
1279
|
+
callout: ({ kind, inlines = [] }) => {
|
|
1280
|
+
const tone = (kind || "NOTE").toUpperCase();
|
|
1281
|
+
const title = tone.charAt(0) + tone.slice(1).toLowerCase();
|
|
1282
|
+
return React4.createElement(
|
|
1283
|
+
"div",
|
|
1284
|
+
{ className: `markdown-callout markdown-callout-${tone.toLowerCase()} border rounded p-3 my-3` },
|
|
1285
|
+
React4.createElement("div", { className: "font-semibold mb-1" }, title),
|
|
1286
|
+
inlines.length > 0 ? renderInlineNodes(inlines, defaultInlineComponents) : null
|
|
1287
|
+
);
|
|
1288
|
+
},
|
|
1289
|
+
// Structured table block (GFM)
|
|
1290
|
+
table: ({
|
|
1291
|
+
header,
|
|
1292
|
+
rows,
|
|
1293
|
+
align,
|
|
1294
|
+
elements
|
|
1295
|
+
}) => {
|
|
1296
|
+
const El = getDefaultTableElements(elements);
|
|
1297
|
+
const renderCells = (cells, tag, rowIdx) => cells.map((cell, i) => {
|
|
1298
|
+
const columnAlign = align?.[i] ?? void 0;
|
|
1299
|
+
const cellStyle = columnAlign ? { textAlign: columnAlign } : void 0;
|
|
1300
|
+
return React4.createElement(
|
|
1301
|
+
tag === "th" ? El.Th : El.Td,
|
|
1302
|
+
{
|
|
1303
|
+
key: `${rowIdx}-${i}`,
|
|
1304
|
+
style: cellStyle,
|
|
1305
|
+
// Also pass align attribute so CSS selectors like [&[align=center]] can be used by consumers
|
|
1306
|
+
align: columnAlign ?? void 0
|
|
1307
|
+
},
|
|
1308
|
+
renderInlineNodes(cell, defaultInlineComponents)
|
|
1309
|
+
);
|
|
1310
|
+
});
|
|
1311
|
+
return React4.createElement(
|
|
1312
|
+
El.Table,
|
|
1313
|
+
{ className: "markdown-table" },
|
|
1314
|
+
header && header.length > 0 ? React4.createElement(El.Thead, {}, React4.createElement(El.Tr, {}, renderCells(header, "th", -1))) : null,
|
|
1315
|
+
React4.createElement(
|
|
1316
|
+
El.Tbody,
|
|
1317
|
+
{},
|
|
1318
|
+
rows.map((row, r) => React4.createElement(El.Tr, { key: r }, renderCells(row, "td", r)))
|
|
1319
|
+
)
|
|
1320
|
+
);
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
var ComponentRegistry = class {
|
|
1324
|
+
constructor(blockComponents = {}, inlineComponents = {}) {
|
|
1325
|
+
this.blockComponentMapCache = null;
|
|
1326
|
+
this.inlineComponentMapCache = null;
|
|
1327
|
+
this.blockComponents = { ...defaultBlockComponents, ...blockComponents };
|
|
1328
|
+
this.inlineComponents = { ...defaultInlineComponents, ...inlineComponents };
|
|
1329
|
+
this.htmlElements = getDefaultHtmlElements();
|
|
1330
|
+
this.tableElements = getDefaultTableElements();
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Update block components
|
|
1334
|
+
*/
|
|
1335
|
+
setBlockComponents(components) {
|
|
1336
|
+
this.blockComponents = { ...this.blockComponents, ...components };
|
|
1337
|
+
this.blockComponentMapCache = null;
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* Update inline components
|
|
1341
|
+
*/
|
|
1342
|
+
setInlineComponents(components) {
|
|
1343
|
+
this.inlineComponents = { ...this.inlineComponents, ...components };
|
|
1344
|
+
this.inlineComponentMapCache = null;
|
|
1345
|
+
}
|
|
1346
|
+
/** Update HTML element mapping for html blocks */
|
|
1347
|
+
setHtmlElements(map) {
|
|
1348
|
+
this.htmlElements = { ...this.htmlElements, ...map };
|
|
1349
|
+
}
|
|
1350
|
+
/** Update table element mapping for table blocks */
|
|
1351
|
+
setTableElements(map) {
|
|
1352
|
+
this.tableElements = { ...this.tableElements, ...map };
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* Get block component
|
|
1356
|
+
*/
|
|
1357
|
+
getBlockComponent(type) {
|
|
1358
|
+
return this.blockComponents[type] || this.blockComponents.paragraph;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Get inline components
|
|
1362
|
+
*/
|
|
1363
|
+
getInlineComponents() {
|
|
1364
|
+
return this.inlineComponents;
|
|
1365
|
+
}
|
|
1366
|
+
getBlockComponentMap() {
|
|
1367
|
+
if (!this.blockComponentMapCache) {
|
|
1368
|
+
this.blockComponentMapCache = { ...this.blockComponents };
|
|
1369
|
+
}
|
|
1370
|
+
return this.blockComponentMapCache;
|
|
1371
|
+
}
|
|
1372
|
+
getInlineComponentMap() {
|
|
1373
|
+
if (!this.inlineComponentMapCache) {
|
|
1374
|
+
this.inlineComponentMapCache = { ...this.inlineComponents };
|
|
1375
|
+
}
|
|
1376
|
+
return this.inlineComponentMapCache;
|
|
1377
|
+
}
|
|
1378
|
+
getTableElements() {
|
|
1379
|
+
return this.tableElements;
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Render a block
|
|
1383
|
+
*/
|
|
1384
|
+
renderBlock(block) {
|
|
1385
|
+
const Component = this.getBlockComponent(block.type);
|
|
1386
|
+
const props = this.getBlockProps(block);
|
|
1387
|
+
return React4.createElement(Component, {
|
|
1388
|
+
key: block.id,
|
|
1389
|
+
...props
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Get props for a block based on its type
|
|
1394
|
+
*/
|
|
1395
|
+
getBlockProps(block) {
|
|
1396
|
+
switch (block.type) {
|
|
1397
|
+
case "heading": {
|
|
1398
|
+
const meta = block.payload.meta ?? {};
|
|
1399
|
+
const inlineNodes = Array.isArray(block.payload.inline) ? block.payload.inline : [];
|
|
1400
|
+
const levelFromMeta = typeof meta.headingLevel === "number" ? meta.headingLevel : void 0;
|
|
1401
|
+
const normalizedLevel = Number.isFinite(levelFromMeta) ? Math.min(Math.max(levelFromMeta, 1), 6) : void 0;
|
|
1402
|
+
const rawHeading = typeof block.payload.raw === "string" ? block.payload.raw : "";
|
|
1403
|
+
const headingText = typeof meta.headingText === "string" && meta.headingText.trim().length > 0 ? meta.headingText : removeHeadingMarkers(rawHeading).trim();
|
|
1404
|
+
const level = normalizedLevel ?? this.extractHeadingLevel(rawHeading);
|
|
1405
|
+
return {
|
|
1406
|
+
level,
|
|
1407
|
+
inlines: inlineNodes,
|
|
1408
|
+
text: headingText,
|
|
1409
|
+
meta
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
case "paragraph":
|
|
1413
|
+
return {
|
|
1414
|
+
inlines: block.payload.inline || [],
|
|
1415
|
+
raw: block.payload.raw,
|
|
1416
|
+
meta: block.payload.meta
|
|
1417
|
+
};
|
|
1418
|
+
case "blockquote":
|
|
1419
|
+
return {
|
|
1420
|
+
inlines: block.payload.inline || []
|
|
1421
|
+
};
|
|
1422
|
+
case "hr": {
|
|
1423
|
+
const range = block.payload.range;
|
|
1424
|
+
return {
|
|
1425
|
+
className: "markdown-hr",
|
|
1426
|
+
"data-start": typeof range?.from === "number" ? range.from : void 0,
|
|
1427
|
+
"data-end": typeof range?.to === "number" ? range.to : void 0
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
case "code":
|
|
1431
|
+
return {
|
|
1432
|
+
html: block.payload.highlightedHtml,
|
|
1433
|
+
meta: block.payload.meta,
|
|
1434
|
+
lang: typeof block.payload.meta?.lang === "string" ? String(block.payload.meta?.lang) : void 0
|
|
1435
|
+
};
|
|
1436
|
+
case "list": {
|
|
1437
|
+
const items = Array.isArray(block.payload.meta?.items) ? block.payload.meta?.items : [];
|
|
1438
|
+
return {
|
|
1439
|
+
ordered: Boolean(block.payload.meta?.ordered),
|
|
1440
|
+
items
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
case "html": {
|
|
1444
|
+
const trusted = block.payload.sanitizedHtml ?? block.payload.raw;
|
|
1445
|
+
return {
|
|
1446
|
+
// Server render should not depend on DOMPurify (which requires a DOM `window`).
|
|
1447
|
+
// In worker-compiled flows, `sanitizedHtml` is already sanitized at the source.
|
|
1448
|
+
__trustedHtml: typeof window === "undefined" ? String(trusted ?? "") : createTrustedHTML(String(trusted ?? "")),
|
|
1449
|
+
elements: this.htmlElements
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
case "mdx":
|
|
1453
|
+
return (() => {
|
|
1454
|
+
const meta = block.payload.meta;
|
|
1455
|
+
const rawStatus = typeof meta?.mdxStatus === "string" ? meta.mdxStatus : void 0;
|
|
1456
|
+
const status = rawStatus === "pending" || rawStatus === "compiled" || rawStatus === "error" ? rawStatus : void 0;
|
|
1457
|
+
const errorMessage = typeof meta?.mdxError === "string" ? String(meta.mdxError) : void 0;
|
|
1458
|
+
const compiledModule = block.payload.compiledMdxModule ?? null;
|
|
1459
|
+
const compiledRef = block.payload.compiledMdxRef ?? (compiledModule ? { id: compiledModule.id } : void 0);
|
|
1460
|
+
return {
|
|
1461
|
+
compiledRef: compiledRef ?? { id: "pending" },
|
|
1462
|
+
compiledModule,
|
|
1463
|
+
status,
|
|
1464
|
+
errorMessage,
|
|
1465
|
+
raw: typeof block.payload.raw === "string" ? block.payload.raw : void 0
|
|
1466
|
+
};
|
|
1467
|
+
})();
|
|
1468
|
+
case "table": {
|
|
1469
|
+
const header = Array.isArray(block.payload.meta?.header) ? block.payload.meta?.header : void 0;
|
|
1470
|
+
const rows = Array.isArray(block.payload.meta?.rows) ? block.payload.meta?.rows : [];
|
|
1471
|
+
const align = Array.isArray(block.payload.meta?.align) ? block.payload.meta?.align : void 0;
|
|
1472
|
+
return {
|
|
1473
|
+
header,
|
|
1474
|
+
rows,
|
|
1475
|
+
align,
|
|
1476
|
+
elements: this.tableElements
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
case "footnotes": {
|
|
1480
|
+
const items = Array.isArray(block.payload.meta?.items) ? block.payload.meta?.items : [];
|
|
1481
|
+
return {
|
|
1482
|
+
items
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
case "footnote-def":
|
|
1486
|
+
return {};
|
|
1487
|
+
case "callout": {
|
|
1488
|
+
const kind = typeof block.payload.meta?.kind === "string" ? String(block.payload.meta.kind) : void 0;
|
|
1489
|
+
const inlineNodes = Array.isArray(block.payload.inline) ? block.payload.inline : [];
|
|
1490
|
+
return {
|
|
1491
|
+
kind,
|
|
1492
|
+
inlines: inlineNodes
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
default:
|
|
1496
|
+
return {
|
|
1497
|
+
content: block.payload.raw,
|
|
1498
|
+
meta: block.payload.meta
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
/**
|
|
1503
|
+
* Extract heading level from raw markdown
|
|
1504
|
+
*/
|
|
1505
|
+
extractHeadingLevel(raw) {
|
|
1506
|
+
const match = raw.match(/^(#{1,6})\s/);
|
|
1507
|
+
if (match) {
|
|
1508
|
+
return Math.min(match[1].length, 6);
|
|
1509
|
+
}
|
|
1510
|
+
return 1;
|
|
1511
|
+
}
|
|
1512
|
+
};
|
|
1513
|
+
function getDefaultHtmlElements() {
|
|
1514
|
+
return {
|
|
1515
|
+
// Text semantics
|
|
1516
|
+
p: (props) => React4.createElement("p", props),
|
|
1517
|
+
strong: (props) => React4.createElement("strong", props),
|
|
1518
|
+
em: (props) => React4.createElement("em", props),
|
|
1519
|
+
code: (props) => React4.createElement("code", props),
|
|
1520
|
+
pre: (props) => React4.createElement("pre", props),
|
|
1521
|
+
span: (props) => React4.createElement("span", props),
|
|
1522
|
+
br: (props) => React4.createElement("br", props),
|
|
1523
|
+
hr: (props) => React4.createElement("hr", props),
|
|
1524
|
+
// Lists
|
|
1525
|
+
ul: (props) => React4.createElement("ul", props),
|
|
1526
|
+
ol: (props) => React4.createElement("ol", props),
|
|
1527
|
+
li: (props) => React4.createElement("li", props),
|
|
1528
|
+
// Links & media
|
|
1529
|
+
a: (props) => React4.createElement("a", props),
|
|
1530
|
+
img: (props) => React4.createElement("img", props),
|
|
1531
|
+
// Blockquotes
|
|
1532
|
+
blockquote: (props) => React4.createElement("blockquote", props),
|
|
1533
|
+
// Tables
|
|
1534
|
+
table: (props) => React4.createElement("table", props),
|
|
1535
|
+
thead: (props) => React4.createElement("thead", props),
|
|
1536
|
+
tbody: (props) => React4.createElement("tbody", props),
|
|
1537
|
+
tr: (props) => React4.createElement("tr", props),
|
|
1538
|
+
th: (props) => React4.createElement("th", props),
|
|
1539
|
+
td: (props) => React4.createElement("td", props),
|
|
1540
|
+
// Generic
|
|
1541
|
+
div: (props) => React4.createElement("div", props)
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
function getDefaultTableElements(overrides) {
|
|
1545
|
+
const base = {
|
|
1546
|
+
Table: (props) => React4.createElement("table", props),
|
|
1547
|
+
Thead: (props) => React4.createElement("thead", props),
|
|
1548
|
+
Tbody: (props) => React4.createElement("tbody", props),
|
|
1549
|
+
Tr: (props) => React4.createElement("tr", props),
|
|
1550
|
+
Th: (props) => React4.createElement("th", props),
|
|
1551
|
+
Td: (props) => React4.createElement("td", props)
|
|
1552
|
+
};
|
|
1553
|
+
return { ...base, ...overrides || {} };
|
|
1554
|
+
}
|
|
1555
|
+
function mapHtmlToReact(html, elements) {
|
|
1556
|
+
const parser = new DOMParser();
|
|
1557
|
+
const doc = parser.parseFromString(html, "text/html");
|
|
1558
|
+
const children = [];
|
|
1559
|
+
doc.body.childNodes.forEach((node, index) => {
|
|
1560
|
+
const element = toReact(node, elements, `root-${index}`);
|
|
1561
|
+
if (element) {
|
|
1562
|
+
children.push(element);
|
|
1563
|
+
}
|
|
1564
|
+
});
|
|
1565
|
+
return React4.createElement(React4.Fragment, {}, ...children);
|
|
1566
|
+
}
|
|
1567
|
+
function toReact(node, elements, key) {
|
|
1568
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
1569
|
+
const text = node.textContent ?? "";
|
|
1570
|
+
return React4.createElement(React4.Fragment, { key }, text);
|
|
1571
|
+
}
|
|
1572
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
1573
|
+
return null;
|
|
1574
|
+
}
|
|
1575
|
+
const el = node;
|
|
1576
|
+
const tag = el.tagName.toLowerCase();
|
|
1577
|
+
const props = {};
|
|
1578
|
+
for (const attr of Array.from(el.attributes)) {
|
|
1579
|
+
const name = attr.name === "class" ? "className" : attr.name;
|
|
1580
|
+
props[name] = attr.value;
|
|
1581
|
+
}
|
|
1582
|
+
const children = [];
|
|
1583
|
+
el.childNodes.forEach((childNode, childIndex) => {
|
|
1584
|
+
const child = toReact(childNode, elements, `${key}-${childIndex}`);
|
|
1585
|
+
if (child) {
|
|
1586
|
+
children.push(child);
|
|
1587
|
+
}
|
|
1588
|
+
});
|
|
1589
|
+
const component = elements[tag];
|
|
1590
|
+
const elementChildren = children.length > 0 ? children : void 0;
|
|
1591
|
+
if (component) {
|
|
1592
|
+
return React4.createElement(component, { ...props, key }, elementChildren);
|
|
1593
|
+
}
|
|
1594
|
+
return React4.createElement(tag, { ...props, key }, elementChildren);
|
|
1595
|
+
}
|
|
1596
|
+
function attrsToProps(attrs) {
|
|
1597
|
+
if (!attrs) return {};
|
|
1598
|
+
const result = {};
|
|
1599
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
1600
|
+
if (key === "class") {
|
|
1601
|
+
result.className = value;
|
|
1602
|
+
} else if (key === "style") {
|
|
1603
|
+
result.style = parseStyleAttribute2(value);
|
|
1604
|
+
} else if (key === "tabindex" || key === "tabIndex") {
|
|
1605
|
+
const numericValue = Number(value);
|
|
1606
|
+
if (!Number.isNaN(numericValue)) {
|
|
1607
|
+
result.tabIndex = numericValue;
|
|
1608
|
+
}
|
|
1609
|
+
} else {
|
|
1610
|
+
result[key] = value;
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
return result;
|
|
1614
|
+
}
|
|
1615
|
+
function escapeHtml(value) {
|
|
1616
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1617
|
+
}
|
|
1618
|
+
function parseStyleAttribute2(value) {
|
|
1619
|
+
const style = {};
|
|
1620
|
+
if (!value) return style;
|
|
1621
|
+
const parts = value.split(";");
|
|
1622
|
+
for (const part of parts) {
|
|
1623
|
+
if (!part.trim()) continue;
|
|
1624
|
+
const [prop, val] = part.split(":");
|
|
1625
|
+
if (!prop || !val) continue;
|
|
1626
|
+
const camelProp = prop.trim().replace(/-([a-z])/g, (_, char) => char.toUpperCase());
|
|
1627
|
+
style[camelProp] = val.trim();
|
|
1628
|
+
}
|
|
1629
|
+
return style;
|
|
1630
|
+
}
|
|
1631
|
+
function renderParagraphMixedSegments(segments, inlineComponents, inlineHtmlRenderers) {
|
|
1632
|
+
const result = [];
|
|
1633
|
+
let inlineBuffer = [];
|
|
1634
|
+
let inlineGroupIndex = 0;
|
|
1635
|
+
const pushRenderedNodes = (nodes, target, baseKey) => {
|
|
1636
|
+
nodes.forEach((node, idx) => {
|
|
1637
|
+
if (node === null || node === void 0) return;
|
|
1638
|
+
const key = `${baseKey}-${idx}`;
|
|
1639
|
+
if (React4.isValidElement(node)) {
|
|
1640
|
+
target.push(node.key === key ? node : React4.cloneElement(node, { key }));
|
|
1641
|
+
} else if (typeof node === "string" || typeof node === "number") {
|
|
1642
|
+
target.push(React4.createElement(React4.Fragment, { key }, node));
|
|
1643
|
+
} else {
|
|
1644
|
+
target.push(React4.createElement(React4.Fragment, { key }, node));
|
|
1645
|
+
}
|
|
1646
|
+
});
|
|
1647
|
+
};
|
|
1648
|
+
const ensureArray2 = (value) => {
|
|
1649
|
+
if (value === null || value === void 0) {
|
|
1650
|
+
return [];
|
|
1651
|
+
}
|
|
1652
|
+
return Array.isArray(value) ? value : [value];
|
|
1653
|
+
};
|
|
1654
|
+
const flushInline = () => {
|
|
1655
|
+
if (inlineBuffer.length === 0) {
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
const key = `paragraph-inline-group-${inlineGroupIndex++}`;
|
|
1659
|
+
result.push(
|
|
1660
|
+
React4.createElement(
|
|
1661
|
+
"p",
|
|
1662
|
+
{
|
|
1663
|
+
key,
|
|
1664
|
+
className: "markdown-paragraph"
|
|
1665
|
+
},
|
|
1666
|
+
inlineBuffer
|
|
1667
|
+
)
|
|
1668
|
+
);
|
|
1669
|
+
inlineBuffer = [];
|
|
1670
|
+
};
|
|
1671
|
+
segments.forEach((segment, index) => {
|
|
1672
|
+
const key = `paragraph-segment-${index}`;
|
|
1673
|
+
switch (segment.kind) {
|
|
1674
|
+
case "text": {
|
|
1675
|
+
const inlineNodes = Array.isArray(segment.inline) ? segment.inline : [];
|
|
1676
|
+
if (inlineNodes.length === 0) {
|
|
1677
|
+
if (segment.value) {
|
|
1678
|
+
inlineBuffer.push(React4.createElement(React4.Fragment, { key }, segment.value));
|
|
1679
|
+
}
|
|
1680
|
+
break;
|
|
1681
|
+
}
|
|
1682
|
+
let chunk = [];
|
|
1683
|
+
const pushChunk = (chunkNodes, chunkKey) => {
|
|
1684
|
+
if (chunkNodes.length === 0) return;
|
|
1685
|
+
const rendered = renderInlineNodes(chunkNodes, inlineComponents);
|
|
1686
|
+
pushRenderedNodes(ensureArray2(rendered), inlineBuffer, chunkKey);
|
|
1687
|
+
};
|
|
1688
|
+
inlineNodes.forEach((inlineNode, inlineIdx) => {
|
|
1689
|
+
if (inlineNode.kind === "math-display") {
|
|
1690
|
+
pushChunk(chunk, `${key}-chunk-${inlineIdx}`);
|
|
1691
|
+
chunk = [];
|
|
1692
|
+
flushInline();
|
|
1693
|
+
const rendered = renderInlineNodes([inlineNode], inlineComponents);
|
|
1694
|
+
pushRenderedNodes(ensureArray2(rendered), result, `${key}-math-${inlineIdx}`);
|
|
1695
|
+
} else {
|
|
1696
|
+
chunk.push(inlineNode);
|
|
1697
|
+
}
|
|
1698
|
+
});
|
|
1699
|
+
pushChunk(chunk, `${key}-chunk-tail`);
|
|
1700
|
+
break;
|
|
1701
|
+
}
|
|
1702
|
+
case "mdx": {
|
|
1703
|
+
const status = segment.status ?? "pending";
|
|
1704
|
+
let element;
|
|
1705
|
+
if (status === "compiled") {
|
|
1706
|
+
element = React4.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
|
|
1707
|
+
} else if (status === "error") {
|
|
1708
|
+
const message = segment.value || "MDX error";
|
|
1709
|
+
element = React4.createElement("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error" }, message);
|
|
1710
|
+
} else {
|
|
1711
|
+
element = React4.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": status }, segment.value);
|
|
1712
|
+
}
|
|
1713
|
+
inlineBuffer.push(React4.createElement(React4.Fragment, { key }, element));
|
|
1714
|
+
break;
|
|
1715
|
+
}
|
|
1716
|
+
case "html": {
|
|
1717
|
+
const html = segment.sanitized ?? segment.value;
|
|
1718
|
+
const isBlockLevel = isBlockLevelHtml(html);
|
|
1719
|
+
const element = renderInlineHtmlSegment(segment.value, segment.sanitized, {
|
|
1720
|
+
key,
|
|
1721
|
+
renderers: inlineHtmlRenderers
|
|
1722
|
+
});
|
|
1723
|
+
if (isBlockLevel) {
|
|
1724
|
+
flushInline();
|
|
1725
|
+
if (element) {
|
|
1726
|
+
result.push(element);
|
|
1727
|
+
} else if (html) {
|
|
1728
|
+
result.push(
|
|
1729
|
+
React4.createElement("div", {
|
|
1730
|
+
key,
|
|
1731
|
+
className: "markdown-inline-html-block",
|
|
1732
|
+
dangerouslySetInnerHTML: { __html: html }
|
|
1733
|
+
})
|
|
1734
|
+
);
|
|
1735
|
+
}
|
|
1736
|
+
} else if (element) {
|
|
1737
|
+
inlineBuffer.push(element);
|
|
1738
|
+
}
|
|
1739
|
+
break;
|
|
1740
|
+
}
|
|
1741
|
+
default:
|
|
1742
|
+
break;
|
|
1743
|
+
}
|
|
1744
|
+
});
|
|
1745
|
+
flushInline();
|
|
1746
|
+
if (result.length === 0) {
|
|
1747
|
+
return [
|
|
1748
|
+
React4.createElement(
|
|
1749
|
+
"p",
|
|
1750
|
+
{
|
|
1751
|
+
key: "paragraph-inline-group-0",
|
|
1752
|
+
className: "markdown-paragraph"
|
|
1753
|
+
},
|
|
1754
|
+
inlineBuffer
|
|
1755
|
+
)
|
|
1756
|
+
];
|
|
1757
|
+
}
|
|
1758
|
+
return result;
|
|
1759
|
+
}
|
|
1760
|
+
function isBlockLevelHtml(html) {
|
|
1761
|
+
if (!html) return false;
|
|
1762
|
+
const trimmed = html.trim();
|
|
1763
|
+
if (!trimmed.startsWith("<")) {
|
|
1764
|
+
return false;
|
|
1765
|
+
}
|
|
1766
|
+
const match = trimmed.match(/^<([A-Za-z][\w:-]*)\b/);
|
|
1767
|
+
if (!match) {
|
|
1768
|
+
return false;
|
|
1769
|
+
}
|
|
1770
|
+
const tag = match[1].toLowerCase();
|
|
1771
|
+
return BLOCK_LEVEL_TAGS.has(tag);
|
|
1772
|
+
}
|
|
1773
|
+
var BLOCK_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
1774
|
+
"address",
|
|
1775
|
+
"article",
|
|
1776
|
+
"aside",
|
|
1777
|
+
"blockquote",
|
|
1778
|
+
"canvas",
|
|
1779
|
+
"div",
|
|
1780
|
+
"dl",
|
|
1781
|
+
"fieldset",
|
|
1782
|
+
"figcaption",
|
|
1783
|
+
"figure",
|
|
1784
|
+
"footer",
|
|
1785
|
+
"form",
|
|
1786
|
+
"h1",
|
|
1787
|
+
"h2",
|
|
1788
|
+
"h3",
|
|
1789
|
+
"h4",
|
|
1790
|
+
"h5",
|
|
1791
|
+
"h6",
|
|
1792
|
+
"header",
|
|
1793
|
+
"hr",
|
|
1794
|
+
"li",
|
|
1795
|
+
"main",
|
|
1796
|
+
"nav",
|
|
1797
|
+
"ol",
|
|
1798
|
+
"p",
|
|
1799
|
+
"pre",
|
|
1800
|
+
"section",
|
|
1801
|
+
"table",
|
|
1802
|
+
"ul",
|
|
1803
|
+
"math"
|
|
1804
|
+
]);
|
|
1805
|
+
|
|
1806
|
+
// src/renderer/code-highlight-context.tsx
|
|
1807
|
+
import React5 from "react";
|
|
1808
|
+
var CodeHighlightRequestContext = React5.createContext(null);
|
|
1809
|
+
function useCodeHighlightRequester() {
|
|
1810
|
+
return React5.useContext(CodeHighlightRequestContext);
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
// src/renderer/deferred-render-context.tsx
|
|
1814
|
+
import React6 from "react";
|
|
1815
|
+
var DeferredRenderContext = React6.createContext(null);
|
|
1816
|
+
|
|
1817
|
+
// src/renderer/store.ts
|
|
1818
|
+
import {
|
|
1819
|
+
cloneBlock,
|
|
1820
|
+
createBlockSnapshot,
|
|
1821
|
+
extractCodeWrapperAttributes,
|
|
1822
|
+
getDefaultCodeWrapperAttributes,
|
|
1823
|
+
sanitizeCodeHTML,
|
|
1824
|
+
sanitizeHTML as sanitizeHTML2,
|
|
1825
|
+
PATCH_ROOT_ID
|
|
1826
|
+
} from "@stream-mdx/core";
|
|
1827
|
+
import { getPatchKind } from "@stream-mdx/core/perf/patch-batching";
|
|
1828
|
+
|
|
1829
|
+
// src/renderer/list-utils.ts
|
|
1830
|
+
function updateNodeDepth(node, depth) {
|
|
1831
|
+
if (!node) return false;
|
|
1832
|
+
const currentDepth = typeof node.props?.depth === "number" ? node.props.depth : void 0;
|
|
1833
|
+
if (currentDepth === depth) {
|
|
1834
|
+
return false;
|
|
1835
|
+
}
|
|
1836
|
+
const nextProps = { ...node.props ?? {} };
|
|
1837
|
+
nextProps.depth = depth;
|
|
1838
|
+
node.props = nextProps;
|
|
1839
|
+
node.version++;
|
|
1840
|
+
return true;
|
|
1841
|
+
}
|
|
1842
|
+
function normalizeAllListDepths(map, touched, rootId = "__root__") {
|
|
1843
|
+
const root = map.get(rootId);
|
|
1844
|
+
if (!root) return;
|
|
1845
|
+
for (const childId of root.children) {
|
|
1846
|
+
const child = map.get(childId);
|
|
1847
|
+
if (child && child.type === "list") {
|
|
1848
|
+
normalizeListDepthRecursive(map, child, 0, touched);
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
function normalizeListDepthsForIds(map, touched, listIds, rootId = "__root__") {
|
|
1853
|
+
if (listIds.size === 0) {
|
|
1854
|
+
normalizeAllListDepths(map, touched, rootId);
|
|
1855
|
+
return;
|
|
1856
|
+
}
|
|
1857
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1858
|
+
for (const listId of listIds) {
|
|
1859
|
+
const base = map.get(listId);
|
|
1860
|
+
if (!base) continue;
|
|
1861
|
+
const listNode = base.type === "list" ? base : findNearestListAncestor(map, base);
|
|
1862
|
+
if (!listNode || visited.has(listNode.id)) continue;
|
|
1863
|
+
visited.add(listNode.id);
|
|
1864
|
+
const depth = computeListDepth(map, listNode, rootId);
|
|
1865
|
+
normalizeListDepthRecursive(map, listNode, depth, touched);
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
function normalizeListDepthRecursive(map, listNode, depth, touched) {
|
|
1869
|
+
if (!listNode) return;
|
|
1870
|
+
if (updateNodeDepth(listNode, depth)) {
|
|
1871
|
+
touched.add(listNode.id);
|
|
1872
|
+
}
|
|
1873
|
+
for (const childId of listNode.children) {
|
|
1874
|
+
const child = map.get(childId);
|
|
1875
|
+
if (!child) continue;
|
|
1876
|
+
if (child.type === "list-item") {
|
|
1877
|
+
if (updateNodeDepth(child, depth)) {
|
|
1878
|
+
touched.add(child.id);
|
|
1879
|
+
}
|
|
1880
|
+
for (const grandchildId of child.children) {
|
|
1881
|
+
const grandchild = map.get(grandchildId);
|
|
1882
|
+
if (!grandchild) continue;
|
|
1883
|
+
if (grandchild.type === "list") {
|
|
1884
|
+
normalizeListDepthRecursive(map, grandchild, depth + 1, touched);
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
} else if (child.type === "list") {
|
|
1888
|
+
normalizeListDepthRecursive(map, child, depth + 1, touched);
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
function findNearestListAncestor(map, node) {
|
|
1893
|
+
let current = node;
|
|
1894
|
+
while (current) {
|
|
1895
|
+
if (current.type === "list") return current;
|
|
1896
|
+
if (!current.parentId) return void 0;
|
|
1897
|
+
current = map.get(current.parentId);
|
|
1898
|
+
}
|
|
1899
|
+
return void 0;
|
|
1900
|
+
}
|
|
1901
|
+
function computeListDepth(map, listNode, rootId) {
|
|
1902
|
+
let depth = 0;
|
|
1903
|
+
let current = listNode;
|
|
1904
|
+
while (current && current.parentId && current.parentId !== rootId) {
|
|
1905
|
+
const parent = map.get(current.parentId);
|
|
1906
|
+
if (!parent) break;
|
|
1907
|
+
if (parent.type === "list") {
|
|
1908
|
+
depth += 1;
|
|
1909
|
+
}
|
|
1910
|
+
current = parent;
|
|
1911
|
+
}
|
|
1912
|
+
return depth;
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
// src/renderer/patch-coalescing.ts
|
|
1916
|
+
import {
|
|
1917
|
+
DEFAULT_COALESCE_CONFIG,
|
|
1918
|
+
coalescePatches,
|
|
1919
|
+
coalescePatchesLinear,
|
|
1920
|
+
coalescePatchesQuadratic,
|
|
1921
|
+
coalescePatchesWithMetrics
|
|
1922
|
+
} from "@stream-mdx/core";
|
|
1923
|
+
|
|
1924
|
+
// src/renderer/store.ts
|
|
1925
|
+
function snapshotToBlock(node) {
|
|
1926
|
+
const candidate = node.props?.block;
|
|
1927
|
+
if (candidate && typeof candidate === "object") {
|
|
1928
|
+
return cloneBlock(candidate);
|
|
1929
|
+
}
|
|
1930
|
+
return null;
|
|
1931
|
+
}
|
|
1932
|
+
var nodeSnapshotCacheByMap = /* @__PURE__ */ new WeakMap();
|
|
1933
|
+
var childrenSnapshotCacheByMap = /* @__PURE__ */ new WeakMap();
|
|
1934
|
+
var NODE_SNAPSHOT_CACHE_LIMIT = 5e4;
|
|
1935
|
+
var CHILDREN_SNAPSHOT_CACHE_LIMIT = 5e4;
|
|
1936
|
+
var NODE_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(NODE_SNAPSHOT_CACHE_LIMIT * 0.1));
|
|
1937
|
+
var CHILDREN_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(CHILDREN_SNAPSHOT_CACHE_LIMIT * 0.1));
|
|
1938
|
+
function getNodeSnapshotCacheForMap(map) {
|
|
1939
|
+
let cache = nodeSnapshotCacheByMap.get(map);
|
|
1940
|
+
if (!cache) {
|
|
1941
|
+
cache = /* @__PURE__ */ new Map();
|
|
1942
|
+
nodeSnapshotCacheByMap.set(map, cache);
|
|
1943
|
+
}
|
|
1944
|
+
return cache;
|
|
1945
|
+
}
|
|
1946
|
+
function getChildrenSnapshotCacheForMap(map) {
|
|
1947
|
+
let cache = childrenSnapshotCacheByMap.get(map);
|
|
1948
|
+
if (!cache) {
|
|
1949
|
+
cache = /* @__PURE__ */ new Map();
|
|
1950
|
+
childrenSnapshotCacheByMap.set(map, cache);
|
|
1951
|
+
}
|
|
1952
|
+
return cache;
|
|
1953
|
+
}
|
|
1954
|
+
function pruneCache(cache, max, buffer) {
|
|
1955
|
+
if (cache.size <= max + buffer) return;
|
|
1956
|
+
let remaining = cache.size - max;
|
|
1957
|
+
for (const key of cache.keys()) {
|
|
1958
|
+
cache.delete(key);
|
|
1959
|
+
remaining -= 1;
|
|
1960
|
+
if (remaining <= 0) break;
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
function deleteSnapshotCacheEntry(map, id) {
|
|
1964
|
+
getNodeSnapshotCacheForMap(map).delete(id);
|
|
1965
|
+
getChildrenSnapshotCacheForMap(map).delete(id);
|
|
1966
|
+
}
|
|
1967
|
+
function clearSnapshotCaches(map) {
|
|
1968
|
+
getNodeSnapshotCacheForMap(map).clear();
|
|
1969
|
+
getChildrenSnapshotCacheForMap(map).clear();
|
|
1970
|
+
}
|
|
1971
|
+
var EMPTY_CHILDREN = Object.freeze([]);
|
|
1972
|
+
var EMPTY_NODE_SNAPSHOT = Object.freeze({ version: -1, node: void 0 });
|
|
1973
|
+
var EMPTY_CHILDREN_SNAPSHOT = Object.freeze({
|
|
1974
|
+
version: -1,
|
|
1975
|
+
children: EMPTY_CHILDREN
|
|
1976
|
+
});
|
|
1977
|
+
function isListPatchDebugEnabled() {
|
|
1978
|
+
if (typeof globalThis !== "undefined") {
|
|
1979
|
+
const flag = globalThis.__STREAMING_LIST_DEBUG__;
|
|
1980
|
+
if (flag === true) return true;
|
|
1981
|
+
}
|
|
1982
|
+
if (typeof process !== "undefined" && process.env.NEXT_PUBLIC_STREAMING_LIST_DEBUG === "true") {
|
|
1983
|
+
return true;
|
|
1984
|
+
}
|
|
1985
|
+
return false;
|
|
1986
|
+
}
|
|
1987
|
+
var CODE_BLOCK_DEBUG_ENABLED = (() => {
|
|
1988
|
+
try {
|
|
1989
|
+
if (typeof process !== "undefined" && process.env && process.env.NEXT_PUBLIC_STREAMING_DEBUG_CODELINES === "1") {
|
|
1990
|
+
return true;
|
|
1991
|
+
}
|
|
1992
|
+
if (typeof globalThis !== "undefined") {
|
|
1993
|
+
const debug = globalThis?.__STREAMING_DEBUG__;
|
|
1994
|
+
if (debug?.codeLines) {
|
|
1995
|
+
return true;
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
} catch {
|
|
1999
|
+
}
|
|
2000
|
+
return false;
|
|
2001
|
+
})() || false;
|
|
2002
|
+
var CODE_BLOCK_VALIDATION_ENABLED = typeof process !== "undefined" && process.env ? process.env.NODE_ENV !== "production" : true;
|
|
2003
|
+
var PATCH_PERF_HISTORY_LIMIT = 120;
|
|
2004
|
+
var getPerfNow = (() => {
|
|
2005
|
+
if (typeof performance !== "undefined" && typeof performance.now === "function") {
|
|
2006
|
+
return () => performance.now();
|
|
2007
|
+
}
|
|
2008
|
+
return () => Date.now();
|
|
2009
|
+
})();
|
|
2010
|
+
function isPatchPerfDebugEnabled() {
|
|
2011
|
+
try {
|
|
2012
|
+
if (typeof process !== "undefined" && process.env) {
|
|
2013
|
+
const value = process.env.NEXT_PUBLIC_STREAMING_DEBUG_PATCH_PERF;
|
|
2014
|
+
if (value === "1" || value === "true") {
|
|
2015
|
+
return true;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
} catch {
|
|
2019
|
+
}
|
|
2020
|
+
try {
|
|
2021
|
+
const debug = globalThis.__STREAMING_DEBUG__;
|
|
2022
|
+
if (debug?.patchPerf) {
|
|
2023
|
+
return true;
|
|
2024
|
+
}
|
|
2025
|
+
} catch {
|
|
2026
|
+
}
|
|
2027
|
+
return false;
|
|
2028
|
+
}
|
|
2029
|
+
function recordPatchPerf(summary) {
|
|
2030
|
+
try {
|
|
2031
|
+
if (typeof globalThis === "undefined") return;
|
|
2032
|
+
const root = globalThis;
|
|
2033
|
+
const history = root.__STREAM_MDX_PATCH_STATS__ ?? [];
|
|
2034
|
+
history.push(summary);
|
|
2035
|
+
if (history.length > PATCH_PERF_HISTORY_LIMIT) {
|
|
2036
|
+
history.splice(0, history.length - PATCH_PERF_HISTORY_LIMIT);
|
|
2037
|
+
}
|
|
2038
|
+
root.__STREAM_MDX_PATCH_STATS__ = history;
|
|
2039
|
+
root.__STREAM_MDX_PATCH_STATS_LAST__ = summary;
|
|
2040
|
+
const totals = root.__STREAM_MDX_PATCH_STATS_TOTALS__ ?? {
|
|
2041
|
+
calls: 0,
|
|
2042
|
+
totalMs: 0,
|
|
2043
|
+
applyMs: 0,
|
|
2044
|
+
coalesceMs: 0,
|
|
2045
|
+
listNormalizeMs: 0,
|
|
2046
|
+
patches: 0,
|
|
2047
|
+
coalescedPatches: 0,
|
|
2048
|
+
ops: {},
|
|
2049
|
+
setPropsByType: {},
|
|
2050
|
+
setPropsBySize: {}
|
|
2051
|
+
};
|
|
2052
|
+
totals.calls += 1;
|
|
2053
|
+
totals.totalMs += summary.totalMs;
|
|
2054
|
+
totals.applyMs += summary.applyMs;
|
|
2055
|
+
totals.coalesceMs += summary.coalesceMs;
|
|
2056
|
+
totals.listNormalizeMs += summary.listNormalizeMs;
|
|
2057
|
+
totals.patches += summary.patches;
|
|
2058
|
+
totals.coalescedPatches += summary.coalescedPatches;
|
|
2059
|
+
for (const [op, stats] of Object.entries(summary.ops)) {
|
|
2060
|
+
const entry = totals.ops[op] ?? { count: 0, durationMs: 0 };
|
|
2061
|
+
entry.count += stats.count;
|
|
2062
|
+
entry.durationMs += stats.durationMs;
|
|
2063
|
+
totals.ops[op] = entry;
|
|
2064
|
+
}
|
|
2065
|
+
if (summary.setPropsByType) {
|
|
2066
|
+
for (const [key, stats] of Object.entries(summary.setPropsByType)) {
|
|
2067
|
+
const entry = totals.setPropsByType[key] ?? { count: 0, durationMs: 0 };
|
|
2068
|
+
entry.count += stats.count;
|
|
2069
|
+
entry.durationMs += stats.durationMs;
|
|
2070
|
+
totals.setPropsByType[key] = entry;
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
if (summary.setPropsBySize) {
|
|
2074
|
+
for (const [key, stats] of Object.entries(summary.setPropsBySize)) {
|
|
2075
|
+
const entry = totals.setPropsBySize[key] ?? { count: 0, durationMs: 0 };
|
|
2076
|
+
entry.count += stats.count;
|
|
2077
|
+
entry.durationMs += stats.durationMs;
|
|
2078
|
+
totals.setPropsBySize[key] = entry;
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
root.__STREAM_MDX_PATCH_STATS_TOTALS__ = totals;
|
|
2082
|
+
} catch {
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
function estimateBlockPayloadSize(block) {
|
|
2086
|
+
if (!block || !block.payload) return 0;
|
|
2087
|
+
let size = 0;
|
|
2088
|
+
const payload = block.payload;
|
|
2089
|
+
if (typeof payload.raw === "string") size += payload.raw.length;
|
|
2090
|
+
if (typeof payload.highlightedHtml === "string") size += payload.highlightedHtml.length;
|
|
2091
|
+
if (typeof payload.sanitizedHtml === "string") size += payload.sanitizedHtml.length;
|
|
2092
|
+
if (typeof payload.compiledMdxModule?.code === "string") size += payload.compiledMdxModule.code.length;
|
|
2093
|
+
if (Array.isArray(payload.inline)) size += payload.inline.length * 8;
|
|
2094
|
+
return size;
|
|
2095
|
+
}
|
|
2096
|
+
function estimatePropsSize(props, block) {
|
|
2097
|
+
let size = 0;
|
|
2098
|
+
if (props) {
|
|
2099
|
+
for (const [key, value] of Object.entries(props)) {
|
|
2100
|
+
if (key === "block") continue;
|
|
2101
|
+
if (typeof value === "string") {
|
|
2102
|
+
size += value.length;
|
|
2103
|
+
} else if (typeof value === "number") {
|
|
2104
|
+
size += 8;
|
|
2105
|
+
} else if (typeof value === "boolean") {
|
|
2106
|
+
size += 4;
|
|
2107
|
+
} else if (Array.isArray(value)) {
|
|
2108
|
+
size += value.length * 4;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
if (block) {
|
|
2113
|
+
size += estimateBlockPayloadSize(block);
|
|
2114
|
+
}
|
|
2115
|
+
return size;
|
|
2116
|
+
}
|
|
2117
|
+
function bucketBySize(size) {
|
|
2118
|
+
if (size < 1024) return "<1k";
|
|
2119
|
+
if (size < 10 * 1024) return "1-10k";
|
|
2120
|
+
if (size < 50 * 1024) return "10-50k";
|
|
2121
|
+
if (size < 200 * 1024) return "50-200k";
|
|
2122
|
+
return ">=200k";
|
|
2123
|
+
}
|
|
2124
|
+
function debugCodeBlock(event, payload) {
|
|
2125
|
+
if (!CODE_BLOCK_DEBUG_ENABLED) return;
|
|
2126
|
+
try {
|
|
2127
|
+
console.debug(`[renderer-store][code-block] ${event}`, payload);
|
|
2128
|
+
} catch {
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
function createRootRecord() {
|
|
2132
|
+
return {
|
|
2133
|
+
id: PATCH_ROOT_ID,
|
|
2134
|
+
type: "__root__",
|
|
2135
|
+
parentId: null,
|
|
2136
|
+
children: [],
|
|
2137
|
+
props: {},
|
|
2138
|
+
version: 0,
|
|
2139
|
+
blockEpoch: 0
|
|
2140
|
+
};
|
|
2141
|
+
}
|
|
2142
|
+
function readNumericEpoch(value) {
|
|
2143
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
2144
|
+
return void 0;
|
|
2145
|
+
}
|
|
2146
|
+
return value;
|
|
2147
|
+
}
|
|
2148
|
+
function readSnapshotBlockEpoch(snapshot) {
|
|
2149
|
+
return readNumericEpoch(snapshot.meta?.blockEpoch);
|
|
2150
|
+
}
|
|
2151
|
+
function readPatchBlockEpoch(patch) {
|
|
2152
|
+
if (patch.op === "setHTML") {
|
|
2153
|
+
return readNumericEpoch(patch.patchMeta?.blockEpoch);
|
|
2154
|
+
}
|
|
2155
|
+
return readNumericEpoch(patch.meta?.blockEpoch);
|
|
2156
|
+
}
|
|
2157
|
+
function readPatchParseEpoch(patch) {
|
|
2158
|
+
if (patch.op === "setHTML") {
|
|
2159
|
+
return readNumericEpoch(patch.patchMeta?.parseEpoch);
|
|
2160
|
+
}
|
|
2161
|
+
return readNumericEpoch(patch.meta?.parseEpoch);
|
|
2162
|
+
}
|
|
2163
|
+
function readPatchTx(patch) {
|
|
2164
|
+
if (patch.op === "setHTML") {
|
|
2165
|
+
return readNumericEpoch(patch.patchMeta?.tx);
|
|
2166
|
+
}
|
|
2167
|
+
return readNumericEpoch(patch.meta?.tx);
|
|
2168
|
+
}
|
|
2169
|
+
function assignSubtreeBlockEpoch(map, rootId, blockEpoch, touched) {
|
|
2170
|
+
const root = map.get(rootId);
|
|
2171
|
+
if (!root) return;
|
|
2172
|
+
const stack = [root];
|
|
2173
|
+
while (stack.length > 0) {
|
|
2174
|
+
const node = stack.pop();
|
|
2175
|
+
if (!node) continue;
|
|
2176
|
+
if (node.blockEpoch !== blockEpoch) {
|
|
2177
|
+
node.blockEpoch = blockEpoch;
|
|
2178
|
+
node.version += 1;
|
|
2179
|
+
touched?.add(node.id);
|
|
2180
|
+
}
|
|
2181
|
+
for (const childId of node.children) {
|
|
2182
|
+
const child = map.get(childId);
|
|
2183
|
+
if (child) {
|
|
2184
|
+
stack.push(child);
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
function ensureArray(value) {
|
|
2190
|
+
return Array.isArray(value) ? value : [];
|
|
2191
|
+
}
|
|
2192
|
+
function shallowEqualRecords(a, b) {
|
|
2193
|
+
if (a === b) return true;
|
|
2194
|
+
if (!a || !b) {
|
|
2195
|
+
return !a && !b;
|
|
2196
|
+
}
|
|
2197
|
+
const keysA = Object.keys(a);
|
|
2198
|
+
const keysB = Object.keys(b);
|
|
2199
|
+
if (keysA.length !== keysB.length) return false;
|
|
2200
|
+
for (const key of keysA) {
|
|
2201
|
+
if (!Object.prototype.hasOwnProperty.call(b, key)) {
|
|
2202
|
+
return false;
|
|
2203
|
+
}
|
|
2204
|
+
if (a[key] !== b[key]) {
|
|
2205
|
+
return false;
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
return true;
|
|
2209
|
+
}
|
|
2210
|
+
function ensureUniqueChildren(parent, touched) {
|
|
2211
|
+
if (!parent || parent.children.length <= 1) {
|
|
2212
|
+
return;
|
|
2213
|
+
}
|
|
2214
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2215
|
+
const deduped = [];
|
|
2216
|
+
let mutated = false;
|
|
2217
|
+
for (const childId of parent.children) {
|
|
2218
|
+
if (seen.has(childId)) {
|
|
2219
|
+
mutated = true;
|
|
2220
|
+
continue;
|
|
2221
|
+
}
|
|
2222
|
+
seen.add(childId);
|
|
2223
|
+
deduped.push(childId);
|
|
2224
|
+
}
|
|
2225
|
+
if (mutated) {
|
|
2226
|
+
parent.children = deduped;
|
|
2227
|
+
parent.version++;
|
|
2228
|
+
if (touched) {
|
|
2229
|
+
touched.add(parent.id);
|
|
2230
|
+
}
|
|
2231
|
+
console.error("[renderer-store] removed duplicate children", {
|
|
2232
|
+
parentId: parent.id,
|
|
2233
|
+
deduped: parent.children.slice()
|
|
2234
|
+
});
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
function parseLineIndexFromId(id) {
|
|
2238
|
+
const match = id.match(/::line:(\d+)$/);
|
|
2239
|
+
if (!match) return Number.NaN;
|
|
2240
|
+
const value = Number(match[1]);
|
|
2241
|
+
return Number.isFinite(value) ? value : Number.NaN;
|
|
2242
|
+
}
|
|
2243
|
+
function escapeHtml2(value) {
|
|
2244
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2245
|
+
}
|
|
2246
|
+
function stripOuterLineSpan(html) {
|
|
2247
|
+
if (!html) return null;
|
|
2248
|
+
const openTagMatch = html.match(/<span[^>]*class="[^"]*\bline\b[^"]*"[^>]*>/i);
|
|
2249
|
+
if (!openTagMatch) {
|
|
2250
|
+
return null;
|
|
2251
|
+
}
|
|
2252
|
+
const openTag = openTagMatch[0];
|
|
2253
|
+
const startIndex = html.indexOf(openTag);
|
|
2254
|
+
if (startIndex === -1) {
|
|
2255
|
+
return null;
|
|
2256
|
+
}
|
|
2257
|
+
const contentStart = startIndex + openTag.length;
|
|
2258
|
+
const endIndex = html.lastIndexOf("</span>");
|
|
2259
|
+
if (endIndex === -1 || endIndex < contentStart) {
|
|
2260
|
+
return null;
|
|
2261
|
+
}
|
|
2262
|
+
return html.slice(contentStart, endIndex);
|
|
2263
|
+
}
|
|
2264
|
+
function sanitizeLineInnerHtml(innerHtml, fallbackText) {
|
|
2265
|
+
if (innerHtml && innerHtml.trim().length > 0) {
|
|
2266
|
+
const wrapped = `<span class="line">${innerHtml}</span>`;
|
|
2267
|
+
const sanitized = sanitizeCodeHTML(wrapped);
|
|
2268
|
+
const inner = stripOuterLineSpan(typeof sanitized === "string" ? sanitized : String(sanitized));
|
|
2269
|
+
if (inner !== null) {
|
|
2270
|
+
return inner;
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
return escapeHtml2(fallbackText);
|
|
2274
|
+
}
|
|
2275
|
+
function normalizeCodeBlockChildren(nodes, parent, touched) {
|
|
2276
|
+
if (parent.type !== "code") return;
|
|
2277
|
+
const previousChildren = parent.children.slice();
|
|
2278
|
+
const originalOrder = /* @__PURE__ */ new Map();
|
|
2279
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
2280
|
+
const codeLineNodes = [];
|
|
2281
|
+
const anomalies = [];
|
|
2282
|
+
for (let idx = 0; idx < previousChildren.length; idx++) {
|
|
2283
|
+
const childId = previousChildren[idx];
|
|
2284
|
+
const node = nodes.get(childId);
|
|
2285
|
+
if (!node) {
|
|
2286
|
+
anomalies.push(`missing:${childId}`);
|
|
2287
|
+
continue;
|
|
2288
|
+
}
|
|
2289
|
+
if (node.parentId !== parent.id) {
|
|
2290
|
+
node.parentId = parent.id;
|
|
2291
|
+
node.version++;
|
|
2292
|
+
touched.add(node.id);
|
|
2293
|
+
}
|
|
2294
|
+
if (node.type !== "code-line") {
|
|
2295
|
+
anomalies.push(`type-mismatch:${node.id}:${node.type}`);
|
|
2296
|
+
nodes.delete(node.id);
|
|
2297
|
+
deleteSnapshotCacheEntry(nodes, node.id);
|
|
2298
|
+
touched.add(node.id);
|
|
2299
|
+
continue;
|
|
2300
|
+
}
|
|
2301
|
+
if (seenIds.has(childId)) {
|
|
2302
|
+
anomalies.push(`duplicate-id:${childId}`);
|
|
2303
|
+
continue;
|
|
2304
|
+
}
|
|
2305
|
+
seenIds.add(childId);
|
|
2306
|
+
codeLineNodes.push(node);
|
|
2307
|
+
originalOrder.set(node.id, idx);
|
|
2308
|
+
}
|
|
2309
|
+
if (anomalies.length > 0) {
|
|
2310
|
+
debugCodeBlock("code-block-anomalies", {
|
|
2311
|
+
parentId: parent.id,
|
|
2312
|
+
anomalies,
|
|
2313
|
+
children: previousChildren
|
|
2314
|
+
});
|
|
2315
|
+
if (anomalies.some((entry) => entry.startsWith("duplicate-id"))) {
|
|
2316
|
+
console.warn("[renderer-store] duplicate code-line ids detected", {
|
|
2317
|
+
parentId: parent.id,
|
|
2318
|
+
anomalies,
|
|
2319
|
+
children: previousChildren
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
const sorted = codeLineNodes.slice().sort((a, b) => {
|
|
2324
|
+
const ai = typeof a.props?.index === "number" ? a.props.index : parseLineIndexFromId(a.id);
|
|
2325
|
+
const bi = typeof b.props?.index === "number" ? b.props.index : parseLineIndexFromId(b.id);
|
|
2326
|
+
if (Number.isFinite(ai) && Number.isFinite(bi) && ai !== bi) {
|
|
2327
|
+
return ai - bi;
|
|
2328
|
+
}
|
|
2329
|
+
const ao = originalOrder.get(a.id) ?? 0;
|
|
2330
|
+
const bo = originalOrder.get(b.id) ?? 0;
|
|
2331
|
+
return ao - bo;
|
|
2332
|
+
});
|
|
2333
|
+
const nextChildren = [];
|
|
2334
|
+
let mutated = false;
|
|
2335
|
+
for (let idx = 0; idx < sorted.length; idx++) {
|
|
2336
|
+
const node = sorted[idx];
|
|
2337
|
+
const desiredId = `${parent.id}::line:${idx}`;
|
|
2338
|
+
const existing = nodes.get(desiredId);
|
|
2339
|
+
if (existing && existing !== node) {
|
|
2340
|
+
nodes.delete(desiredId);
|
|
2341
|
+
deleteSnapshotCacheEntry(nodes, desiredId);
|
|
2342
|
+
touched.add(desiredId);
|
|
2343
|
+
mutated = true;
|
|
2344
|
+
}
|
|
2345
|
+
if (node.id !== desiredId) {
|
|
2346
|
+
const previousId = node.id;
|
|
2347
|
+
nodes.delete(node.id);
|
|
2348
|
+
deleteSnapshotCacheEntry(nodes, previousId);
|
|
2349
|
+
node.id = desiredId;
|
|
2350
|
+
nodes.set(desiredId, node);
|
|
2351
|
+
touched.add(desiredId);
|
|
2352
|
+
mutated = true;
|
|
2353
|
+
} else if (!nodes.has(desiredId)) {
|
|
2354
|
+
nodes.set(desiredId, node);
|
|
2355
|
+
}
|
|
2356
|
+
if (node.parentId !== parent.id) {
|
|
2357
|
+
node.parentId = parent.id;
|
|
2358
|
+
node.version++;
|
|
2359
|
+
touched.add(node.id);
|
|
2360
|
+
mutated = true;
|
|
2361
|
+
}
|
|
2362
|
+
const incoming = { index: idx, text: node.props?.text, html: node.props?.html };
|
|
2363
|
+
if (Object.prototype.hasOwnProperty.call(node.props ?? {}, "tokens")) {
|
|
2364
|
+
incoming.tokens = node.props.tokens;
|
|
2365
|
+
}
|
|
2366
|
+
const normalizedProps = normalizeCodeLineProps(incoming, node.props);
|
|
2367
|
+
if (normalizedProps !== node.props) {
|
|
2368
|
+
node.props = normalizedProps;
|
|
2369
|
+
node.version++;
|
|
2370
|
+
touched.add(node.id);
|
|
2371
|
+
mutated = true;
|
|
2372
|
+
}
|
|
2373
|
+
nextChildren.push(desiredId);
|
|
2374
|
+
}
|
|
2375
|
+
const allowed = new Set(nextChildren);
|
|
2376
|
+
for (const [id, record] of nodes) {
|
|
2377
|
+
if (record.parentId === parent.id && record.type === "code-line" && !allowed.has(id)) {
|
|
2378
|
+
nodes.delete(id);
|
|
2379
|
+
deleteSnapshotCacheEntry(nodes, id);
|
|
2380
|
+
touched.add(id);
|
|
2381
|
+
mutated = true;
|
|
2382
|
+
}
|
|
2383
|
+
}
|
|
2384
|
+
if (!arraysEqual(previousChildren, nextChildren)) {
|
|
2385
|
+
parent.children = nextChildren;
|
|
2386
|
+
parent.version++;
|
|
2387
|
+
touched.add(parent.id);
|
|
2388
|
+
mutated = true;
|
|
2389
|
+
}
|
|
2390
|
+
const duplicateIds = [];
|
|
2391
|
+
const postSeenIds = /* @__PURE__ */ new Set();
|
|
2392
|
+
for (const childId of parent.children) {
|
|
2393
|
+
if (postSeenIds.has(childId)) {
|
|
2394
|
+
duplicateIds.push(childId);
|
|
2395
|
+
} else {
|
|
2396
|
+
postSeenIds.add(childId);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
if (duplicateIds.length > 0) {
|
|
2400
|
+
console.error("[renderer-store] duplicate code-line children detected post-normalize", {
|
|
2401
|
+
parentId: parent.id,
|
|
2402
|
+
duplicates: duplicateIds,
|
|
2403
|
+
children: parent.children.slice()
|
|
2404
|
+
});
|
|
2405
|
+
}
|
|
2406
|
+
if (mutated) {
|
|
2407
|
+
debugCodeBlock("code-block-normalized", {
|
|
2408
|
+
parentId: parent.id,
|
|
2409
|
+
children: parent.children.slice()
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
if (CODE_BLOCK_VALIDATION_ENABLED) {
|
|
2413
|
+
const validation = validateCodeBlockChildren(nodes, parent);
|
|
2414
|
+
if (!validation.ok) {
|
|
2415
|
+
debugCodeBlock("code-block-validation-failed", {
|
|
2416
|
+
parentId: parent.id,
|
|
2417
|
+
issues: validation.issues
|
|
2418
|
+
});
|
|
2419
|
+
if (!rebuildCodeBlockFromSnapshot(nodes, parent, touched, validation.issues)) {
|
|
2420
|
+
console.warn("[renderer-store] unable to fully normalize code block", {
|
|
2421
|
+
parentId: parent.id,
|
|
2422
|
+
issues: validation.issues
|
|
2423
|
+
});
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
function normalizeCodeLineProps(incoming, previous) {
|
|
2429
|
+
const previousIndex = typeof previous?.index === "number" ? previous?.index : 0;
|
|
2430
|
+
const index = typeof incoming.index === "number" ? incoming.index : previousIndex;
|
|
2431
|
+
const previousText = typeof previous?.text === "string" ? previous?.text : "";
|
|
2432
|
+
const previousHtml = typeof previous?.html === "string" ? previous?.html : null;
|
|
2433
|
+
const previousTokens = Object.prototype.hasOwnProperty.call(previous ?? {}, "tokens") ? previous?.tokens : void 0;
|
|
2434
|
+
const hasIncomingText = typeof incoming.text === "string";
|
|
2435
|
+
const hasIncomingHtml = typeof incoming.html === "string";
|
|
2436
|
+
const hasIncomingTokens = Object.prototype.hasOwnProperty.call(incoming, "tokens");
|
|
2437
|
+
const incomingTokens = hasIncomingTokens ? incoming.tokens : void 0;
|
|
2438
|
+
const rawText = hasIncomingText ? incoming.text : previousText;
|
|
2439
|
+
if (previous && !hasIncomingHtml && !hasIncomingTokens && index === previousIndex && (!hasIncomingText || rawText === previousText)) {
|
|
2440
|
+
return previous;
|
|
2441
|
+
}
|
|
2442
|
+
if (previous && hasIncomingHtml && !hasIncomingTokens && incoming.html === previousHtml && index === previousIndex && (!hasIncomingText || rawText === previousText)) {
|
|
2443
|
+
return previous;
|
|
2444
|
+
}
|
|
2445
|
+
let highlight = null;
|
|
2446
|
+
if (hasIncomingHtml) {
|
|
2447
|
+
highlight = incoming.html;
|
|
2448
|
+
} else if (!hasIncomingText || rawText === previousText) {
|
|
2449
|
+
highlight = previousHtml;
|
|
2450
|
+
}
|
|
2451
|
+
let tokens = void 0;
|
|
2452
|
+
if (hasIncomingTokens) {
|
|
2453
|
+
tokens = incomingTokens ?? null;
|
|
2454
|
+
} else if (!hasIncomingText || rawText === previousText) {
|
|
2455
|
+
tokens = previousTokens;
|
|
2456
|
+
} else {
|
|
2457
|
+
tokens = null;
|
|
2458
|
+
}
|
|
2459
|
+
return createCodeLineProps(index, rawText, highlight, tokens);
|
|
2460
|
+
}
|
|
2461
|
+
function createCodeLineProps(index, text, highlight, tokens) {
|
|
2462
|
+
const safeText = typeof text === "string" ? text : "";
|
|
2463
|
+
const hasIncomingHighlight = typeof highlight === "string" && highlight.trim().length > 0;
|
|
2464
|
+
const sanitized = hasIncomingHighlight ? sanitizeLineInnerHtml(highlight, safeText) : null;
|
|
2465
|
+
const hasRenderableTokens = tokens !== void 0 && tokens !== null;
|
|
2466
|
+
const html = sanitized && sanitized.length >= safeText.length ? sanitized : hasRenderableTokens ? null : escapeHtml2(safeText);
|
|
2467
|
+
const props = {
|
|
2468
|
+
index,
|
|
2469
|
+
text: safeText,
|
|
2470
|
+
html
|
|
2471
|
+
};
|
|
2472
|
+
if (tokens !== void 0) {
|
|
2473
|
+
props.tokens = tokens;
|
|
2474
|
+
}
|
|
2475
|
+
return props;
|
|
2476
|
+
}
|
|
2477
|
+
function clampIndex(index, length) {
|
|
2478
|
+
if (!Number.isFinite(index)) return 0;
|
|
2479
|
+
if (length <= 0) return 0;
|
|
2480
|
+
return Math.max(0, Math.min(index, length));
|
|
2481
|
+
}
|
|
2482
|
+
var INLINE_SEGMENT_TYPES = /* @__PURE__ */ new Set(["paragraph-text", "blockquote-text", "list-item-text"]);
|
|
2483
|
+
function isInlineSegmentType(type) {
|
|
2484
|
+
return INLINE_SEGMENT_TYPES.has(type);
|
|
2485
|
+
}
|
|
2486
|
+
function mergeInlineSegmentProps(previous, incoming) {
|
|
2487
|
+
const result = previous ? { ...previous } : {};
|
|
2488
|
+
for (const [key, value] of Object.entries(incoming)) {
|
|
2489
|
+
if (value === void 0) {
|
|
2490
|
+
delete result[key];
|
|
2491
|
+
} else {
|
|
2492
|
+
result[key] = value;
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
const inlineProvided = Object.prototype.hasOwnProperty.call(incoming, "inline");
|
|
2496
|
+
if (inlineProvided) {
|
|
2497
|
+
const inlineValue = Array.isArray(incoming.inline) ? incoming.inline : void 0;
|
|
2498
|
+
if (inlineValue) {
|
|
2499
|
+
result.inline = inlineValue;
|
|
2500
|
+
} else {
|
|
2501
|
+
result.inline = void 0;
|
|
2502
|
+
}
|
|
2503
|
+
} else if (previous && Array.isArray(previous.inline) && !Array.isArray(result.inline)) {
|
|
2504
|
+
result.inline = previous.inline;
|
|
2505
|
+
}
|
|
2506
|
+
const textProvided = Object.prototype.hasOwnProperty.call(incoming, "text");
|
|
2507
|
+
if (textProvided) {
|
|
2508
|
+
result.text = typeof incoming.text === "string" ? incoming.text : "";
|
|
2509
|
+
} else if (previous && typeof previous.text === "string" && typeof result.text !== "string") {
|
|
2510
|
+
result.text = previous.text;
|
|
2511
|
+
}
|
|
2512
|
+
return result;
|
|
2513
|
+
}
|
|
2514
|
+
function applyCodeBlockMetadata(record) {
|
|
2515
|
+
const block = record.block;
|
|
2516
|
+
const highlightedHtml = block?.payload.highlightedHtml ?? "";
|
|
2517
|
+
const lang = typeof block?.payload.meta?.lang === "string" ? block?.payload.meta?.lang : record.props?.lang;
|
|
2518
|
+
let { preAttrs, codeAttrs } = extractCodeWrapperAttributes(highlightedHtml);
|
|
2519
|
+
if (!preAttrs || !codeAttrs) {
|
|
2520
|
+
const defaults = getDefaultCodeWrapperAttributes(typeof lang === "string" ? lang : void 0);
|
|
2521
|
+
preAttrs = preAttrs ?? defaults.preAttrs;
|
|
2522
|
+
codeAttrs = codeAttrs ?? defaults.codeAttrs;
|
|
2523
|
+
}
|
|
2524
|
+
record.props = {
|
|
2525
|
+
...record.props ?? {},
|
|
2526
|
+
lang,
|
|
2527
|
+
preAttrs,
|
|
2528
|
+
codeAttrs
|
|
2529
|
+
};
|
|
2530
|
+
}
|
|
2531
|
+
function normalizeNodeProps(snapshot) {
|
|
2532
|
+
if (snapshot.type === "code-line") {
|
|
2533
|
+
const index = typeof snapshot.props?.index === "number" ? snapshot.props?.index : 0;
|
|
2534
|
+
const text = typeof snapshot.props?.text === "string" ? snapshot.props?.text : "";
|
|
2535
|
+
const html = typeof snapshot.props?.html === "string" ? snapshot.props?.html : null;
|
|
2536
|
+
const tokens = Object.prototype.hasOwnProperty.call(snapshot.props ?? {}, "tokens") ? snapshot.props?.tokens : void 0;
|
|
2537
|
+
return createCodeLineProps(index, text, html, tokens);
|
|
2538
|
+
}
|
|
2539
|
+
if (isInlineSegmentType(snapshot.type)) {
|
|
2540
|
+
const incoming = snapshot.props ? { ...snapshot.props } : {};
|
|
2541
|
+
return mergeInlineSegmentProps(void 0, incoming);
|
|
2542
|
+
}
|
|
2543
|
+
return snapshot.props ? { ...snapshot.props } : {};
|
|
2544
|
+
}
|
|
2545
|
+
function validateCodeBlockChildren(nodes, parent) {
|
|
2546
|
+
const issues = [];
|
|
2547
|
+
const expectedPrefix = `${parent.id}::line:`;
|
|
2548
|
+
const allowed = /* @__PURE__ */ new Set();
|
|
2549
|
+
for (let idx = 0; idx < parent.children.length; idx++) {
|
|
2550
|
+
const childId = parent.children[idx];
|
|
2551
|
+
allowed.add(childId);
|
|
2552
|
+
const node = nodes.get(childId);
|
|
2553
|
+
if (!node) {
|
|
2554
|
+
issues.push({ kind: "missing-node", id: childId, expected: `${expectedPrefix}${idx}` });
|
|
2555
|
+
continue;
|
|
2556
|
+
}
|
|
2557
|
+
if (node.parentId !== parent.id) {
|
|
2558
|
+
issues.push({ kind: "parent-mismatch", id: childId, expected: parent.id, actual: node.parentId });
|
|
2559
|
+
}
|
|
2560
|
+
if (node.type !== "code-line") {
|
|
2561
|
+
issues.push({ kind: "unexpected-type", id: childId, expected: "code-line", actual: node.type });
|
|
2562
|
+
}
|
|
2563
|
+
const expectedId = `${expectedPrefix}${idx}`;
|
|
2564
|
+
if (childId !== expectedId) {
|
|
2565
|
+
issues.push({ kind: "id-mismatch", id: childId, expected: expectedId, actual: childId });
|
|
2566
|
+
}
|
|
2567
|
+
const indexProp = typeof node.props?.index === "number" ? node.props.index : null;
|
|
2568
|
+
if (indexProp !== idx) {
|
|
2569
|
+
issues.push({ kind: "index-mismatch", id: childId, expected: idx, actual: indexProp });
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
for (const [id, record] of nodes) {
|
|
2573
|
+
if (record.parentId === parent.id && record.type === "code-line" && !allowed.has(id)) {
|
|
2574
|
+
issues.push({ kind: "dangling-node", id });
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
if (parent.block?.isFinalized) {
|
|
2578
|
+
const snapshot = createBlockSnapshot(cloneBlock(parent.block));
|
|
2579
|
+
const expectedChildren = ensureArray(snapshot.children).filter((child) => child.type === "code-line");
|
|
2580
|
+
if (expectedChildren.length !== parent.children.length) {
|
|
2581
|
+
issues.push({
|
|
2582
|
+
kind: "line-count-mismatch",
|
|
2583
|
+
id: parent.id,
|
|
2584
|
+
expected: expectedChildren.length,
|
|
2585
|
+
actual: parent.children.length
|
|
2586
|
+
});
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
return { ok: issues.length === 0, issues };
|
|
2590
|
+
}
|
|
2591
|
+
function rebuildCodeBlockFromSnapshot(nodes, parent, touched, issues) {
|
|
2592
|
+
if (!parent.block) {
|
|
2593
|
+
return false;
|
|
2594
|
+
}
|
|
2595
|
+
const ancestor = parent.parentId ? nodes.get(parent.parentId) : void 0;
|
|
2596
|
+
if (!ancestor) {
|
|
2597
|
+
return false;
|
|
2598
|
+
}
|
|
2599
|
+
const index = ancestor.children.indexOf(parent.id);
|
|
2600
|
+
if (index === -1) {
|
|
2601
|
+
return false;
|
|
2602
|
+
}
|
|
2603
|
+
const snapshot = createBlockSnapshot(cloneBlock(parent.block));
|
|
2604
|
+
removeSubtree(nodes, parent.id, touched);
|
|
2605
|
+
const inserted = insertSnapshotAt(nodes, ancestor, index, snapshot, touched, parent.blockEpoch);
|
|
2606
|
+
if (!inserted) {
|
|
2607
|
+
return false;
|
|
2608
|
+
}
|
|
2609
|
+
for (const id of inserted.insertedIds) {
|
|
2610
|
+
touched.add(id);
|
|
2611
|
+
}
|
|
2612
|
+
ancestor.version++;
|
|
2613
|
+
touched.add(ancestor.id);
|
|
2614
|
+
console.warn("[renderer-store] rebuilt code block from snapshot", {
|
|
2615
|
+
parentId: parent.id,
|
|
2616
|
+
issues
|
|
2617
|
+
});
|
|
2618
|
+
return true;
|
|
2619
|
+
}
|
|
2620
|
+
function arraysEqual(a, b) {
|
|
2621
|
+
if (a === b) return true;
|
|
2622
|
+
if (a.length !== b.length) return false;
|
|
2623
|
+
for (let i = 0; i < a.length; i++) {
|
|
2624
|
+
if (a[i] !== b[i]) return false;
|
|
2625
|
+
}
|
|
2626
|
+
return true;
|
|
2627
|
+
}
|
|
2628
|
+
function expectedCodeLineId(parentId, index) {
|
|
2629
|
+
return `${parentId}::line:${index}`;
|
|
2630
|
+
}
|
|
2631
|
+
function collectStoreInvariantViolations(nodes) {
|
|
2632
|
+
const violations = [];
|
|
2633
|
+
for (const [id, node] of nodes) {
|
|
2634
|
+
if (node.type === "__root__") continue;
|
|
2635
|
+
if (node.children.length > 1) {
|
|
2636
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2637
|
+
for (const childId of node.children) {
|
|
2638
|
+
if (seen.has(childId)) {
|
|
2639
|
+
violations.push(`duplicate child id:${id}:${childId}`);
|
|
2640
|
+
} else {
|
|
2641
|
+
seen.add(childId);
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
if (node.type === "list") {
|
|
2646
|
+
const parent = node.parentId ? nodes.get(node.parentId) : void 0;
|
|
2647
|
+
if (parent?.type === "list-item" && node.children.length === 0) {
|
|
2648
|
+
violations.push(`empty nested list:${id}`);
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
if (node.type === "code") {
|
|
2652
|
+
for (let index = 0; index < node.children.length; index += 1) {
|
|
2653
|
+
const childId = node.children[index];
|
|
2654
|
+
const child = nodes.get(childId);
|
|
2655
|
+
if (!child) {
|
|
2656
|
+
violations.push(`missing code-line node:${node.id}:${childId}`);
|
|
2657
|
+
continue;
|
|
2658
|
+
}
|
|
2659
|
+
if (child.type !== "code-line") {
|
|
2660
|
+
violations.push(`non-code child in code block:${node.id}:${child.id}:${child.type}`);
|
|
2661
|
+
continue;
|
|
2662
|
+
}
|
|
2663
|
+
const expectedId = expectedCodeLineId(node.id, index);
|
|
2664
|
+
if (child.id !== expectedId) {
|
|
2665
|
+
violations.push(`code-line id mismatch:${node.id}:${child.id}:${expectedId}`);
|
|
2666
|
+
}
|
|
2667
|
+
const indexProp = typeof child.props?.index === "number" ? child.props.index : null;
|
|
2668
|
+
if (indexProp !== index) {
|
|
2669
|
+
violations.push(`code-line index mismatch:${node.id}:${child.id}:${indexProp}:${index}`);
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
return violations;
|
|
2675
|
+
}
|
|
2676
|
+
function buildNodeFromSnapshot(map, snapshot, parentId, blockEpoch) {
|
|
2677
|
+
const record = {
|
|
2678
|
+
id: snapshot.id,
|
|
2679
|
+
type: snapshot.type,
|
|
2680
|
+
parentId,
|
|
2681
|
+
children: [],
|
|
2682
|
+
props: normalizeNodeProps(snapshot),
|
|
2683
|
+
meta: snapshot.meta ? { ...snapshot.meta } : void 0,
|
|
2684
|
+
range: snapshot.range ? { ...snapshot.range } : void 0,
|
|
2685
|
+
version: 0,
|
|
2686
|
+
blockEpoch,
|
|
2687
|
+
block: snapshotToBlock(snapshot) ?? void 0
|
|
2688
|
+
};
|
|
2689
|
+
if (record.type === "code") {
|
|
2690
|
+
applyCodeBlockMetadata(record);
|
|
2691
|
+
}
|
|
2692
|
+
map.set(record.id, record);
|
|
2693
|
+
const childSnapshots = ensureArray(snapshot.children);
|
|
2694
|
+
for (const child of childSnapshots) {
|
|
2695
|
+
const childRecord = buildNodeFromSnapshot(map, child, record.id, blockEpoch);
|
|
2696
|
+
record.children.push(childRecord.id);
|
|
2697
|
+
}
|
|
2698
|
+
return record;
|
|
2699
|
+
}
|
|
2700
|
+
function removeSubtree(map, id, touched) {
|
|
2701
|
+
const record = map.get(id);
|
|
2702
|
+
if (!record) return;
|
|
2703
|
+
const stack = [record];
|
|
2704
|
+
const affectedParents = /* @__PURE__ */ new Set();
|
|
2705
|
+
while (stack.length > 0) {
|
|
2706
|
+
const node = stack.pop();
|
|
2707
|
+
if (!node) {
|
|
2708
|
+
continue;
|
|
2709
|
+
}
|
|
2710
|
+
if (node.parentId) {
|
|
2711
|
+
const parent = map.get(node.parentId);
|
|
2712
|
+
if (parent) {
|
|
2713
|
+
const idx = parent.children.indexOf(node.id);
|
|
2714
|
+
if (idx !== -1) {
|
|
2715
|
+
parent.children.splice(idx, 1);
|
|
2716
|
+
parent.version++;
|
|
2717
|
+
touched.add(parent.id);
|
|
2718
|
+
affectedParents.add(parent.id);
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
map.delete(node.id);
|
|
2723
|
+
deleteSnapshotCacheEntry(map, node.id);
|
|
2724
|
+
touched.add(node.id);
|
|
2725
|
+
for (const childId of node.children) {
|
|
2726
|
+
const child = map.get(childId);
|
|
2727
|
+
if (child) stack.push(child);
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
for (const parentId of affectedParents) {
|
|
2731
|
+
const parent = map.get(parentId);
|
|
2732
|
+
if (parent && parent.type === "code") {
|
|
2733
|
+
normalizeCodeBlockChildren(map, parent, touched);
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
function convertNodeToBlocks(map, root) {
|
|
2738
|
+
const result = [];
|
|
2739
|
+
for (const childId of root.children) {
|
|
2740
|
+
const child = map.get(childId);
|
|
2741
|
+
if (!child || !child.block) continue;
|
|
2742
|
+
result.push(cloneBlock(child.block));
|
|
2743
|
+
}
|
|
2744
|
+
return result;
|
|
2745
|
+
}
|
|
2746
|
+
function resolveParent(map, path) {
|
|
2747
|
+
if (path.nodeId) {
|
|
2748
|
+
return map.get(path.nodeId);
|
|
2749
|
+
}
|
|
2750
|
+
if (path.blockId === PATCH_ROOT_ID) {
|
|
2751
|
+
return map.get(PATCH_ROOT_ID);
|
|
2752
|
+
}
|
|
2753
|
+
return map.get(path.blockId);
|
|
2754
|
+
}
|
|
2755
|
+
function insertSnapshotAt(map, parent, index, snapshot, touched, blockEpoch) {
|
|
2756
|
+
if (!parent) return null;
|
|
2757
|
+
const existingIndex = parent.children.indexOf(snapshot.id);
|
|
2758
|
+
if (existingIndex !== -1) {
|
|
2759
|
+
removeSubtree(map, parent.children[existingIndex], touched ?? /* @__PURE__ */ new Set());
|
|
2760
|
+
}
|
|
2761
|
+
const record = buildNodeFromSnapshot(map, snapshot, parent.id, blockEpoch ?? readSnapshotBlockEpoch(snapshot) ?? parent.blockEpoch);
|
|
2762
|
+
const insertedIds = [];
|
|
2763
|
+
const queue = [record];
|
|
2764
|
+
while (queue.length > 0) {
|
|
2765
|
+
const node = queue.pop();
|
|
2766
|
+
if (!node) continue;
|
|
2767
|
+
insertedIds.push(node.id);
|
|
2768
|
+
for (const childId of node.children) {
|
|
2769
|
+
const child = map.get(childId);
|
|
2770
|
+
if (child) queue.push(child);
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
const clampedIndex = Math.min(Math.max(index, 0), parent.children.length);
|
|
2774
|
+
parent.children.splice(clampedIndex, 0, record.id);
|
|
2775
|
+
parent.version++;
|
|
2776
|
+
ensureUniqueChildren(parent, touched);
|
|
2777
|
+
return { record, insertedIds };
|
|
2778
|
+
}
|
|
2779
|
+
function replaceSnapshotAt(map, parent, index, snapshot, touched, blockEpoch) {
|
|
2780
|
+
if (!parent) return;
|
|
2781
|
+
if (index < 0 || index >= parent.children.length) return;
|
|
2782
|
+
const targetId = parent.children[index];
|
|
2783
|
+
parent.children.splice(index, 1);
|
|
2784
|
+
removeSubtree(map, targetId, touched);
|
|
2785
|
+
const inserted = insertSnapshotAt(map, parent, index, snapshot, touched, blockEpoch);
|
|
2786
|
+
if (inserted) {
|
|
2787
|
+
for (const id of inserted.insertedIds) {
|
|
2788
|
+
touched.add(id);
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
if (parent.type === "code") {
|
|
2792
|
+
normalizeCodeBlockChildren(map, parent, touched);
|
|
2793
|
+
} else {
|
|
2794
|
+
ensureUniqueChildren(parent, touched);
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
function createRendererStore(initialBlocks = []) {
|
|
2798
|
+
let nodes = /* @__PURE__ */ new Map();
|
|
2799
|
+
let version = 0;
|
|
2800
|
+
let blocksCache = [];
|
|
2801
|
+
let blocksDirty = true;
|
|
2802
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2803
|
+
let notifyScheduled = false;
|
|
2804
|
+
let lastCoalescingMetrics = null;
|
|
2805
|
+
let invariantViolations = [];
|
|
2806
|
+
let transientDiagnostics = [];
|
|
2807
|
+
let nextBlockEpoch = 1;
|
|
2808
|
+
const debugCounters = {
|
|
2809
|
+
appendLineGuardRejected: 0,
|
|
2810
|
+
staleEpochRejected: 0,
|
|
2811
|
+
storeInvariantViolationCount: 0
|
|
2812
|
+
};
|
|
2813
|
+
const allocateBlockEpoch = (preferred) => {
|
|
2814
|
+
const resolved = readNumericEpoch(preferred);
|
|
2815
|
+
if (resolved !== void 0) {
|
|
2816
|
+
nextBlockEpoch = Math.max(nextBlockEpoch, resolved + 1);
|
|
2817
|
+
return resolved;
|
|
2818
|
+
}
|
|
2819
|
+
const epoch = nextBlockEpoch;
|
|
2820
|
+
nextBlockEpoch += 1;
|
|
2821
|
+
return epoch;
|
|
2822
|
+
};
|
|
2823
|
+
const getRaf = () => {
|
|
2824
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.requestAnimationFrame === "function") {
|
|
2825
|
+
return globalThis.requestAnimationFrame;
|
|
2826
|
+
}
|
|
2827
|
+
return null;
|
|
2828
|
+
};
|
|
2829
|
+
function scheduleNotify() {
|
|
2830
|
+
if (notifyScheduled) return;
|
|
2831
|
+
notifyScheduled = true;
|
|
2832
|
+
const raf = getRaf();
|
|
2833
|
+
if (raf) {
|
|
2834
|
+
raf(() => {
|
|
2835
|
+
notifyScheduled = false;
|
|
2836
|
+
notify();
|
|
2837
|
+
});
|
|
2838
|
+
} else {
|
|
2839
|
+
setTimeout(() => {
|
|
2840
|
+
notifyScheduled = false;
|
|
2841
|
+
notify();
|
|
2842
|
+
}, 0);
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
function notify() {
|
|
2846
|
+
for (const listener of listeners) {
|
|
2847
|
+
try {
|
|
2848
|
+
listener();
|
|
2849
|
+
} catch (error) {
|
|
2850
|
+
console.error("RendererStore listener failed", error);
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
function appendDiagnostic(message) {
|
|
2855
|
+
transientDiagnostics = [...transientDiagnostics, message];
|
|
2856
|
+
invariantViolations = [...invariantViolations, message];
|
|
2857
|
+
}
|
|
2858
|
+
function rebuildFromBlocks(blocks) {
|
|
2859
|
+
clearSnapshotCaches(nodes);
|
|
2860
|
+
nodes = /* @__PURE__ */ new Map();
|
|
2861
|
+
const root = createRootRecord();
|
|
2862
|
+
nodes.set(root.id, root);
|
|
2863
|
+
root.children = [];
|
|
2864
|
+
lastCoalescingMetrics = null;
|
|
2865
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
2866
|
+
const block = cloneBlock(blocks[i]);
|
|
2867
|
+
const snapshot = createBlockSnapshot(block);
|
|
2868
|
+
insertSnapshotAt(nodes, root, root.children.length, snapshot, void 0, allocateBlockEpoch(readSnapshotBlockEpoch(snapshot)));
|
|
2869
|
+
}
|
|
2870
|
+
normalizeAllListDepths(nodes, /* @__PURE__ */ new Set(), PATCH_ROOT_ID);
|
|
2871
|
+
transientDiagnostics = [];
|
|
2872
|
+
invariantViolations = collectStoreInvariantViolations(nodes);
|
|
2873
|
+
debugCounters.storeInvariantViolationCount += invariantViolations.length;
|
|
2874
|
+
version++;
|
|
2875
|
+
blocksDirty = true;
|
|
2876
|
+
scheduleNotify();
|
|
2877
|
+
}
|
|
2878
|
+
rebuildFromBlocks(initialBlocks);
|
|
2879
|
+
const store = {
|
|
2880
|
+
reset(nextBlocks) {
|
|
2881
|
+
rebuildFromBlocks(nextBlocks);
|
|
2882
|
+
},
|
|
2883
|
+
applyPatches(patches, options) {
|
|
2884
|
+
const touched = /* @__PURE__ */ new Set();
|
|
2885
|
+
if (!patches || patches.length === 0) {
|
|
2886
|
+
lastCoalescingMetrics = options?.metrics ?? null;
|
|
2887
|
+
return touched;
|
|
2888
|
+
}
|
|
2889
|
+
const perfEnabled = isPatchPerfDebugEnabled();
|
|
2890
|
+
const perfStart = perfEnabled ? getPerfNow() : 0;
|
|
2891
|
+
const opStats = perfEnabled ? {} : {};
|
|
2892
|
+
const setPropsByType = perfEnabled ? {} : {};
|
|
2893
|
+
const setPropsBySize = perfEnabled ? {} : {};
|
|
2894
|
+
let applyMs = 0;
|
|
2895
|
+
let listNormalizeMs = 0;
|
|
2896
|
+
let coalescedPatches = patches;
|
|
2897
|
+
let metrics = options?.metrics ?? null;
|
|
2898
|
+
if (!options?.coalesced) {
|
|
2899
|
+
const result = coalescePatchesWithMetrics(patches, DEFAULT_COALESCE_CONFIG);
|
|
2900
|
+
coalescedPatches = result.patches;
|
|
2901
|
+
metrics = result.metrics;
|
|
2902
|
+
}
|
|
2903
|
+
lastCoalescingMetrics = metrics;
|
|
2904
|
+
const root = nodes.get(PATCH_ROOT_ID);
|
|
2905
|
+
if (!root) {
|
|
2906
|
+
nodes.set(PATCH_ROOT_ID, createRootRecord());
|
|
2907
|
+
}
|
|
2908
|
+
let mutatedBlocks = false;
|
|
2909
|
+
let listDepthDirty = false;
|
|
2910
|
+
const listDepthDirtyNodes = /* @__PURE__ */ new Set();
|
|
2911
|
+
const debugListPatches = isListPatchDebugEnabled();
|
|
2912
|
+
const isListRelated = (type) => type === "list" || type === "list-item";
|
|
2913
|
+
const logListPatch = (label, details) => {
|
|
2914
|
+
if (!debugListPatches) return;
|
|
2915
|
+
try {
|
|
2916
|
+
console.debug(`[list-patch] ${label}`, details);
|
|
2917
|
+
} catch {
|
|
2918
|
+
}
|
|
2919
|
+
};
|
|
2920
|
+
const findNearestListNode = (nodeId) => {
|
|
2921
|
+
if (!nodeId) return void 0;
|
|
2922
|
+
let current = nodes.get(nodeId);
|
|
2923
|
+
while (current) {
|
|
2924
|
+
if (current.type === "list") return current;
|
|
2925
|
+
if (!current.parentId) return void 0;
|
|
2926
|
+
current = nodes.get(current.parentId);
|
|
2927
|
+
}
|
|
2928
|
+
return void 0;
|
|
2929
|
+
};
|
|
2930
|
+
const markListDepthDirty = (nodeId) => {
|
|
2931
|
+
const listNode = findNearestListNode(nodeId);
|
|
2932
|
+
if (listNode) {
|
|
2933
|
+
listDepthDirtyNodes.add(listNode.id);
|
|
2934
|
+
} else {
|
|
2935
|
+
listDepthDirty = true;
|
|
2936
|
+
}
|
|
2937
|
+
};
|
|
2938
|
+
const semanticTxEpochs = /* @__PURE__ */ new Map();
|
|
2939
|
+
const resolveBlockEpochTarget = (patch, at) => {
|
|
2940
|
+
if ((patch.op === "insertChild" || patch.op === "replaceChild") && at.blockId === PATCH_ROOT_ID) {
|
|
2941
|
+
const nodeId = patch.node?.id;
|
|
2942
|
+
return nodeId ? nodes.get(nodeId) : void 0;
|
|
2943
|
+
}
|
|
2944
|
+
return nodes.get(at.blockId) ?? (at.nodeId ? nodes.get(at.nodeId) : void 0);
|
|
2945
|
+
};
|
|
2946
|
+
const rejectStaleEpochPatch = (patch, at) => {
|
|
2947
|
+
const expectedBlockEpoch = readPatchBlockEpoch(patch);
|
|
2948
|
+
const patchTx = readPatchTx(patch);
|
|
2949
|
+
if (expectedBlockEpoch === void 0) {
|
|
2950
|
+
return false;
|
|
2951
|
+
}
|
|
2952
|
+
if (getPatchKind(patch) !== "semantic" || !at) {
|
|
2953
|
+
return false;
|
|
2954
|
+
}
|
|
2955
|
+
const target = resolveBlockEpochTarget(patch, at);
|
|
2956
|
+
if (!target || target.blockEpoch === expectedBlockEpoch) {
|
|
2957
|
+
return false;
|
|
2958
|
+
}
|
|
2959
|
+
const txEpoch = at.blockId && patchTx !== void 0 ? semanticTxEpochs.get(at.blockId) : void 0;
|
|
2960
|
+
if (txEpoch && txEpoch.tx === patchTx && txEpoch.blockEpoch === target.blockEpoch) {
|
|
2961
|
+
return false;
|
|
2962
|
+
}
|
|
2963
|
+
debugCounters.staleEpochRejected += 1;
|
|
2964
|
+
appendDiagnostic(
|
|
2965
|
+
`stale epoch rejected:${patch.op}:${target.id}:expected=${expectedBlockEpoch}:actual=${target.blockEpoch}`
|
|
2966
|
+
);
|
|
2967
|
+
return true;
|
|
2968
|
+
};
|
|
2969
|
+
const advanceBlockEpoch = (blockId, touchedSet, preferredEpoch, tx) => {
|
|
2970
|
+
if (!blockId || blockId === PATCH_ROOT_ID) {
|
|
2971
|
+
return null;
|
|
2972
|
+
}
|
|
2973
|
+
const blockRoot = nodes.get(blockId);
|
|
2974
|
+
if (!blockRoot) {
|
|
2975
|
+
return null;
|
|
2976
|
+
}
|
|
2977
|
+
const nextEpoch = allocateBlockEpoch(preferredEpoch);
|
|
2978
|
+
assignSubtreeBlockEpoch(nodes, blockRoot.id, nextEpoch, touchedSet);
|
|
2979
|
+
if (tx !== void 0) {
|
|
2980
|
+
semanticTxEpochs.set(blockRoot.id, { tx, blockEpoch: nextEpoch });
|
|
2981
|
+
}
|
|
2982
|
+
return nextEpoch;
|
|
2983
|
+
};
|
|
2984
|
+
const applyPropsUpdate = (at, props, preferredEpoch, tx, semanticUpdate = false) => {
|
|
2985
|
+
const perfStartLocal = perfEnabled ? getPerfNow() : 0;
|
|
2986
|
+
const targetId = at.nodeId ?? at.blockId;
|
|
2987
|
+
if (!targetId) return;
|
|
2988
|
+
let target = nodes.get(targetId);
|
|
2989
|
+
if (!target) return;
|
|
2990
|
+
const parentType = target.parentId ? nodes.get(target.parentId)?.type : void 0;
|
|
2991
|
+
if (debugListPatches && (isListRelated(target.type) || isListRelated(parentType))) {
|
|
2992
|
+
logListPatch("setProps", {
|
|
2993
|
+
id: target.id,
|
|
2994
|
+
type: target.type,
|
|
2995
|
+
parentType,
|
|
2996
|
+
keys: props ? Object.keys(props) : []
|
|
2997
|
+
});
|
|
2998
|
+
}
|
|
2999
|
+
let propsChanged = false;
|
|
3000
|
+
if (target.type === "code-line") {
|
|
3001
|
+
const incoming = {
|
|
3002
|
+
index: props?.index,
|
|
3003
|
+
text: props?.text,
|
|
3004
|
+
html: props?.html
|
|
3005
|
+
};
|
|
3006
|
+
if (Object.prototype.hasOwnProperty.call(props ?? {}, "tokens")) {
|
|
3007
|
+
incoming.tokens = props.tokens;
|
|
3008
|
+
}
|
|
3009
|
+
const normalized = normalizeCodeLineProps(incoming, target.props);
|
|
3010
|
+
if (normalized !== target.props) {
|
|
3011
|
+
target.props = normalized;
|
|
3012
|
+
propsChanged = true;
|
|
3013
|
+
}
|
|
3014
|
+
if (propsChanged) {
|
|
3015
|
+
if (semanticUpdate) {
|
|
3016
|
+
advanceBlockEpoch(at.blockId, touched, preferredEpoch, tx);
|
|
3017
|
+
}
|
|
3018
|
+
target.version++;
|
|
3019
|
+
touched.add(target.id);
|
|
3020
|
+
const parent = target.parentId ? nodes.get(target.parentId) : void 0;
|
|
3021
|
+
if (parent) {
|
|
3022
|
+
parent.version++;
|
|
3023
|
+
touched.add(parent.id);
|
|
3024
|
+
if (parent.type === "code") {
|
|
3025
|
+
normalizeCodeBlockChildren(nodes, parent, touched);
|
|
3026
|
+
}
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
if (perfEnabled) {
|
|
3030
|
+
const duration = getPerfNow() - perfStartLocal;
|
|
3031
|
+
const typeKey = target.type || "unknown";
|
|
3032
|
+
const sizeKey = bucketBySize(estimatePropsSize(props, void 0));
|
|
3033
|
+
const typeEntry = setPropsByType[typeKey] ?? { count: 0, durationMs: 0 };
|
|
3034
|
+
typeEntry.count += 1;
|
|
3035
|
+
typeEntry.durationMs += duration;
|
|
3036
|
+
setPropsByType[typeKey] = typeEntry;
|
|
3037
|
+
const sizeEntry = setPropsBySize[sizeKey] ?? { count: 0, durationMs: 0 };
|
|
3038
|
+
sizeEntry.count += 1;
|
|
3039
|
+
sizeEntry.durationMs += duration;
|
|
3040
|
+
setPropsBySize[sizeKey] = sizeEntry;
|
|
3041
|
+
}
|
|
3042
|
+
return;
|
|
3043
|
+
} else if (isInlineSegmentType(target.type)) {
|
|
3044
|
+
const nextProps = props ? { ...props } : {};
|
|
3045
|
+
if ("block" in nextProps) {
|
|
3046
|
+
delete nextProps.block;
|
|
3047
|
+
}
|
|
3048
|
+
const mergedSegments = mergeInlineSegmentProps(target.props, nextProps);
|
|
3049
|
+
if (!shallowEqualRecords(target.props, mergedSegments)) {
|
|
3050
|
+
target.props = mergedSegments;
|
|
3051
|
+
propsChanged = true;
|
|
3052
|
+
}
|
|
3053
|
+
} else {
|
|
3054
|
+
const nextProps = props ? { ...props } : {};
|
|
3055
|
+
if ("block" in nextProps) {
|
|
3056
|
+
delete nextProps.block;
|
|
3057
|
+
}
|
|
3058
|
+
const base = target.props ? { ...target.props } : {};
|
|
3059
|
+
let localChanged = false;
|
|
3060
|
+
if (Object.prototype.hasOwnProperty.call(base, "block")) {
|
|
3061
|
+
delete base.block;
|
|
3062
|
+
localChanged = true;
|
|
3063
|
+
}
|
|
3064
|
+
for (const [key, value] of Object.entries(nextProps)) {
|
|
3065
|
+
if (value === void 0) {
|
|
3066
|
+
if (Object.prototype.hasOwnProperty.call(base, key)) {
|
|
3067
|
+
delete base[key];
|
|
3068
|
+
localChanged = true;
|
|
3069
|
+
}
|
|
3070
|
+
} else if (base[key] !== value) {
|
|
3071
|
+
base[key] = value;
|
|
3072
|
+
localChanged = true;
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
if (localChanged) {
|
|
3076
|
+
target.props = base;
|
|
3077
|
+
propsChanged = true;
|
|
3078
|
+
}
|
|
3079
|
+
}
|
|
3080
|
+
let blockChanged = false;
|
|
3081
|
+
let typeChanged = false;
|
|
3082
|
+
let rebuiltFromFinalizedBlock = false;
|
|
3083
|
+
let blockEpochAdvanced = false;
|
|
3084
|
+
const incomingBlock = props?.block;
|
|
3085
|
+
if (incomingBlock && typeof incomingBlock === "object") {
|
|
3086
|
+
target.block = cloneBlock(incomingBlock);
|
|
3087
|
+
const previousType = target.type;
|
|
3088
|
+
const incomingType = typeof target.block.type === "string" ? target.block.type : target.type;
|
|
3089
|
+
if (incomingType !== target.type) {
|
|
3090
|
+
target.type = incomingType;
|
|
3091
|
+
typeChanged = true;
|
|
3092
|
+
if (isListRelated(previousType) || isListRelated(target.type)) {
|
|
3093
|
+
markListDepthDirty(target.id);
|
|
3094
|
+
}
|
|
3095
|
+
}
|
|
3096
|
+
if (target.type === "code") {
|
|
3097
|
+
applyCodeBlockMetadata(target);
|
|
3098
|
+
}
|
|
3099
|
+
if (semanticUpdate) {
|
|
3100
|
+
advanceBlockEpoch(at.blockId, touched, preferredEpoch, tx);
|
|
3101
|
+
blockEpochAdvanced = true;
|
|
3102
|
+
}
|
|
3103
|
+
const shouldRebuildFinalizedTree = !at.nodeId && target.id === at.blockId && Boolean(target.block?.isFinalized) && target.type !== "code" && Boolean(target.parentId);
|
|
3104
|
+
if (shouldRebuildFinalizedTree) {
|
|
3105
|
+
const parent = target.parentId ? nodes.get(target.parentId) : void 0;
|
|
3106
|
+
const index = parent ? parent.children.indexOf(target.id) : -1;
|
|
3107
|
+
if (parent && index !== -1) {
|
|
3108
|
+
const snapshot = createBlockSnapshot(cloneBlock(target.block));
|
|
3109
|
+
replaceSnapshotAt(nodes, parent, index, snapshot, touched, target.blockEpoch);
|
|
3110
|
+
mutatedBlocks = true;
|
|
3111
|
+
blockChanged = true;
|
|
3112
|
+
rebuiltFromFinalizedBlock = true;
|
|
3113
|
+
const rebuilt = nodes.get(target.id);
|
|
3114
|
+
if (isListRelated(previousType) || isListRelated(rebuilt?.type)) {
|
|
3115
|
+
markListDepthDirty(target.id);
|
|
3116
|
+
}
|
|
3117
|
+
target = rebuilt ?? target;
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
mutatedBlocks = true;
|
|
3121
|
+
blockChanged = true;
|
|
3122
|
+
}
|
|
3123
|
+
if (rebuiltFromFinalizedBlock) {
|
|
3124
|
+
return;
|
|
3125
|
+
}
|
|
3126
|
+
if (propsChanged || blockChanged || typeChanged) {
|
|
3127
|
+
if (semanticUpdate && !blockEpochAdvanced) {
|
|
3128
|
+
advanceBlockEpoch(at.blockId, touched, preferredEpoch, tx);
|
|
3129
|
+
blockEpochAdvanced = true;
|
|
3130
|
+
}
|
|
3131
|
+
target.version++;
|
|
3132
|
+
touched.add(target.id);
|
|
3133
|
+
let parentForNormalization;
|
|
3134
|
+
if (target.parentId) {
|
|
3135
|
+
const parent = nodes.get(target.parentId);
|
|
3136
|
+
if (parent) {
|
|
3137
|
+
if (target.type === "code-line") {
|
|
3138
|
+
parent.version++;
|
|
3139
|
+
touched.add(parent.id);
|
|
3140
|
+
}
|
|
3141
|
+
if (parent.type === "code") {
|
|
3142
|
+
parentForNormalization = parent;
|
|
3143
|
+
}
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
if (target.type === "code") {
|
|
3147
|
+
normalizeCodeBlockChildren(nodes, target, touched);
|
|
3148
|
+
} else if (parentForNormalization) {
|
|
3149
|
+
normalizeCodeBlockChildren(nodes, parentForNormalization, touched);
|
|
3150
|
+
}
|
|
3151
|
+
const parentType2 = target.parentId ? nodes.get(target.parentId)?.type : void 0;
|
|
3152
|
+
if (isListRelated(target.type) || isListRelated(parentType2)) {
|
|
3153
|
+
markListDepthDirty(target.id);
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
if (perfEnabled) {
|
|
3157
|
+
const duration = getPerfNow() - perfStartLocal;
|
|
3158
|
+
const typeKey = target.type || "unknown";
|
|
3159
|
+
const sizeKey = bucketBySize(estimatePropsSize(props, incomingBlock && typeof incomingBlock === "object" ? incomingBlock : void 0));
|
|
3160
|
+
const typeEntry = setPropsByType[typeKey] ?? { count: 0, durationMs: 0 };
|
|
3161
|
+
typeEntry.count += 1;
|
|
3162
|
+
typeEntry.durationMs += duration;
|
|
3163
|
+
setPropsByType[typeKey] = typeEntry;
|
|
3164
|
+
const sizeEntry = setPropsBySize[sizeKey] ?? { count: 0, durationMs: 0 };
|
|
3165
|
+
sizeEntry.count += 1;
|
|
3166
|
+
sizeEntry.durationMs += duration;
|
|
3167
|
+
setPropsBySize[sizeKey] = sizeEntry;
|
|
3168
|
+
}
|
|
3169
|
+
};
|
|
3170
|
+
const applyPatch = (patch) => {
|
|
3171
|
+
switch (patch.op) {
|
|
3172
|
+
case "insertChild": {
|
|
3173
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3174
|
+
const parent = resolveParent(nodes, patch.at);
|
|
3175
|
+
const inserted = insertSnapshotAt(
|
|
3176
|
+
nodes,
|
|
3177
|
+
parent,
|
|
3178
|
+
patch.index,
|
|
3179
|
+
patch.node,
|
|
3180
|
+
touched,
|
|
3181
|
+
allocateBlockEpoch(readPatchParseEpoch(patch) ?? readSnapshotBlockEpoch(patch.node))
|
|
3182
|
+
);
|
|
3183
|
+
if (inserted) {
|
|
3184
|
+
for (const id of inserted.insertedIds) {
|
|
3185
|
+
touched.add(id);
|
|
3186
|
+
}
|
|
3187
|
+
mutatedBlocks = true;
|
|
3188
|
+
advanceBlockEpoch(patch.at.blockId, touched, readPatchParseEpoch(patch), readPatchTx(patch));
|
|
3189
|
+
if (isListRelated(inserted.record.type) || isListRelated(parent?.type)) {
|
|
3190
|
+
markListDepthDirty(inserted.record.id);
|
|
3191
|
+
if (parent) {
|
|
3192
|
+
markListDepthDirty(parent.id);
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
if (debugListPatches && (isListRelated(inserted.record.type) || isListRelated(parent?.type))) {
|
|
3196
|
+
logListPatch("insertChild", {
|
|
3197
|
+
id: inserted.record.id,
|
|
3198
|
+
type: inserted.record.type,
|
|
3199
|
+
parentId: parent?.id,
|
|
3200
|
+
parentType: parent?.type,
|
|
3201
|
+
index: patch.index
|
|
3202
|
+
});
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
break;
|
|
3206
|
+
}
|
|
3207
|
+
case "deleteChild": {
|
|
3208
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3209
|
+
const parent = resolveParent(nodes, patch.at);
|
|
3210
|
+
if (!parent) break;
|
|
3211
|
+
if (patch.index < 0 || patch.index >= parent.children.length) break;
|
|
3212
|
+
const childId = parent.children.splice(patch.index, 1)[0];
|
|
3213
|
+
if (childId) {
|
|
3214
|
+
const removedNode = nodes.get(childId);
|
|
3215
|
+
removeSubtree(nodes, childId, touched);
|
|
3216
|
+
parent.version++;
|
|
3217
|
+
touched.add(parent.id);
|
|
3218
|
+
ensureUniqueChildren(parent, touched);
|
|
3219
|
+
mutatedBlocks = true;
|
|
3220
|
+
advanceBlockEpoch(patch.at.blockId, touched, readPatchParseEpoch(patch), readPatchTx(patch));
|
|
3221
|
+
if (isListRelated(parent.type) || isListRelated(removedNode?.type)) {
|
|
3222
|
+
markListDepthDirty(parent.id);
|
|
3223
|
+
}
|
|
3224
|
+
if (debugListPatches && (isListRelated(parent.type) || isListRelated(removedNode?.type))) {
|
|
3225
|
+
logListPatch("deleteChild", {
|
|
3226
|
+
id: childId,
|
|
3227
|
+
type: removedNode?.type,
|
|
3228
|
+
parentId: parent.id,
|
|
3229
|
+
parentType: parent.type,
|
|
3230
|
+
index: patch.index
|
|
3231
|
+
});
|
|
3232
|
+
}
|
|
3233
|
+
}
|
|
3234
|
+
break;
|
|
3235
|
+
}
|
|
3236
|
+
case "replaceChild": {
|
|
3237
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3238
|
+
const parent = resolveParent(nodes, patch.at);
|
|
3239
|
+
if (!parent) break;
|
|
3240
|
+
replaceSnapshotAt(
|
|
3241
|
+
nodes,
|
|
3242
|
+
parent,
|
|
3243
|
+
patch.index,
|
|
3244
|
+
patch.node,
|
|
3245
|
+
touched,
|
|
3246
|
+
allocateBlockEpoch(readPatchParseEpoch(patch) ?? readSnapshotBlockEpoch(patch.node))
|
|
3247
|
+
);
|
|
3248
|
+
touched.add(parent.id);
|
|
3249
|
+
mutatedBlocks = true;
|
|
3250
|
+
advanceBlockEpoch(patch.at.blockId, touched, readPatchParseEpoch(patch), readPatchTx(patch));
|
|
3251
|
+
if (isListRelated(parent.type)) {
|
|
3252
|
+
markListDepthDirty(parent.id);
|
|
3253
|
+
}
|
|
3254
|
+
if (debugListPatches && isListRelated(parent.type)) {
|
|
3255
|
+
logListPatch("replaceChild", {
|
|
3256
|
+
parentId: parent.id,
|
|
3257
|
+
parentType: parent.type,
|
|
3258
|
+
index: patch.index
|
|
3259
|
+
});
|
|
3260
|
+
}
|
|
3261
|
+
break;
|
|
3262
|
+
}
|
|
3263
|
+
case "setProps": {
|
|
3264
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3265
|
+
applyPropsUpdate(patch.at, patch.props, readPatchParseEpoch(patch), readPatchTx(patch), getPatchKind(patch) === "semantic");
|
|
3266
|
+
break;
|
|
3267
|
+
}
|
|
3268
|
+
case "setPropsBatch": {
|
|
3269
|
+
const entries2 = Array.isArray(patch.entries) ? patch.entries : [];
|
|
3270
|
+
for (const entry of entries2) {
|
|
3271
|
+
if (!entry || !entry.at) continue;
|
|
3272
|
+
const entryPatch = {
|
|
3273
|
+
op: "setProps",
|
|
3274
|
+
at: entry.at,
|
|
3275
|
+
props: entry.props,
|
|
3276
|
+
meta: entry.meta ?? patch.meta
|
|
3277
|
+
};
|
|
3278
|
+
if (rejectStaleEpochPatch(entryPatch, entry.at)) continue;
|
|
3279
|
+
applyPropsUpdate(
|
|
3280
|
+
entry.at,
|
|
3281
|
+
entry.props,
|
|
3282
|
+
readPatchParseEpoch(entryPatch),
|
|
3283
|
+
readPatchTx(entryPatch),
|
|
3284
|
+
getPatchKind(entryPatch) === "semantic"
|
|
3285
|
+
);
|
|
3286
|
+
}
|
|
3287
|
+
break;
|
|
3288
|
+
}
|
|
3289
|
+
case "finalize": {
|
|
3290
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3291
|
+
const target = nodes.get(patch.at.nodeId ?? patch.at.blockId);
|
|
3292
|
+
if (!target || !target.block) break;
|
|
3293
|
+
if (!target.block.isFinalized) {
|
|
3294
|
+
target.block = cloneBlock(target.block);
|
|
3295
|
+
target.block.isFinalized = true;
|
|
3296
|
+
target.version++;
|
|
3297
|
+
touched.add(target.id);
|
|
3298
|
+
mutatedBlocks = true;
|
|
3299
|
+
if (!patch.at.nodeId && target.id === patch.at.blockId && target.type !== "code" && target.parentId) {
|
|
3300
|
+
const parent = nodes.get(target.parentId);
|
|
3301
|
+
const index = parent ? parent.children.indexOf(target.id) : -1;
|
|
3302
|
+
if (parent && index !== -1) {
|
|
3303
|
+
const snapshot = createBlockSnapshot(cloneBlock(target.block));
|
|
3304
|
+
replaceSnapshotAt(nodes, parent, index, snapshot, touched, target.blockEpoch);
|
|
3305
|
+
if (isListRelated(target.type) || isListRelated(snapshot.type)) {
|
|
3306
|
+
markListDepthDirty(target.id);
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
}
|
|
3311
|
+
if (isListRelated(target.type)) {
|
|
3312
|
+
markListDepthDirty(target.id);
|
|
3313
|
+
}
|
|
3314
|
+
if (debugListPatches && isListRelated(target.type)) {
|
|
3315
|
+
logListPatch("finalize", {
|
|
3316
|
+
id: target.id,
|
|
3317
|
+
type: target.type
|
|
3318
|
+
});
|
|
3319
|
+
}
|
|
3320
|
+
break;
|
|
3321
|
+
}
|
|
3322
|
+
case "reorder": {
|
|
3323
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3324
|
+
const parent = resolveParent(nodes, patch.at);
|
|
3325
|
+
if (!parent) break;
|
|
3326
|
+
const length = parent.children.length;
|
|
3327
|
+
if (length === 0 || patch.count <= 0) break;
|
|
3328
|
+
const from = clampIndex(patch.from, length - 1);
|
|
3329
|
+
const count = Math.max(1, Math.min(patch.count, length - from));
|
|
3330
|
+
let to = clampIndex(patch.to, length);
|
|
3331
|
+
if (to > from) {
|
|
3332
|
+
to = Math.max(0, to - count);
|
|
3333
|
+
}
|
|
3334
|
+
const moved = parent.children.splice(from, count);
|
|
3335
|
+
parent.children.splice(to, 0, ...moved);
|
|
3336
|
+
parent.version++;
|
|
3337
|
+
touched.add(parent.id);
|
|
3338
|
+
if (getPatchKind(patch) === "semantic") {
|
|
3339
|
+
advanceBlockEpoch(patch.at.blockId, touched, readPatchParseEpoch(patch), readPatchTx(patch));
|
|
3340
|
+
}
|
|
3341
|
+
if (isListRelated(parent.type)) {
|
|
3342
|
+
markListDepthDirty(parent.id);
|
|
3343
|
+
}
|
|
3344
|
+
if (debugListPatches && isListRelated(parent.type)) {
|
|
3345
|
+
logListPatch("reorder", {
|
|
3346
|
+
parentId: parent.id,
|
|
3347
|
+
parentType: parent.type,
|
|
3348
|
+
from: patch.from,
|
|
3349
|
+
to: patch.to,
|
|
3350
|
+
count: patch.count
|
|
3351
|
+
});
|
|
3352
|
+
}
|
|
3353
|
+
break;
|
|
3354
|
+
}
|
|
3355
|
+
case "appendLines": {
|
|
3356
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3357
|
+
const parent = resolveParent(nodes, patch.at);
|
|
3358
|
+
if (!parent) break;
|
|
3359
|
+
if (parent.type !== "code") {
|
|
3360
|
+
debugCounters.appendLineGuardRejected += 1;
|
|
3361
|
+
appendDiagnostic(`appendLines target not code:${parent.id}:${parent.type}`);
|
|
3362
|
+
break;
|
|
3363
|
+
}
|
|
3364
|
+
const requestedStartIndex = Math.max(0, patch.startIndex);
|
|
3365
|
+
const startIndex = Math.max(0, Math.min(requestedStartIndex, parent.children.length));
|
|
3366
|
+
const lineCount = patch.lines?.length ?? 0;
|
|
3367
|
+
if (lineCount === 0) break;
|
|
3368
|
+
const prefixMatches = parent.children.every((childId, index) => childId === expectedCodeLineId(parent.id, index));
|
|
3369
|
+
const isStrictTailAppend = requestedStartIndex === parent.children.length;
|
|
3370
|
+
if (!isStrictTailAppend || !prefixMatches) {
|
|
3371
|
+
debugCounters.appendLineGuardRejected += 1;
|
|
3372
|
+
appendDiagnostic(
|
|
3373
|
+
`appendLines guard rejected:${parent.id}:requestedStart=${requestedStartIndex}:childCount=${parent.children.length}:prefixMatches=${prefixMatches}`
|
|
3374
|
+
);
|
|
3375
|
+
break;
|
|
3376
|
+
}
|
|
3377
|
+
const originalChildren = parent.children.slice();
|
|
3378
|
+
const insertedIds = [];
|
|
3379
|
+
const insertedSet = /* @__PURE__ */ new Set();
|
|
3380
|
+
const isTrailingAppend = true;
|
|
3381
|
+
let parentChildrenChanged = false;
|
|
3382
|
+
let codeLinesMutated = false;
|
|
3383
|
+
for (let offset = 0; offset < lineCount; offset++) {
|
|
3384
|
+
const absoluteIndex = startIndex + offset;
|
|
3385
|
+
const lineId = `${parent.id}::line:${absoluteIndex}`;
|
|
3386
|
+
insertedIds.push(lineId);
|
|
3387
|
+
insertedSet.add(lineId);
|
|
3388
|
+
const hasTokens = Object.prototype.hasOwnProperty.call(patch, "tokens");
|
|
3389
|
+
const nextTokens = hasTokens ? patch.tokens?.[offset] ?? null : void 0;
|
|
3390
|
+
const nextLineProps = createCodeLineProps(
|
|
3391
|
+
absoluteIndex,
|
|
3392
|
+
patch.lines[offset] ?? "",
|
|
3393
|
+
patch.highlight?.[offset] ?? null,
|
|
3394
|
+
nextTokens
|
|
3395
|
+
);
|
|
3396
|
+
const existing = nodes.get(lineId);
|
|
3397
|
+
if (existing && existing.type === "code-line") {
|
|
3398
|
+
const existingIndex = parent.children.indexOf(lineId);
|
|
3399
|
+
if (existingIndex !== -1) {
|
|
3400
|
+
parent.children.splice(existingIndex, 1);
|
|
3401
|
+
parentChildrenChanged = true;
|
|
3402
|
+
}
|
|
3403
|
+
if (existing.parentId !== parent.id) {
|
|
3404
|
+
existing.parentId = parent.id;
|
|
3405
|
+
existing.version++;
|
|
3406
|
+
touched.add(lineId);
|
|
3407
|
+
codeLinesMutated = true;
|
|
3408
|
+
}
|
|
3409
|
+
if (!shallowEqualRecords(existing.props, nextLineProps)) {
|
|
3410
|
+
existing.props = nextLineProps;
|
|
3411
|
+
existing.version++;
|
|
3412
|
+
touched.add(lineId);
|
|
3413
|
+
codeLinesMutated = true;
|
|
3414
|
+
}
|
|
3415
|
+
} else {
|
|
3416
|
+
const record = {
|
|
3417
|
+
id: lineId,
|
|
3418
|
+
type: "code-line",
|
|
3419
|
+
parentId: parent.id,
|
|
3420
|
+
children: [],
|
|
3421
|
+
props: nextLineProps,
|
|
3422
|
+
version: 0,
|
|
3423
|
+
blockEpoch: parent.blockEpoch
|
|
3424
|
+
};
|
|
3425
|
+
nodes.set(lineId, record);
|
|
3426
|
+
touched.add(lineId);
|
|
3427
|
+
codeLinesMutated = true;
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
if (insertedIds.length > 0) {
|
|
3431
|
+
let nextChildren;
|
|
3432
|
+
if (isTrailingAppend) {
|
|
3433
|
+
nextChildren = [...originalChildren, ...insertedIds];
|
|
3434
|
+
} else {
|
|
3435
|
+
const cleanedChildren = originalChildren.filter((childId) => !insertedSet.has(childId));
|
|
3436
|
+
const clampedStart = Math.max(0, Math.min(startIndex, cleanedChildren.length));
|
|
3437
|
+
nextChildren = [...cleanedChildren.slice(0, clampedStart), ...insertedIds, ...cleanedChildren.slice(clampedStart)];
|
|
3438
|
+
}
|
|
3439
|
+
if (!arraysEqual(originalChildren, nextChildren)) {
|
|
3440
|
+
parent.children = nextChildren;
|
|
3441
|
+
parentChildrenChanged = true;
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
if (!isTrailingAppend) {
|
|
3445
|
+
for (let idx = 0; idx < parent.children.length; idx++) {
|
|
3446
|
+
const childId = parent.children[idx];
|
|
3447
|
+
const child = nodes.get(childId);
|
|
3448
|
+
if (child && child.type === "code-line") {
|
|
3449
|
+
const incoming = { index: idx, text: child.props?.text, html: child.props?.html };
|
|
3450
|
+
if (Object.prototype.hasOwnProperty.call(child.props ?? {}, "tokens")) {
|
|
3451
|
+
incoming.tokens = child.props.tokens;
|
|
3452
|
+
}
|
|
3453
|
+
const normalized = normalizeCodeLineProps(incoming, child.props);
|
|
3454
|
+
if (normalized !== child.props) {
|
|
3455
|
+
child.props = normalized;
|
|
3456
|
+
child.version++;
|
|
3457
|
+
touched.add(child.id);
|
|
3458
|
+
codeLinesMutated = true;
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
}
|
|
3463
|
+
if (parentChildrenChanged || codeLinesMutated) {
|
|
3464
|
+
parent.version++;
|
|
3465
|
+
touched.add(parent.id);
|
|
3466
|
+
if (!isTrailingAppend) {
|
|
3467
|
+
normalizeCodeBlockChildren(nodes, parent, touched);
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
break;
|
|
3471
|
+
}
|
|
3472
|
+
case "setHTML": {
|
|
3473
|
+
if (rejectStaleEpochPatch(patch, patch.at)) break;
|
|
3474
|
+
const target = nodes.get(patch.at.nodeId ?? patch.at.blockId);
|
|
3475
|
+
if (!target) break;
|
|
3476
|
+
const sanitized = patch.sanitized ? patch.html : sanitizeHTML2(patch.html);
|
|
3477
|
+
target.props = {
|
|
3478
|
+
...target.props ?? {},
|
|
3479
|
+
html: sanitized,
|
|
3480
|
+
policy: patch.policy || "markdown-renderer-v2",
|
|
3481
|
+
meta: patch.meta ? { ...patch.meta } : target.props?.meta
|
|
3482
|
+
};
|
|
3483
|
+
if (patch.block) {
|
|
3484
|
+
target.block = cloneBlock(patch.block);
|
|
3485
|
+
if (!target.block.payload.meta) {
|
|
3486
|
+
target.block.payload.meta = {};
|
|
3487
|
+
}
|
|
3488
|
+
target.block.payload.sanitizedHtml = sanitized;
|
|
3489
|
+
mutatedBlocks = true;
|
|
3490
|
+
}
|
|
3491
|
+
target.version++;
|
|
3492
|
+
touched.add(target.id);
|
|
3493
|
+
break;
|
|
3494
|
+
}
|
|
3495
|
+
default:
|
|
3496
|
+
break;
|
|
3497
|
+
}
|
|
3498
|
+
};
|
|
3499
|
+
if (perfEnabled) {
|
|
3500
|
+
const loopStart = getPerfNow();
|
|
3501
|
+
for (const patch of coalescedPatches) {
|
|
3502
|
+
const opStart = getPerfNow();
|
|
3503
|
+
applyPatch(patch);
|
|
3504
|
+
const opDuration = getPerfNow() - opStart;
|
|
3505
|
+
const entry = opStats[patch.op] ?? { count: 0, durationMs: 0 };
|
|
3506
|
+
entry.count += 1;
|
|
3507
|
+
entry.durationMs += opDuration;
|
|
3508
|
+
opStats[patch.op] = entry;
|
|
3509
|
+
}
|
|
3510
|
+
applyMs = getPerfNow() - loopStart;
|
|
3511
|
+
} else {
|
|
3512
|
+
for (const patch of coalescedPatches) {
|
|
3513
|
+
applyPatch(patch);
|
|
3514
|
+
}
|
|
3515
|
+
}
|
|
3516
|
+
const finalizedTableRoots = /* @__PURE__ */ new Set();
|
|
3517
|
+
for (const touchedId of touched) {
|
|
3518
|
+
let cursor = nodes.get(touchedId);
|
|
3519
|
+
while (cursor && cursor.id !== PATCH_ROOT_ID) {
|
|
3520
|
+
if (cursor.type === "table" && cursor.block?.isFinalized && cursor.parentId) {
|
|
3521
|
+
finalizedTableRoots.add(cursor.id);
|
|
3522
|
+
break;
|
|
3523
|
+
}
|
|
3524
|
+
cursor = cursor.parentId ? nodes.get(cursor.parentId) : void 0;
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
if (finalizedTableRoots.size > 0) {
|
|
3528
|
+
for (const tableId of finalizedTableRoots) {
|
|
3529
|
+
const tableNode = nodes.get(tableId);
|
|
3530
|
+
if (!tableNode || !tableNode.block || !tableNode.parentId) continue;
|
|
3531
|
+
const parent = nodes.get(tableNode.parentId);
|
|
3532
|
+
if (!parent) continue;
|
|
3533
|
+
const index = parent.children.indexOf(tableNode.id);
|
|
3534
|
+
if (index === -1) continue;
|
|
3535
|
+
const snapshot = createBlockSnapshot(cloneBlock(tableNode.block));
|
|
3536
|
+
replaceSnapshotAt(nodes, parent, index, snapshot, touched, tableNode.blockEpoch);
|
|
3537
|
+
mutatedBlocks = true;
|
|
3538
|
+
}
|
|
3539
|
+
}
|
|
3540
|
+
if (mutatedBlocks) {
|
|
3541
|
+
blocksDirty = true;
|
|
3542
|
+
}
|
|
3543
|
+
if (listDepthDirty) {
|
|
3544
|
+
if (perfEnabled) {
|
|
3545
|
+
const start = getPerfNow();
|
|
3546
|
+
normalizeAllListDepths(nodes, touched, PATCH_ROOT_ID);
|
|
3547
|
+
listNormalizeMs = getPerfNow() - start;
|
|
3548
|
+
} else {
|
|
3549
|
+
normalizeAllListDepths(nodes, touched, PATCH_ROOT_ID);
|
|
3550
|
+
}
|
|
3551
|
+
} else if (listDepthDirtyNodes.size > 0) {
|
|
3552
|
+
if (perfEnabled) {
|
|
3553
|
+
const start = getPerfNow();
|
|
3554
|
+
normalizeListDepthsForIds(nodes, touched, listDepthDirtyNodes, PATCH_ROOT_ID);
|
|
3555
|
+
listNormalizeMs = getPerfNow() - start;
|
|
3556
|
+
} else {
|
|
3557
|
+
normalizeListDepthsForIds(nodes, touched, listDepthDirtyNodes, PATCH_ROOT_ID);
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
invariantViolations = [...collectStoreInvariantViolations(nodes), ...transientDiagnostics];
|
|
3561
|
+
debugCounters.storeInvariantViolationCount += invariantViolations.length;
|
|
3562
|
+
if (touched.size > 0 || mutatedBlocks) {
|
|
3563
|
+
version++;
|
|
3564
|
+
scheduleNotify();
|
|
3565
|
+
}
|
|
3566
|
+
if (perfEnabled) {
|
|
3567
|
+
const totalMs = getPerfNow() - perfStart;
|
|
3568
|
+
const coalesceMs = typeof metrics?.durationMs === "number" ? metrics.durationMs : 0;
|
|
3569
|
+
recordPatchPerf({
|
|
3570
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3571
|
+
totalMs,
|
|
3572
|
+
applyMs,
|
|
3573
|
+
coalesceMs,
|
|
3574
|
+
listNormalizeMs,
|
|
3575
|
+
patches: patches.length,
|
|
3576
|
+
coalescedPatches: coalescedPatches.length,
|
|
3577
|
+
touchedCount: touched.size,
|
|
3578
|
+
mutatedBlocks,
|
|
3579
|
+
ops: opStats,
|
|
3580
|
+
setPropsByType,
|
|
3581
|
+
setPropsBySize
|
|
3582
|
+
});
|
|
3583
|
+
}
|
|
3584
|
+
return touched;
|
|
3585
|
+
},
|
|
3586
|
+
getBlocks() {
|
|
3587
|
+
if (!blocksDirty) {
|
|
3588
|
+
return blocksCache;
|
|
3589
|
+
}
|
|
3590
|
+
const root = nodes.get(PATCH_ROOT_ID);
|
|
3591
|
+
if (!root) {
|
|
3592
|
+
blocksCache = [];
|
|
3593
|
+
} else {
|
|
3594
|
+
blocksCache = convertNodeToBlocks(nodes, root);
|
|
3595
|
+
}
|
|
3596
|
+
blocksDirty = false;
|
|
3597
|
+
return blocksCache;
|
|
3598
|
+
},
|
|
3599
|
+
getVersion() {
|
|
3600
|
+
return version;
|
|
3601
|
+
},
|
|
3602
|
+
getNode(id) {
|
|
3603
|
+
return nodes.get(id);
|
|
3604
|
+
},
|
|
3605
|
+
getNodeWithVersion(id) {
|
|
3606
|
+
const record = nodes.get(id);
|
|
3607
|
+
if (!record) {
|
|
3608
|
+
return EMPTY_NODE_SNAPSHOT;
|
|
3609
|
+
}
|
|
3610
|
+
const nodeSnapshotCache = getNodeSnapshotCacheForMap(nodes);
|
|
3611
|
+
const cached = nodeSnapshotCache.get(id);
|
|
3612
|
+
if (cached && cached.version === record.version && cached.node === record) {
|
|
3613
|
+
return cached;
|
|
3614
|
+
}
|
|
3615
|
+
const snapshot = { version: record.version, node: record };
|
|
3616
|
+
nodeSnapshotCache.set(id, snapshot);
|
|
3617
|
+
pruneCache(nodeSnapshotCache, NODE_SNAPSHOT_CACHE_LIMIT, NODE_SNAPSHOT_CACHE_BUFFER);
|
|
3618
|
+
return snapshot;
|
|
3619
|
+
},
|
|
3620
|
+
getChildren(id) {
|
|
3621
|
+
const record = nodes.get(id);
|
|
3622
|
+
if (!record) return EMPTY_CHILDREN;
|
|
3623
|
+
return record.children;
|
|
3624
|
+
},
|
|
3625
|
+
getChildrenWithVersion(id) {
|
|
3626
|
+
const record = nodes.get(id);
|
|
3627
|
+
if (!record) {
|
|
3628
|
+
return EMPTY_CHILDREN_SNAPSHOT;
|
|
3629
|
+
}
|
|
3630
|
+
const childrenSnapshotCache = getChildrenSnapshotCacheForMap(nodes);
|
|
3631
|
+
const cached = childrenSnapshotCache.get(id);
|
|
3632
|
+
if (cached && cached.version === record.version) {
|
|
3633
|
+
return cached;
|
|
3634
|
+
}
|
|
3635
|
+
const snapshot = { version: record.version, children: record.children.slice() };
|
|
3636
|
+
childrenSnapshotCache.set(id, snapshot);
|
|
3637
|
+
pruneCache(childrenSnapshotCache, CHILDREN_SNAPSHOT_CACHE_LIMIT, CHILDREN_SNAPSHOT_CACHE_BUFFER);
|
|
3638
|
+
return snapshot;
|
|
3639
|
+
},
|
|
3640
|
+
getInvariantViolations() {
|
|
3641
|
+
return invariantViolations.slice();
|
|
3642
|
+
},
|
|
3643
|
+
getDebugCounters() {
|
|
3644
|
+
return { ...debugCounters };
|
|
3645
|
+
},
|
|
3646
|
+
getLastCoalescingMetrics() {
|
|
3647
|
+
return lastCoalescingMetrics;
|
|
3648
|
+
},
|
|
3649
|
+
subscribe(listener) {
|
|
3650
|
+
listeners.add(listener);
|
|
3651
|
+
return () => {
|
|
3652
|
+
listeners.delete(listener);
|
|
3653
|
+
};
|
|
3654
|
+
}
|
|
3655
|
+
};
|
|
3656
|
+
return store;
|
|
3657
|
+
}
|
|
3658
|
+
|
|
3659
|
+
// src/renderer/virtualized-code.tsx
|
|
3660
|
+
import { useCallback, useEffect as useEffect2, useMemo as useMemo2, useRef, useState as useState2 } from "react";
|
|
3661
|
+
var DEFAULT_VIRTUALIZED_CODE_CONFIG = {
|
|
3662
|
+
enabled: true,
|
|
3663
|
+
windowSize: 100,
|
|
3664
|
+
// Render 100 lines at a time
|
|
3665
|
+
bufferSize: 50,
|
|
3666
|
+
// +50 lines buffer above/below
|
|
3667
|
+
virtualizeThreshold: 200
|
|
3668
|
+
// Only virtualize if 200+ lines
|
|
3669
|
+
};
|
|
3670
|
+
function calculateCodeWindow(lines, scrollTop, containerHeight, lineHeight, config) {
|
|
3671
|
+
const totalLines = lines.length;
|
|
3672
|
+
if (!config.enabled || totalLines < config.virtualizeThreshold) {
|
|
3673
|
+
return {
|
|
3674
|
+
startIndex: 0,
|
|
3675
|
+
endIndex: totalLines,
|
|
3676
|
+
visibleStart: 0,
|
|
3677
|
+
visibleEnd: totalLines,
|
|
3678
|
+
visibleLines: lines,
|
|
3679
|
+
totalLines,
|
|
3680
|
+
mountedLines: totalLines
|
|
3681
|
+
};
|
|
3682
|
+
}
|
|
3683
|
+
const firstVisibleLine = Math.floor(scrollTop / lineHeight);
|
|
3684
|
+
const lastVisibleLine = Math.ceil((scrollTop + containerHeight) / lineHeight);
|
|
3685
|
+
const visibleStart = Math.max(0, firstVisibleLine);
|
|
3686
|
+
const visibleEnd = Math.min(totalLines, Math.max(visibleStart, lastVisibleLine));
|
|
3687
|
+
const startIndex = Math.max(0, visibleStart - config.bufferSize);
|
|
3688
|
+
const endIndex = Math.min(totalLines, visibleEnd + config.bufferSize);
|
|
3689
|
+
return {
|
|
3690
|
+
startIndex,
|
|
3691
|
+
endIndex,
|
|
3692
|
+
visibleStart,
|
|
3693
|
+
visibleEnd,
|
|
3694
|
+
visibleLines: lines.slice(startIndex, endIndex),
|
|
3695
|
+
totalLines,
|
|
3696
|
+
mountedLines: endIndex - startIndex
|
|
3697
|
+
};
|
|
3698
|
+
}
|
|
3699
|
+
function useVirtualizedCode(lines, config = DEFAULT_VIRTUALIZED_CODE_CONFIG) {
|
|
3700
|
+
const containerRef = useRef(null);
|
|
3701
|
+
const [scrollTop, setScrollTop] = useState2(0);
|
|
3702
|
+
const [containerHeight, setContainerHeight] = useState2(0);
|
|
3703
|
+
const lineHeightRef = useRef(20);
|
|
3704
|
+
useEffect2(() => {
|
|
3705
|
+
if (!containerRef.current || lines.length === 0) return;
|
|
3706
|
+
const timeoutId = setTimeout(() => {
|
|
3707
|
+
if (!containerRef.current) return;
|
|
3708
|
+
const firstLine = containerRef.current.querySelector(".line");
|
|
3709
|
+
if (firstLine) {
|
|
3710
|
+
const measuredHeight = firstLine.offsetHeight || 20;
|
|
3711
|
+
if (measuredHeight !== lineHeightRef.current) {
|
|
3712
|
+
lineHeightRef.current = measuredHeight;
|
|
3713
|
+
}
|
|
3714
|
+
}
|
|
3715
|
+
}, 0);
|
|
3716
|
+
return () => clearTimeout(timeoutId);
|
|
3717
|
+
}, [lines.length]);
|
|
3718
|
+
const handleScroll = useCallback((e) => {
|
|
3719
|
+
const target = e.currentTarget;
|
|
3720
|
+
setScrollTop(target.scrollTop);
|
|
3721
|
+
setContainerHeight(target.clientHeight);
|
|
3722
|
+
}, []);
|
|
3723
|
+
useEffect2(() => {
|
|
3724
|
+
if (!containerRef.current) return;
|
|
3725
|
+
const resizeObserver = new ResizeObserver((entries2) => {
|
|
3726
|
+
for (const entry of entries2) {
|
|
3727
|
+
setContainerHeight(entry.contentRect.height);
|
|
3728
|
+
}
|
|
3729
|
+
});
|
|
3730
|
+
resizeObserver.observe(containerRef.current);
|
|
3731
|
+
return () => resizeObserver.disconnect();
|
|
3732
|
+
}, []);
|
|
3733
|
+
const window2 = useMemo2(() => {
|
|
3734
|
+
return calculateCodeWindow(lines, scrollTop, containerHeight, lineHeightRef.current, config);
|
|
3735
|
+
}, [lines, scrollTop, containerHeight, config]);
|
|
3736
|
+
const scrollToLine = useCallback((lineIndex) => {
|
|
3737
|
+
if (!containerRef.current) return;
|
|
3738
|
+
const targetScrollTop = lineIndex * lineHeightRef.current;
|
|
3739
|
+
containerRef.current.scrollTop = targetScrollTop;
|
|
3740
|
+
setScrollTop(targetScrollTop);
|
|
3741
|
+
}, []);
|
|
3742
|
+
return {
|
|
3743
|
+
containerRef,
|
|
3744
|
+
window: window2,
|
|
3745
|
+
handleScroll,
|
|
3746
|
+
scrollToLine,
|
|
3747
|
+
lineHeight: lineHeightRef.current,
|
|
3748
|
+
config
|
|
3749
|
+
};
|
|
3750
|
+
}
|
|
3751
|
+
|
|
3752
|
+
// src/renderer/node-views.tsx
|
|
3753
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3754
|
+
var BlockNodeRenderer = ({ store, blockId, registry }) => {
|
|
3755
|
+
const node = useRendererNode(store, blockId);
|
|
3756
|
+
const block = node?.block;
|
|
3757
|
+
if (!node || !block) return null;
|
|
3758
|
+
switch (block.type) {
|
|
3759
|
+
case "paragraph":
|
|
3760
|
+
return /* @__PURE__ */ jsx(ParagraphBlockView, { store, blockId: block.id, registry });
|
|
3761
|
+
case "blockquote":
|
|
3762
|
+
return /* @__PURE__ */ jsx(BlockquoteBlockView, { store, blockId: block.id, registry });
|
|
3763
|
+
case "list":
|
|
3764
|
+
return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: block.id, registry, depth: 0 });
|
|
3765
|
+
case "table":
|
|
3766
|
+
return /* @__PURE__ */ jsx(TableBlockView, { store, blockId: block.id, registry });
|
|
3767
|
+
case "code":
|
|
3768
|
+
return /* @__PURE__ */ jsx(CodeBlockView, { store, blockId: block.id, registry });
|
|
3769
|
+
case "html":
|
|
3770
|
+
return /* @__PURE__ */ jsx(HtmlBlockView, { store, blockId: block.id, registry });
|
|
3771
|
+
case "mdx":
|
|
3772
|
+
return /* @__PURE__ */ jsx(MdxBlockView, { store, blockId: block.id, registry });
|
|
3773
|
+
default:
|
|
3774
|
+
return registry.renderBlock(block);
|
|
3775
|
+
}
|
|
3776
|
+
};
|
|
3777
|
+
var ParagraphBlockView = React7.memo(({ store, blockId, registry }) => {
|
|
3778
|
+
const node = useRendererNode(store, blockId);
|
|
3779
|
+
const block = node?.block;
|
|
3780
|
+
const childIds = useRendererChildren(store, blockId);
|
|
3781
|
+
if (!node || !block) {
|
|
3782
|
+
return null;
|
|
3783
|
+
}
|
|
3784
|
+
const inlineComponents = registry.getInlineComponents();
|
|
3785
|
+
if (!block.isFinalized) {
|
|
3786
|
+
const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
|
|
3787
|
+
const meta = block.payload.meta ?? {};
|
|
3788
|
+
const segments2 = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
|
|
3789
|
+
if (segments2.length > 0) {
|
|
3790
|
+
const allowMixedStreaming = Boolean(meta.allowMixedStreaming);
|
|
3791
|
+
if (!allowMixedStreaming) {
|
|
3792
|
+
return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
|
|
3793
|
+
}
|
|
3794
|
+
const structured = renderParagraphMixedSegments(segments2, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
|
|
3795
|
+
if (structured.length === 1) {
|
|
3796
|
+
const [single] = structured;
|
|
3797
|
+
return React7.isValidElement(single) ? single : single;
|
|
3798
|
+
}
|
|
3799
|
+
return structured;
|
|
3800
|
+
}
|
|
3801
|
+
if (meta.inlineStatus === "complete" || meta.inlineStatus === "anticipated") {
|
|
3802
|
+
const inlineNodes2 = block.payload.inline ?? [];
|
|
3803
|
+
const containsDisplayMath2 = inlineNodes2.some((node2) => node2.kind === "math-display");
|
|
3804
|
+
if (containsDisplayMath2) {
|
|
3805
|
+
const derivedSegments = [
|
|
3806
|
+
{
|
|
3807
|
+
kind: "text",
|
|
3808
|
+
value: raw,
|
|
3809
|
+
inline: inlineNodes2
|
|
3810
|
+
}
|
|
3811
|
+
];
|
|
3812
|
+
const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
|
|
3813
|
+
if (structured.length === 1) {
|
|
3814
|
+
const [single] = structured;
|
|
3815
|
+
return React7.isValidElement(single) ? single : single;
|
|
3816
|
+
}
|
|
3817
|
+
return structured;
|
|
3818
|
+
}
|
|
3819
|
+
return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: renderInlineNodes(inlineNodes2, inlineComponents) });
|
|
3820
|
+
}
|
|
3821
|
+
return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
|
|
3822
|
+
}
|
|
3823
|
+
const propsBlock = node.props?.block;
|
|
3824
|
+
const inlineStatus = propsBlock?.payload?.meta?.inlineStatus ?? block.payload.meta?.inlineStatus ?? node.props?.inlineStatus;
|
|
3825
|
+
if (inlineStatus && inlineStatus !== "complete") {
|
|
3826
|
+
const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
|
|
3827
|
+
return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: raw });
|
|
3828
|
+
}
|
|
3829
|
+
const segments = Array.isArray(block.payload.meta?.mixedSegments) ? block.payload.meta.mixedSegments : void 0;
|
|
3830
|
+
if (segments && segments.length > 0) {
|
|
3831
|
+
const structured = renderParagraphMixedSegments(segments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
|
|
3832
|
+
if (structured.length === 1) {
|
|
3833
|
+
const [single] = structured;
|
|
3834
|
+
return React7.isValidElement(single) ? single : single;
|
|
3835
|
+
}
|
|
3836
|
+
return structured;
|
|
3837
|
+
}
|
|
3838
|
+
const inlineNodes = block.payload.inline ?? [];
|
|
3839
|
+
const containsDisplayMath = inlineNodes.some((node2) => node2.kind === "math-display");
|
|
3840
|
+
if (containsDisplayMath) {
|
|
3841
|
+
const derivedSegments = [
|
|
3842
|
+
{
|
|
3843
|
+
kind: "text",
|
|
3844
|
+
value: typeof block.payload.raw === "string" ? block.payload.raw : "",
|
|
3845
|
+
inline: inlineNodes
|
|
3846
|
+
}
|
|
3847
|
+
];
|
|
3848
|
+
const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
|
|
3849
|
+
if (structured.length === 1) {
|
|
3850
|
+
const [single] = structured;
|
|
3851
|
+
return React7.isValidElement(single) ? single : single;
|
|
3852
|
+
}
|
|
3853
|
+
return structured;
|
|
3854
|
+
}
|
|
3855
|
+
const ParagraphComponent = registry.getBlockComponent("paragraph");
|
|
3856
|
+
const baseElement = React7.createElement(ParagraphComponent, {
|
|
3857
|
+
inlines: block.payload.inline ?? [],
|
|
3858
|
+
raw: block.payload.raw,
|
|
3859
|
+
meta: block.payload.meta
|
|
3860
|
+
});
|
|
3861
|
+
if (childIds.length > 0) {
|
|
3862
|
+
const renderedChildren = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
|
|
3863
|
+
if (React7.isValidElement(baseElement)) {
|
|
3864
|
+
const { children: _ignored, className = "markdown-paragraph", inlines: _inlines, raw: _raw, meta: _meta, ...rest } = baseElement.props ?? {};
|
|
3865
|
+
return React7.createElement("p", { ...rest, className }, renderedChildren);
|
|
3866
|
+
}
|
|
3867
|
+
return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderedChildren });
|
|
3868
|
+
}
|
|
3869
|
+
if (React7.isValidElement(baseElement)) {
|
|
3870
|
+
return baseElement;
|
|
3871
|
+
}
|
|
3872
|
+
return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderInlineNodes(block.payload.inline ?? [], inlineComponents) });
|
|
3873
|
+
});
|
|
3874
|
+
ParagraphBlockView.displayName = "ParagraphBlockView";
|
|
3875
|
+
var BlockquoteBlockView = React7.memo(({ store, blockId, registry }) => {
|
|
3876
|
+
const node = useRendererNode(store, blockId);
|
|
3877
|
+
const block = node?.block;
|
|
3878
|
+
const childIds = useRendererChildren(store, blockId);
|
|
3879
|
+
if (!node || !block) {
|
|
3880
|
+
return null;
|
|
3881
|
+
}
|
|
3882
|
+
const meta = block.payload.meta ?? {};
|
|
3883
|
+
const mixedSegments = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
|
|
3884
|
+
const normalizedText = typeof meta.normalizedText === "string" && meta.normalizedText.length > 0 ? meta.normalizedText : typeof block.payload.raw === "string" ? block.payload.raw : "";
|
|
3885
|
+
const inlineComponents = registry.getInlineComponents();
|
|
3886
|
+
const renderTextWithBreaks = (text, keyPrefix) => {
|
|
3887
|
+
const lines = text.split("\n");
|
|
3888
|
+
const lastIndex = lines.length - 1;
|
|
3889
|
+
let offset = 0;
|
|
3890
|
+
return lines.map((line, idx) => {
|
|
3891
|
+
const key = `${keyPrefix}${offset}`;
|
|
3892
|
+
offset += line.length + 1;
|
|
3893
|
+
return /* @__PURE__ */ jsxs("span", { className: "markdown-blockquote-line", children: [
|
|
3894
|
+
line,
|
|
3895
|
+
idx < lastIndex ? /* @__PURE__ */ jsx("br", {}) : null
|
|
3896
|
+
] }, key);
|
|
3897
|
+
});
|
|
3898
|
+
};
|
|
3899
|
+
const renderInlineContent = (inline, keyPrefix) => {
|
|
3900
|
+
if (inline && inline.length > 0) {
|
|
3901
|
+
return renderInlineNodes(inline, inlineComponents);
|
|
3902
|
+
}
|
|
3903
|
+
return null;
|
|
3904
|
+
};
|
|
3905
|
+
const renderMixedSegments = () => {
|
|
3906
|
+
if (!mixedSegments.length) {
|
|
3907
|
+
return [];
|
|
3908
|
+
}
|
|
3909
|
+
const elements = [];
|
|
3910
|
+
mixedSegments.forEach((segment, segmentIndex) => {
|
|
3911
|
+
switch (segment.kind) {
|
|
3912
|
+
case "html": {
|
|
3913
|
+
const htmlNode = renderInlineHtmlSegment(segment.value, segment.sanitized ?? segment.value, {
|
|
3914
|
+
key: `blockquote-html-${block.id}-${segmentIndex}`,
|
|
3915
|
+
renderers: DEFAULT_INLINE_HTML_RENDERERS
|
|
3916
|
+
});
|
|
3917
|
+
if (htmlNode) {
|
|
3918
|
+
elements.push(htmlNode);
|
|
3919
|
+
} else {
|
|
3920
|
+
elements.push(
|
|
3921
|
+
React7.createElement("span", {
|
|
3922
|
+
key: `blockquote-html-${block.id}-${segmentIndex}`,
|
|
3923
|
+
className: "markdown-inline-html",
|
|
3924
|
+
/* biome-ignore lint/security/noDangerouslySetInnerHtml: segment content is sanitized by the worker before streaming */
|
|
3925
|
+
dangerouslySetInnerHTML: { __html: segment.sanitized ?? segment.value }
|
|
3926
|
+
})
|
|
3927
|
+
);
|
|
3928
|
+
}
|
|
3929
|
+
break;
|
|
3930
|
+
}
|
|
3931
|
+
case "mdx":
|
|
3932
|
+
elements.push(
|
|
3933
|
+
/* @__PURE__ */ jsx("span", { "data-mdx-status": segment.status ?? "pending", children: segment.value }, `blockquote-mdx-${block.id}-${segmentIndex}`)
|
|
3934
|
+
);
|
|
3935
|
+
break;
|
|
3936
|
+
default: {
|
|
3937
|
+
const inline = renderInlineContent(segment.inline, `blockquote-text-inline-${block.id}-${segmentIndex}-`);
|
|
3938
|
+
if (inline) {
|
|
3939
|
+
elements.push(/* @__PURE__ */ jsx(React7.Fragment, { children: inline }, `blockquote-inline-${block.id}-${segmentIndex}`));
|
|
3940
|
+
} else {
|
|
3941
|
+
elements.push(
|
|
3942
|
+
/* @__PURE__ */ jsx(React7.Fragment, { children: renderTextWithBreaks(segment.value, `blockquote-text-${block.id}-${segmentIndex}-`) }, `blockquote-text-${block.id}-${segmentIndex}`)
|
|
3943
|
+
);
|
|
3944
|
+
}
|
|
3945
|
+
break;
|
|
3946
|
+
}
|
|
3947
|
+
}
|
|
3948
|
+
});
|
|
3949
|
+
return elements;
|
|
3950
|
+
};
|
|
3951
|
+
const mixedSegmentElements = renderMixedSegments();
|
|
3952
|
+
const fallbackElements = normalizedText ? renderTextWithBreaks(normalizedText, `blockquote-fallback-${block.id}-`) : null;
|
|
3953
|
+
const inlineNodes = block.payload.inline ?? [];
|
|
3954
|
+
const inlineElements = inlineNodes.length > 0 ? renderInlineNodes(inlineNodes, inlineComponents) : null;
|
|
3955
|
+
if (!block.isFinalized) {
|
|
3956
|
+
const streamingContent = mixedSegmentElements.length ? mixedSegmentElements : inlineElements ? inlineElements : fallbackElements;
|
|
3957
|
+
const shouldShowStreaming = !block.isFinalized && (!streamingContent || Array.isArray(streamingContent) && streamingContent.length === 0);
|
|
3958
|
+
const className = shouldShowStreaming ? "markdown-blockquote streaming-partial" : "markdown-blockquote";
|
|
3959
|
+
return /* @__PURE__ */ jsx("blockquote", { className, children: streamingContent });
|
|
3960
|
+
}
|
|
3961
|
+
const childContent = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
|
|
3962
|
+
const renderedContent = (() => {
|
|
3963
|
+
if (mixedSegmentElements.length > 0) {
|
|
3964
|
+
return mixedSegmentElements;
|
|
3965
|
+
}
|
|
3966
|
+
if (childIds.length > 0) {
|
|
3967
|
+
const resolved = childContent.filter((child) => child !== null);
|
|
3968
|
+
if (resolved.length > 0) {
|
|
3969
|
+
return resolved;
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
if (inlineElements) {
|
|
3973
|
+
return inlineElements;
|
|
3974
|
+
}
|
|
3975
|
+
if (fallbackElements && fallbackElements.length > 0) {
|
|
3976
|
+
return fallbackElements;
|
|
3977
|
+
}
|
|
3978
|
+
return null;
|
|
3979
|
+
})();
|
|
3980
|
+
const BlockquoteComponent = registry.getBlockComponent("blockquote");
|
|
3981
|
+
const baseElement = React7.createElement(
|
|
3982
|
+
BlockquoteComponent,
|
|
3983
|
+
{
|
|
3984
|
+
inlines: block.payload.inline ?? [],
|
|
3985
|
+
renderedContent
|
|
3986
|
+
},
|
|
3987
|
+
renderedContent
|
|
3988
|
+
);
|
|
3989
|
+
if (React7.isValidElement(baseElement)) {
|
|
3990
|
+
return baseElement;
|
|
3991
|
+
}
|
|
3992
|
+
return /* @__PURE__ */ jsx("blockquote", { className: "markdown-blockquote", children: renderedContent });
|
|
3993
|
+
});
|
|
3994
|
+
BlockquoteBlockView.displayName = "BlockquoteBlockView";
|
|
3995
|
+
var MixedSegmentView = React7.memo(({ store, nodeId, inlineComponents }) => {
|
|
3996
|
+
const node = useRendererNode(store, nodeId);
|
|
3997
|
+
if (!node) return null;
|
|
3998
|
+
switch (node.type) {
|
|
3999
|
+
case "paragraph-text":
|
|
4000
|
+
case "blockquote-text":
|
|
4001
|
+
case "list-item-text": {
|
|
4002
|
+
const inline = node.props?.inline ?? [];
|
|
4003
|
+
if (inline.length > 0) {
|
|
4004
|
+
return renderInlineNodes(inline, inlineComponents);
|
|
4005
|
+
}
|
|
4006
|
+
const text = typeof node.props?.text === "string" ? node.props?.text : "";
|
|
4007
|
+
if (!text) return null;
|
|
4008
|
+
return text;
|
|
4009
|
+
}
|
|
4010
|
+
case "paragraph-html":
|
|
4011
|
+
case "blockquote-html":
|
|
4012
|
+
case "list-item-html": {
|
|
4013
|
+
const raw = typeof node.props?.raw === "string" ? node.props.raw : void 0;
|
|
4014
|
+
const html = typeof node.props?.html === "string" ? node.props?.html : "";
|
|
4015
|
+
const rendered = renderInlineHtmlSegment(raw, html, {
|
|
4016
|
+
key: node.id,
|
|
4017
|
+
renderers: DEFAULT_INLINE_HTML_RENDERERS
|
|
4018
|
+
});
|
|
4019
|
+
if (rendered) {
|
|
4020
|
+
return rendered;
|
|
4021
|
+
}
|
|
4022
|
+
if (!html) return null;
|
|
4023
|
+
return React7.createElement("span", {
|
|
4024
|
+
className: "markdown-inline-html",
|
|
4025
|
+
/* biome-ignore lint/security/noDangerouslySetInnerHtml: html is sanitized upstream before reaching the renderer */
|
|
4026
|
+
dangerouslySetInnerHTML: { __html: html }
|
|
4027
|
+
});
|
|
4028
|
+
}
|
|
4029
|
+
case "paragraph-mdx":
|
|
4030
|
+
case "blockquote-mdx":
|
|
4031
|
+
case "list-item-mdx": {
|
|
4032
|
+
const status = node.props?.status ?? "pending";
|
|
4033
|
+
const raw = typeof node.props?.raw === "string" ? node.props?.raw : "";
|
|
4034
|
+
if (status === "compiled") {
|
|
4035
|
+
return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
|
|
4036
|
+
}
|
|
4037
|
+
if (status === "error") {
|
|
4038
|
+
const message = raw || "MDX error";
|
|
4039
|
+
return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error", children: message });
|
|
4040
|
+
}
|
|
4041
|
+
return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": status, children: status === "compiled" ? "" : raw });
|
|
4042
|
+
}
|
|
4043
|
+
default:
|
|
4044
|
+
return null;
|
|
4045
|
+
}
|
|
4046
|
+
});
|
|
4047
|
+
MixedSegmentView.displayName = "MixedSegmentView";
|
|
4048
|
+
var HtmlBlockView = React7.memo(({ store, blockId, registry }) => {
|
|
4049
|
+
const node = useRendererNode(store, blockId);
|
|
4050
|
+
if (!node || !node.block) return null;
|
|
4051
|
+
return registry.renderBlock(node.block);
|
|
4052
|
+
});
|
|
4053
|
+
HtmlBlockView.displayName = "HtmlBlockView";
|
|
4054
|
+
var MdxBlockView = React7.memo(({ store, blockId, registry }) => {
|
|
4055
|
+
const node = useRendererNode(store, blockId);
|
|
4056
|
+
if (!node || !node.block) return null;
|
|
4057
|
+
return registry.renderBlock(node.block);
|
|
4058
|
+
});
|
|
4059
|
+
MdxBlockView.displayName = "MdxBlockView";
|
|
4060
|
+
var ListBlockView = React7.memo(
|
|
4061
|
+
({ store, blockId, registry, depth = 0 }) => {
|
|
4062
|
+
const node = useRendererNode(store, blockId);
|
|
4063
|
+
const block = node?.block;
|
|
4064
|
+
const childIds = useRendererChildren(store, blockId);
|
|
4065
|
+
const inlineComponents = registry.getInlineComponents();
|
|
4066
|
+
const ordered = Boolean(node?.props?.ordered ?? block?.payload.meta?.ordered);
|
|
4067
|
+
const Tag = ordered ? "ol" : "ul";
|
|
4068
|
+
const listDebugEnabled = isListPatchDebugEnabled();
|
|
4069
|
+
const listItemIds = React7.useMemo(() => {
|
|
4070
|
+
const ids = [];
|
|
4071
|
+
for (const childId of childIds) {
|
|
4072
|
+
const childNode = store.getNode(childId);
|
|
4073
|
+
if (childNode?.type === "list-item") {
|
|
4074
|
+
ids.push(childId);
|
|
4075
|
+
}
|
|
4076
|
+
}
|
|
4077
|
+
return ids;
|
|
4078
|
+
}, [childIds, store]);
|
|
4079
|
+
React7.useEffect(() => {
|
|
4080
|
+
if (!listDebugEnabled) return;
|
|
4081
|
+
const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
|
|
4082
|
+
console.info("[stream-mdx:list-render]", {
|
|
4083
|
+
listId: blockId,
|
|
4084
|
+
depth,
|
|
4085
|
+
ordered,
|
|
4086
|
+
childIds,
|
|
4087
|
+
childTypes,
|
|
4088
|
+
listItemIds,
|
|
4089
|
+
listItems: listItemIds.length,
|
|
4090
|
+
totalChildren: childIds.length,
|
|
4091
|
+
isFinalized: block?.isFinalized ?? false
|
|
4092
|
+
});
|
|
4093
|
+
}, [listDebugEnabled, blockId, depth, ordered, childIds, listItemIds, store, block?.isFinalized]);
|
|
4094
|
+
const { listStyle, markerDigits } = React7.useMemo(() => {
|
|
4095
|
+
if (!ordered || listItemIds.length === 0) {
|
|
4096
|
+
return { listStyle: void 0, markerDigits: 1 };
|
|
4097
|
+
}
|
|
4098
|
+
let maxDigits = 1;
|
|
4099
|
+
listItemIds.forEach((childId, index) => {
|
|
4100
|
+
const childNode = store.getNode(childId);
|
|
4101
|
+
const raw = typeof childNode?.block?.payload?.raw === "string" ? childNode.block.payload.raw : void 0;
|
|
4102
|
+
const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
|
|
4103
|
+
const marker = markerMatch?.[1]?.trim();
|
|
4104
|
+
const text = marker ?? `${index + 1}.`;
|
|
4105
|
+
const digitMatch = text.match(/\d/g);
|
|
4106
|
+
const digits = digitMatch ? digitMatch.length : text.length;
|
|
4107
|
+
if (digits > maxDigits) maxDigits = digits;
|
|
4108
|
+
});
|
|
4109
|
+
const baseIndent = depth === 0 ? "2rem" : depth === 1 ? "1.75rem" : "1.5rem";
|
|
4110
|
+
const extraDigits = Math.max(0, maxDigits - 1);
|
|
4111
|
+
return {
|
|
4112
|
+
markerDigits: maxDigits,
|
|
4113
|
+
listStyle: {
|
|
4114
|
+
["--list-indent"]: extraDigits > 0 ? `calc(${baseIndent} + ${extraDigits}ch)` : baseIndent,
|
|
4115
|
+
["--list-marker-digits"]: String(maxDigits)
|
|
4116
|
+
}
|
|
4117
|
+
};
|
|
4118
|
+
}, [ordered, listItemIds, store, depth]);
|
|
4119
|
+
if (listItemIds.length === 0) return null;
|
|
4120
|
+
return /* @__PURE__ */ jsx(
|
|
4121
|
+
Tag,
|
|
4122
|
+
{
|
|
4123
|
+
className: `markdown-list ${ordered ? "ordered" : "unordered"}`,
|
|
4124
|
+
"data-list-depth": depth,
|
|
4125
|
+
"data-marker-digits": ordered ? markerDigits : void 0,
|
|
4126
|
+
"data-list-id": listDebugEnabled ? blockId : void 0,
|
|
4127
|
+
style: listStyle,
|
|
4128
|
+
children: listItemIds.map((childId, index) => /* @__PURE__ */ jsx(
|
|
4129
|
+
ListItemView,
|
|
4130
|
+
{
|
|
4131
|
+
store,
|
|
4132
|
+
nodeId: childId,
|
|
4133
|
+
inlineComponents,
|
|
4134
|
+
registry,
|
|
4135
|
+
ordered,
|
|
4136
|
+
index,
|
|
4137
|
+
depth
|
|
4138
|
+
},
|
|
4139
|
+
childId
|
|
4140
|
+
))
|
|
4141
|
+
}
|
|
4142
|
+
);
|
|
4143
|
+
}
|
|
4144
|
+
);
|
|
4145
|
+
ListBlockView.displayName = "ListBlockView";
|
|
4146
|
+
var ListItemView = React7.memo(({ store, nodeId, inlineComponents, registry, ordered, index, depth }) => {
|
|
4147
|
+
const node = useRendererNode(store, nodeId);
|
|
4148
|
+
const childIds = useRendererChildren(store, nodeId);
|
|
4149
|
+
const inline = node?.props?.inline ?? [];
|
|
4150
|
+
const isTask = Boolean(node?.props?.task);
|
|
4151
|
+
const isChecked = Boolean(node?.props?.checked);
|
|
4152
|
+
const block = node?.block;
|
|
4153
|
+
const raw = typeof block?.payload?.raw === "string" ? block.payload.raw : void 0;
|
|
4154
|
+
const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
|
|
4155
|
+
const marker = markerMatch?.[1]?.trim();
|
|
4156
|
+
const inferredIndex = typeof node?.props?.index === "number" ? Number(node?.props?.index) : index;
|
|
4157
|
+
const isOrdered = Boolean(node?.props?.ordered ?? ordered);
|
|
4158
|
+
const counterText = !isTask ? isOrdered ? marker ? marker : `${inferredIndex + 1}.` : "\u2022" : void 0;
|
|
4159
|
+
const listDebugEnabled = isListPatchDebugEnabled();
|
|
4160
|
+
const inlineLength = inline.length;
|
|
4161
|
+
const [segmentChildIds, contentChildIds] = React7.useMemo(() => {
|
|
4162
|
+
const segments = [];
|
|
4163
|
+
const structural = [];
|
|
4164
|
+
for (const childId of childIds) {
|
|
4165
|
+
const childNode = store.getNode(childId);
|
|
4166
|
+
if (!childNode) continue;
|
|
4167
|
+
if (childNode.type?.startsWith("list-item-")) {
|
|
4168
|
+
segments.push(childId);
|
|
4169
|
+
} else {
|
|
4170
|
+
structural.push(childId);
|
|
4171
|
+
}
|
|
4172
|
+
}
|
|
4173
|
+
return [segments, structural];
|
|
4174
|
+
}, [childIds, store]);
|
|
4175
|
+
const segmentElements = React7.useMemo(() => {
|
|
4176
|
+
return segmentChildIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
|
|
4177
|
+
}, [segmentChildIds, store, inlineComponents]);
|
|
4178
|
+
const primaryContent = React7.useMemo(() => {
|
|
4179
|
+
if (segmentChildIds.length > 0) {
|
|
4180
|
+
return segmentElements;
|
|
4181
|
+
}
|
|
4182
|
+
return renderInlineNodes(inline, inlineComponents);
|
|
4183
|
+
}, [segmentChildIds, segmentElements, inline, inlineComponents]);
|
|
4184
|
+
const trailingChildren = React7.useMemo(() => {
|
|
4185
|
+
return contentChildIds.map((childId) => {
|
|
4186
|
+
const childNode = store.getNode(childId);
|
|
4187
|
+
if (!childNode) return null;
|
|
4188
|
+
switch (childNode.type) {
|
|
4189
|
+
case "paragraph": {
|
|
4190
|
+
const childInline = childNode.props?.inline ?? [];
|
|
4191
|
+
return /* @__PURE__ */ jsx("p", { className: "markdown-list-item-paragraph", children: renderInlineNodes(childInline, inlineComponents) }, childId);
|
|
4192
|
+
}
|
|
4193
|
+
case "list":
|
|
4194
|
+
return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: childId, registry, depth: depth + 1 }, childId);
|
|
4195
|
+
default:
|
|
4196
|
+
return /* @__PURE__ */ jsx(BlockNodeRenderer, { store, blockId: childId, registry }, childId);
|
|
4197
|
+
}
|
|
4198
|
+
});
|
|
4199
|
+
}, [contentChildIds, store, inlineComponents, registry, depth]);
|
|
4200
|
+
const filteredChildren = trailingChildren.filter((child) => Boolean(child));
|
|
4201
|
+
const hasChildren = filteredChildren.length > 0;
|
|
4202
|
+
React7.useEffect(() => {
|
|
4203
|
+
if (!listDebugEnabled) return;
|
|
4204
|
+
const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
|
|
4205
|
+
console.info("[stream-mdx:list-item-render]", {
|
|
4206
|
+
itemId: nodeId,
|
|
4207
|
+
depth,
|
|
4208
|
+
ordered: isOrdered,
|
|
4209
|
+
inferredIndex,
|
|
4210
|
+
marker,
|
|
4211
|
+
isTask,
|
|
4212
|
+
isChecked,
|
|
4213
|
+
childIds,
|
|
4214
|
+
childTypes,
|
|
4215
|
+
segmentChildIds,
|
|
4216
|
+
contentChildIds,
|
|
4217
|
+
inlineLength,
|
|
4218
|
+
hasChildren,
|
|
4219
|
+
isFinalized: block?.isFinalized ?? false
|
|
4220
|
+
});
|
|
4221
|
+
}, [
|
|
4222
|
+
listDebugEnabled,
|
|
4223
|
+
nodeId,
|
|
4224
|
+
depth,
|
|
4225
|
+
isOrdered,
|
|
4226
|
+
inferredIndex,
|
|
4227
|
+
marker,
|
|
4228
|
+
isTask,
|
|
4229
|
+
isChecked,
|
|
4230
|
+
childIds,
|
|
4231
|
+
segmentChildIds,
|
|
4232
|
+
contentChildIds,
|
|
4233
|
+
inlineLength,
|
|
4234
|
+
hasChildren,
|
|
4235
|
+
store,
|
|
4236
|
+
block?.isFinalized
|
|
4237
|
+
]);
|
|
4238
|
+
return /* @__PURE__ */ jsxs(
|
|
4239
|
+
"li",
|
|
4240
|
+
{
|
|
4241
|
+
className: `markdown-list-item${isTask ? " markdown-list-item-task" : ""}`,
|
|
4242
|
+
"data-counter-text": counterText,
|
|
4243
|
+
"data-list-depth": depth,
|
|
4244
|
+
"data-list-item-id": listDebugEnabled ? nodeId : void 0,
|
|
4245
|
+
children: [
|
|
4246
|
+
isTask ? /* @__PURE__ */ jsxs("div", { className: "markdown-task", children: [
|
|
4247
|
+
/* @__PURE__ */ jsx("input", { type: "checkbox", className: "markdown-task-checkbox", checked: isChecked, readOnly: true, disabled: true, tabIndex: -1, "aria-checked": isChecked }),
|
|
4248
|
+
/* @__PURE__ */ jsx("span", { className: "markdown-task-content", children: primaryContent })
|
|
4249
|
+
] }) : primaryContent,
|
|
4250
|
+
hasChildren ? /* @__PURE__ */ jsx("div", { className: "markdown-list-item-children", children: filteredChildren }) : null
|
|
4251
|
+
]
|
|
4252
|
+
}
|
|
4253
|
+
);
|
|
4254
|
+
});
|
|
4255
|
+
ListItemView.displayName = "ListItemView";
|
|
4256
|
+
var TableBlockView = React7.memo(({ store, blockId, registry }) => {
|
|
4257
|
+
const tableElements = registry.getTableElements();
|
|
4258
|
+
const childIds = useRendererChildren(store, blockId);
|
|
4259
|
+
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)) });
|
|
4260
|
+
});
|
|
4261
|
+
TableBlockView.displayName = "TableBlockView";
|
|
4262
|
+
var TableSectionView = React7.memo(({ store, nodeId, registry }) => {
|
|
4263
|
+
const node = useRendererNode(store, nodeId);
|
|
4264
|
+
if (!node) return null;
|
|
4265
|
+
const tableElements = registry.getTableElements();
|
|
4266
|
+
if (node.type === "table-header") {
|
|
4267
|
+
const childIds = useRendererChildren(store, nodeId);
|
|
4268
|
+
return /* @__PURE__ */ jsx(tableElements.Thead, { children: /* @__PURE__ */ jsx(tableElements.Tr, { children: childIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) }) });
|
|
4269
|
+
}
|
|
4270
|
+
if (node.type === "table-body") {
|
|
4271
|
+
const rowIds = useRendererChildren(store, nodeId);
|
|
4272
|
+
return /* @__PURE__ */ jsx(tableElements.Tbody, { children: rowIds.map((rowId) => /* @__PURE__ */ jsx(TableRowView, { store, nodeId: rowId, registry }, rowId)) });
|
|
4273
|
+
}
|
|
4274
|
+
return null;
|
|
4275
|
+
});
|
|
4276
|
+
TableSectionView.displayName = "TableSectionView";
|
|
4277
|
+
var TableRowView = React7.memo(({ store, nodeId, registry }) => {
|
|
4278
|
+
const tableElements = registry.getTableElements();
|
|
4279
|
+
const cellIds = useRendererChildren(store, nodeId);
|
|
4280
|
+
return /* @__PURE__ */ jsx(tableElements.Tr, { children: cellIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) });
|
|
4281
|
+
});
|
|
4282
|
+
TableRowView.displayName = "TableRowView";
|
|
4283
|
+
var TableCellView = React7.memo(({ store, nodeId, registry }) => {
|
|
4284
|
+
const node = useRendererNode(store, nodeId);
|
|
4285
|
+
const inlineComponents = registry.getInlineComponents();
|
|
4286
|
+
const tableElements = registry.getTableElements();
|
|
4287
|
+
if (!node) return null;
|
|
4288
|
+
const Tag = node.type === "table-header-cell" ? tableElements.Th : tableElements.Td;
|
|
4289
|
+
const inline = node.props?.inline ?? [];
|
|
4290
|
+
const align = node.props?.align;
|
|
4291
|
+
const content = renderInlineNodes(inline, inlineComponents);
|
|
4292
|
+
const alignProps = align ? { align } : void 0;
|
|
4293
|
+
return /* @__PURE__ */ jsx(Tag, { ...alignProps, children: content });
|
|
4294
|
+
});
|
|
4295
|
+
TableCellView.displayName = "TableCellView";
|
|
4296
|
+
var CodeBlockView = React7.memo(({ store, blockId, registry }) => {
|
|
4297
|
+
const node = useRendererNode(store, blockId);
|
|
4298
|
+
const childIds = useRendererChildren(store, blockId);
|
|
4299
|
+
const CodeComponent = registry.getBlockComponent("code");
|
|
4300
|
+
const deferredConfig = React7.useContext(DeferredRenderContext);
|
|
4301
|
+
const deferredRef = React7.useRef(null);
|
|
4302
|
+
const shouldRenderDeferred = useDeferredRender(
|
|
4303
|
+
deferredRef,
|
|
4304
|
+
deferredConfig ? { ...deferredConfig, enabled: true } : { enabled: false }
|
|
4305
|
+
);
|
|
4306
|
+
if (!node || !node.block) return null;
|
|
4307
|
+
const blockIsFinalized = node.block.isFinalized;
|
|
4308
|
+
const nodeVersion = node.version;
|
|
4309
|
+
const lines = React7.useMemo(() => {
|
|
4310
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
4311
|
+
const seenIndices = /* @__PURE__ */ new Set();
|
|
4312
|
+
const deduped = [];
|
|
4313
|
+
for (const childId of childIds) {
|
|
4314
|
+
const child = store.getNode(childId);
|
|
4315
|
+
if (!child) continue;
|
|
4316
|
+
const index = typeof child.props?.index === "number" ? child.props?.index : deduped.length;
|
|
4317
|
+
const text = typeof child.props?.text === "string" ? child.props?.text : "";
|
|
4318
|
+
const html = typeof child.props?.html === "string" ? child.props?.html : null;
|
|
4319
|
+
const tokens = Object.prototype.hasOwnProperty.call(child.props ?? {}, "tokens") ? child.props?.tokens : void 0;
|
|
4320
|
+
if (seenIds.has(child.id) || seenIndices.has(index)) {
|
|
4321
|
+
console.warn("[renderer-view] duplicate code line detected", {
|
|
4322
|
+
blockId,
|
|
4323
|
+
childId: child.id,
|
|
4324
|
+
index
|
|
4325
|
+
});
|
|
4326
|
+
continue;
|
|
4327
|
+
}
|
|
4328
|
+
seenIds.add(child.id);
|
|
4329
|
+
seenIndices.add(index);
|
|
4330
|
+
deduped.push({ id: child.id, index, text, html, tokens });
|
|
4331
|
+
}
|
|
4332
|
+
deduped.sort((a, b) => a.index - b.index);
|
|
4333
|
+
return deduped;
|
|
4334
|
+
}, [childIds, store, blockId, nodeVersion]);
|
|
4335
|
+
const lang = typeof node.props?.lang === "string" ? node.props?.lang : node.block.payload.meta?.lang;
|
|
4336
|
+
const preAttrs = node.props?.preAttrs ?? void 0;
|
|
4337
|
+
const codeAttrs = node.props?.codeAttrs ?? void 0;
|
|
4338
|
+
const blockMeta = node.block.payload.meta ?? void 0;
|
|
4339
|
+
const lazyEnabled = Boolean(blockMeta?.lazyTokenization);
|
|
4340
|
+
const lazyTokenizedUntil = typeof blockMeta?.lazyTokenizedUntil === "number" ? blockMeta.lazyTokenizedUntil : 0;
|
|
4341
|
+
const lazyHighlightedLines = Array.isArray(blockMeta?.highlightedLines) ? blockMeta.highlightedLines.length : 0;
|
|
4342
|
+
const lazyTokenLines = Array.isArray(blockMeta?.tokenLines) ? blockMeta.tokenLines.length : 0;
|
|
4343
|
+
const lazySourceTextLineCount = React7.useMemo(() => {
|
|
4344
|
+
const raw = typeof node.block?.payload.raw === "string" ? node.block.payload.raw : "";
|
|
4345
|
+
const metaCode = typeof blockMeta?.code === "string" ? blockMeta.code : null;
|
|
4346
|
+
const sourceText = resolveCodeSourceText(raw, metaCode);
|
|
4347
|
+
if (sourceText.length === 0) return 0;
|
|
4348
|
+
return sourceText.split("\n").length;
|
|
4349
|
+
}, [blockMeta, node.block?.payload.raw]);
|
|
4350
|
+
const totalLazyLineCount = Math.max(lines.length, lazyHighlightedLines, lazyTokenLines, lazySourceTextLineCount);
|
|
4351
|
+
const virtualizationConfig = DEFAULT_VIRTUALIZED_CODE_CONFIG;
|
|
4352
|
+
const virtualizationDisabled = typeof process !== "undefined" && typeof process.env === "object" && process.env.STREAM_MDX_DISABLE_VIRTUALIZED_CODE === "true";
|
|
4353
|
+
const canVirtualize = node.block.isFinalized && !lazyEnabled;
|
|
4354
|
+
const shouldVirtualize = canVirtualize && !virtualizationDisabled && virtualizationConfig.enabled && lines.length >= virtualizationConfig.virtualizeThreshold;
|
|
4355
|
+
const virtualization = useVirtualizedCode(lines, shouldVirtualize ? virtualizationConfig : { ...virtualizationConfig, enabled: false });
|
|
4356
|
+
const highlightRequester = useCodeHighlightRequester();
|
|
4357
|
+
const lastRangeRef = React7.useRef(null);
|
|
4358
|
+
const rafRef = React7.useRef(null);
|
|
4359
|
+
const idleRef = React7.useRef(null);
|
|
4360
|
+
React7.useEffect(() => {
|
|
4361
|
+
if (!shouldVirtualize || !lazyEnabled || !highlightRequester) return;
|
|
4362
|
+
const { visibleStart, visibleEnd, startIndex, endIndex } = virtualization.window;
|
|
4363
|
+
if (endIndex <= lazyTokenizedUntil) return;
|
|
4364
|
+
const nextRange = {
|
|
4365
|
+
visibleStart,
|
|
4366
|
+
visibleEnd,
|
|
4367
|
+
prefetchStart: startIndex,
|
|
4368
|
+
prefetchEnd: endIndex,
|
|
4369
|
+
tokenizedUntil: lazyTokenizedUntil
|
|
4370
|
+
};
|
|
4371
|
+
const last = lastRangeRef.current;
|
|
4372
|
+
if (last && last.visibleStart === nextRange.visibleStart && last.visibleEnd === nextRange.visibleEnd && last.prefetchStart === nextRange.prefetchStart && last.prefetchEnd === nextRange.prefetchEnd && last.tokenizedUntil === nextRange.tokenizedUntil) {
|
|
4373
|
+
return;
|
|
4374
|
+
}
|
|
4375
|
+
lastRangeRef.current = nextRange;
|
|
4376
|
+
if (rafRef.current !== null && typeof cancelAnimationFrame === "function") {
|
|
4377
|
+
cancelAnimationFrame(rafRef.current);
|
|
4378
|
+
}
|
|
4379
|
+
if (typeof requestAnimationFrame === "function") {
|
|
4380
|
+
rafRef.current = requestAnimationFrame(() => {
|
|
4381
|
+
highlightRequester({
|
|
4382
|
+
blockId,
|
|
4383
|
+
startLine: visibleStart,
|
|
4384
|
+
endLine: visibleEnd,
|
|
4385
|
+
priority: "visible",
|
|
4386
|
+
reason: "scroll"
|
|
4387
|
+
});
|
|
4388
|
+
rafRef.current = null;
|
|
4389
|
+
});
|
|
4390
|
+
} else {
|
|
4391
|
+
highlightRequester({
|
|
4392
|
+
blockId,
|
|
4393
|
+
startLine: visibleStart,
|
|
4394
|
+
endLine: visibleEnd,
|
|
4395
|
+
priority: "visible",
|
|
4396
|
+
reason: "scroll"
|
|
4397
|
+
});
|
|
4398
|
+
}
|
|
4399
|
+
const prefetchNeeded = startIndex < visibleStart || endIndex > visibleEnd;
|
|
4400
|
+
if (prefetchNeeded) {
|
|
4401
|
+
const idleCallback = globalThis.requestIdleCallback;
|
|
4402
|
+
const cancelIdle = globalThis.cancelIdleCallback;
|
|
4403
|
+
if (idleRef.current !== null) {
|
|
4404
|
+
if (typeof cancelIdle === "function") {
|
|
4405
|
+
cancelIdle(idleRef.current);
|
|
4406
|
+
} else if (typeof clearTimeout === "function") {
|
|
4407
|
+
clearTimeout(idleRef.current);
|
|
4408
|
+
}
|
|
4409
|
+
}
|
|
4410
|
+
const schedule = () => {
|
|
4411
|
+
highlightRequester({
|
|
4412
|
+
blockId,
|
|
4413
|
+
startLine: startIndex,
|
|
4414
|
+
endLine: endIndex,
|
|
4415
|
+
priority: "prefetch",
|
|
4416
|
+
reason: "buffer"
|
|
4417
|
+
});
|
|
4418
|
+
idleRef.current = null;
|
|
4419
|
+
};
|
|
4420
|
+
if (typeof idleCallback === "function") {
|
|
4421
|
+
idleRef.current = idleCallback(() => schedule());
|
|
4422
|
+
} else if (typeof setTimeout === "function") {
|
|
4423
|
+
idleRef.current = setTimeout(schedule, 80);
|
|
4424
|
+
}
|
|
4425
|
+
}
|
|
4426
|
+
}, [
|
|
4427
|
+
blockId,
|
|
4428
|
+
highlightRequester,
|
|
4429
|
+
lazyEnabled,
|
|
4430
|
+
lazyTokenizedUntil,
|
|
4431
|
+
shouldVirtualize,
|
|
4432
|
+
virtualization.window.visibleStart,
|
|
4433
|
+
virtualization.window.visibleEnd,
|
|
4434
|
+
virtualization.window.startIndex,
|
|
4435
|
+
virtualization.window.endIndex
|
|
4436
|
+
]);
|
|
4437
|
+
React7.useEffect(() => {
|
|
4438
|
+
if (shouldVirtualize || !blockIsFinalized || !lazyEnabled || !highlightRequester) return;
|
|
4439
|
+
if (totalLazyLineCount <= 0 || lazyTokenizedUntil >= totalLazyLineCount) return;
|
|
4440
|
+
const nextRange = {
|
|
4441
|
+
visibleStart: 0,
|
|
4442
|
+
visibleEnd: totalLazyLineCount,
|
|
4443
|
+
prefetchStart: 0,
|
|
4444
|
+
prefetchEnd: totalLazyLineCount,
|
|
4445
|
+
tokenizedUntil: lazyTokenizedUntil
|
|
4446
|
+
};
|
|
4447
|
+
const last = lastRangeRef.current;
|
|
4448
|
+
if (last && last.visibleStart === nextRange.visibleStart && last.visibleEnd === nextRange.visibleEnd && last.prefetchStart === nextRange.prefetchStart && last.prefetchEnd === nextRange.prefetchEnd && last.tokenizedUntil === nextRange.tokenizedUntil) {
|
|
4449
|
+
return;
|
|
4450
|
+
}
|
|
4451
|
+
lastRangeRef.current = nextRange;
|
|
4452
|
+
if (rafRef.current !== null && typeof cancelAnimationFrame === "function") {
|
|
4453
|
+
cancelAnimationFrame(rafRef.current);
|
|
4454
|
+
}
|
|
4455
|
+
const requestFullHighlight = () => {
|
|
4456
|
+
highlightRequester({
|
|
4457
|
+
blockId,
|
|
4458
|
+
startLine: 0,
|
|
4459
|
+
endLine: totalLazyLineCount,
|
|
4460
|
+
priority: "visible",
|
|
4461
|
+
reason: "finalize-full"
|
|
4462
|
+
});
|
|
4463
|
+
rafRef.current = null;
|
|
4464
|
+
};
|
|
4465
|
+
if (typeof requestAnimationFrame === "function") {
|
|
4466
|
+
rafRef.current = requestAnimationFrame(requestFullHighlight);
|
|
4467
|
+
} else {
|
|
4468
|
+
requestFullHighlight();
|
|
4469
|
+
}
|
|
4470
|
+
}, [blockId, blockIsFinalized, highlightRequester, lazyEnabled, lazyTokenizedUntil, shouldVirtualize, totalLazyLineCount]);
|
|
4471
|
+
const highlightedHtml = React7.useMemo(() => {
|
|
4472
|
+
const blockHtml = node.block?.payload.highlightedHtml ?? "";
|
|
4473
|
+
const raw = typeof node.block?.payload.raw === "string" ? node.block.payload.raw : "";
|
|
4474
|
+
const metaCode = typeof node.block?.payload.meta?.code === "string" ? (node.block?.payload.meta).code : null;
|
|
4475
|
+
const sourceText = resolveCodeSourceText(raw, metaCode);
|
|
4476
|
+
const sourceEndsWithNewline = sourceText.endsWith("\n");
|
|
4477
|
+
const sourceLines = sourceText.length > 0 ? sourceText.split("\n") : [];
|
|
4478
|
+
const rawFallbackLines = buildCodeFallbackLines(raw);
|
|
4479
|
+
const deterministicWrapperAttrs = getDefaultCodeWrapperAttributes2(lang);
|
|
4480
|
+
const composedPreAttrs = deterministicWrapperAttrs.preAttrs;
|
|
4481
|
+
const composedCodeAttrs = deterministicWrapperAttrs.codeAttrs;
|
|
4482
|
+
const shouldAppendTerminalNewline = (renderedLines) => {
|
|
4483
|
+
if (!sourceEndsWithNewline || renderedLines.length === 0 || lines.length === 0) {
|
|
4484
|
+
return false;
|
|
4485
|
+
}
|
|
4486
|
+
const lastRendered = renderedLines[renderedLines.length - 1];
|
|
4487
|
+
const lastKnown = lines[lines.length - 1];
|
|
4488
|
+
if (!lastRendered || !lastKnown || lastRendered.index !== lastKnown.index || lastRendered.text === "") {
|
|
4489
|
+
return false;
|
|
4490
|
+
}
|
|
4491
|
+
const expectedRenderedLineCount = Math.max(0, sourceLines.length - 1);
|
|
4492
|
+
const expectedLastRenderedLine = sourceLines.length >= 2 ? sourceLines[sourceLines.length - 2] ?? "" : "";
|
|
4493
|
+
return renderedLines.length === expectedRenderedLineCount && lastRendered.text === expectedLastRenderedLine;
|
|
4494
|
+
};
|
|
4495
|
+
if (lines.length > 0) {
|
|
4496
|
+
const hasLineHtml = lines.some((line) => typeof line.html === "string" && line.html.length > 0);
|
|
4497
|
+
if (!hasLineHtml && blockHtml) {
|
|
4498
|
+
return blockHtml;
|
|
4499
|
+
}
|
|
4500
|
+
if (shouldVirtualize) {
|
|
4501
|
+
return composeHighlightedHtml(
|
|
4502
|
+
virtualization.window.visibleLines,
|
|
4503
|
+
composedPreAttrs,
|
|
4504
|
+
composedCodeAttrs,
|
|
4505
|
+
shouldAppendTerminalNewline(virtualization.window.visibleLines)
|
|
4506
|
+
);
|
|
4507
|
+
}
|
|
4508
|
+
return composeHighlightedHtml(lines, composedPreAttrs, composedCodeAttrs, shouldAppendTerminalNewline(lines));
|
|
4509
|
+
}
|
|
4510
|
+
if (!shouldVirtualize && blockHtml) {
|
|
4511
|
+
const hasHighlightedLines = blockHtml.includes('class="line"');
|
|
4512
|
+
if (!hasHighlightedLines && rawFallbackLines.length > 0) {
|
|
4513
|
+
return composeHighlightedHtml(
|
|
4514
|
+
rawFallbackLines,
|
|
4515
|
+
composedPreAttrs,
|
|
4516
|
+
composedCodeAttrs,
|
|
4517
|
+
sourceEndsWithNewline && rawFallbackLines[rawFallbackLines.length - 1]?.text !== ""
|
|
4518
|
+
);
|
|
4519
|
+
}
|
|
4520
|
+
return blockHtml;
|
|
4521
|
+
}
|
|
4522
|
+
if (blockHtml?.trim().match(/^```[\w-]*\s*$/)) {
|
|
4523
|
+
if (rawFallbackLines.length > 0) {
|
|
4524
|
+
return composeHighlightedHtml(
|
|
4525
|
+
rawFallbackLines,
|
|
4526
|
+
composedPreAttrs,
|
|
4527
|
+
composedCodeAttrs,
|
|
4528
|
+
sourceEndsWithNewline && rawFallbackLines[rawFallbackLines.length - 1]?.text !== ""
|
|
4529
|
+
);
|
|
4530
|
+
}
|
|
4531
|
+
}
|
|
4532
|
+
if (!blockHtml && rawFallbackLines.length > 0) {
|
|
4533
|
+
return composeHighlightedHtml(
|
|
4534
|
+
rawFallbackLines,
|
|
4535
|
+
composedPreAttrs,
|
|
4536
|
+
composedCodeAttrs,
|
|
4537
|
+
sourceEndsWithNewline && rawFallbackLines[rawFallbackLines.length - 1]?.text !== ""
|
|
4538
|
+
);
|
|
4539
|
+
}
|
|
4540
|
+
return blockHtml;
|
|
4541
|
+
}, [blockIsFinalized, shouldVirtualize, node.block?.payload.highlightedHtml, node.block?.payload.meta, lines, lang, virtualization.window.visibleLines, node.block?.payload.raw]);
|
|
4542
|
+
const rendered = /* @__PURE__ */ jsx(
|
|
4543
|
+
CodeComponent,
|
|
4544
|
+
{
|
|
4545
|
+
html: highlightedHtml,
|
|
4546
|
+
meta: node.block.payload.meta,
|
|
4547
|
+
lines: shouldVirtualize ? virtualization.window.visibleLines : lines,
|
|
4548
|
+
lang,
|
|
4549
|
+
preAttrs,
|
|
4550
|
+
codeAttrs
|
|
4551
|
+
}
|
|
4552
|
+
);
|
|
4553
|
+
const effectiveLineCount = React7.useMemo(() => {
|
|
4554
|
+
if (lines.length > 0) {
|
|
4555
|
+
return lines.length;
|
|
4556
|
+
}
|
|
4557
|
+
return 1;
|
|
4558
|
+
}, [lines.length]);
|
|
4559
|
+
const codeFrameClass = "not-prose flex flex-col rounded-lg border border-input pt-1 font-mono text-sm";
|
|
4560
|
+
const codeMetricsAttrs = {
|
|
4561
|
+
"data-code-block": "true",
|
|
4562
|
+
"data-block-id": blockId,
|
|
4563
|
+
"data-code-virtualized": shouldVirtualize ? "true" : "false",
|
|
4564
|
+
"data-code-total-lines": String(effectiveLineCount),
|
|
4565
|
+
"data-code-mounted-lines": String(shouldVirtualize ? virtualization.window.mountedLines : effectiveLineCount),
|
|
4566
|
+
"data-code-window-size": String(virtualization.config.windowSize)
|
|
4567
|
+
};
|
|
4568
|
+
const codeView = shouldVirtualize ? (() => {
|
|
4569
|
+
const { containerRef, window: window2, handleScroll, lineHeight } = virtualization;
|
|
4570
|
+
const spacerTop = window2.startIndex * lineHeight;
|
|
4571
|
+
const spacerBottom = (window2.totalLines - window2.endIndex) * lineHeight;
|
|
4572
|
+
return /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: /* @__PURE__ */ jsxs(
|
|
4573
|
+
"div",
|
|
4574
|
+
{
|
|
4575
|
+
ref: containerRef,
|
|
4576
|
+
className: "markdown-code-block-container relative",
|
|
4577
|
+
style: { overflowY: "auto", overflowX: "hidden", maxHeight: "600px" },
|
|
4578
|
+
onScroll: handleScroll,
|
|
4579
|
+
children: [
|
|
4580
|
+
/* @__PURE__ */ jsx("div", { style: { height: spacerTop }, "aria-hidden": "true" }),
|
|
4581
|
+
rendered,
|
|
4582
|
+
/* @__PURE__ */ jsx("div", { style: { height: spacerBottom }, "aria-hidden": "true" })
|
|
4583
|
+
]
|
|
4584
|
+
}
|
|
4585
|
+
) });
|
|
4586
|
+
})() : /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: rendered });
|
|
4587
|
+
const blockComponentMap = registry.getBlockComponentMap();
|
|
4588
|
+
const MermaidComponent = Object.prototype.hasOwnProperty.call(blockComponentMap, "mermaid") ? blockComponentMap.mermaid : null;
|
|
4589
|
+
if ((lang ?? "").toLowerCase() === "mermaid" && MermaidComponent) {
|
|
4590
|
+
const raw = typeof node.block.payload.raw === "string" ? node.block.payload.raw : "";
|
|
4591
|
+
const fenced = stripCodeFence(raw);
|
|
4592
|
+
const code = fenced.hadFence ? fenced.code : raw;
|
|
4593
|
+
if (deferredConfig) {
|
|
4594
|
+
return /* @__PURE__ */ jsx("div", { ref: deferredRef, children: shouldRenderDeferred ? React7.createElement(MermaidComponent, {
|
|
4595
|
+
code,
|
|
4596
|
+
renderCode: codeView,
|
|
4597
|
+
meta: node.block.payload.meta,
|
|
4598
|
+
isFinalized: node.block.isFinalized
|
|
4599
|
+
}) : codeView });
|
|
4600
|
+
}
|
|
4601
|
+
return React7.createElement(MermaidComponent, {
|
|
4602
|
+
code,
|
|
4603
|
+
renderCode: codeView,
|
|
4604
|
+
meta: node.block.payload.meta,
|
|
4605
|
+
isFinalized: node.block.isFinalized
|
|
4606
|
+
});
|
|
4607
|
+
}
|
|
4608
|
+
return codeView;
|
|
4609
|
+
});
|
|
4610
|
+
CodeBlockView.displayName = "CodeBlockView";
|
|
4611
|
+
function composeHighlightedHtml(lines, preAttrs, codeAttrs, appendTerminalNewline = false) {
|
|
4612
|
+
const lineMarkup = lines.map((line) => {
|
|
4613
|
+
const content = line.html ?? renderTokenLineHtml(line.tokens) ?? escapeHtml3(line.text);
|
|
4614
|
+
const dataLine = Number.isFinite(line.index) ? ` data-line="${line.index + 1}"` : "";
|
|
4615
|
+
return `<span class="line"${dataLine}>${content}</span>`;
|
|
4616
|
+
}).join("\n");
|
|
4617
|
+
const preAttr = attrsToString(preAttrs);
|
|
4618
|
+
const codeAttr = attrsToString(codeAttrs);
|
|
4619
|
+
return `<pre${preAttr}><code${codeAttr}>${lineMarkup}${appendTerminalNewline ? "\n" : ""}</code></pre>`;
|
|
4620
|
+
}
|
|
4621
|
+
var TOKEN_FONT_STYLE_ITALIC = 1;
|
|
4622
|
+
var TOKEN_FONT_STYLE_BOLD = 2;
|
|
4623
|
+
var TOKEN_FONT_STYLE_UNDERLINE = 4;
|
|
4624
|
+
var TOKEN_FONT_STYLE_STRIKETHROUGH = 8;
|
|
4625
|
+
function renderTokenLineHtml(tokens) {
|
|
4626
|
+
if (!tokens || !Array.isArray(tokens.spans)) {
|
|
4627
|
+
return null;
|
|
4628
|
+
}
|
|
4629
|
+
return mergeRenderableTokenSpans(tokens.spans).map((span) => renderTokenSpanHtml(span)).join("");
|
|
4630
|
+
}
|
|
4631
|
+
function renderTokenSpanHtml(span) {
|
|
4632
|
+
const dark = span.v?.dark;
|
|
4633
|
+
const light = span.v?.light;
|
|
4634
|
+
const single = span.s;
|
|
4635
|
+
const styles = [];
|
|
4636
|
+
if (dark?.fg) {
|
|
4637
|
+
styles.push(`--shiki-dark:${dark.fg}`);
|
|
4638
|
+
}
|
|
4639
|
+
if (light?.fg) {
|
|
4640
|
+
styles.push(`--shiki-light:${light.fg}`);
|
|
4641
|
+
}
|
|
4642
|
+
if (!light?.fg && !dark?.fg && single?.fg) {
|
|
4643
|
+
styles.push(`color:${single.fg}`);
|
|
4644
|
+
}
|
|
4645
|
+
const fontStyle = light?.fs ?? dark?.fs ?? single?.fs;
|
|
4646
|
+
if (typeof fontStyle === "number" && fontStyle > 0) {
|
|
4647
|
+
if (fontStyle & TOKEN_FONT_STYLE_ITALIC) {
|
|
4648
|
+
styles.push("font-style: italic");
|
|
4649
|
+
}
|
|
4650
|
+
if (fontStyle & TOKEN_FONT_STYLE_BOLD) {
|
|
4651
|
+
styles.push("font-weight: bold");
|
|
4652
|
+
}
|
|
4653
|
+
const decorations = [];
|
|
4654
|
+
if (fontStyle & TOKEN_FONT_STYLE_UNDERLINE) {
|
|
4655
|
+
decorations.push("underline");
|
|
4656
|
+
}
|
|
4657
|
+
if (fontStyle & TOKEN_FONT_STYLE_STRIKETHROUGH) {
|
|
4658
|
+
decorations.push("line-through");
|
|
4659
|
+
}
|
|
4660
|
+
if (decorations.length > 0) {
|
|
4661
|
+
styles.push(`text-decoration: ${decorations.join(" ")}`);
|
|
4662
|
+
}
|
|
4663
|
+
}
|
|
4664
|
+
const content = escapeHtml3(span.t ?? "");
|
|
4665
|
+
if (styles.length === 0) {
|
|
4666
|
+
return content;
|
|
4667
|
+
}
|
|
4668
|
+
return `<span style="${styles.join(";")}">${content}</span>`;
|
|
4669
|
+
}
|
|
4670
|
+
function mergeRenderableTokenSpans(spans) {
|
|
4671
|
+
if (spans.length <= 1) {
|
|
4672
|
+
return spans.slice();
|
|
4673
|
+
}
|
|
4674
|
+
const merged = [];
|
|
4675
|
+
let pendingWhitespace = "";
|
|
4676
|
+
for (const span of spans) {
|
|
4677
|
+
const text = typeof span.t === "string" ? span.t : "";
|
|
4678
|
+
if (/^[\t ]+$/.test(text)) {
|
|
4679
|
+
pendingWhitespace += text;
|
|
4680
|
+
continue;
|
|
4681
|
+
}
|
|
4682
|
+
const nextSpan = pendingWhitespace ? { ...span, t: `${pendingWhitespace}${text}` } : span;
|
|
4683
|
+
pendingWhitespace = "";
|
|
4684
|
+
const previous = merged[merged.length - 1];
|
|
4685
|
+
if (previous && sameTokenSpanStyle(previous, nextSpan)) {
|
|
4686
|
+
previous.t += nextSpan.t;
|
|
4687
|
+
} else {
|
|
4688
|
+
merged.push({ ...nextSpan });
|
|
4689
|
+
}
|
|
4690
|
+
}
|
|
4691
|
+
if (pendingWhitespace) {
|
|
4692
|
+
const previous = merged[merged.length - 1];
|
|
4693
|
+
if (previous) {
|
|
4694
|
+
previous.t += pendingWhitespace;
|
|
4695
|
+
} else {
|
|
4696
|
+
merged.push({ t: pendingWhitespace });
|
|
4697
|
+
}
|
|
4698
|
+
}
|
|
4699
|
+
return merged;
|
|
4700
|
+
}
|
|
4701
|
+
function sameTokenSpanStyle(a, b) {
|
|
4702
|
+
const variantKeys = /* @__PURE__ */ new Set([
|
|
4703
|
+
...Object.keys(a.v ?? {}),
|
|
4704
|
+
...Object.keys(b.v ?? {})
|
|
4705
|
+
]);
|
|
4706
|
+
for (const key of variantKeys) {
|
|
4707
|
+
const aStyle = a.v?.[key];
|
|
4708
|
+
const bStyle = b.v?.[key];
|
|
4709
|
+
if ((aStyle?.fg ?? null) !== (bStyle?.fg ?? null)) return false;
|
|
4710
|
+
if ((aStyle?.bg ?? null) !== (bStyle?.bg ?? null)) return false;
|
|
4711
|
+
if ((aStyle?.fs ?? null) !== (bStyle?.fs ?? null)) return false;
|
|
4712
|
+
}
|
|
4713
|
+
if ((a.s?.fg ?? null) !== (b.s?.fg ?? null)) return false;
|
|
4714
|
+
if ((a.s?.bg ?? null) !== (b.s?.bg ?? null)) return false;
|
|
4715
|
+
if ((a.s?.fs ?? null) !== (b.s?.fs ?? null)) return false;
|
|
4716
|
+
return true;
|
|
4717
|
+
}
|
|
4718
|
+
function resolveCodeSourceText(raw, metaCode) {
|
|
4719
|
+
if (metaCode !== null) {
|
|
4720
|
+
return metaCode.replace(/\r\n?/g, "\n");
|
|
4721
|
+
}
|
|
4722
|
+
if (!raw) return "";
|
|
4723
|
+
const normalized = raw.replace(/\r\n?/g, "\n");
|
|
4724
|
+
const fenced = stripCodeFence(normalized);
|
|
4725
|
+
return fenced.hadFence ? fenced.code : normalized;
|
|
4726
|
+
}
|
|
4727
|
+
function attrsToString(attrs) {
|
|
4728
|
+
if (!attrs) return "";
|
|
4729
|
+
return Object.entries(attrs).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("");
|
|
4730
|
+
}
|
|
4731
|
+
function buildCodeFallbackLines(raw) {
|
|
4732
|
+
const normalized = normalizeCodeFallbackRaw(raw);
|
|
4733
|
+
if (normalized.length === 0) {
|
|
4734
|
+
if (/^\s*```[^\n]*\n?\s*$/.test(raw)) {
|
|
4735
|
+
return [{ id: "temp-0", index: 0, text: "", html: null }];
|
|
4736
|
+
}
|
|
4737
|
+
return [];
|
|
4738
|
+
}
|
|
4739
|
+
return normalized.split("\n").map((line, index) => ({
|
|
4740
|
+
id: `temp-${index}`,
|
|
4741
|
+
index,
|
|
4742
|
+
text: line,
|
|
4743
|
+
html: null
|
|
4744
|
+
}));
|
|
4745
|
+
}
|
|
4746
|
+
function normalizeCodeFallbackRaw(raw) {
|
|
4747
|
+
if (!raw) return "";
|
|
4748
|
+
const normalized = raw.replace(/\r\n?/g, "\n");
|
|
4749
|
+
const fenced = stripCodeFence(normalized);
|
|
4750
|
+
if (!fenced.hadFence) {
|
|
4751
|
+
return normalized.replace(/\n+$/, "");
|
|
4752
|
+
}
|
|
4753
|
+
let code = fenced.code;
|
|
4754
|
+
code = code.replace(/\n+$/, "");
|
|
4755
|
+
return code;
|
|
4756
|
+
}
|
|
4757
|
+
function escapeHtml3(value) {
|
|
4758
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
4759
|
+
}
|
|
4760
|
+
function escapeAttribute(value) {
|
|
4761
|
+
return value.replace(/"/g, """);
|
|
4762
|
+
}
|
|
4763
|
+
|
|
4764
|
+
// src/renderer/blocks-renderer.tsx
|
|
4765
|
+
var MarkdownBlocksRenderer = React8.memo(({ blocks, componentRegistry, className = "markdown-renderer", style, store }) => {
|
|
4766
|
+
if (store) {
|
|
4767
|
+
return React8.createElement(
|
|
4768
|
+
"div",
|
|
4769
|
+
{
|
|
4770
|
+
className,
|
|
4771
|
+
style: { contain: "content", ...style ?? {} }
|
|
4772
|
+
// CSS containment for performance
|
|
4773
|
+
},
|
|
4774
|
+
React8.createElement(StoreBackedBlocks, { store, componentRegistry })
|
|
4775
|
+
);
|
|
4776
|
+
}
|
|
4777
|
+
const renderedBlocks = useMemo3(() => {
|
|
4778
|
+
return blocks.map((block) => {
|
|
4779
|
+
const key = getBlockKey(block);
|
|
4780
|
+
return React8.createElement(BlockRenderer, {
|
|
4781
|
+
key,
|
|
4782
|
+
block,
|
|
4783
|
+
componentRegistry,
|
|
4784
|
+
isFinalized: block.isFinalized
|
|
4785
|
+
});
|
|
4786
|
+
});
|
|
4787
|
+
}, [blocks, componentRegistry]);
|
|
4788
|
+
return React8.createElement(
|
|
4789
|
+
"div",
|
|
4790
|
+
{
|
|
4791
|
+
className,
|
|
4792
|
+
style: { contain: "content", ...style ?? {} }
|
|
4793
|
+
// CSS containment for performance
|
|
4794
|
+
},
|
|
4795
|
+
renderedBlocks
|
|
4796
|
+
);
|
|
4797
|
+
});
|
|
4798
|
+
var StoreBackedBlocks = React8.memo(
|
|
4799
|
+
({ store, componentRegistry }) => {
|
|
4800
|
+
const blockIds = useRendererChildren(store, PATCH_ROOT_ID2);
|
|
4801
|
+
return React8.createElement(
|
|
4802
|
+
React8.Fragment,
|
|
4803
|
+
null,
|
|
4804
|
+
blockIds.map((blockId) => React8.createElement(BlockNodeRenderer, { key: blockId, store, blockId, registry: componentRegistry }))
|
|
4805
|
+
);
|
|
4806
|
+
}
|
|
4807
|
+
);
|
|
4808
|
+
StoreBackedBlocks.displayName = "StoreBackedBlocks";
|
|
4809
|
+
var BlockRenderer = React8.memo(({ block, componentRegistry, isFinalized }) => {
|
|
4810
|
+
const element = useMemo3(() => {
|
|
4811
|
+
return componentRegistry.renderBlock(block);
|
|
4812
|
+
}, [block, componentRegistry]);
|
|
4813
|
+
const className = `markdown-block markdown-block-${block.type} ${isFinalized ? "finalized" : "dirty"}`;
|
|
4814
|
+
return React8.cloneElement(element, {
|
|
4815
|
+
className: `${element.props.className || ""} ${className}`.trim(),
|
|
4816
|
+
"data-block-id": block.id,
|
|
4817
|
+
"data-finalized": isFinalized
|
|
4818
|
+
});
|
|
4819
|
+
});
|
|
4820
|
+
export {
|
|
4821
|
+
ComponentRegistry,
|
|
4822
|
+
MarkdownBlocksRenderer,
|
|
4823
|
+
createRendererStore
|
|
4824
|
+
};
|