-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathRenderHTML.tsx
More file actions
356 lines (332 loc) · 11.5 KB
/
Copy pathRenderHTML.tsx
File metadata and controls
356 lines (332 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/* Copyright 2026 Marimo. All rights reserved. */
import parse, {
type DOMNode,
Element,
type HTMLReactParserOptions,
} from "html-react-parser";
import React, {
isValidElement,
type JSX,
type ReactNode,
useMemo,
useRef,
} from "react";
import { CopyClipboardIcon } from "@/components/icons/copy-icon";
import { QueryParamPreservingLink } from "@/components/ui/query-param-preserving-link";
import { Tooltip } from "@/components/ui/tooltip";
import { DocHoverTarget } from "@/core/documentation/DocHoverTarget";
import { hasTrustedNotebookContext } from "@/core/static/export-context";
import { Logger } from "@/utils/Logger";
import { getRuntimeManager } from "@/core/runtime/config";
import { sanitizeHtml, useSanitizeHtml } from "./sanitize";
type ReplacementFn = NonNullable<HTMLReactParserOptions["replace"]>;
type TransformFn = NonNullable<HTMLReactParserOptions["transform"]>;
interface Options {
html: string;
/**
* Whether to sanitize the HTML.
* @default true
*/
alwaysSanitizeHtml?: boolean;
additionalReplacements?: ReplacementFn[];
}
// Resolve a virtual file URL (./@file/... or @file/...) to an absolute URL
// using the runtime base, ensuring a trailing slash so the notebook-ID path
// segment is never dropped during relative resolution.
function resolveVirtualFileUrl(src: string): string {
const base = getRuntimeManager().httpURL;
if (!base.pathname.endsWith("/")) {
base.pathname += "/";
}
return new URL(src.replace(/^\.\//,""), base).toString();
}
// Rewrite relative @file virtual-file URLs to absolute URLs so they resolve
// correctly even when the page URL has no trailing slash (e.g., molab edit mode).
// The virtual file URL is generated as "./@file/SIZE-filename" (relative). When
// the page URL has no trailing slash (e.g., /notebooks/nb_xxx), the browser
// resolves "./@file/..." to "/notebooks/@file/..." — dropping the notebook ID.
// We fix this by resolving against the runtime base URL with a guaranteed
// trailing slash, making the URL unambiguous.
const VIRTUAL_FILE_SRC_TAGS = new Set(["img", "source", "audio", "video"]);
const replaceVirtualFileSrc = (domNode: DOMNode): JSX.Element | undefined => {
if (
domNode instanceof Element &&
VIRTUAL_FILE_SRC_TAGS.has(domNode.name) &&
domNode.attribs?.src
) {
const src = domNode.attribs.src;
if (src.includes("/@file/") || src.startsWith("@file/")) {
const absoluteSrc = resolveVirtualFileUrl(src);
const props = { ...domNode.attribs, src: absoluteSrc };
return React.createElement(domNode.name, props);
}
}
};
const replaceValidTags = (domNode: DOMNode) => {
// Don't render invalid tags
if (domNode instanceof Element && !/^[A-Za-z][\w-]*$/.test(domNode.name)) {
return React.createElement(React.Fragment);
}
};
const removeWrappingBodyTags: TransformFn = (
reactNode: ReactNode,
domNode: DOMNode,
) => {
// Remove body tags and just render their children
if (domNode instanceof Element && domNode.name === "body") {
if (isValidElement(reactNode) && "props" in reactNode) {
const props = reactNode.props as { children?: ReactNode };
const children = props.children;
return <>{children}</>; // oxlint-disable-line react/jsx-no-useless-fragment
}
return;
}
};
const removeWrappingHtmlTags: TransformFn = (
reactNode: ReactNode,
domNode: DOMNode,
) => {
// Remove html tags and just render their children
if (domNode instanceof Element && domNode.name === "html") {
if (isValidElement(reactNode) && "props" in reactNode) {
const props = reactNode.props as { children?: ReactNode };
const children = props.children;
return <>{children}</>; // oxlint-disable-line react/jsx-no-useless-fragment
}
return;
}
};
const replaceValidIframes = (domNode: DOMNode) => {
// For iframe, we just want to use dangerouslySetInnerHTML so:
// 1) we can remount the iframe when the src changes
// 2) keep event attributes (onload, etc.) since this library removes them
if (
domNode instanceof Element &&
domNode.attribs &&
domNode.name === "iframe"
) {
const element = document.createElement("iframe");
Object.entries(domNode.attribs).forEach(([key, value]) => {
// If it is wrapped in quotes, remove them
// html-react-parser will return quoted keys if they are
// valueless attributes (e.g. "allowfullscreen")
if (key.startsWith('"') && key.endsWith('"')) {
key = key.slice(1, -1);
}
// Rewrite relative @file URLs to absolute (same fix as replaceVirtualFileSrc)
if (key === "src" && (value.includes("/@file/") || value.startsWith("@file/"))) {
value = resolveVirtualFileUrl(value);
}
element.setAttribute(key, value);
});
return <div dangerouslySetInnerHTML={{ __html: element.outerHTML }} />;
}
};
const replaceSrcScripts = (domNode: DOMNode): JSX.Element | undefined => {
if (domNode instanceof Element && domNode.name === "script") {
// Missing src, we don't handle inline scripts
const src = domNode.attribs.src;
if (!src) {
return;
}
// Only append notebook-authored scripts when the page is a trusted
// context (the user has run a cell, the page is a trusted export, or
// we're running in read/app mode). In untrusted edit mode before any
// user interaction, drop the script and log a warning. Outer
// sanitization will normally strip <script> tags already; this is
// defense-in-depth for flows that reparse children with
// alwaysSanitizeHtml: false (see registerReactComponent.getChildren).
if (!hasTrustedNotebookContext()) {
Logger.warn(
`[RenderHTML] refusing <script src> in untrusted context: ${src}`,
);
// oxlint-disable-next-line react/jsx-no-useless-fragment
return <></>;
}
// Check if script already exists. Avoid building a CSS selector from
// notebook-provided input, which can throw for valid URLs containing
// selector-significant characters (e.g. IPv6 hosts with `[`/`]`).
const scriptExists = [...document.querySelectorAll("script[src]")].some(
(existingScript) => existingScript.getAttribute("src") === src,
);
if (!scriptExists) {
const script = document.createElement("script");
script.src = src;
document.head.append(script);
}
// oxlint-disable-next-line react/jsx-no-useless-fragment
return <></>;
}
};
const preserveQueryParamsInAnchorLinks: TransformFn = (
reactNode: ReactNode,
domNode: DOMNode,
): JSX.Element | undefined => {
if (domNode instanceof Element && domNode.name === "a") {
const href = domNode.attribs.href;
// Only handle anchor links (starting with #)
if (href?.startsWith("#") && !href.startsWith("#code/")) {
// Get the children from the parsed React node
let children: ReactNode = null;
if (isValidElement(reactNode) && "props" in reactNode) {
const props = reactNode.props as { children?: ReactNode };
children = props.children;
}
return (
<QueryParamPreservingLink href={href} {...domNode.attribs}>
{children}
</QueryParamPreservingLink>
);
}
}
};
// Add copy button to codehilite blocks
const addCopyButtonToCodehilite: TransformFn = (
reactNode: ReactNode,
domNode: DOMNode,
index: number,
): JSX.Element | undefined => {
if (
domNode instanceof Element &&
domNode.name === "div" &&
domNode.attribs?.class?.includes("codehilite")
) {
return <CopyableCode key={index}>{reactNode}</CopyableCode>;
}
};
// Wrap elements with data-marimo-doc attribute in a DocHoverTarget
const wrapDocHoverTargets: TransformFn = (
reactNode: ReactNode,
domNode: DOMNode,
): JSX.Element | undefined => {
if (domNode instanceof Element && domNode.attribs?.["data-marimo-doc"]) {
const qualifiedName = domNode.attribs["data-marimo-doc"];
return (
<DocHoverTarget qualifiedName={qualifiedName}>{reactNode}</DocHoverTarget>
);
}
};
// Wrap elements with data-tooltip attribute in a Tooltip component.
// This renders the tooltip in a portal (top layer), fixing clipping inside
// containers with overflow:hidden (e.g. grid cells).
//
// Marimo custom elements (marimo-button, etc.) are skipped — they handle
// tooltips via the plugin system inside their Shadow DOM. Wrapping them here
// would create a duplicate tooltip with incorrect positioning and
// un-decoded JSON content (the data-* value is JSON-encoded by the backend).
const wrapTooltipTargets: TransformFn = (
reactNode: ReactNode,
domNode: DOMNode,
): JSX.Element | undefined => {
if (domNode instanceof Element && domNode.attribs?.["data-tooltip"]) {
const tagName = domNode.name?.toLowerCase() ?? "";
if (tagName.startsWith("marimo-")) {
return undefined;
}
const tooltipContent = domNode.attribs["data-tooltip"];
return (
<Tooltip content={tooltipContent}>{reactNode as JSX.Element}</Tooltip>
);
}
};
const CopyableCode = ({ children }: { children: ReactNode }) => {
const ref = useRef<HTMLDivElement>(null);
return (
<div className="relative group codehilite-wrapper" ref={ref}>
{children}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<CopyClipboardIcon
tooltip={false}
className="p-1"
value={() => {
const codeElement = ref.current?.firstChild;
if (codeElement) {
return codeElement.textContent || "";
}
return "";
}}
/>
</div>
</div>
);
};
/**
*
* @param html - The HTML to render.
* @param additionalReplacements - Additional replacements to apply to the HTML.
* @param alwaysSanitizeHtml - Whether to sanitize the HTML.
* @returns
*/
export const renderHTML = ({
html,
additionalReplacements = [],
alwaysSanitizeHtml = true,
}: Options) => {
return (
<RenderHTML
html={html}
alwaysSanitizeHtml={alwaysSanitizeHtml}
additionalReplacements={additionalReplacements}
/>
);
};
const RenderHTML = ({
html,
additionalReplacements = [],
alwaysSanitizeHtml,
}: Options) => {
const shouldSanitizeHtml = useSanitizeHtml();
const sanitizedHtml = useMemo(() => {
if (alwaysSanitizeHtml || shouldSanitizeHtml) {
return sanitizeHtml(html);
}
return html;
}, [html, alwaysSanitizeHtml, shouldSanitizeHtml]);
return parseHtml({
html: sanitizedHtml,
additionalReplacements,
});
};
function parseHtml({
html,
additionalReplacements = [],
}: Pick<Options, "html" | "additionalReplacements">) {
const renderFunctions: ReplacementFn[] = [
replaceVirtualFileSrc,
replaceValidTags,
replaceValidIframes,
replaceSrcScripts,
...additionalReplacements,
];
const transformFunctions: TransformFn[] = [
addCopyButtonToCodehilite,
preserveQueryParamsInAnchorLinks,
wrapDocHoverTargets,
wrapTooltipTargets,
removeWrappingBodyTags,
removeWrappingHtmlTags,
];
return parse(html, {
replace: (domNode: DOMNode, index: number) => {
for (const renderFunction of renderFunctions) {
const replacement = renderFunction(domNode, index);
if (replacement) {
return replacement;
}
}
return domNode;
},
transform: (reactNode: ReactNode, domNode: DOMNode, index: number) => {
for (const transformFunction of transformFunctions) {
const transformed = transformFunction(reactNode, domNode, index);
if (transformed) {
return transformed;
}
}
return reactNode as JSX.Element;
},
});
}
export const visibleForTesting = {
parseHtml,
};