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.

fix: re-rendering of latex (#7010)

Myles Scolnick2e569dde2ce5
diff --git a/frontend/src/plugins/layout/TexPlugin.tsx b/frontend/src/plugins/layout/TexPlugin.tsx
index 0c10eefdd6..1a355f7dde 100644
--- a/frontend/src/plugins/layout/TexPlugin.tsx
+++ b/frontend/src/plugins/layout/TexPlugin.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { type JSX, useLayoutEffect, useRef } from "react";
+import { type JSX, useLayoutEffect, useRef, useState } from "react";
import { z } from "zod";
import { once } from "@/utils/once";
@@ -21,7 +21,10 @@ export class TexPlugin implements IStatelessPlugin<{}> {
render(props: IStatelessPluginProps<{}>): JSX.Element {
return (
- <TexComponent tex={props.host.textContent || props.host.innerHTML} />
+ <TexComponent
+ host={props.host}
+ tex={props.host.textContent || props.host.innerHTML}
+ />
);
}
}
@@ -67,8 +70,33 @@ async function renderLatex(mount: HTMLElement, tex: string): Promise<void> {
}
}
-const TexComponent = ({ tex }: { tex: string }): JSX.Element => {
+const TexComponent = ({
+ host,
+ tex,
+}: {
+ host: HTMLElement;
+ tex: string;
+}): JSX.Element => {
const ref = useRef<HTMLSpanElement>(null);
+ const [currentTex, setCurrentTex] = useState(tex);
+
+ // Watch for changes to the host element's direct children
+ useLayoutEffect(() => {
+ const observer = new MutationObserver(() => {
+ const newTex = host.textContent || host.innerHTML;
+ setCurrentTex(newTex);
+ });
+
+ observer.observe(host, {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [host]);
// The arithmatex markdown extension we use in Python produces nested
// marimo-tex tags when $$...$$ math is used in a paragraph, with dummy
@@ -94,9 +122,9 @@ const TexComponent = ({ tex }: { tex: string }): JSX.Element => {
// Re-render when the text content changes.
useLayoutEffect(() => {
if (ref.current) {
- renderLatex(ref.current, tex);
+ renderLatex(ref.current, currentTex);
}
- }, [tex]);
+ }, [currentTex]);
return <span ref={ref} />;
};
diff --git a/marimo/_smoke_tests/markdown/rerendering_latex.py b/marimo/_smoke_tests/markdown/rerendering_latex.py
new file mode 100644
index 0000000000..ee8aeb975c
--- /dev/null
+++ b/marimo/_smoke_tests/markdown/rerendering_latex.py
@@ -0,0 +1,33 @@
+import marimo
+
+__generated_with = "0.17.4"
+app = marimo.App(width="medium")
+
+
+def _():
+ return
+
+
+def _(mo):
+ a=mo.ui.table({"a":[1,2,3]},selection="single",initial_selection=[0])
+ a
+ return (a,)
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+def _(a, mo):
+ md = mo.md(f"$a={a.value["a"][0]}$")
+ md
+ return
+
+
+if __name__ == "__main__":
+ app.run()