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: remount <img> on src change in mo.Html to avoid stale paint (#9472)

Myles Scolnick297fc2e39dfb
diff --git a/frontend/src/plugins/core/RenderHTML.tsx b/frontend/src/plugins/core/RenderHTML.tsx
index 4d7d21de4d..68391e4c5c 100644
--- a/frontend/src/plugins/core/RenderHTML.tsx
+++ b/frontend/src/plugins/core/RenderHTML.tsx
@@ -6,6 +6,7 @@ import parse, {
type HTMLReactParserOptions,
} from "html-react-parser";
import React, {
+ cloneElement,
isValidElement,
type JSX,
type ReactNode,
@@ -169,6 +170,35 @@ const addCopyButtonToCodehilite: TransformFn = (
}
};
+// Decorator (not a match-and-replace transform): applies a src-based key
+// to <img> elements so they remount on src change. Reusing an <img> across
+// src changes can leave the previous image painted (e.g. when the new
+// request is slow/blocked, served stale by a CDN, or fails CORS), so the
+// user sees the old image even though the HTML source is up to date.
+//
+// Runs unconditionally after the match-and-replace transforms so it still
+// applies when an <img> was already wrapped by, say, wrapTooltipTargets.
+const keyImagesBySrc: TransformFn = (
+ reactNode: ReactNode,
+ domNode: DOMNode,
+ index: number,
+): JSX.Element | undefined => {
+ if (!(domNode instanceof Element) || domNode.name !== "img") {
+ return undefined;
+ }
+ const src = domNode.attribs?.src;
+ if (!src || !isValidElement(reactNode)) {
+ return undefined;
+ }
+ // data: URIs are inline — no network fetch — so they can't go stale.
+ // Skip to avoid bloating the React key with a megabyte base64 payload.
+ // URI schemes are case-insensitive per RFC 3986.
+ if (/^data:/i.test(src)) {
+ return undefined;
+ }
+ return cloneElement(reactNode, { key: `${src}-${index}` });
+};
+
// Wrap elements with data-marimo-doc attribute in a DocHoverTarget
const wrapDocHoverTargets: TransformFn = (
reactNode: ReactNode,
@@ -281,6 +311,8 @@ function parseHtml({
...additionalReplacements,
];
+ // Match-and-replace transforms: the first one that returns a value wins
+ // (short-circuits the rest).
const transformFunctions: TransformFn[] = [
addCopyButtonToCodehilite,
preserveQueryParamsInAnchorLinks,
@@ -290,6 +322,12 @@ function parseHtml({
removeWrappingHtmlTags,
];
+ // Decorators: run unconditionally on the result of the transform pipeline
+ // and may further wrap/clone it. Used for cross-cutting concerns that
+ // should apply regardless of which (if any) match-and-replace transform
+ // ran above.
+ const decoratorFunctions: TransformFn[] = [keyImagesBySrc];
+
return parse(html, {
replace: (domNode: DOMNode, index: number) => {
for (const renderFunction of renderFunctions) {
@@ -301,13 +339,21 @@ function parseHtml({
return domNode;
},
transform: (reactNode: ReactNode, domNode: DOMNode, index: number) => {
+ let result: ReactNode = reactNode as JSX.Element;
for (const transformFunction of transformFunctions) {
- const transformed = transformFunction(reactNode, domNode, index);
+ const transformed = transformFunction(result, domNode, index);
if (transformed) {
- return transformed;
+ result = transformed;
+ break;
+ }
+ }
+ for (const decorate of decoratorFunctions) {
+ const decorated = decorate(result, domNode, index);
+ if (decorated) {
+ result = decorated;
}
}
- return reactNode as JSX.Element;
+ return result as JSX.Element;
},
});
}
diff --git a/frontend/src/plugins/core/__test__/RenderHTML.test.ts b/frontend/src/plugins/core/__test__/RenderHTML.test.ts
index 11db5fc6ae..a048ce9f94 100644
--- a/frontend/src/plugins/core/__test__/RenderHTML.test.ts
+++ b/frontend/src/plugins/core/__test__/RenderHTML.test.ts
@@ -60,6 +60,60 @@ describe("parseHtml", () => {
`);
});
+ test("img has key derived from src so React remounts on src change", () => {
+ const html = '<img src="https://cdn.example.com/a.png" alt="a">';
+ const result = parseHtml({ html }) as React.ReactElement;
+ expect(result.key).toBe("https://cdn.example.com/a.png-0");
+ });
+
+ test("multiple imgs each get distinct keys", () => {
+ const html =
+ '<div><img src="https://cdn.example.com/a.png"><img src="https://cdn.example.com/b.png"></div>';
+ const result = parseHtml({ html }) as React.ReactElement<{
+ children: React.ReactElement[];
+ }>;
+ const children = result.props.children;
+ expect(children[0].key).toBe("https://cdn.example.com/a.png-0");
+ expect(children[1].key).toBe("https://cdn.example.com/b.png-1");
+ });
+
+ test("img without src is left alone", () => {
+ const html = "<img>";
+ const result = parseHtml({ html }) as React.ReactElement;
+ expect(result.key).toBeNull();
+ });
+
+ test("img with data: URI is not keyed (inline, no network fetch)", () => {
+ const longPayload = "A".repeat(10_000);
+ const html = `<img src="data:image/png;base64,${longPayload}">`;
+ const result = parseHtml({ html }) as React.ReactElement;
+ // No remount-on-src needed for inline images, so we leave the key
+ // unset rather than bloat it with the base64 payload.
+ expect(result.key).toBeNull();
+ });
+
+ test("img with uppercase DATA: URI is also skipped (scheme is case-insensitive)", () => {
+ const html = `<img src="DATA:image/png;base64,${"A".repeat(100)}">`;
+ const result = parseHtml({ html }) as React.ReactElement;
+ expect(result.key).toBeNull();
+ });
+
+ test("img wrapped by data-tooltip is still keyed by src", () => {
+ const html =
+ '<img src="https://cdn.example.com/a.png" data-tooltip="hi" alt="a">';
+ const result = parseHtml({ html }) as React.ReactElement;
+ // Outer Tooltip carries the src-based key so it remounts on src change,
+ // forcing the inner <img> to remount as well.
+ expect(result.key).toBe("https://cdn.example.com/a.png-0");
+ });
+
+ test("img wrapped by data-marimo-doc is still keyed by src", () => {
+ const html =
+ '<img src="https://cdn.example.com/b.png" data-marimo-doc="foo.bar">';
+ const result = parseHtml({ html }) as React.ReactElement;
+ expect(result.key).toBe("https://cdn.example.com/b.png-0");
+ });
+
test("codehilite with copy button", () => {
const html =
'<div class="codehilite"><pre><code>console.log("Hello");</code></pre></div>';
diff --git a/marimo/_smoke_tests/img_rerender.py b/marimo/_smoke_tests/img_rerender.py
new file mode 100644
index 0000000000..1bd888e718
--- /dev/null
+++ b/marimo/_smoke_tests/img_rerender.py
@@ -0,0 +1,73 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "marimo",
+# ]
+# ///
+# Smoke test for stale <img> rendering when mo.Html re-runs with new src URLs.
+#
+# Repro: pick a set, run the cell, then change the radio to swap the
+# URLs. Each <img> should display the newly selected image. Before the
+# RenderHTML key-by-src fix, the prior images stayed painted.
+
+import marimo
+
+__generated_with = "0.23.5"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
+def _(mo):
+ sets = {
+ "set A (cats)": [
+ "https://placecats.com/200/200",
+ "https://placecats.com/201/200",
+ "https://placecats.com/202/200",
+ "https://placecats.com/203/200",
+ "https://placecats.com/204/200",
+ ],
+ "set B (bears)": [
+ "https://placebear.com/200/200",
+ "https://placebear.com/201/200",
+ "https://placebear.com/202/200",
+ "https://placebear.com/203/200",
+ "https://placebear.com/204/200",
+ ],
+ }
+ choice = mo.ui.radio(options=list(sets), value="set A (cats)")
+ choice
+ return choice, sets
+
+
+def _(choice, mo, sets):
+ urls = sets[choice.value]
+ imgs = "".join(
+ f'<img src="{u}" width="120" height="120" style="margin:4px"/>'
+ for u in urls
+ )
+ mo.Html(f'<div>{imgs}</div>')
+ return
+
+
+def _(mo):
+ mo.md("""
+ ### What to check
+ - Toggle the radio between the two sets repeatedly.
+ - Each `<img>` should swap to the newly selected URL.
+ - Open devtools and confirm the rendered `<img>` `src` attributes
+ match the selected set, and that the painted images match too.
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()