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: patch matplotlib interactive to not steal focus on mount (#5586)

Myles Scolnick2e4aaf962e63
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index 060fb2075a..d610bbed23 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -133,7 +133,7 @@ def create_application() -> Starlette:
async def mpl_js(request: Request) -> Response:
del request
return Response(
- content=FigureManagerWebAgg.get_javascript(), # type: ignore[no-untyped-call]
+ content=patch_javascript(FigureManagerWebAgg.get_javascript()), # type: ignore[no-untyped-call]
media_type="application/javascript",
)
@@ -509,3 +509,17 @@ select.mpl-widget,
filter: invert(0.3);
}
""".strip()
+
+
+def patch_javascript(javascript: str) -> str:
+ # Comment out canvas.focus() and canvas_div.focus() calls
+ # https://github.com/matplotlib/matplotlib/blob/4c345b42048811a2122ba0db68551c6ea4ddaf6a/lib/matplotlib/backends/web_backend/js/mpl.js#L338-L343
+ javascript = javascript.replace(
+ " canvas.focus();",
+ "// canvas.focus(); // don't steal focus when in marimo",
+ )
+ javascript = javascript.replace(
+ " canvas_div.focus();",
+ "// canvas_div.focus(); // don't steal focus when in marimo",
+ )
+ return javascript
diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.py
index 3017424fd6..5ffebf8582 100644
--- a/tests/_plugins/stateless/test_mpl.py
+++ b/tests/_plugins/stateless/test_mpl.py
@@ -64,3 +64,19 @@ async def test_mpl_show(k: Kernel, exec_req: ExecReqProvider) -> None:
)
]
)
+
+
+ not DependencyManager.matplotlib.has(),
+ reason="matplotlib is not installed",
+)
+def test_patch_javascript() -> None:
+ from matplotlib.backends.backend_webagg_core import FigureManagerWebAgg
+
+ from marimo._plugins.stateless.mpl._mpl import patch_javascript
+
+ javascript: str = str(FigureManagerWebAgg.get_javascript()) # type: ignore[no-untyped-call]
+ assert javascript is not None
+ javascript = patch_javascript(javascript)
+ assert javascript.count("// canvas.focus();") == 1
+ assert javascript.count("// canvas_div.focus();") == 1