Skip to content

Commit

Permalink
improvement: add --no-show-code to marimo export wasm (#3184)
Browse files Browse the repository at this point in the history
Fixes #3171

add --no-show-code to marimo export wasm
  • Loading branch information
mscolnick authored Dec 16, 2024
1 parent c9f0a7f commit 9a183bd
Show file tree
Hide file tree
Showing 10 changed files with 65 additions and 10 deletions.
1 change: 1 addition & 0 deletions docs/guides/exporting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: note
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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>;
Expand All @@ -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 = () => {
Expand Down
18 changes: 18 additions & 0 deletions frontend/src/core/dom/marimo-tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface MarimoSettings {
getMarimoUserConfig: () => unknown;
getMarimoConfigOverrides: () => unknown;
getMarimoCode: () => string;
getMarimoShowCode: () => boolean;
}

const domBasedMarimoSettings: MarimoSettings = {
Expand Down Expand Up @@ -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 = {
Expand All @@ -60,6 +74,9 @@ const islandsBasedMarimoSettings: MarimoSettings = {
getMarimoCode: () => {
return "";
},
getMarimoShowCode: () => {
return true;
},
};

export const {
Expand All @@ -69,6 +86,7 @@ export const {
getMarimoUserConfig,
getMarimoConfigOverrides,
getMarimoCode,
getMarimoShowCode,
} = isIslands() ? islandsBasedMarimoSettings : domBasedMarimoSettings;

function getMarimoDOMValue(tagName: string, key: string) {
Expand Down
15 changes: 13 additions & 2 deletions marimo/_cli/export/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
)

Expand Down Expand Up @@ -372,19 +374,28 @@ def export_callback(file_path: MarimoPath) -> ExportResult:
@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,
)
@click.option(
"--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 file
if os.path.isfile(output):
Expand Down
2 changes: 2 additions & 0 deletions marimo/_server/export/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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],
Expand Down
2 changes: 2 additions & 0 deletions marimo/_server/export/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ def export_as_wasm(
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."""
Expand All @@ -340,6 +341,7 @@ def export_as_wasm(
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")
Expand Down
3 changes: 2 additions & 1 deletion marimo/_server/templates/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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 body
Expand Down
10 changes: 8 additions & 2 deletions tests/_cli/test_cli_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ def test_cli_export_html_wasm(temp_marimo_file: str) -> None:
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
Expand All @@ -100,7 +103,10 @@ def test_cli_export_html_wasm_read(temp_marimo_file: str) -> None:
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

@staticmethod
Expand Down
2 changes: 2 additions & 0 deletions tests/_server/export/test_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ def cell_1():
display_config=DEFAULT_CONFIG["display"],
mode="edit",
code=file_manager.to_code(),
show_code=True,
)

assert filename == "notebook.wasm.html"
Expand All @@ -333,6 +334,7 @@ def cell_1():
display_config=DEFAULT_CONFIG["display"],
mode="run",
code=file_manager.to_code(),
show_code=True,
)

assert filename == "notebook.wasm.html"
Expand Down
7 changes: 6 additions & 1 deletion tests/_server/templates/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,13 +392,14 @@ def test_wasm_notebook_template(self) -> None:
config_overrides=self.config_overrides,
app_config=self.app_config,
code=self.code,
show_code=False,
)

assert self.filename in result
assert self.mode in result
assert json.dumps(self.user_config) in result
assert '<marimo-wasm hidden="">' in result
assert '<marimo-code hidden="">' in result
assert '<marimo-code hidden="" data-show-code="false">' in result

def test_wasm_notebook_template_custom_css_and_assets(self) -> None:
# Create css file
Expand All @@ -419,11 +420,13 @@ def test_wasm_notebook_template_custom_css_and_assets(self) -> None:
app_config=_AppConfig(css_file="custom.css"),
code=self.code,
asset_url="https://my.cdn.com",
show_code=True,
)

assert css in result
assert '<marimo-wasm hidden="">' in result
assert "https://my.cdn.com/assets/" in result
assert '<marimo-code hidden="" data-show-code="true">' in result
finally:
os.remove(css_file)

Expand Down Expand Up @@ -455,9 +458,11 @@ def test_wasm_notebook_template_custom_head(self) -> None:
config_overrides=self.config_overrides,
app_config=_AppConfig(html_head_file="head.html"),
code=self.code,
show_code=False,
)

assert head in result
assert '<marimo-wasm hidden="">' in result
assert '<marimo-code hidden="" data-show-code="false">' in result
finally:
os.remove(head_file)

0 comments on commit 9a183bd

Please sign in to comment.