Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Improve renderHTML and TexPlugin (#2)

Myles Scolnick7aa9a047da86
diff --git a/Makefile b/Makefile
index 697088c30b..9a84a5a52c 100644
--- a/Makefile
+++ b/Makefile
@@ -33,7 +33,7 @@ fe-check: fe-lint fe-typecheck
.PHONY: fe-test
# test frontend
fe-test:
- cd frontend; pnpm test
+ cd frontend; CI=true pnpm test
.PHONY: e2e
# test end-to-end
diff --git a/frontend/package.json b/frontend/package.json
index be9b194d5a..e3ee248b2f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -76,7 +76,7 @@
},
"scripts": {
"preinstall": "npx only-allow pnpm",
- "ci": "run-s lint typecheck test build",
+ "ci": "CI=true run-s lint typecheck test build",
"start": "vite",
"dev": "vite",
"dev:msw": "VITE_MSW=true vite",
diff --git a/frontend/src/editor/output/HtmlOutput.tsx b/frontend/src/editor/output/HtmlOutput.tsx
index a931025e6e..ac175d1616 100644
--- a/frontend/src/editor/output/HtmlOutput.tsx
+++ b/frontend/src/editor/output/HtmlOutput.tsx
@@ -2,7 +2,7 @@
import { memo, useLayoutEffect, useRef } from "react";
import { lookupScript, updateScriptCache } from "./scripts";
import { Logger } from "../../utils/Logger";
-import { RenderHTML } from "../../plugins/core/RenderHTML";
+import { renderHTML } from "../../plugins/core/RenderHTML";
import { cn } from "../../lib/utils";
interface Props {
@@ -78,7 +78,7 @@ export const HtmlOutput: React.FC<Props> = memo(
})}
ref={nodeRef}
>
- <RenderHTML html={html} />
+ {renderHTML({ html })}
</div>
);
}
diff --git a/frontend/src/plugins/core/RenderHTML.tsx b/frontend/src/plugins/core/RenderHTML.tsx
index 42f97c6aed..b1446b2e11 100644
--- a/frontend/src/plugins/core/RenderHTML.tsx
+++ b/frontend/src/plugins/core/RenderHTML.tsx
@@ -1,40 +1,32 @@
/* Copyright 2023 Marimo. All rights reserved. */
import parse, { Element } from "html-react-parser";
-import React from "react";
-interface Props {
+interface Options {
html: string;
}
/**
- * Wrapper for customer dangerouslySetInnerHTML.
* We instead render HTML to React elements using html-react-parser as this keeps
* React elements in place so React's reconciliation algorithm will update nodes instead of unmounting and remounting.
*/
-export const RenderHTML: React.FC<Props> = ({ html }) => {
- return (
- <>
- {parse(html, {
- replace: (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]) => {
- element.setAttribute(key, value as string);
- });
- return (
- <div dangerouslySetInnerHTML={{ __html: element.outerHTML }} />
- );
- }
- return domNode;
- },
- })}
- </>
- );
+export const renderHTML = ({ html }: Options) => {
+ return parse(html, {
+ replace: (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]) => {
+ element.setAttribute(key, value as string);
+ });
+ return <div dangerouslySetInnerHTML={{ __html: element.outerHTML }} />;
+ }
+ return domNode;
+ },
+ });
};
diff --git a/frontend/src/plugins/core/componentFactory.tsx b/frontend/src/plugins/core/componentFactory.tsx
index 4853a771f4..92e4b8df51 100644
--- a/frontend/src/plugins/core/componentFactory.tsx
+++ b/frontend/src/plugins/core/componentFactory.tsx
@@ -28,7 +28,7 @@ import { parseAttrValue, parseInitialValue } from "../../core/dom/htmlUtils";
import { IPlugin } from "../types";
import { Objects } from "../../utils/objects";
import { renderError } from "./BadPlugin";
-import { RenderHTML } from "./RenderHTML";
+import { renderHTML } from "./RenderHTML";
import { invariant } from "../../utils/invariant";
import { Logger } from "../../utils/Logger";
@@ -245,27 +245,9 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {
/**
* Get the children of the element as React nodes.
- * Any text nodes will be wrapped in a <span> element.
- *
- * TODO: would be nicer to just do `<RenderHTML html={this.innerHTML} />
- * but downstream plugins (like Tex) may assume a wrapped element.
- * We can fix this in future.
*/
private getChildren(): React.ReactNode {
- return Array.from(this.childNodes)
- .map((child) => {
- if (
- child.nodeType === Node.ELEMENT_NODE &&
- child instanceof HTMLElement
- ) {
- return <RenderHTML html={child.outerHTML} />;
- } else if (child.nodeType === Node.TEXT_NODE) {
- return <span>{child.textContent}</span>;
- } else {
- return undefined;
- }
- })
- .filter(Boolean);
+ return renderHTML({ html: this.innerHTML });
}
/**
diff --git a/frontend/src/plugins/impl/ButtonPlugin.tsx b/frontend/src/plugins/impl/ButtonPlugin.tsx
index f77250c794..804c530c75 100644
--- a/frontend/src/plugins/impl/ButtonPlugin.tsx
+++ b/frontend/src/plugins/impl/ButtonPlugin.tsx
@@ -3,7 +3,7 @@ import { z } from "zod";
import { IPlugin, IPluginProps } from "../types";
import { Button } from "../../components/ui/button";
-import { RenderHTML } from "../core/RenderHTML";
+import { renderHTML } from "../core/RenderHTML";
export class ButtonPlugin implements IPlugin<number, { label: string }> {
tagName = "marimo-button";
@@ -19,7 +19,7 @@ export class ButtonPlugin implements IPlugin<number, { label: string }> {
onClick={() => props.setValue((v) => v + 1)}
type="submit"
>
- <RenderHTML html={props.data.label} />
+ {renderHTML({ html: props.data.label })}
</Button>
);
}
diff --git a/frontend/src/plugins/impl/CheckboxPlugin.tsx b/frontend/src/plugins/impl/CheckboxPlugin.tsx
index b682682314..436dd74da3 100644
--- a/frontend/src/plugins/impl/CheckboxPlugin.tsx
+++ b/frontend/src/plugins/impl/CheckboxPlugin.tsx
@@ -7,7 +7,7 @@ import * as labelStyles from "./Label.styles";
import { Checkbox } from "../../components/ui/checkbox";
import { Label } from "../../components/ui/label";
import { CheckedState } from "@radix-ui/react-checkbox";
-import { RenderHTML } from "../core/RenderHTML";
+import { renderHTML } from "../core/RenderHTML";
export class CheckboxPlugin
implements IPlugin<boolean, { label: string | null }>
@@ -40,7 +40,7 @@ const CheckboxComponent = ({
const labelElement =
data.label === null ? null : (
<Label htmlFor={id} className="text-md">
- <RenderHTML html={data.label} />
+ {renderHTML({ html: data.label })}
</Label>
);
diff --git a/frontend/src/plugins/impl/SwitchPlugin.tsx b/frontend/src/plugins/impl/SwitchPlugin.tsx
index 7c272941b0..2db7a65347 100644
--- a/frontend/src/plugins/impl/SwitchPlugin.tsx
+++ b/frontend/src/plugins/impl/SwitchPlugin.tsx
@@ -7,7 +7,7 @@ import { Label } from "@/components/ui/label";
import { IPlugin, IPluginProps } from "@/plugins/types";
import * as labelStyles from "@/plugins/impl/Label.styles";
import { cn } from "@/lib/utils";
-import { RenderHTML } from "../core/RenderHTML";
+import { renderHTML } from "../core/RenderHTML";
export class SwitchPlugin
implements IPlugin<boolean, { label: string | null }>
@@ -33,7 +33,7 @@ const SwitchComponent = ({
const labelElement =
data.label === null ? null : (
<Label htmlFor={id} className="text-md">
- <RenderHTML html={data.label} />
+ {renderHTML({ html: data.label })}
</Label>
);
diff --git a/frontend/src/plugins/layout/AccordionPlugin.tsx b/frontend/src/plugins/layout/AccordionPlugin.tsx
index 12860f0dc6..bfdb97cc5e 100644
--- a/frontend/src/plugins/layout/AccordionPlugin.tsx
+++ b/frontend/src/plugins/layout/AccordionPlugin.tsx
@@ -9,7 +9,7 @@ import {
} from "@/components/ui/accordion";
import { z } from "zod";
import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";
-import { RenderHTML } from "../core/RenderHTML";
+import { renderHTML } from "../core/RenderHTML";
interface Data {
/**
@@ -54,7 +54,7 @@ const AccordionComponent = ({
className="border-muted-foreground-20"
>
<AccordionTrigger className="py-2 text-md">
- <RenderHTML html={labels[index]} />
+ {renderHTML({ html: labels[index] })}
</AccordionTrigger>
<AccordionContent className="text-md">{child}</AccordionContent>
</AccordionItem>
diff --git a/frontend/src/plugins/layout/TabsPlugin.tsx b/frontend/src/plugins/layout/TabsPlugin.tsx
index c639f3a3eb..f418a44a8b 100644
--- a/frontend/src/plugins/layout/TabsPlugin.tsx
+++ b/frontend/src/plugins/layout/TabsPlugin.tsx
@@ -9,7 +9,7 @@ import {
} from "../../components/ui/tabs";
import { z } from "zod";
import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";
-import { RenderHTML } from "../core/RenderHTML";
+import { renderHTML } from "../core/RenderHTML";
interface Data {
/**
@@ -39,7 +39,7 @@ const TabComponent = ({
<TabsList>
{tabs.map((tab, index) => (
<TabsTrigger key={index} value={index.toString()}>
- <RenderHTML html={tab} />
+ {renderHTML({ html: tab })}
</TabsTrigger>
))}
</TabsList>
diff --git a/frontend/src/plugins/layout/TexPlugin.tsx b/frontend/src/plugins/layout/TexPlugin.tsx
index 81d603a7cc..a04584c788 100644
--- a/frontend/src/plugins/layout/TexPlugin.tsx
+++ b/frontend/src/plugins/layout/TexPlugin.tsx
@@ -1,5 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import React, { PropsWithChildren, useLayoutEffect, useRef } from "react";
+import { useLayoutEffect, useRef } from "react";
import katex from "katex";
import { z } from "zod";
@@ -17,32 +17,33 @@ export class TexPlugin implements IStatelessPlugin<{}> {
validator = z.object({});
render(props: IStatelessPluginProps<{}>): JSX.Element {
- return <TexComponent>{props.children}</TexComponent>;
+ return (
+ <TexComponent tex={props.host.textContent || props.host.innerHTML} />
+ );
}
}
-function renderLatex(element: HTMLElement) {
- const tex = element.textContent || element.innerText;
+function renderLatex(mount: HTMLElement, tex: string) {
if (tex.startsWith("||(||(") && tex.endsWith("||)||)")) {
// when $$...$$ is used without newlines before/after the $$.
- katex.render(tex.slice(6, -6), element, {
+ katex.render(tex.slice(6, -6), mount, {
displayMode: true,
throwOnError: false,
});
} else if (tex.startsWith("||(") && tex.endsWith("||)")) {
- katex.render(tex.slice(3, -3), element, {
+ katex.render(tex.slice(3, -3), mount, {
displayMode: false,
throwOnError: false,
});
} else if (tex.startsWith("||[") && tex.endsWith("||]")) {
- katex.render(tex.slice(3, -3), element, {
+ katex.render(tex.slice(3, -3), mount, {
displayMode: true,
throwOnError: false,
});
}
}
-const TexComponent = ({ children }: PropsWithChildren<{}>): JSX.Element => {
+const TexComponent = ({ tex }: { tex: string }): JSX.Element => {
const ref = useRef<HTMLSpanElement>(null);
// The arithmatex markdown extension we use in Python produces nested
@@ -68,19 +69,10 @@ const TexComponent = ({ children }: PropsWithChildren<{}>): JSX.Element => {
// Re-render when the text content changes.
useLayoutEffect(() => {
- if (ref.current?.firstElementChild) {
- renderLatex(ref.current.firstElementChild as HTMLElement);
+ if (ref.current) {
+ renderLatex(ref.current, tex);
}
- }, [ref.current?.textContent]);
+ }, [tex]);
- // When we > 1 children, we're in display math mode, so style accordingly.
- const childrenToRender =
- React.Children.count(children) > 1 ? (
- <div className="block my-4 text-center">
- {React.Children.toArray(children)[1]}
- </div>
- ) : (
- children
- );
- return <span ref={ref}>{childrenToRender}</span>;
+ return <span ref={ref} />;
};