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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: add --no-show-code to marimo export wasm (#3184)
Myles Scolnick9a183bdc31fe
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.mdindex 8fa9b9c055..92bfd8ef7c 100644--- a/docs/guides/exporting.md+++ b/docs/guides/exporting.md@@ -149,6 +149,7 @@ Options:- `--mode`: Choose between `run` (read-only) or `edit` (allows editing)- `--output`: Directory to save the HTML and required assets+- `--show-code/--no-show-code`: Whether to initially show or hide the code in the notebook```{admonition} Note:class: notediff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex 239030b80a..8da9cd3548 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -39,6 +39,7 @@ import { KnownQueryParams } from "@/core/constants";import { useResolvedMarimoConfig } from "@/core/config/config";import { MarkdownLanguageAdapter } from "@/core/codemirror/language/markdown";import { isErrorMime } from "@/core/mime";+import { getMarimoShowCode } from "@/core/dom/marimo-tag";type VerticalLayout = null;type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;@@ -53,12 +54,18 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({const [userConfig] = useResolvedMarimoConfig();const urlParams = new URLSearchParams(window.location.search);- const showCodeDefault = urlParams.get(KnownQueryParams.showCode);const [showCode, setShowCode] = useState(() => {- // Default to showing code if the notebook is static or wasm- return showCodeDefault === null+ // Check marimo-code tag setting first+ const showCodePreference = getMarimoShowCode();+ if (!showCodePreference) {+ return false;+ }+ // If 'auto' or not found, use URL param+ // If url param is not set, we default to true for static notebooks, wasm notebooks, and kiosk mode+ const showCodeByQueryParam = urlParams.get(KnownQueryParams.showCode);+ return showCodeByQueryParam === null? isStaticNotebook() || isWasm() || kioskMode- : showCodeDefault === "true";+ : showCodeByQueryParam === "true";});const evaluateCanShowCode = () => {diff --git a/frontend/src/core/dom/marimo-tag.ts b/frontend/src/core/dom/marimo-tag.tsindex 5a65d15139..613ee993ca 100644--- a/frontend/src/core/dom/marimo-tag.ts+++ b/frontend/src/core/dom/marimo-tag.ts@@ -10,6 +10,7 @@ interface MarimoSettings {getMarimoUserConfig: () => unknown;getMarimoConfigOverrides: () => unknown;getMarimoCode: () => string;+ getMarimoShowCode: () => boolean;}const domBasedMarimoSettings: MarimoSettings = {@@ -38,6 +39,19 @@ const domBasedMarimoSettings: MarimoSettings = {const inner = tag.innerHTML;return decodeURIComponent(inner).trim();},+ getMarimoShowCode: () => {+ try {+ const tag = document.querySelector<HTMLElement>("marimo-code");+ invariant(tag, "internal-error: marimo-code not tag not found");+ const showCode = tag.dataset.showCode;+ if (showCode === "false") {+ return false;+ }+ return true;+ } catch {+ return true;+ }+ },};const islandsBasedMarimoSettings: MarimoSettings = {@@ -60,6 +74,9 @@ const islandsBasedMarimoSettings: MarimoSettings = {getMarimoCode: () => {return "";},+ getMarimoShowCode: () => {+ return true;+ },};export const {@@ -69,6 +86,7 @@ export const {getMarimoUserConfig,getMarimoConfigOverrides,getMarimoCode,+ getMarimoShowCode,} = isIslands() ? islandsBasedMarimoSettings : domBasedMarimoSettings;function getMarimoDOMValue(tagName: string, key: string) {diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 103f80004d..fb60ae22ce 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -151,7 +151,9 @@ def html(def export_callback(file_path: MarimoPath) -> ExportResult:return asyncio_run(run_app_then_export_as_html(- file_path, include_code=include_code, cli_args=cli_args+ file_path,+ include_code=include_code,+ cli_args=cli_args,))@@ -372,19 +374,28 @@ and cannot be opened directly from the file system (e.g. file://).@click.option("--mode",type=click.Choice(["edit", "run"]),+ default="run",help="Whether the notebook code should be editable or readonly",+ show_default=True,required=True,)+ "--show-code/--no-show-code",+ default=True,+ show_default=True,+ help="Whether to show code by default in the exported HTML file.",+)@click.argument("name", required=True, callback=validators.is_file_path)def html_wasm(name: str,output: str,mode: Literal["edit", "run"],+ show_code: bool,) -> None:"""Export a notebook as a WASM-powered standalone HTML file."""def export_callback(file_path: MarimoPath) -> ExportResult:- return export_as_wasm(file_path, mode)+ return export_as_wasm(file_path, mode, show_code=show_code)# Validate output is not a fileif os.path.isfile(output):diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex 2b57a7918b..b99e6790ae 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -86,6 +86,7 @@ def export_as_ipynb(def export_as_wasm(path: MarimoPath,mode: Literal["edit", "run"],+ show_code: bool,asset_url: Optional[str] = None,) -> ExportResult:file_router = AppFileRouter.from_filename(path)@@ -100,6 +101,7 @@ def export_as_wasm(mode=mode,code=file_manager.to_code(),asset_url=asset_url,+ show_code=show_code,)return ExportResult(contents=result[0],diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 3f12df5e83..c30d609c81 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -318,6 +318,7 @@ class Exporter:display_config: DisplayConfig,code: str,mode: Literal["edit", "run"],+ show_code: bool,asset_url: Optional[str] = None,) -> tuple[str, str]:"""Export notebook as a WASM-powered standalone HTML file."""@@ -340,6 +341,7 @@ class Exporter:app_config=file_manager.app.config,code=code,asset_url=asset_url,+ show_code=show_code,)download_filename = get_download_filename(file_manager, "wasm.html")diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 6e2689c168..99b5e9fd91 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -237,6 +237,7 @@ def wasm_notebook_template(app_config: _AppConfig,mode: Literal["edit", "run"],code: str,+ show_code: bool,asset_url: Optional[str] = None,) -> str:"""Template for WASM notebooks."""@@ -291,7 +292,7 @@ def wasm_notebook_template(body = body.replace("</head>",- f'<marimo-code hidden="">{uri_encode_component(code)}</marimo-code></head>',+ f'<marimo-code hidden="" data-show-code="{json.dumps(show_code)}">{uri_encode_component(code)}</marimo-code></head>',)return bodydiff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 1c631be1cd..eac12ad517 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -78,7 +78,10 @@ class TestExportHTML:assert p.returncode == 0, p.stderr.decode()html = Path(out_dir / "index.html").read_text()assert "<marimo-mode data-mode='edit'" in html- assert '<marimo-code hidden=""></marimo-code>' not in html+ assert (+ '<marimo-code hidden="" data-show-code="false"></marimo-code>'+ not in html+ )assert "<marimo-wasm" in html@staticmethod@@ -100,7 +103,10 @@ class TestExportHTML:assert p.returncode == 0, p.stderr.decode()html = Path(out_dir / "index.html").read_text()assert "<marimo-mode data-mode='read'" in html- assert '<marimo-code hidden=""></marimo-code>' not in html+ assert (+ '<marimo-code hidden="" data-show-code="false"></marimo-code>'+ not in html+ )assert "<marimo-wasm" in html@staticmethoddiff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.pyindex 497c89b319..6f9e43d8ba 100644--- a/tests/_server/export/test_exporter.py+++ b/tests/_server/export/test_exporter.py@@ -310,6 +310,7 @@ async def test_export_wasm_edit():display_config=DEFAULT_CONFIG["display"],mode="edit",code=file_manager.to_code(),+ show_code=True,)assert filename == "notebook.wasm.html"@@ -333,6 +334,7 @@ async def test_export_wasm_run():display_config=DEFAULT_CONFIG["display"],mode="run",code=file_manager.to_code(),+ show_code=True,)assert filename == "notebook.wasm.html"diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 4587a87495..55fa09cb8f 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -392,13 +392,14 @@ class TestWasmNotebookTemplate(unittest.TestCase):config_overrides=self.config_overrides,app_config=self.app_config,code=self.code,+ show_code=False,)assert self.filename in resultassert self.mode in resultassert json.dumps(self.user_config) in resultassert '<marimo-wasm hidden="">' in result- assert '<marimo-code hidden="">' in result+ assert '<marimo-code hidden="" data-show-code="false">' in resultdef test_wasm_notebook_template_custom_css_and_assets(self) -> None:# Create css file@@ -419,11 +420,13 @@ class TestWasmNotebookTemplate(unittest.TestCase):app_config=_AppConfig(css_file="custom.css"),code=self.code,asset_url="https://my.cdn.com",+ show_code=True,)assert css in resultassert '<marimo-wasm hidden="">' in resultassert "https://my.cdn.com/assets/" in result+ assert '<marimo-code hidden="" data-show-code="true">' in resultfinally:os.remove(css_file)@@ -455,9 +458,11 @@ class TestWasmNotebookTemplate(unittest.TestCase):config_overrides=self.config_overrides,app_config=_AppConfig(html_head_file="head.html"),code=self.code,+ show_code=False,)assert head in resultassert '<marimo-wasm hidden="">' in result+ assert '<marimo-code hidden="" data-show-code="false">' in resultfinally:os.remove(head_file)