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.

improvement: revive islands (#9071)

Myles Scolnick953ffbf82877
diff --git a/frontend/islands/development.md b/frontend/islands/development.md
index fc9922329e..affc1b38b7 100644
--- a/frontend/islands/development.md
+++ b/frontend/islands/development.md
@@ -4,17 +4,44 @@ marimo islands are a way to render HTML "islands" each with static outputs and c
## Development
-**Islands demo page**
+**Quick start - Run the demo**
```bash
pnpm dev:islands
+# Using a prebuilt marimo wheel
+VITE_WASM_MARIMO_PREBUILT_WHEEL=true pnpm dev:islands
```
-**Generate an HTML page with islands**
+This will:
+
+- Auto-generate the demo HTML from `generate.py`
+- Start Vite dev server with HMR
+- Watch `generate.py` for changes and auto-reload
+
+**Update the demo islands**
+
+Just edit `islands/generate.py`, save, and the browser will automatically reload with your changes.
+
+**Generate production HTML**
```bash
-# Generate
+# Generate with CDN links (default - for deployment)
uv run ./islands/generate.py > islands/__demo__/index.html
-# Run the Vite server
-pnpm dev:islands
+
+# Generate for local production build testing
+MODE=local uv run ./islands/generate.py > islands/__demo__/index.html
+
+# Generate for Vite dev server (auto-done by pnpm dev:islands)
+MODE=dev uv run ./islands/generate.py > islands/__demo__/index.html
+```
+
+## Build for Production
+
+```bash
+# Build the islands bundle
+pnpm build:islands
+
+# Output:
+# - frontend/islands/dist/main.js
+# - frontend/islands/dist/style.css
```
diff --git a/frontend/islands/generate.py b/frontend/islands/generate.py
index 73358632b2..40f539cb5d 100644
--- a/frontend/islands/generate.py
+++ b/frontend/islands/generate.py
@@ -6,184 +6,607 @@
# [tool.uv.sources]
# marimo = { path = "../../", editable = true }
# ///
+"""
+Generate demo HTML for marimo islands.
+
+Usage:
+ # Generate and save to file (for production)
+ uv run ./islands/generate.py > islands/__demo__/index.html
+
+ # Generate for local development (auto-injected by Vite)
+ pnpm dev:islands
+
+ # Generate with specific mode
+ MODE=cdn uv run ./islands/generate.py # Use CDN (default)
+ MODE=local uv run ./islands/generate.py # Use local build
+ MODE=dev uv run ./islands/generate.py # Use Vite dev server
+"""
import asyncio
+import os
from textwrap import dedent
+from typing import Any
import marimo
generator = marimo.MarimoIslandGenerator()
-def run():
+def get_script_tags(mode: str) -> str:
+ """Generate appropriate script tags based on mode.
+
+ Args:
+ mode: One of 'cdn', 'local', or 'dev'
+ """
+ if mode == "dev":
+ return """
+ <!-- Vite development mode -->
+ <script type="module">import { injectIntoGlobalHook } from "/@react-refresh";
+ injectIntoGlobalHook(window);
+ window.$RefreshReg$ = () => {};
+ window.$RefreshSig$ = () => (type) => type;</script>
+
+ <script type="module" src="/@vite/client"></script>
+ <script type="module" src="/src/core/islands/main.ts"></script>"""
+ elif mode == "local":
+ return """
+ <!-- Local production build -->
+ <script type="module" src="http://127.0.0.1:8001/main.js"></script>
+ <link
+ href="http://127.0.0.1:8001/style.css"
+ rel="stylesheet"
+ crossorigin="anonymous"
+ />"""
+ else:
+ return f"""
+ {generator.render_head()}"""
- stubs = [
- # Basic
+
+def create_examples() -> list[tuple[str, list[Any]]]:
+ """Create organized examples showcasing marimo islands features."""
+ examples: list[tuple[str, list[Any]]] = []
+
+ # ============================================================================
+ # Getting Started
+ # ============================================================================
+ examples.append(("Getting Started", [
generator.add_code("import marimo as mo"),
- generator.add_code("mo.md('Hello, islands!')"),
+ generator.add_code(
+ """
+ mo.md(
+ \"\"\"
+ # 🏝️ marimo Islands Demo
- # Slider
+ Welcome! This page demonstrates marimo islands - interactive Python
+ code that runs in your browser. Each island is independent and reactive.
+ \"\"\"
+ )
+ """
+ ),
+ ]))
+
+ # ============================================================================
+ # Basic UI Components
+ # ============================================================================
+ examples.append(("Basic UI Components", [
+ generator.add_code(
+ """
+ mo.md("## Sliders")
+ """
+ ),
generator.add_code(
"""
- slider = mo.ui.slider(0, 100, 2)
- slider
- """
+ slider = mo.ui.slider(0, 100, value=50, label="Value")
+ slider
+ """
),
generator.add_code(
"""
- mo.md(f"Slider value: {slider.value}")
- """
+ mo.md(f"**Current value:** {slider.value}")
+ """
),
- # display_code=True
- generator.add_code("""
- mo.md("We can also show the island code!")
- """, display_code=True),
+ generator.add_code(
+ """
+ mo.md("## Buttons")
+ """
+ ),
+ generator.add_code(
+ """
+ counter = mo.ui.button(
+ value=0,
+ label="Click me!",
+ on_click=lambda v: v + 1
+ )
+ counter
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Button clicked {counter.value} times**")
+ """
+ ),
- # is_reactive=False
- generator.add_code("""
- # Also run expensive outputs without performing them in the browser
- import matplotlib.pyplot as plt
- import numpy as np
- x = np.linspace(0, 2*np.pi, 100)
- y = np.sin(x)
- plt.plot(x, y)
- plt.gca()
- """, display_code=True, is_reactive=False),
+ generator.add_code(
+ """
+ mo.md("## Text Inputs")
+ """
+ ),
+ generator.add_code(
+ """
+ name_input = mo.ui.text(value="", placeholder="Enter your name")
+ name_input
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Hello, {name_input.value or 'stranger'}!**")
+ """
+ ),
- # Error
generator.add_code(
- """
- import idk_package
- "Should raise an error"
- """
+ """
+ mo.md("## Dropdowns")
+ """
+ ),
+ generator.add_code(
+ """
+ color = mo.ui.dropdown(
+ options=["red", "blue", "green", "yellow"],
+ value="blue",
+ label="Choose a color"
+ )
+ color
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Selected color:** {color.value}")
+ """
),
- # Markdown
generator.add_code(
"""
- mo.md(
- \"\"\"
- # Hello, Markdown!
+ mo.md("## Checkboxes & Switches")
+ """
+ ),
+ generator.add_code(
+ """
+ checkbox = mo.ui.checkbox(label="Enable feature", value=True)
+ switch = mo.ui.switch(label="Dark mode", value=False)
- Use marimo's "`md`" function to embed rich text into your marimo
- apps. This function compiles Markdown into HTML that marimo
- can display.
+ mo.hstack([checkbox, switch], justify="start", gap=2)
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(
+ f\"\"\"
+ - Checkbox: **{'✓' if checkbox.value else '✗'}**
+ - Switch: **{'ON' if switch.value else 'OFF'}**
+ \"\"\"
+ )
+ """
+ ),
- For example, here's the code that rendered the above title and
- paragraph:
+ generator.add_code(
+ """
+ mo.md("## Radio Buttons")
+ """
+ ),
+ generator.add_code(
+ """
+ size = mo.ui.radio(
+ options=["Small", "Medium", "Large"],
+ value="Medium",
+ label="Size"
+ )
+ size
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Selected size:** {size.value}")
+ """
+ ),
- ```python3
- mo.md(
- '''
- # Hello, Markdown!
+ generator.add_code(
+ """
+ mo.md("## Number Inputs")
+ """
+ ),
+ generator.add_code(
+ """
+ number = mo.ui.number(
+ start=0,
+ stop=100,
+ step=5,
+ value=25,
+ label="Quantity"
+ )
+ number
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Quantity:** {number.value}")
+ """
+ ),
+ ]))
- Use marimo's "`md`" function to embed rich text into your marimo
- apps. This function compiles your Markdown into HTML that marimo
- can display.
- '''
+ # ============================================================================
+ # Advanced UI Components
+ # ============================================================================
+ examples.append(("Advanced Components", [
+ generator.add_code(
+ """
+ mo.md("## Multiselect")
+ """
+ ),
+ generator.add_code(
+ """
+ fruits = mo.ui.multiselect(
+ options=["Apple", "Banana", "Cherry", "Date", "Elderberry"],
+ value=["Apple", "Banana"],
+ label="Select fruits"
)
- ```
- \"\"\"
- )
- """
+ fruits
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Selected:** {', '.join(fruits.value) if fruits.value else 'None'}")
+ """
),
- # LaTeX
generator.add_code(
"""
- mo.md(
- r\"\"\"
- ## LaTeX
- You can embed LaTeX in Markdown.
+ mo.md("## Range Slider")
+ """
+ ),
+ generator.add_code(
+ """
+ price_range = mo.ui.range_slider(
+ start=0,
+ stop=1000,
+ value=[100, 500],
+ label="Price range"
+ )
+ price_range
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Price range:** ${price_range.value[0]} - ${price_range.value[1]}")
+ """
+ ),
- For example,
+ generator.add_code(
+ """
+ mo.md("## Tabs")
+ """
+ ),
+ generator.add_code(
+ """
+ tabs = mo.ui.tabs(
+ {
+ "Overview": mo.md("## Overview\\n\\nThis is the overview tab."),
+ "Details": mo.md("## Details\\n\\nThis is the details tab."),
+ "Settings": mo.md("## Settings\\n\\nThis is the settings tab."),
+ }
+ )
+ tabs
+ """
+ ),
- ```python3
- mo.md(r'$f : \mathbf{R} \to \mathbf{R}$')
- ```
+ generator.add_code(
+ """
+ mo.md("## Code Editor")
+ """
+ ),
+ generator.add_code(
+ """
+ code = mo.ui.code_editor(
+ value='print("Hello, marimo!")',
+ language="python",
+ label="Python code"
+ )
+ code
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f\"\"\"
+ **Code length:** {len(code.value)} characters
+ \"\"\")
+ """
+ ),
+ ]))
- renders $f : \mathbf{R} \to \mathbf{R}$, while
+ # ============================================================================
+ # Data Display
+ # ============================================================================
+ examples.append(("Data Display", [
+ generator.add_code(
+ """
+ mo.md("## Tables")
+ """
+ ),
+ generator.add_code(
+ """
+ import pandas as pd
+
+ df = pd.DataFrame({
+ "Name": ["Alice", "Bob", "Charlie"],
+ "Age": [25, 30, 35],
+ "City": ["New York", "London", "Tokyo"]
+ })
+
+ table = mo.ui.table(df, label="User Data")
+ table
+ """
+ ),
- ```python3
+ generator.add_code(
+ """
+ mo.md("## Markdown Rendering")
+ """
+ ),
+ generator.add_code(
+ """
mo.md(
- r'''
- \[
- f: \mathbf{R} \to \mathbf{R}
- \]
- '''
+ \"\"\"
+ ### Rich Text Support
+
+ marimo supports **bold**, *italic*, and `code` formatting.
+
+ - Lists work great
+ - With multiple items
+ - And nested sub-items
+
+ > Blockquotes are also supported!
+ \"\"\"
)
- ```
+ """
+ ),
- renders the display math
+ generator.add_code(
+ """
+ mo.md("## LaTeX Math")
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(
+ r\"\"\"
+ ### Mathematical Expressions
+
+ Inline math: $E = mc^2$
- \[
- f: \mathbf{R} \to \mathbf{R}.
- \]
- \"\"\"
- )
- """
+ Display math:
+
+ $$
+ \\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}
+ $$
+
+ Complex equations:
+
+ $$
+ \\nabla \\times \\mathbf{F} = \\left( \\frac{\\partial F_z}{\\partial y} - \\frac{\\partial F_y}{\\partial z} \\right) \\mathbf{i} + \\cdots
+ $$
+ \"\"\"
+ )
+ """
),
- ]
+ ]))
- app = asyncio.run(generator.build())
+ # ============================================================================
+ # Layout & Composition
+ # ============================================================================
+ examples.append(("Layout & Composition", [
+ generator.add_code(
+ """
+ mo.md("## Layout Components")
+ """
+ ),
+ generator.add_code(
+ """
+ x = mo.ui.slider(0, 10, value=5, label="X")
+ y = mo.ui.slider(0, 10, value=5, label="Y")
- NEW_LINE = "\n"
- output = f"""
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <meta name="theme-color" content="#000000" />
- <meta name="description" content="a marimo app" />
- <title>🏝️</title>
-
- {generator.render_head()}
-
- <!-- If running a local server of the production build -->
- <!-- <script type="module" src="http://127.0.0.1:8001/main.js"></script>
- <link
- href="http://127.0.0.1:8001/style.css"
- rel="stylesheet"
- crossorigin="anonymous"
- /> -->
+ mo.hstack([x, y], justify="start", gap=2)
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(f"**Position:** ({x.value}, {y.value})")
+ """
+ ),
+
+ generator.add_code(
+ """
+ mo.md("## Forms")
+ """
+ ),
+ generator.add_code(
+ """
+ form = mo.ui.form(
+ mo.ui.dictionary(
+ {
+ "name": mo.ui.text(placeholder="Name"),
+ "email": mo.ui.text(placeholder="Email"),
+ "age": mo.ui.number(start=0, stop=120, value=25),
+ }
+ ),
+ submit_button_label="Submit"
+ )
+ form
+ """
+ ),
+ generator.add_code(
+ """
+ if form.value:
+ v = form.value
+ mo.md(
+ f\"\"\"
+ **Form submitted!**
+
+ - Name: {v['name']}
+ - Email: {v['email']}
+ - Age: {v['age']}
+ \"\"\"
+ )
+ else:
+ mo.md("Fill out the form above and click submit.")
+ """
+ ),
+ ]))
- <!-- If running from Vite -->
- <!-- <script type="module" src="/src/core/islands/main.ts"></script> -->
- </head>
- <body>
+ # ============================================================================
+ # Island Features
+ # ============================================================================
+ examples.append(("Island Features", [
+ generator.add_code(
+ """
+ mo.md("## Display Code")
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md("You can show the code that generated this island!")
+ """,
+ display_code=True
+ ),
- {dedent(NEW_LINE.join([stub.render() for stub in stubs]))}
+ generator.add_code(
+ """
+ mo.md("## Non-Reactive Islands")
+ """
+ ),
+ generator.add_code(
+ """
+ mo.md(
+ \"\"\"
+ This island is non-reactive - it runs once and doesn't update
+ when other islands change. Perfect for expensive computations
+ or static content.
+ \"\"\"
+ )
+ """,
+ is_reactive=False
+ ),
+ generator.add_code(
+ """
+ mo.md("## Combined Features")
+ """
+ ),
+ generator.add_code(
+ """
+ # This island shows code AND is non-reactive
+ mo.md("Static content with code visible")
+ """,
+ display_code=True,
+ is_reactive=False
+ ),
+ ]))
- <br />
- <br />
- <br />
- <br />
- <hr />
- <div class="bg-background p-4 border-2 text-primary font-bold bg-background">
- this should not be affected by global tailwind styles
+ # ============================================================================
+ # Error Handling
+ # ============================================================================
+ examples.append(("Error Handling", [
+ generator.add_code(
+ """
+ mo.md("## Error Display")
+ """
+ ),
+ generator.add_code(
+ """
+ # This will raise an error
+ import nonexistent_module
+ "This won't execute"
+ """
+ ),
+ ]))
+
+ return examples
+
+
+def render_section_divider(title: str) -> str:
+ """Render a section divider."""
+ return f"""
+ <hr style="margin: 1rem 0; border: none; border-top: 2px solid #e5e7eb;" />
+ <div style="margin: 1rem 0;">
+ <h2 style="font-size: 1.5rem; font-weight: 600; margin-bottom: 1rem;">
+ {title}
+ </h2>
</div>
- <div class="marimo">
- <div class="bg-background p-4 border-2 text-primary font-bold text-foreground">
- this should be affected by global tailwind styles
+ """
+
+
+def run(mode: str):
+ """Generate and print the HTML output."""
+ examples = create_examples()
+
+ # Build all islands
+ app = asyncio.run(generator.build())
+
+ script_tags = get_script_tags(mode)
+
+ # Render all stubs
+ rendered_sections: list[str] = []
+ for section_title, stubs in examples:
+ rendered_sections.append(render_section_divider(section_title))
+ rendered_sections.extend([stub.render() for stub in stubs])
+
+ # Add Tailwind test section
+ tailwind_test = """
+ <hr style="margin: 1rem 0; border: none; border-top: 2px solid #e5e7eb;" />
+ <div style="margin: 1rem 0;">
+ <h2 style="font-size: 1.5rem; font-weight: 600; margin-bottom: 1rem;">
+ Tailwind CSS Isolation Test
+ </h2>
</div>
+ <div class="bg-background p-4 border-2 text-primary font-bold bg-background">
+ This should NOT be affected by global Tailwind styles
</div>
<div class="marimo">
- <div class="dark">
<div class="bg-background p-4 border-2 text-primary font-bold text-foreground">
- this should be affected by global tailwind styles (dark)
+ This SHOULD be affected by global Tailwind styles
</div>
</div>
+ <div class="marimo">
+ <div class="dark">
+ <div class="bg-background p-4 border-2 text-primary font-bold text-foreground">
+ This SHOULD be affected by global Tailwind styles (dark mode)
+ </div>
+ </div>
</div>
- </div>
+ """
+
+ output = f"""
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="marimo islands demo - interactive Python in the browser" />
+ <title>🏝️ marimo Islands Demo</title>
+
+ {script_tags}
+ </head>
+ <body style="max-width: 1200px; margin: 0 auto; padding: 1rem; font-family: system-ui, -apple-system, sans-serif;">
+
+ {dedent("".join(rendered_sections))}
+
+ {tailwind_test}
- </body>
- </html>
+ </body>
+</html>
"""
print(output)
if __name__ == "__main__":
- run()
+ run(os.environ.get("MODE", "cdn"))
diff --git a/frontend/islands/vite.config.mts b/frontend/islands/vite.config.mts
index 13abe2096f..3a8f8a6bb7 100644
--- a/frontend/islands/vite.config.mts
+++ b/frontend/islands/vite.config.mts
@@ -1,24 +1,64 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import { execFile, execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
+import { promisify } from "node:util";
import react from "@vitejs/plugin-react";
import { defineConfig, type Plugin } from "vite";
import topLevelAwait from "vite-plugin-top-level-await";
import wasm from "vite-plugin-wasm";
import packageJson from "../package.json";
+const execFileAsync = promisify(execFile);
+
const htmlDevPlugin = (): Plugin => {
- return {
- apply: "serve",
- name: "html-transform",
- transformIndexHtml: async () => {
+ const generateHtml = async (): Promise<string> => {
+ // Auto-regenerate HTML in dev mode by running the Python script
+ const scriptPath = path.resolve(__dirname, "generate.py");
+ try {
+ const { stdout } = await execFileAsync("uv", ["run", scriptPath], {
+ env: { ...process.env, MODE: "dev" },
+ });
+ return stdout;
+ } catch (error) {
+ console.error("Failed to generate demo HTML:", error);
+ // Fallback to existing file if generation fails
const indexHtml = await fs.promises.readFile(
path.resolve(__dirname, "__demo__", "index.html"),
"utf-8",
);
+ const preamble = `<!DOCTYPE html>\n
+<script type="module">import { injectIntoGlobalHook } from "/@react-refresh";
+injectIntoGlobalHook(window);
+window.$RefreshReg$ = () => {};
+window.$RefreshSig$ = () => (type) => type;</script>
+
+<script type="module" src="/@vite/client"></script>
+ `;
+ return `${preamble}\n${indexHtml}`;
+ }
+ };
- return `<!DOCTYPE html>\n${indexHtml}`;
+ return {
+ apply: "serve",
+ name: "html-transform",
+ transformIndexHtml: async () => {
+ return await generateHtml();
+ },
+ // Watch the generate.py file and trigger HMR on changes
+ configureServer(server) {
+ const scriptPath = path.resolve(__dirname, "generate.py");
+ server.watcher.add(scriptPath);
+ server.watcher.on("change", (file) => {
+ if (file === scriptPath) {
+ console.log("Demo script changed, regenerating HTML...");
+ server.ws.send({
+ type: "full-reload",
+ path: "*",
+ });
+ }
+ });
},
};
};
@@ -27,6 +67,14 @@ const ReactCompilerConfig = {
target: "19",
};
+function getMarimoVersion(): string {
+ try {
+ return execFileSync("uv", ["run", "marimo", "--version"]).toString().trim();
+ } catch {
+ return packageJson.version;
+ }
+}
+
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
@@ -45,12 +93,10 @@ export default defineConfig({
"process.env.LOG": JSON.stringify(""),
"process.env.VSCODE_TEXTMATE_DEBUG": JSON.stringify(false),
"process.env.NODE_DEBUG": JSON.stringify(false),
- // Precedence: VITE_MARIMO_VERSION > package.json version > "latest"
- "import.meta.env.VITE_MARIMO_VERSION": process.env.VITE_MARIMO_VERSION
- ? JSON.stringify(process.env.VITE_MARIMO_VERSION)
- : process.env.NODE_ENV === "production"
- ? JSON.stringify(packageJson.version)
- : JSON.stringify("latest"),
+ // Precedence: VITE_MARIMO_VERSION > uv run marimo --version > package.json
+ "import.meta.env.VITE_MARIMO_VERSION": JSON.stringify(
+ process.env.VITE_MARIMO_VERSION || getMarimoVersion(),
+ ),
},
server: {
headers: {
diff --git a/frontend/package.json b/frontend/package.json
index 89917c242c..552940869c 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -123,6 +123,7 @@
"path-to-regexp": "^8.4.0",
"plotly.js": "^3.3.1",
"pyodide": "0.27.7",
+ "radix-ui": "1.4.3",
"react-arborist": "^3.4.3",
"react-aria": "3.47.0",
"react-aria-components": "1.16.0",
@@ -159,8 +160,7 @@
"vscode-jsonrpc": "^8.2.1",
"vscode-languageserver-protocol": "^3.17.5",
"web-vitals": "^4.2.4",
- "zod": "^4.3.6",
- "radix-ui": "1.4.3"
+ "zod": "^4.3.6"
},
"scripts": {
"preinstall": "npx only-allow pnpm",
@@ -217,7 +217,7 @@
"oxfmt": "^0.42.0",
"oxlint": "^1.58.0",
"postcss": "^8.5.6",
- "postcss-plugin-namespace": "^0.0.3",
+ "postcss-prefix-selector": "^2.1.1",
"react": "^19.2.4",
"react-compiler-runtime": "19.1.0-rc.3",
"react-dom": "^19.2.4",
diff --git a/frontend/postcss.config.cjs b/frontend/postcss.config.cjs
index 275401e699..21e90dd092 100644
--- a/frontend/postcss.config.cjs
+++ b/frontend/postcss.config.cjs
@@ -1,10 +1,30 @@
/* Copyright 2026 Marimo. All rights reserved. */
+
+/**
+ * Selectors that should be replaced with the prefix rather than prepended.
+ * e.g., `:root { --spacing: 0.25rem }` becomes `.marimo { --spacing: 0.25rem }`
+ * so CSS custom properties are set directly on island container elements.
+ */
+const GLOBAL_SELECTORS = new Set([":root", ":host", "html", "body"]);
+
const config = {
plugins: [
require("@tailwindcss/postcss"),
process.env.VITE_MARIMO_ISLANDS === "true"
- ? require("postcss-plugin-namespace")(".marimo", {
- ignore: [".marimo", "html", ".marimo:is(.dark *)"],
+ ? require("postcss-prefix-selector")({
+ prefix: ".marimo",
+ transform(prefix, selector) {
+ // Global selectors → replace with prefix
+ if (GLOBAL_SELECTORS.has(selector)) {
+ return prefix;
+ }
+ // Already scoped under .marimo
+ if (selector.startsWith(".marimo")) {
+ return selector;
+ }
+ // Normal prefixing: .flex → .marimo .flex
+ return `${prefix} ${selector}`;
+ },
})
: undefined,
process.env.NODE_ENV === "production" ? require("cssnano") : undefined,
diff --git a/frontend/src/core/islands/__tests__/bridge.test.ts b/frontend/src/core/islands/__tests__/bridge.test.ts
index 0dc11ab3ad..86b06e185b 100644
--- a/frontend/src/core/islands/__tests__/bridge.test.ts
+++ b/frontend/src/core/islands/__tests__/bridge.test.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { components } from "@marimo-team/marimo-api";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import {
cellId,
requestId,
@@ -83,17 +83,7 @@ describe("IslandsPyodideBridge", () => {
beforeEach(() => {
vi.clearAllMocks();
- // Reset the singleton by clearing the window property
- // oxlint-disable-next-line typescript/no-explicit-any
- delete (window as any)._marimo_private_IslandsPyodideBridge;
- // Access the singleton - creates a fresh instance
- bridge = IslandsPyodideBridge.INSTANCE;
- });
-
- afterEach(() => {
- // Clean up singleton
- // oxlint-disable-next-line typescript/no-explicit-any
- delete (window as any)._marimo_private_IslandsPyodideBridge;
+ bridge = new IslandsPyodideBridge({ autoStartSessions: false });
});
describe("sendComponentValues", () => {
diff --git a/frontend/src/core/islands/__tests__/islands-harness.test.ts b/frontend/src/core/islands/__tests__/islands-harness.test.ts
new file mode 100644
index 0000000000..74a88b60cb
--- /dev/null
+++ b/frontend/src/core/islands/__tests__/islands-harness.test.ts
@@ -0,0 +1,348 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { afterEach, describe, expect, it } from "vitest";
+import { ISLAND_DATA_ATTRIBUTES } from "@/core/islands/constants";
+import {
+ extractIslandCodeFromEmbed,
+ parseIslandElement,
+ parseIslandElementsIntoApps,
+ parseMarimoIslandApps,
+} from "../parse";
+import {
+ buildIslandHTML,
+ createIslandHarness,
+ type IslandHarness,
+} from "./test-utils.tsx";
+
+let harness: IslandHarness;
+
+afterEach(() => {
+ harness?.cleanup();
+});
+
+// ============================================================================
+// Reactive vs Non-Reactive Parsing
+// ============================================================================
+
+describe("reactive vs non-reactive islands", () => {
+ it("should parse reactive islands into apps with code", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: "x = 1", output: "<div>1</div>" },
+ { reactive: true, code: "y = 2", output: "<div>2</div>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps).toHaveLength(1);
+ expect(apps[0].cells).toHaveLength(2);
+ expect(apps[0].cells[0].code).toBe("x = 1");
+ expect(apps[0].cells[1].code).toBe("y = 2");
+ });
+
+ it("should skip non-reactive islands during parsing (no code sent to kernel)", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: "x = 1", output: "<div>1</div>" },
+ { reactive: false, output: "<div>static content</div>" },
+ { reactive: true, code: "y = 2", output: "<div>2</div>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps).toHaveLength(1);
+ // Only the 2 reactive islands become cells
+ expect(apps[0].cells).toHaveLength(2);
+ expect(apps[0].cells[0].code).toBe("x = 1");
+ expect(apps[0].cells[1].code).toBe("y = 2");
+ });
+
+ it("should not set data-cell-idx on non-reactive islands", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: "x = 1", output: "<div>1</div>" },
+ { reactive: false, output: "<div>static</div>" },
+ ]),
+ );
+
+ parseMarimoIslandApps(harness.container);
+
+ const [reactiveIsland, nonReactiveIsland] = harness.islands;
+
+ // Reactive island gets a cell index
+ expect(reactiveIsland.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe(
+ "0",
+ );
+ // Non-reactive island does NOT get a cell index
+ expect(
+ nonReactiveIsland.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX),
+ ).toBeNull();
+ });
+
+ it("should handle all-non-reactive islands (empty app list)", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: false, output: "<div>static 1</div>" },
+ { reactive: false, output: "<div>static 2</div>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps).toHaveLength(0);
+ });
+});
+
+// ============================================================================
+// extractIslandCodeFromEmbed
+// ============================================================================
+
+describe("extractIslandCodeFromEmbed with harness", () => {
+ it("should return code for reactive islands", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: 'mo.md("hello")', output: "<div>hello</div>" },
+ ]),
+ );
+
+ const code = extractIslandCodeFromEmbed(harness.islands[0]);
+ expect(code).toBe('mo.md("hello")');
+ });
+
+ it("should return empty string for non-reactive islands", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ {
+ reactive: false,
+ code: 'mo.md("hello")',
+ output: "<div>hello</div>",
+ },
+ ]),
+ );
+
+ const code = extractIslandCodeFromEmbed(harness.islands[0]);
+ expect(code).toBe("");
+ });
+});
+
+// ============================================================================
+// parseIslandElement
+// ============================================================================
+
+describe("parseIslandElement with harness", () => {
+ it("should return cell data for reactive island with output and code", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: "x = 1", output: "<div>1</div>" },
+ ]),
+ );
+
+ const result = parseIslandElement(harness.islands[0]);
+ expect(result).not.toBeNull();
+ expect(result!.code).toBe("x = 1");
+ expect(result!.output).toBe("<div>1</div>");
+ });
+
+ it("should return null for non-reactive island (code is empty)", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([{ reactive: false, output: "<div>static</div>" }]),
+ );
+
+ const result = parseIslandElement(harness.islands[0]);
+ expect(result).toBeNull();
+ });
+});
+
+// ============================================================================
+// Multi-app parsing
+// ============================================================================
+
+describe("multi-app parsing with harness", () => {
+ it("should group islands by app-id", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { appId: "app-1", reactive: true, code: "a = 1", output: "<div/>" },
+ { appId: "app-2", reactive: true, code: "b = 2", output: "<div/>" },
+ { appId: "app-1", reactive: true, code: "c = 3", output: "<div/>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps).toHaveLength(2);
+
+ const app1 = apps.find((a) => a.id === "app-1")!;
+ const app2 = apps.find((a) => a.id === "app-2")!;
+
+ expect(app1.cells).toHaveLength(2);
+ expect(app1.cells[0].code).toBe("a = 1");
+ expect(app1.cells[1].code).toBe("c = 3");
+
+ expect(app2.cells).toHaveLength(1);
+ expect(app2.cells[0].code).toBe("b = 2");
+ });
+
+ it("should assign sequential cell indices within each app", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { appId: "app-1", reactive: true, code: "a", output: "<div/>" },
+ { appId: "app-1", reactive: true, code: "b", output: "<div/>" },
+ { appId: "app-1", reactive: true, code: "c", output: "<div/>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps[0].cells.map((c) => c.idx)).toEqual([0, 1, 2]);
+ });
+
+ it("should skip non-reactive islands in cell index assignment", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: "a = 1", output: "<div/>" },
+ { reactive: false, output: "<div>static</div>" },
+ { reactive: true, code: "b = 2", output: "<div/>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps[0].cells).toHaveLength(2);
+ expect(apps[0].cells[0].idx).toBe(0);
+ expect(apps[0].cells[1].idx).toBe(1);
+
+ // Verify DOM: reactive islands get indices, non-reactive does not
+ expect(
+ harness.islands[0].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX),
+ ).toBe("0");
+ expect(
+ harness.islands[1].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX),
+ ).toBeNull();
+ expect(
+ harness.islands[2].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX),
+ ).toBe("1");
+ });
+});
+
+// ============================================================================
+// Mixed reactive/non-reactive scenarios (regression tests)
+// ============================================================================
+
+describe("mixed reactive/non-reactive island scenarios", () => {
+ it("should handle the generate.py demo pattern: reactive + non-reactive + display_code", () => {
+ // Mirrors the "Island Features" section of generate.py
+ harness = createIslandHarness(
+ buildIslandHTML([
+ // Section header (reactive)
+ {
+ reactive: true,
+ code: 'mo.md("## Display Code")',
+ output: "<div><h2>Display Code</h2></div>",
+ },
+ // display_code island (reactive)
+ {
+ reactive: true,
+ code: 'mo.md("You can show the code")',
+ output: "<div>You can show the code</div>",
+ displayCode: true,
+ },
+ // Non-reactive section header
+ {
+ reactive: true,
+ code: 'mo.md("## Non-Reactive Islands")',
+ output: "<div><h2>Non-Reactive Islands</h2></div>",
+ },
+ // Non-reactive island — the one that was crashing
+ {
+ reactive: false,
+ code: 'mo.md("This island is non-reactive")',
+ output:
+ "<div>This island is non-reactive - it runs once and doesn't update</div>",
+ },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+
+ // Only 3 reactive islands become cells
+ expect(apps).toHaveLength(1);
+ expect(apps[0].cells).toHaveLength(3);
+
+ // Non-reactive island (index 3) has no cell-idx
+ expect(
+ harness.islands[3].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX),
+ ).toBeNull();
+ expect(
+ harness.islands[3].getAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE),
+ ).toBe("false");
+ });
+
+ it("should handle non-reactive island at the start", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: false, output: "<div>static header</div>" },
+ { reactive: true, code: "x = 1", output: "<div>1</div>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps).toHaveLength(1);
+ expect(apps[0].cells).toHaveLength(1);
+ expect(apps[0].cells[0].code).toBe("x = 1");
+ expect(apps[0].cells[0].idx).toBe(0);
+
+ // First island (non-reactive) has no index
+ expect(
+ harness.islands[0].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX),
+ ).toBeNull();
+ // Second island (reactive) gets index 0
+ expect(
+ harness.islands[1].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX),
+ ).toBe("0");
+ });
+
+ it("should handle alternating reactive and non-reactive islands", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: "a = 1", output: "<div/>" },
+ { reactive: false, output: "<div>static</div>" },
+ { reactive: true, code: "b = 2", output: "<div/>" },
+ { reactive: false, output: "<div>static</div>" },
+ { reactive: true, code: "c = 3", output: "<div/>" },
+ ]),
+ );
+
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps[0].cells).toHaveLength(3);
+ expect(apps[0].cells.map((c) => c.code)).toEqual([
+ "a = 1",
+ "b = 2",
+ "c = 3",
+ ]);
+ expect(apps[0].cells.map((c) => c.idx)).toEqual([0, 1, 2]);
+ });
+});
+
+// ============================================================================
+// parseIslandElementsIntoApps (direct element-level tests)
+// ============================================================================
+
+describe("parseIslandElementsIntoApps with mixed elements", () => {
+ it("should preserve DOM order for cell indices", () => {
+ harness = createIslandHarness(
+ buildIslandHTML([
+ { reactive: true, code: "first", output: "<div/>" },
+ { reactive: true, code: "second", output: "<div/>" },
+ { reactive: true, code: "third", output: "<div/>" },
+ ]),
+ );
+
+ const apps = parseIslandElementsIntoApps(harness.islands);
+ expect(apps[0].cells.map((c) => c.code)).toEqual([
+ "first",
+ "second",
+ "third",
+ ]);
+ });
+
+ it("should handle empty container", () => {
+ harness = createIslandHarness("");
+ const apps = parseMarimoIslandApps(harness.container);
+ expect(apps).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/core/islands/__tests__/parse.test.ts b/frontend/src/core/islands/__tests__/parse.test.ts
index ce91f40e4e..5c575b8162 100644
--- a/frontend/src/core/islands/__tests__/parse.test.ts
+++ b/frontend/src/core/islands/__tests__/parse.test.ts
@@ -1,6 +1,19 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { describe, expect, it } from "vitest";
-import { createMarimoFile, parseIslandCode } from "../parse";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ ISLAND_DATA_ATTRIBUTES,
+ ISLAND_TAG_NAMES,
+} from "@/core/islands/constants";
+import {
+ createMarimoFile,
+ extractIslandCodeFromEmbed,
+ parseIslandCode,
+ parseIslandEditor,
+ parseIslandElement,
+ parseIslandElementsIntoApps,
+ parseMarimoIslandApps,
+} from "../parse";
+import { createMockIslandElement, createMockIslands } from "./test-utils.tsx";
describe("createMarimoFile", () => {
it("should return a string", () => {
@@ -24,15 +37,14 @@ describe("createMarimoFile", () => {
],
};
const result = createMarimoFile(app);
- const expected = [
- "import marimo",
- "app = marimo.App()",
- "@app.cell",
- "def __():",
- ' print("Hello, World!")',
- " return",
- ].join("\n");
- expect(result).toBe(expected);
+ expect(result).toMatchInlineSnapshot(`
+ "import marimo
+ app = marimo.App()
+ @app.cell
+ def __():
+ print("Hello, World!")
+ return"
+ `);
});
it("should correctly format multiple cells", () => {
@@ -47,19 +59,54 @@ describe("createMarimoFile", () => {
],
};
const result = createMarimoFile(app);
- const expected = [
- "import marimo",
- "app = marimo.App()",
- "@app.cell",
- "def __():",
- ' print("Hello, World!")',
- " return",
- "@app.cell",
- "def __():",
- ' print("Goodbye, World!")',
- " return",
- ].join("\n");
- expect(result).toBe(expected);
+ expect(result).toMatchInlineSnapshot(`
+ "import marimo
+ app = marimo.App()
+ @app.cell
+ def __():
+ print("Hello, World!")
+ return
+ @app.cell
+ def __():
+ print("Goodbye, World!")
+ return"
+ `);
+ });
+
+ it("should create an async marimo file from cells", () => {
+ const app = {
+ cells: [{ code: "await asyncio.sleep(1)" }],
+ };
+
+ const result = createMarimoFile(app);
+
+ expect(result).toMatchInlineSnapshot(`
+ "import marimo
+ app = marimo.App()
+ @app.cell
+ async def __():
+ await asyncio.sleep(1)
+ return"
+ `);
+ });
+
+ it("should properly indent multi-line code", () => {
+ const app = {
+ cells: [{ code: "if True:\n print('hello')\n print('world')" }],
+ };
+
+ const result = createMarimoFile(app);
+
+ expect(result).toMatchInlineSnapshot(`
+ "import marimo
+ app = marimo.App()
+ @app.cell
+ def __():
+ if True:
+ print('hello')
+ print('world')
+ return"
+ `);
});
});
@@ -86,4 +133,399 @@ describe("parseIslandCode", () => {
expect(result).toBe(expected);
},
);
+
+ it("should parse URI-encoded code with special characters", () => {
+ const code = "print(%22Hello%2C%20world!%22)";
+
+ const result = parseIslandCode(code);
+
+ expect(result).toBe('print("Hello, world!")');
+ });
+
+ it("should handle null and undefined", () => {
+ expect(parseIslandCode(null)).toBe("");
+ expect(parseIslandCode(undefined)).toBe("");
+ });
+});
+
+describe("parseIslandEditor", () => {
+ it("should parse JSON-encoded code", () => {
+ const code = '"print(\\"Hello\\")"';
+
+ const result = parseIslandEditor(code);
+
+ expect(result).toBe('print("Hello")');
+ });
+
+ it("should return raw code if JSON parsing fails", () => {
+ const code = 'print("Hello")';
+
+ const result = parseIslandEditor(code);
+
+ expect(result).toBe('print("Hello")');
+ });
+
+ it("should handle null and undefined", () => {
+ expect(parseIslandEditor(null)).toBe("");
+ expect(parseIslandEditor(undefined)).toBe("");
+ });
+});
+
+describe("extractIslandCodeFromEmbed", () => {
+ it("should extract code from marimo-cell-code element", () => {
+ const element = createMockIslandElement({
+ code: 'print("test")',
+ });
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+
+ const result = extractIslandCodeFromEmbed(element);
+
+ expect(result).toBe('print("test")');
+ });
+
+ it("should return empty string for non-reactive cells", () => {
+ const element = createMockIslandElement({
+ code: 'print("test")',
+ });
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "false");
+
+ const result = extractIslandCodeFromEmbed(element);
+
+ expect(result).toBe("");
+ });
+
+ it("should extract code from editor element if code element not found", () => {
+ const element = document.createElement(ISLAND_TAG_NAMES.ISLAND);
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ const editor = document.createElement(ISLAND_TAG_NAMES.CODE_EDITOR);
+ editor.setAttribute("data-initial-value", '"print(\\"hello\\")"');
+ element.appendChild(editor);
+
+ const result = extractIslandCodeFromEmbed(element);
+
+ expect(result).toBe('print("hello")');
+ });
+
+ it("should return empty string if no code elements found", () => {
+ const element = document.createElement(ISLAND_TAG_NAMES.ISLAND);
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+
+ const result = extractIslandCodeFromEmbed(element);
+
+ expect(result).toBe("");
+ });
+});
+
+describe("parseIslandElement", () => {
+ it("should parse a valid island element", () => {
+ const element = createMockIslandElement({
+ code: 'print("test")',
+ innerHTML: "<div>output</div>",
+ });
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+
+ const result = parseIslandElement(element);
+
+ expect(result).toMatchInlineSnapshot(`
+ {
+ "code": "print("test")",
+ "output": "<div>output</div>",
+ }
+ `);
+ });
+
+ it("should return null if output is missing", () => {
+ const element = document.createElement(ISLAND_TAG_NAMES.ISLAND);
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ const codeElement = document.createElement(ISLAND_TAG_NAMES.CELL_CODE);
+ codeElement.textContent = encodeURIComponent('print("test")');
+ element.appendChild(codeElement);
+
+ const result = parseIslandElement(element);
+
+ expect(result).toBeNull();
+ });
+
+ it("should return null if code is missing", () => {
+ const element = document.createElement(ISLAND_TAG_NAMES.ISLAND);
+ const outputElement = document.createElement(ISLAND_TAG_NAMES.CELL_OUTPUT);
+ outputElement.innerHTML = "<div>output</div>";
+ element.appendChild(outputElement);
+
+ const result = parseIslandElement(element);
+
+ expect(result).toBeNull();
+ });
+});
+
+describe("parseIslandElementsIntoApps", () => {
+ it("should parse single app with single cell", () => {
+ const elements = [
+ createMockIslandElement({
+ appId: "app1",
+ cellIdx: "0",
+ code: 'print("hello")',
+ innerHTML: "<div>output1</div>",
+ }),
+ ];
+ elements[0].setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+
+ const result = parseIslandElementsIntoApps(elements);
+
+ expect(result).toHaveLength(1);
+ expect(result).toMatchInlineSnapshot(`
+ [
+ {
+ "cells": [
+ {
+ "code": "print("hello")",
+ "idx": 0,
+ "output": "<div>output1</div>",
+ },
+ ],
+ "id": "app1",
+ },
+ ]
+ `);
+ });
+
+ it("should parse single app with multiple cells", () => {
+ const elements = createMockIslands(3, "app1").map((el) => {
+ el.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ return el;
+ });
+
+ const result = parseIslandElementsIntoApps(elements);
+
+ expect(result).toHaveLength(1);
+ expect(result).toMatchInlineSnapshot(`
+ [
+ {
+ "cells": [
+ {
+ "code": "cell_0 = 0",
+ "idx": 0,
+ "output": "<div>output 0</div>",
+ },
+ {
+ "code": "cell_1 = 1",
+ "idx": 1,
+ "output": "<div>output 1</div>",
+ },
+ {
+ "code": "cell_2 = 2",
+ "idx": 2,
+ "output": "<div>output 2</div>",
+ },
+ ],
+ "id": "app1",
+ },
+ ]
+ `);
+ });
+
+ it("should parse multiple apps", () => {
+ const elements = [
+ ...createMockIslands(2, "app1"),
+ ...createMockIslands(2, "app2"),
+ ].map((el) => {
+ el.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ return el;
+ });
+
+ const result = parseIslandElementsIntoApps(elements);
+
+ expect(result).toHaveLength(2);
+ expect(result).toMatchInlineSnapshot(`
+ [
+ {
+ "cells": [
+ {
+ "code": "cell_0 = 0",
+ "idx": 0,
+ "output": "<div>output 0</div>",
+ },
+ {
+ "code": "cell_1 = 1",
+ "idx": 1,
+ "output": "<div>output 1</div>",
+ },
+ ],
+ "id": "app1",
+ },
+ {
+ "cells": [
+ {
+ "code": "cell_0 = 0",
+ "idx": 0,
+ "output": "<div>output 0</div>",
+ },
+ {
+ "code": "cell_1 = 1",
+ "idx": 1,
+ "output": "<div>output 1</div>",
+ },
+ ],
+ "id": "app2",
+ },
+ ]
+ `);
+ });
+
+ it("should skip elements without app-id", () => {
+ const validElement = createMockIslandElement({
+ appId: "app1",
+ code: 'print("test")',
+ innerHTML: "<div>output</div>",
+ });
+ validElement.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+
+ const invalidElement = document.createElement(ISLAND_TAG_NAMES.ISLAND);
+ invalidElement.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+
+ const result = parseIslandElementsIntoApps([validElement, invalidElement]);
+
+ expect(result).toHaveLength(1);
+ expect(result).toMatchInlineSnapshot(`
+ [
+ {
+ "cells": [
+ {
+ "code": "print("test")",
+ "idx": 0,
+ "output": "<div>output</div>",
+ },
+ ],
+ "id": "app1",
+ },
+ ]
+ `);
+ });
+
+ it("should assign correct cell indices", () => {
+ const elements = createMockIslands(3, "app1").map((el) => {
+ el.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ return el;
+ });
+
+ const result = parseIslandElementsIntoApps(elements);
+
+ expect(result).toMatchInlineSnapshot(`
+ [
+ {
+ "cells": [
+ {
+ "code": "cell_0 = 0",
+ "idx": 0,
+ "output": "<div>output 0</div>",
+ },
+ {
+ "code": "cell_1 = 1",
+ "idx": 1,
+ "output": "<div>output 1</div>",
+ },
+ {
+ "code": "cell_2 = 2",
+ "idx": 2,
+ "output": "<div>output 2</div>",
+ },
+ ],
+ "id": "app1",
+ },
+ ]
+ `);
+ });
+
+ it("should set data-cell-idx attribute on elements", () => {
+ const elements = createMockIslands(2, "app1").map((el) => {
+ el.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ return el;
+ });
+
+ parseIslandElementsIntoApps(elements);
+
+ expect(elements[0].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("0");
+ expect(elements[1].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("1");
+ });
+});
+
+describe("parseMarimoIslandApps", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ document.body.removeChild(container);
+ });
+
+ it("should parse islands from document", () => {
+ const elements = createMockIslands(2, "app1").map((el) => {
+ el.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ return el;
+ });
+ for (const el of elements) {
+ container.appendChild(el);
+ }
+
+ const result = parseMarimoIslandApps(container);
+
+ expect(result).toHaveLength(1);
+ expect(result).toMatchInlineSnapshot(`
+ [
+ {
+ "cells": [
+ {
+ "code": "cell_0 = 0",
+ "idx": 0,
+ "output": "<div>output 0</div>",
+ },
+ {
+ "code": "cell_1 = 1",
+ "idx": 1,
+ "output": "<div>output 1</div>",
+ },
+ ],
+ "id": "app1",
+ },
+ ]
+ `);
+ });
+
+ it("should return empty array if no islands found", () => {
+ const result = parseMarimoIslandApps(container);
+
+ expect(result).toEqual([]);
+ });
+
+ it("should accept custom root element", () => {
+ const customRoot = document.createElement("div");
+ const elements = createMockIslands(1, "app1").map((el) => {
+ el.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ return el;
+ });
+ for (const el of elements) {
+ customRoot.appendChild(el);
+ }
+
+ const result = parseMarimoIslandApps(customRoot);
+
+ expect(result).toHaveLength(1);
+ expect(result).toMatchInlineSnapshot(`
+ [
+ {
+ "cells": [
+ {
+ "code": "cell_0 = 0",
+ "idx": 0,
+ "output": "<div>output 0</div>",
+ },
+ ],
+ "id": "app1",
+ },
+ ]
+ `);
+ });
});
diff --git a/frontend/src/core/islands/__tests__/test-utils.tsx b/frontend/src/core/islands/__tests__/test-utils.tsx
new file mode 100644
index 0000000000..86d82bfd38
--- /dev/null
+++ b/frontend/src/core/islands/__tests__/test-utils.tsx
@@ -0,0 +1,263 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { type RenderOptions, render } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import type { ReactElement } from "react";
+import {
+ ISLAND_DATA_ATTRIBUTES,
+ ISLAND_TAG_NAMES,
+} from "@/core/islands/constants";
+import type { WorkerFactory } from "@/core/islands/worker-factory";
+
+/**
+ * Test utilities for islands components and logic
+ */
+
+// ============================================================================
+// DOM Test Utilities
+// ============================================================================
+
+/**
+ * Creates a mock marimo-island element in the DOM
+ */
+export function createMockIslandElement(options: {
+ appId?: string;
+ cellIdx?: string;
+ code?: string;
+ innerHTML?: string;
+}): HTMLElement {
+ const {
+ appId = "test-app",
+ cellIdx = "0",
+ code = "import marimo as mo",
+ innerHTML = "",
+ } = options;
+
+ const element = document.createElement(ISLAND_TAG_NAMES.ISLAND);
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID, appId);
+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX, cellIdx);
+
+ if (code) {
+ const codeElement = document.createElement(ISLAND_TAG_NAMES.CELL_CODE);
+ codeElement.textContent = encodeURIComponent(code);
+ element.appendChild(codeElement);
+ }
+
+ if (innerHTML) {
+ const outputElement = document.createElement(ISLAND_TAG_NAMES.CELL_OUTPUT);
+ outputElement.innerHTML = innerHTML;
+ element.appendChild(outputElement);
+ }
+
+ return element;
+}
+
+/**
+ * Creates multiple island elements for testing
+ */
+export function createMockIslands(
+ count: number,
+ appId = "test-app",
+): HTMLElement[] {
+ return Array.from({ length: count }, (_, idx) =>
+ createMockIslandElement({
+ appId,
+ cellIdx: String(idx),
+ code: `cell_${idx} = ${idx}`,
+ innerHTML: `<div>output ${idx}</div>`,
+ }),
+ );
+}
+
+// ============================================================================
+// React Test Utilities
+// ============================================================================
+
+interface IslandsRenderOptions extends Omit<RenderOptions, "wrapper"> {
+ initialStore?: ReturnType<typeof createStore>;
+}
+
+/**
+ * Renders a React component with Islands providers
+ */
+export function renderWithIslandsProviders(
+ ui: ReactElement,
+ options?: IslandsRenderOptions,
+) {
+ const { initialStore, ...renderOptions } = options || {};
+ const store = initialStore || createStore();
+
+ function Wrapper({ children }: { children: React.ReactNode }) {
+ return <Provider store={store}>{children}</Provider>;
+ }
+
+ return {
+ store,
+ ...render(ui, { wrapper: Wrapper, ...renderOptions }),
+ };
+}
+
+// ============================================================================
+// Assertion Helpers
+// ============================================================================
+
+/**
+ * Waits for a condition to be true with timeout
+ */
+export async function waitForCondition(
+ condition: () => boolean,
+ timeout = 1000,
+ interval = 50,
+): Promise<void> {
+ const startTime = Date.now();
+ while (!condition()) {
+ if (Date.now() - startTime > timeout) {
+ throw new Error("Timeout waiting for condition");
+ }
+ await new Promise((resolve) => setTimeout(resolve, interval));
+ }
+}
+
+/**
+ * Waits for an async function to not throw
+ */
+export async function waitForNoError<T>(
+ fn: () => T | Promise<T>,
+ timeout = 1000,
+): Promise<T> {
+ const startTime = Date.now();
+ let lastError: Error | undefined;
+
+ while (Date.now() - startTime < timeout) {
+ try {
+ return await Promise.resolve(fn());
+ } catch (error) {
+ lastError = error as Error;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ }
+
+ throw lastError || new Error("Timeout waiting for function to succeed");
+}
+
+// ============================================================================
+// HTML-based Island Harness
+// ============================================================================
+
+export interface IslandSpec {
+ appId?: string;
+ reactive?: boolean;
+ code?: string;
+ output?: string;
+ displayCode?: boolean;
+}
+
+/**
+ * Builds island HTML from a declarative spec — mirrors what generate.py produces.
+ * Use with `createIslandHarness()` to parse and inspect the resulting state.
+ */
+export function buildIslandHTML(islands: IslandSpec[]): string {
+ return islands
+ .map((spec) => {
+ const appId = spec.appId ?? "test-app";
+ const reactive = spec.reactive ?? true;
+ const output = spec.output ?? "<div>output</div>";
+ const code = spec.code ?? 'print("hello")';
+
+ const codeTag = code
+ ? `<${ISLAND_TAG_NAMES.CELL_CODE}>${encodeURIComponent(code)}</${ISLAND_TAG_NAMES.CELL_CODE}>`
+ : "";
+ const outputTag = `<${ISLAND_TAG_NAMES.CELL_OUTPUT}>${output}</${ISLAND_TAG_NAMES.CELL_OUTPUT}>`;
+
+ return `<${ISLAND_TAG_NAMES.ISLAND} ${ISLAND_DATA_ATTRIBUTES.APP_ID}="${appId}" ${ISLAND_DATA_ATTRIBUTES.REACTIVE}="${reactive}">${outputTag}${codeTag}</${ISLAND_TAG_NAMES.ISLAND}>`;
+ })
+ .join("\n");
+}
+
+export interface IslandHarness {
+ /** The container element holding all islands */
+ container: HTMLElement;
+ /** All island elements found in the container */
+ islands: HTMLElement[];
+ /** Cleanup — removes container from DOM */
+ cleanup: () => void;
+}
+
+/**
+ * Creates a test harness from raw island HTML.
+ *
+ * Parses the HTML into real DOM elements attached to `document.body` so that
+ * `querySelectorAll`, `getAttribute`, etc. work correctly.
+ *
+ * @example
+ * ```ts
+ * const harness = createIslandHarness(buildIslandHTML([
+ * { reactive: true, code: 'x = 1', output: '<div>1</div>' },
+ * { reactive: false, output: '<div>static</div>' },
+ * ]));
+ * // ... assertions ...
+ * harness.cleanup();
+ * ```
+ */
+export function createIslandHarness(html: string): IslandHarness {
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ document.body.appendChild(container);
+
+ // eslint-disable-next-line unicorn/prefer-spread
+ const islands = Array.from(
+ container.querySelectorAll<HTMLElement>(ISLAND_TAG_NAMES.ISLAND),
+ );
+
+ return {
+ container,
+ islands,
+ cleanup: () => container.remove(),
+ };
+}
+
+// ============================================================================
+// Mock Worker Factory
+// ============================================================================
+
+/**
+ * Mock worker factory for testing
+ */
+export class MockWorkerFactory implements WorkerFactory {
+ public workers: Worker[] = [];
+ private readonly mockWorker?: Worker;
+
+ constructor(mockWorker?: Worker) {
+ this.mockWorker = mockWorker;
+ }
+
+ create(): Worker {
+ const worker = this.mockWorker || this.createMockWorker();
+ this.workers.push(worker);
+ return worker;
+ }
+
+ private createMockWorker(): Worker {
+ return {
+ postMessage: () => {},
+ terminate: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => true,
+ onmessage: null,
+ onerror: null,
+ onmessageerror: null,
+ } as unknown as Worker;
+ }
+
+ getCreatedWorkers(): Worker[] {
+ return this.workers;
+ }
+
+ terminateAll(): void {
+ for (const worker of this.workers) {
+ worker.terminate();
+ }
+ this.workers = [];
+ }
+}
diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.ts
new file mode 100644
index 0000000000..c3a79a0597
--- /dev/null
+++ b/frontend/src/core/islands/bootstrap.ts
@@ -0,0 +1,265 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { toast } from "@/components/ui/use-toast";
+import { ISLAND_CSS_CLASSES, ISLAND_TAG_NAMES } from "@/core/islands/constants";
+import { renderHTML } from "@/plugins/core/RenderHTML";
+import {
+ handleWidgetMessage,
+ MODEL_MANAGER,
+} from "@/plugins/impl/anywidget/model";
+import { initializePlugins } from "@/plugins/plugins";
+import { Functions } from "@/utils/functions";
+import {
+ safeExtractSetUIElementMessageBuffers,
+ type JsonString,
+} from "@/utils/json/base64";
+import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
+import { Logger } from "@/utils/Logger";
+import { logNever } from "@/utils/assertNever";
+import {
+ createNotebookActions,
+ notebookAtom,
+ notebookReducer,
+} from "../cells/cells";
+import { defineCustomElement } from "../dom/defineCustomElement";
+import { MarimoValueInputEvent } from "../dom/events";
+import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
+import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";
+import {
+ handleCellNotificationeration,
+ handleKernelReady,
+ handleRemoveUIElements,
+} from "../kernel/handlers";
+import type {
+ NotificationMessage,
+ NotificationMessageType,
+} from "../kernel/messages";
+import { queryParamHandlers } from "../kernel/queryParamHandlers";
+import { RuntimeState } from "../kernel/RuntimeState";
+import { initialModeAtom } from "../mode";
+import { requestClientAtom } from "../network/requests";
+import { store as defaultStore } from "../state/jotai";
+import type { IslandsPyodideBridge } from "./bridge";
+import { MarimoIslandElement } from "./components/web-components";
+import {
+ shouldShowIslandsWarningIndicatorAtom,
+ userTriedToInteractWithIslandsAtom,
+} from "./state";
+import { dismissIslandsLoadingToast, toastIslandsLoading } from "./toast";
+
+type Store = typeof defaultStore;
+type NotebookActions = ReturnType<typeof createNotebookActions>;
+
+/**
+ * Configuration for the islands bootstrap process
+ */
+export interface IslandsBootstrapConfig {
+ bridge: IslandsPyodideBridge;
+ store?: Store;
+ root?: Document | Element;
+ autoInitializePlugins?: boolean;
+}
+
+/**
+ * Initialize marimo islands: sets up networking, discovers island elements,
+ * wires up the message consumer, and starts the runtime.
+ */
+export async function initializeIslands(
+ config: IslandsBootstrapConfig,
+): Promise<void> {
+ const store = config.store || defaultStore;
+ const root = config.root || document;
+ const bridge = config.bridge;
+
+ // Setup networking
+ store.set(requestClientAtom, bridge);
+ store.set(initialModeAtom, "read");
+
+ // Initialize plugins for rendering static HTML
+ if (config.autoInitializePlugins !== false) {
+ initializePlugins();
+ }
+
+ // Find all island elements
+ // eslint-disable-next-line prefer-spread
+ const islands = Array.from(
+ root.querySelectorAll<HTMLElement>(ISLAND_TAG_NAMES.ISLAND),
+ );
+
+ if (islands.length === 0) {
+ Logger.log("No islands found, skipping initialization");
+ return;
+ }
+
+ Logger.log(`Initializing ${islands.length} island(s)`);
+
+ // Apply styles
+ for (const island of islands) {
+ island.classList.add(ISLAND_CSS_CLASSES.NAMESPACE);
+ }
+
+ // Setup notebook actions
+ const actions = createNotebookActions((action) => {
+ store.set(notebookAtom, (state: typeof notebookAtom.init) =>
+ notebookReducer(state, action),
+ );
+ });
+
+ // Loading indicator: dim islands while Pyodide initializes
+ store.sub(shouldShowIslandsWarningIndicatorAtom, () => {
+ const showing = store.get(shouldShowIslandsWarningIndicatorAtom);
+ if (showing) {
+ toastIslandsLoading();
+ for (const island of islands) {
+ island.style.setProperty("opacity", "0.5");
+ }
+ } else {
+ dismissIslandsLoadingToast();
+ for (const island of islands) {
+ island.style.removeProperty("opacity");
+ }
+ }
+ });
+
+ // Wire up kernel message handling
+ // The wire format is {"op": "...", "data": {"op": "...", ...}} — both
+ // the envelope and the payload carry the op. The bridge types the message
+ // as NotificationPayload (just {data}), but the actual wire format
+ // includes the outer op too.
+ bridge.consumeMessages((message) => {
+ handleMessage(
+ message as unknown as JsonString<IslandsNotificationMessage>,
+ actions,
+ );
+ });
+
+ // Track first user interaction before initialization completes
+ document.addEventListener(
+ MarimoValueInputEvent.TYPE,
+ () => {
+ store.set(userTriedToInteractWithIslandsAtom, true);
+ },
+ { once: true },
+ );
+
+ // Start the runtime
+ RuntimeState.INSTANCE.start(bridge.sendComponentValues);
+}
+
+type IslandsNotificationMessage = {
+ [K in NotificationMessageType]: {
+ data: Extract<NotificationMessage, { op: K }>;
+ op: K;
+ };
+}[NotificationMessageType];
+
+/**
+ * Handles a single message from the kernel.
+ *
+ * Wire format from Python: {"op": "<name>", "data": {"op": "<name>", ...}}
+ */
+function handleMessage(
+ message: JsonString<IslandsNotificationMessage>,
+ actions: NotebookActions,
+): void {
+ try {
+ const msg = jsonParseWithSpecialChar(message);
+ Logger.debug("Islands received message:", msg.op);
+
+ switch (msg.op) {
+ // Unsupported operations in islands mode
+ case "banner":
+ case "missing-package-alert":
+ case "installing-package-alert":
+ case "completion-result":
+ case "reload":
+ case "focus-cell":
+ case "variables":
+ case "variable-values":
+ case "data-column-preview":
+ case "sql-table-preview":
+ case "sql-table-list-preview":
+ case "sql-schema-list-preview":
+ case "datasets":
+ case "data-source-connections":
+ case "validate-sql-result":
+ case "storage-namespaces":
+ case "storage-entries":
+ case "storage-download-ready":
+ case "secret-keys-result":
+ case "startup-logs":
+ case "completed-run":
+ case "interrupted":
+ case "reconnected":
+ case "cache-cleared":
+ case "cache-info":
+ case "kernel-startup-error":
+ case "notebook-document-transaction":
+ return;
+
+ case "kernel-ready":
+ handleKernelReady(msg.data, {
+ autoInstantiate: true,
+ setCells: actions.setCells,
+ setLayoutData: Functions.NOOP,
+ setAppConfig: Functions.NOOP,
+ setCapabilities: Functions.NOOP,
+ setKernelState: Functions.NOOP,
+ onError: Logger.error,
+ });
+ defineCustomElement(ISLAND_TAG_NAMES.ISLAND, MarimoIslandElement);
+ return;
+
+ case "send-ui-element-message":
+ UI_ELEMENT_REGISTRY.broadcastMessage(
+ msg.data.ui_element,
+ msg.data.message,
+ safeExtractSetUIElementMessageBuffers(msg.data),
+ );
+ return;
+
+ case "remove-ui-elements":
+ handleRemoveUIElements(msg.data);
+ return;
+
+ case "function-call-result":
+ FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);
+ return;
+
+ case "cell-op":
+ handleCellNotificationeration(msg.data, actions.handleCellMessage);
+ return;
+
+ case "alert":
+ toast({
+ title: msg.data.title,
+ description: renderHTML({ html: msg.data.description }),
+ variant: msg.data.variant,
+ });
+ return;
+
+ case "query-params-append":
+ queryParamHandlers.append(msg.data);
+ return;
+ case "query-params-set":
+ queryParamHandlers.set(msg.data);
+ return;
+ case "query-params-delete":
+ queryParamHandlers.delete(msg.data);
+ return;
+ case "query-params-clear":
+ queryParamHandlers.clear();
+ return;
+
+ case "model-lifecycle":
+ handleWidgetMessage(MODEL_MANAGER, msg.data);
+ return;
+
+ default:
+ logNever(msg);
+ return;
+ }
+ } catch (error) {
+ Logger.error("Failed to handle kernel message:", error);
+ }
+}
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index e08c69c672..f52f632926 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -8,100 +8,154 @@ import type { JsonString } from "@/utils/json/base64";
import { Logger } from "@/utils/Logger";
import { generateUUID } from "@/utils/uuid";
import type { CommandMessage, NotificationPayload } from "../kernel/messages";
-import { getMarimoVersion } from "../meta/globals";
import type { EditRequests, RunRequests } from "../network/types";
-import { store } from "../state/jotai";
-
+import { store as defaultStore } from "../state/jotai";
import { createMarimoFile, parseMarimoIslandApps } from "./parse";
import { islandsInitializedAtom } from "./state";
import type { WorkerSchema } from "./worker/worker";
-import workerUrl from "./worker/worker.tsx?worker&url";
+import type { WorkerFactory } from "./worker-factory";
+import { DefaultWorkerFactory } from "./worker-factory";
-export class IslandsPyodideBridge implements RunRequests, EditRequests {
+/**
+ * Configuration for creating an IslandsPyodideBridge
+ */
+export interface IslandsBridgeConfig {
/**
- * Lazy singleton instance of the IslandsPyodideBridge.
+ * Optional worker factory for creating workers (for testing)
*/
- static get INSTANCE(): IslandsPyodideBridge {
- const KEY = "_marimo_private_IslandsPyodideBridge";
- if (!window[KEY]) {
- window[KEY] = new IslandsPyodideBridge();
- }
- return window[KEY] as IslandsPyodideBridge;
- }
+ workerFactory?: WorkerFactory;
+ /**
+ * Optional Jotai store (for testing)
+ */
+ store?: typeof defaultStore;
+
+ /**
+ * Optional root element for parsing islands (for testing)
+ */
+ root?: Document | Element;
+
+ /**
+ * Whether to auto-start sessions on worker ready (default: true)
+ */
+ autoStartSessions?: boolean;
+}
+
+/**
+ * Bridge between the browser and Pyodide worker for islands mode.
+ *
+ * This class manages communication with a Web Worker that runs Python code
+ * via Pyodide, enabling interactive marimo islands.
+ *
+ * @example
+ * ```ts
+ * const bridge = new IslandsPyodideBridge();
+ * await bridge.initialized;
+ * bridge.consumeMessages(message => console.log(message));
+ * ```
+ */
+export class IslandsPyodideBridge implements RunRequests, EditRequests {
private rpc: ReturnType<typeof getWorkerRPC<WorkerSchema>>;
private messageConsumer:
| ((message: JsonString<NotificationPayload>) => void)
| undefined;
+ private readonly store: typeof defaultStore;
+ private readonly root: Document | Element;
+ private readonly autoStartSessions: boolean;
public initialized = new Deferred<void>();
- private constructor() {
- // TODO: abstract out into a worker constructor
-
- // . in front of workerUrl is necessary to make it a relative import
- const url = import.meta.env.DEV
- ? workerUrl
- : makeRelativeWorkerUrl(workerUrl);
- const js = `import ${JSON.stringify(new URL(url, import.meta.url))}`;
- const blob = new Blob([js], { type: "application/javascript" });
- const objURL = URL.createObjectURL(blob);
- const worker = new Worker(
- // oxlint-disable-next-line unicorn/relative-url-style
- objURL,
- {
- type: "module",
- // Pass the version to the worker
- /* @vite-ignore */
- name: getMarimoVersion(),
- },
- );
+ constructor(config: IslandsBridgeConfig = {}) {
+ this.store = config.store || defaultStore;
+ this.root = config.root || document;
+ this.autoStartSessions = config.autoStartSessions ?? true;
- worker.addEventListener("error", (e) => {
- // Fallback to cleaning up created object URL
- URL.revokeObjectURL(objURL);
- });
-
- // Create the RPC
- this.rpc = getWorkerRPC<WorkerSchema>(worker);
+ try {
+ const factory = config.workerFactory || new DefaultWorkerFactory();
+ const worker = factory.create();
+ this.rpc = getWorkerRPC<WorkerSchema>(worker);
+ this.setupMessageListeners();
+ } catch (error) {
+ Logger.error("Failed to initialize IslandsPyodideBridge:", error);
+ this.initialized.reject(error);
+ throw error;
+ }
+ }
- // Listeners
- const apps = parseMarimoIslandApps();
+ /**
+ * Sets up message listeners for worker communication
+ */
+ private setupMessageListeners(): void {
this.rpc.addMessageListener("ready", () => {
- for (const app of apps) {
- Logger.debug("Starting session for app", app.id);
- const file = createMarimoFile(app);
- Logger.debug(file);
- this.startSession({
- code: file,
- appId: app.id,
- });
+ if (this.autoStartSessions) {
+ this.startSessionsForAllApps();
}
});
+
this.rpc.addMessageListener("initialized", () => {
- store.set(islandsInitializedAtom, true);
+ this.store.set(islandsInitializedAtom, true);
this.initialized.resolve();
});
- this.rpc.addMessageListener("initializedError", ({ error }) => {
- store.set(islandsInitializedAtom, error);
- this.initialized.reject(new Error(error));
- });
- this.rpc.addMessageListener("kernelMessage", ({ message }) => {
- this.messageConsumer?.(message);
- });
+
+ this.rpc.addMessageListener(
+ "initializedError",
+ ({ error }: { error: string }) => {
+ Logger.error("Islands initialization error:", error);
+ this.store.set(islandsInitializedAtom, error);
+ this.initialized.reject(new Error(error));
+ },
+ );
+
+ this.rpc.addMessageListener(
+ "kernelMessage",
+ ({ message }: { message: JsonString<NotificationPayload> }) => {
+ this.messageConsumer?.(message);
+ },
+ );
}
- async startSession(opts: { code: string; appId: string }) {
+ /**
+ * Starts sessions for all apps found in the DOM
+ */
+ private startSessionsForAllApps(): void {
+ const apps = parseMarimoIslandApps(this.root);
+ Logger.debug(
+ `Starting sessions for ${apps.length} app(s):`,
+ apps.map((a) => `${a.id} (${a.cells.length} cells)`),
+ );
+ for (const app of apps) {
+ const file = createMarimoFile(app);
+ Logger.debug(`App ${app.id} marimo file:\n`, file);
+ this.startSession({
+ code: file,
+ appId: app.id,
+ }).catch((error) => {
+ Logger.error(`Failed to start session for app ${app.id}:`, error);
+ });
+ }
+ }
+
+ /**
+ * Starts a new Python session for an app
+ */
+ async startSession(opts: { code: string; appId: string }): Promise<void> {
await this.rpc.proxy.request.startSession(opts);
}
+ /**
+ * Sets up a consumer for kernel messages
+ */
consumeMessages(
consumer: (message: JsonString<NotificationPayload>) => void,
- ) {
+ ): void {
this.messageConsumer = consumer;
this.rpc.proxy.send.consumerReady({});
}
+ // ============================================================================
+ // RunRequests Implementation
+ // ============================================================================
+
sendComponentValues: RunRequests["sendComponentValues"] = async (
request,
): Promise<null> => {
@@ -113,9 +167,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendInstantiate: RunRequests["sendInstantiate"] = async (
- request,
- ): Promise<null> => {
+ sendInstantiate: RunRequests["sendInstantiate"] = async (): Promise<null> => {
return null;
};
@@ -129,23 +181,31 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendRun: EditRequests["sendRun"] = async (request): Promise<null> => {
- await this.rpc.proxy.request.loadPackages(request.codes.join("\n"));
+ sendModelValue: RunRequests["sendModelValue"] = async (request) => {
await this.putControlRequest({
- type: "execute-cells",
+ type: "model",
...request,
});
return null;
};
- sendModelValue: RunRequests["sendModelValue"] = async (request) => {
+ // ============================================================================
+ // EditRequests Implementation
+ // ============================================================================
+
+ sendRun: EditRequests["sendRun"] = async (request): Promise<null> => {
+ await this.rpc.proxy.request.loadPackages(request.codes.join("\n"));
await this.putControlRequest({
- type: "model",
+ type: "execute-cells",
...request,
});
return null;
};
+ // ============================================================================
+ // Not Implemented (Read-Only Mode)
+ // ============================================================================
+
getUsageStats = throwNotImplemented;
sendRename = throwNotImplemented;
sendSave = throwNotImplemented;
@@ -207,18 +267,37 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
// The kernel uses msgspec to parse control requests, which requires a 'type'
// field for discriminated union deserialization.
- private async putControlRequest(operation: CommandMessage) {
+ private async putControlRequest(operation: CommandMessage): Promise<void> {
await this.rpc.proxy.request.bridge({
functionName: "put_control_request",
payload: operation,
});
}
+
+ /**
+ * Cleans up resources (for testing)
+ */
+ destroy(): void {
+ // Future: terminate worker if we own it
+ }
+}
+
+/**
+ * Global singleton instance.
+ * Use `new IslandsPyodideBridge(config)` in tests for better isolation.
+ */
+let globalBridgeInstance: IslandsPyodideBridge | null = null;
+
+export function getGlobalBridge(): IslandsPyodideBridge {
+ if (!globalBridgeInstance) {
+ globalBridgeInstance = new IslandsPyodideBridge();
+ }
+ return globalBridgeInstance;
}
-function makeRelativeWorkerUrl(url: string) {
- return url.startsWith("./")
- ? url
- : url.startsWith("/")
- ? `.${url}`
- : `./${url}`;
+/**
+ * Resets the global bridge instance (for testing)
+ */
+export function resetGlobalBridge(): void {
+ globalBridgeInstance = null;
}
diff --git a/frontend/src/core/islands/components/IslandControls.tsx b/frontend/src/core/islands/components/IslandControls.tsx
new file mode 100644
index 0000000000..cdc071698c
--- /dev/null
+++ b/frontend/src/core/islands/components/IslandControls.tsx
@@ -0,0 +1,103 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { CopyIcon, PlayIcon } from "lucide-react";
+import type { JSX } from "react";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import type { CellId } from "@/core/cells/ids";
+import { useRequestClient } from "@/core/network/requests";
+import { copyToClipboard } from "@/utils/copy";
+import { Logger } from "@/utils/Logger";
+
+/**
+ * Props for IslandControls component
+ */
+export interface IslandControlsProps {
+ /**
+ * ID of the cell this control operates on
+ */
+ cellId: CellId;
+
+ /**
+ * Callback to get the current code for the cell
+ */
+ codeCallback: () => string;
+
+ /**
+ * Whether the controls should be visible
+ */
+ visible: boolean;
+}
+
+/**
+ * Props for individual control buttons
+ */
+interface IconButtonProps {
+ tooltip: string;
+ icon: JSX.Element;
+ action: () => void;
+}
+
+/**
+ * A single icon button with tooltip
+ */
+const IconButton: React.FC<IconButtonProps> = ({ tooltip, icon, action }) => (
+ <Tooltip content={tooltip} delayDuration={200}>
+ <Button
+ size="icon"
+ variant="outline"
+ className="bg-background h-5 w-5 mb-0"
+ onClick={action}
+ >
+ {icon}
+ </Button>
+ </Tooltip>
+);
+
+/**
+ * Controls for interacting with an island cell.
+ *
+ * Provides buttons to:
+ * - Copy the cell's code to clipboard
+ * - Re-run the cell
+ */
+export const IslandControls: React.FC<IslandControlsProps> = ({
+ cellId,
+ codeCallback,
+ visible,
+}) => {
+ const { sendRun } = useRequestClient();
+
+ const handleCopy = () => {
+ copyToClipboard(codeCallback());
+ };
+
+ const handleRun = async () => {
+ try {
+ await sendRun({
+ cellIds: [cellId],
+ codes: [codeCallback()],
+ });
+ } catch (error) {
+ Logger.error("Failed to run cell:", error);
+ }
+ };
+
+ return (
+ <div
+ className="absolute top-0 right-0 z-50 flex items-center justify-center gap-1"
+ style={{ display: visible ? "flex" : "none" }}
+ >
+ <IconButton
+ tooltip="Copy code"
+ icon={<CopyIcon className="size-3" />}
+ action={handleCopy}
+ />
+ <IconButton
+ tooltip="Re-run cell"
+ icon={<PlayIcon className="size-3" />}
+ action={handleRun}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/core/islands/components/__tests__/IslandControls.test.tsx b/frontend/src/core/islands/components/__tests__/IslandControls.test.tsx
new file mode 100644
index 0000000000..59c200c282
--- /dev/null
+++ b/frontend/src/core/islands/components/__tests__/IslandControls.test.tsx
@@ -0,0 +1,185 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import type { CellId } from "@/core/cells/ids";
+import * as requestsModule from "@/core/network/requests";
+import * as copyModule from "@/utils/copy";
+import { IslandControls } from "../IslandControls";
+
+// Mock the dependencies
+vi.mock("@/core/network/requests", () => ({
+ useRequestClient: vi.fn(),
+}));
+
+vi.mock("@/utils/copy", () => ({
+ copyToClipboard: vi.fn(),
+}));
+
+describe("IslandControls", () => {
+ const mockSendRun = vi.fn();
+ const mockCopyToClipboard = vi.fn();
+ const mockCodeCallback = vi.fn(() => "print('test code')");
+ const cellId = "test-cell-id" as CellId;
+
+ // Helper to render with required providers
+ const renderWithProviders = (component: React.ReactElement) => {
+ return render(<TooltipProvider>{component}</TooltipProvider>);
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockSendRun.mockResolvedValue(undefined);
+
+ vi.spyOn(requestsModule, "useRequestClient").mockReturnValue({
+ sendRun: mockSendRun,
+ } as any);
+
+ vi.spyOn(copyModule, "copyToClipboard").mockImplementation(
+ mockCopyToClipboard,
+ );
+ });
+
+ it("should not display when visible is false", () => {
+ const { container } = renderWithProviders(
+ <IslandControls
+ cellId={cellId}
+ codeCallback={mockCodeCallback}
+ visible={false}
+ />,
+ );
+
+ const controlsDiv = container.firstChild as HTMLElement;
+ expect(controlsDiv).toBeDefined();
+ expect(controlsDiv.style.display).toBe("none");
+ });
+
+ it("should display when visible is true", () => {
+ const { container } = renderWithProviders(
+ <IslandControls
+ cellId={cellId}
+ codeCallback={mockCodeCallback}
+ visible={true}
+ />,
+ );
+
+ const controlsDiv = container.firstChild as HTMLElement;
+ expect(controlsDiv.style.display).toBe("flex");
+ });
+
+ it("should render copy and run buttons", () => {
+ renderWithProviders(
+ <IslandControls
+ cellId={cellId}
+ codeCallback={mockCodeCallback}
+ visible={true}
+ />,
+ );
+
+ // Should have 2 buttons (copy and run)
+ const buttons = screen.getAllByRole("button");
+ expect(buttons).toHaveLength(2);
+ });
+
+ it("should copy code to clipboard when copy button is clicked", async () => {
+ renderWithProviders(
+ <IslandControls
+ cellId={cellId}
+ codeCallback={mockCodeCallback}
+ visible={true}
+ />,
+ );
+
+ const buttons = screen.getAllByRole("button");
+ const copyButton = buttons[0]; // First button is copy
+
+ fireEvent.click(copyButton);
+
+ expect(mockCodeCallback).toHaveBeenCalled();
+ expect(mockCopyToClipboard).toHaveBeenCalledWith("print('test code')");
+ });
+
+ it("should run cell when run button is clicked", async () => {
+ renderWithProviders(
+ <IslandControls
+ cellId={cellId}
+ codeCallback={mockCodeCallback}
+ visible={true}
+ />,
+ );
+
+ const buttons = screen.getAllByRole("button");
+ const runButton = buttons[1]; // Second button is run
+
+ fireEvent.click(runButton);
+
+ // Wait for async operation
+ await vi.waitFor(() => {
+ expect(mockCodeCallback).toHaveBeenCalled();
+ expect(mockSendRun).toHaveBeenCalledWith({
+ cellIds: [cellId],
+ codes: ["print('test code')"],
+ });
+ });
+ });
+
+ it("should handle run errors gracefully", async () => {
+ const consoleErrorSpy = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ mockSendRun.mockRejectedValueOnce(new Error("Run failed"));
+
+ renderWithProviders(
+ <IslandControls
+ cellId={cellId}
+ codeCallback={mockCodeCallback}
+ visible={true}
+ />,
+ );
+
+ const buttons = screen.getAllByRole("button");
+ const runButton = buttons[1];
+
+ fireEvent.click(runButton);
+
+ // Wait for error to be logged
+ await vi.waitFor(() => {
+ expect(consoleErrorSpy).toHaveBeenCalled();
+ });
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ it("should get fresh code on each button click", async () => {
+ let callCount = 0;
+ const dynamicCodeCallback = vi.fn(() => `code version ${++callCount}`);
+
+ renderWithProviders(
+ <IslandControls
+ cellId={cellId}
+ codeCallback={dynamicCodeCallback}
+ visible={true}
+ />,
+ );
+
+ const buttons = screen.getAllByRole("button");
+ const copyButton = buttons[0];
+ const runButton = buttons[1];
+
+ fireEvent.click(copyButton);
+ expect(mockCopyToClipboard).toHaveBeenCalledWith("code version 1");
+
+ fireEvent.click(runButton);
+ await vi.waitFor(() => {
+ expect(mockSendRun).toHaveBeenCalledWith({
+ cellIds: [cellId],
+ codes: ["code version 2"],
+ });
+ });
+
+ fireEvent.click(copyButton);
+ expect(mockCopyToClipboard).toHaveBeenCalledWith("code version 3");
+ });
+});
diff --git a/frontend/src/core/islands/components/__tests__/useIslandControls.test.ts b/frontend/src/core/islands/components/__tests__/useIslandControls.test.ts
new file mode 100644
index 0000000000..84ef734a9e
--- /dev/null
+++ b/frontend/src/core/islands/components/__tests__/useIslandControls.test.ts
@@ -0,0 +1,208 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { useIslandControls } from "../useIslandControls";
+
+describe("useIslandControls", () => {
+ beforeEach(() => {
+ // Clean up any event listeners
+ document.body.innerHTML = "";
+ });
+
+ afterEach(() => {
+ // Clean up
+ document.body.innerHTML = "";
+ });
+
+ it("should return false initially when alwaysShowRun is false", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+ expect(result.current).toBe(false);
+ });
+
+ it("should return true initially when alwaysShowRun is true", () => {
+ const { result } = renderHook(() => useIslandControls(true));
+ expect(result.current).toBe(true);
+ });
+
+ it("should return true when Cmd key is pressed (macOS)", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ expect(result.current).toBe(false);
+
+ act(() => {
+ const event = new KeyboardEvent("keydown", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+
+ expect(result.current).toBe(true);
+ });
+
+ it("should return true when Ctrl key is pressed (Windows/Linux)", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ expect(result.current).toBe(false);
+
+ act(() => {
+ const event = new KeyboardEvent("keydown", { ctrlKey: true });
+ document.dispatchEvent(event);
+ });
+
+ expect(result.current).toBe(true);
+ });
+
+ it("should return false when Cmd key is released", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ // Press Cmd
+ act(() => {
+ const event = new KeyboardEvent("keydown", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ // Release Cmd
+ act(() => {
+ const event = new KeyboardEvent("keyup", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("should return false when Ctrl key is released", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ // Press Ctrl
+ act(() => {
+ const event = new KeyboardEvent("keydown", { ctrlKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ // Release Ctrl
+ act(() => {
+ const event = new KeyboardEvent("keyup", { ctrlKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("should return false when Meta key name is released", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ // Press Cmd
+ act(() => {
+ const event = new KeyboardEvent("keydown", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ // Release by key name
+ act(() => {
+ const event = new KeyboardEvent("keyup", { key: "Meta" });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("should return false when Control key name is released", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ // Press Ctrl
+ act(() => {
+ const event = new KeyboardEvent("keydown", { ctrlKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ // Release by key name
+ act(() => {
+ const event = new KeyboardEvent("keyup", { key: "Control" });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("should return false when window loses focus", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ // Press Cmd
+ act(() => {
+ const event = new KeyboardEvent("keydown", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ // Blur window
+ act(() => {
+ const event = new Event("blur");
+ window.dispatchEvent(event);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("should return false when mouse leaves window", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ // Press Cmd
+ act(() => {
+ const event = new KeyboardEvent("keydown", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ // Mouse leave
+ act(() => {
+ const event = new Event("mouseleave");
+ window.dispatchEvent(event);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("should not register keyboard event listeners when alwaysShowRun is true", () => {
+ const { result } = renderHook(() => useIslandControls(true));
+
+ expect(result.current).toBe(true);
+
+ // Try to change state with keyboard events - should have no effect
+ act(() => {
+ const event = new KeyboardEvent("keydown", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ act(() => {
+ const event = new KeyboardEvent("keyup", { metaKey: true });
+ document.dispatchEvent(event);
+ });
+ expect(result.current).toBe(true);
+
+ // Blur and mouseleave are also no-ops when alwaysShowRun is true
+ act(() => {
+ window.dispatchEvent(new Event("blur"));
+ });
+ expect(result.current).toBe(true);
+ });
+
+ it("should handle rapid key presses correctly", () => {
+ const { result } = renderHook(() => useIslandControls(false));
+
+ expect(result.current).toBe(false);
+
+ // Multiple rapid presses
+ act(() => {
+ document.dispatchEvent(new KeyboardEvent("keydown", { metaKey: true }));
+ document.dispatchEvent(new KeyboardEvent("keydown", { metaKey: true }));
+ document.dispatchEvent(new KeyboardEvent("keydown", { metaKey: true }));
+ });
+ expect(result.current).toBe(true);
+
+ // Multiple rapid releases
+ act(() => {
+ document.dispatchEvent(new KeyboardEvent("keyup", { metaKey: true }));
+ document.dispatchEvent(new KeyboardEvent("keyup", { metaKey: true }));
+ document.dispatchEvent(new KeyboardEvent("keyup", { metaKey: true }));
+ });
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/frontend/src/core/islands/components/output-wrapper.tsx b/frontend/src/core/islands/components/output-wrapper.tsx
index 12748ff85c..d65fcfd67c 100644
--- a/frontend/src/core/islands/components/output-wrapper.tsx
+++ b/frontend/src/core/islands/components/output-wrapper.tsx
@@ -2,139 +2,120 @@
import { useAtomValue } from "jotai";
import { selectAtom } from "jotai/utils";
-import { CopyIcon, Loader2Icon, PlayIcon } from "lucide-react";
+import { Loader2Icon } from "lucide-react";
import React, {
- type JSX,
type PropsWithChildren,
useCallback,
- useState,
+ useEffect,
+ useRef,
} from "react";
import { OutputRenderer } from "@/components/editor/Output";
-import { Button } from "@/components/ui/button";
-import { Tooltip } from "@/components/ui/tooltip";
import { type NotebookState, notebookAtom } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { isOutputEmpty } from "@/core/cells/outputs";
import type { CellRuntimeState } from "@/core/cells/types";
-import { useRequestClient } from "@/core/network/requests";
-import { useEventListener } from "@/hooks/useEventListener";
-import { copyToClipboard } from "@/utils/copy";
-import { Logger } from "@/utils/Logger";
+import { ISLAND_TAG_NAMES } from "../constants";
+import { IslandControls } from "./IslandControls";
+import { useIslandControls } from "./useIslandControls";
-interface Props {
+/**
+ * Props for MarimoOutputWrapper component
+ */
+export interface MarimoOutputWrapperProps {
+ /**
+ * ID of the cell being rendered
+ */
cellId: CellId;
+
+ /**
+ * Callback to get the current code for the cell
+ */
codeCallback: () => string;
+
+ /**
+ * Whether to always show the run button (e.g., when editor is present)
+ */
alwaysShowRun: boolean;
- children: React.ReactNode;
-}
-interface IconButtonProps {
- tooltip: string;
- icon: JSX.Element;
- action: () => void;
+ /**
+ * Initial/static HTML content to display
+ */
+ children: React.ReactNode;
}
-const IconButton: React.FC<IconButtonProps> = ({ tooltip, icon, action }) => (
- <Tooltip content={tooltip} delayDuration={200}>
- <Button
- size="icon"
- variant="outline"
- className="bg-background h-5 w-5 mb-0"
- onClick={action}
- >
- {icon}
- </Button>
- </Tooltip>
-);
-
-export const MarimoOutputWrapper: React.FC<Props> = ({
+/**
+ * Wraps marimo cell output with interactive controls and status indicators.
+ *
+ * This component:
+ * - Renders cell output from the runtime state
+ * - Shows a loading spinner when the cell is running
+ * - Provides controls to copy code and re-run the cell
+ */
+export const MarimoOutputWrapper: React.FC<MarimoOutputWrapperProps> = ({
cellId,
codeCallback,
alwaysShowRun,
children,
}) => {
- const { sendRun } = useRequestClient();
- const [pressed, setPressed] = useState<boolean>(alwaysShowRun);
+ const controlsVisible = useIslandControls(alwaysShowRun);
+ const wrapperRef = useRef<HTMLDivElement>(null);
const selector = useCallback(
(s: NotebookState) => s.cellRuntime[cellId],
[cellId],
);
const runtime = useAtomValue(selectAtom(notebookAtom, selector));
- // No need to register, if display is default.
- // Lint still wants use to have the same event listeners per instance (which
- // makes sense), so noop is used.
- const maybeNoop = (fn: (e: KeyboardEvent) => void) =>
- // oxlint-disable-next-line typescript/no-empty-function
- alwaysShowRun ? () => {} : fn;
-
- useEventListener(
- document,
- "keydown",
- maybeNoop((e) => {
- if (!alwaysShowRun && (e.metaKey || e.ctrlKey)) {
- setPressed(true);
- }
- }),
- );
- useEventListener(
- document,
- "keyup",
- maybeNoop((e) => {
- if (
- !alwaysShowRun &&
- (e.metaKey || e.ctrlKey || e.key === "Meta" || e.key === "Control")
- ) {
- setPressed(false);
- }
- }),
- );
- // Set pressed to false if the window loses focus
- useEventListener(window, "blur", () => setPressed(false));
- useEventListener(window, "mouseleave", () => setPressed(false));
+ // Sync cell status to the host <marimo-island> element as a data attribute
+ // so downstream consumers can style based on status (e.g. [data-status="running"])
+ const status = runtime?.status ?? "idle";
+ useSyncStatusToIsland(wrapperRef, status);
+ // If no runtime yet, show static content
if (!runtime?.output) {
- return <div className="relative min-h-6 empty:hidden">{children}</div>;
+ return (
+ <div ref={wrapperRef} className="relative min-h-6 empty:hidden">
+ {children}
+ </div>
+ );
}
// No output to display
- // Maybe in future, we can configure this to
- // fallback to displaying the code.
if (isOutputEmpty(runtime.output)) {
- return null;
+ return <div ref={wrapperRef} />;
}
return (
- <div className="relative min-h-6">
+ <div ref={wrapperRef} className="relative min-h-6">
<OutputRenderer message={runtime.output} />
- <Indicator state={runtime} />
- <div
- className="absolute top-0 right-0 z-50 flex items-center justify-center gap-1"
- style={{ display: pressed ? "flex" : "none" }}
- >
- <IconButton
- tooltip="Copy code"
- icon={<CopyIcon className="size-3" />}
- action={() => copyToClipboard(codeCallback())}
- />
- <IconButton
- tooltip="Re-run cell"
- icon={<PlayIcon className="size-3" />}
- action={async () => {
- await sendRun({
- cellIds: [cellId],
- codes: [codeCallback()],
- }).catch((error) => {
- Logger.error(error);
- });
- }}
- />
- </div>
+ <RunningIndicator state={runtime} />
+ <IslandControls
+ cellId={cellId}
+ codeCallback={codeCallback}
+ visible={controlsVisible}
+ />
</div>
);
};
-const Indicator: React.FC<{ state: CellRuntimeState }> = ({ state }) => {
+/**
+ * Sets `data-status` on the closest `<marimo-island>` ancestor whenever the
+ * cell's runtime status changes. This lets page authors style islands with
+ * CSS like `marimo-island[data-status="running"] { opacity: 0.5; }`.
+ */
+function useSyncStatusToIsland(
+ ref: React.RefObject<HTMLDivElement | null>,
+ status: string,
+) {
+ useEffect(() => {
+ const island = ref.current?.closest(ISLAND_TAG_NAMES.ISLAND);
+ island?.setAttribute("data-status", status);
+ }, [ref, status]);
+}
+
+/**
+ * Shows a spinning indicator when the cell is running
+ */
+const RunningIndicator: React.FC<{ state: CellRuntimeState }> = ({ state }) => {
if (state.status === "running") {
return (
<DelayRender>
@@ -148,7 +129,9 @@ const Indicator: React.FC<{ state: CellRuntimeState }> = ({ state }) => {
return null;
};
-// Render delay for children 200ms, using only css
+/**
+ * Delays rendering of children by 200ms using CSS animation
+ */
const DelayRender: React.FC<PropsWithChildren> = ({ children }) => {
return <div className="animate-delayed-show-200">{children}</div>;
};
diff --git a/frontend/src/core/islands/components/useIslandControls.ts b/frontend/src/core/islands/components/useIslandControls.ts
new file mode 100644
index 0000000000..be98f10f12
--- /dev/null
+++ b/frontend/src/core/islands/components/useIslandControls.ts
@@ -0,0 +1,60 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useState } from "react";
+import { useEventListener } from "@/hooks/useEventListener";
+
+/**
+ * Hook to manage the visibility of island controls based on keyboard state.
+ *
+ * Controls are shown when:
+ * - alwaysShowRun is true, OR
+ * - User holds Cmd/Ctrl key
+ *
+ * @param alwaysShowRun - If true, controls are always visible
+ * @returns Whether controls should be shown
+ */
+export function useIslandControls(alwaysShowRun: boolean): boolean {
+ const [pressed, setPressed] = useState<boolean>(alwaysShowRun);
+
+ // No need to register if display is always on
+ const maybeNoop = <T>(fn: (e: T) => void) =>
+ // oxlint-disable-next-line typescript/no-empty-function
+ alwaysShowRun ? () => {} : fn;
+
+ useEventListener(
+ document,
+ "keydown",
+ maybeNoop((e: KeyboardEvent) => {
+ if (!alwaysShowRun && (e.metaKey || e.ctrlKey)) {
+ setPressed(true);
+ }
+ }),
+ );
+
+ useEventListener(
+ document,
+ "keyup",
+ maybeNoop((e: KeyboardEvent) => {
+ if (
+ !alwaysShowRun &&
+ (e.metaKey || e.ctrlKey || e.key === "Meta" || e.key === "Control")
+ ) {
+ setPressed(false);
+ }
+ }),
+ );
+
+ // Set pressed to false if the window loses focus
+ useEventListener(
+ window,
+ "blur",
+ maybeNoop(() => setPressed(false)),
+ );
+ useEventListener(
+ window,
+ "mouseleave",
+ maybeNoop(() => setPressed(false)),
+ );
+
+ return pressed;
+}
diff --git a/frontend/src/core/islands/components/web-components.tsx b/frontend/src/core/islands/components/web-components.tsx
index e9b8e80eae..557b5e9002 100644
--- a/frontend/src/core/islands/components/web-components.tsx
+++ b/frontend/src/core/islands/components/web-components.tsx
@@ -11,73 +11,172 @@ import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";
import { LocaleProvider } from "@/core/i18n/locale-provider";
import { renderHTML } from "@/plugins/core/RenderHTML";
import { invariant } from "@/utils/invariant";
-import type { CellId } from "../../cells/ids";
+import type { CellId, UIElementId } from "../../cells/ids";
import { store } from "../../state/jotai";
+import {
+ ISLAND_CSS_CLASSES,
+ ISLAND_DATA_ATTRIBUTES,
+ ISLAND_TAG_NAMES,
+} from "../constants";
import { extractIslandCodeFromEmbed } from "../parse";
import { MarimoOutputWrapper } from "./output-wrapper";
/**
- * A custom element that renders the output of a marimo cell
+ * Configuration for rendering a marimo island
+ */
+export interface IslandRenderConfig {
+ html: string;
+ codeCallback: () => string;
+ editor: JSX.Element | null;
+ cellId: CellId | undefined;
+}
+
+/**
+ * A custom element that renders the output of a marimo cell.
+ *
+ * This web component wraps marimo cell outputs and provides interactive
+ * functionality like re-running cells and copying code.
*/
export class MarimoIslandElement extends HTMLElement {
private root?: Root;
- public static readonly tagName = "marimo-island";
- public static readonly outputTagName = "marimo-cell-output";
- public static readonly codeTagName = "marimo-cell-code";
- public static readonly editorTagName = "marimo-code-editor";
- public static readonly styleNamespace = "marimo";
+ public static readonly tagName = ISLAND_TAG_NAMES.ISLAND;
+ public static readonly outputTagName = ISLAND_TAG_NAMES.CELL_OUTPUT;
+ public static readonly codeTagName = ISLAND_TAG_NAMES.CELL_CODE;
+ public static readonly editorTagName = ISLAND_TAG_NAMES.CODE_EDITOR;
+ public static readonly styleNamespace = ISLAND_CSS_CLASSES.NAMESPACE;
constructor() {
super();
this.classList.add(MarimoIslandElement.styleNamespace);
}
+ /**
+ * Gets the app ID from the element's data attribute
+ */
get appId(): string {
- invariant(this.dataset.appId, "Missing data-app-id attribute");
- return this.dataset.appId;
+ const appId = this.getAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID);
+ invariant(appId, "Missing data-app-id attribute");
+ return appId;
+ }
+
+ /**
+ * Whether this island is reactive (has code sent to Python for execution)
+ */
+ get isReactive(): boolean {
+ return this.getAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE) === "true";
+ }
+
+ /**
+ * Gets the cell ID by looking up the cell index in the notebook state.
+ * Returns undefined for non-reactive islands (they have no corresponding cell).
+ */
+ get cellId(): CellId | undefined {
+ const cellId = this.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID);
+ if (cellId) {
+ return cellId as CellId;
+ }
+
+ const cellIdx = this.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX);
+ if (!cellIdx) {
+ return undefined;
+ }
+ return this.getCellIdFromIndex(Number.parseInt(cellIdx, 10));
}
- get cellId(): CellId {
- // Get the cell ID from the code
- invariant(this.dataset.cellIdx, "Missing data-cell-idx attribute");
+ /**
+ * Gets the code for this island cell
+ */
+ get code(): string {
+ return extractIslandCodeFromEmbed(this);
+ }
+
+ /**
+ * Looks up a cell ID from the notebook state by index
+ */
+ private getCellIdFromIndex(idx: number): CellId {
const { cellIds } = store.get(notebookAtom);
- const idx = Number.parseInt(this.dataset.cellIdx, 10);
const cellId = cellIds.inOrderIds.at(idx);
- invariant(cellId, "Missing cell ID");
+ invariant(cellId, `Missing cell ID at index ${idx}`);
return cellId;
}
- get code(): string {
- return extractIslandCodeFromEmbed(this);
+ /**
+ * Called when the element is added to the DOM.
+ *
+ * Deferred to a microtask because `defineCustomElement` during
+ * `kernel-ready` upgrades all existing elements synchronously,
+ * which can happen inside a React render cycle. Rendering
+ * synchronously from there causes "unmount during render" warnings.
+ */
+ connectedCallback(): void {
+ // Capture config synchronously (before children get cleared by createRoot)
+ const config = this.extractRenderConfig();
+ queueMicrotask(() => {
+ // Guard against disconnect between connectedCallback and microtask
+ if (!this.isConnected) {
+ return;
+ }
+ this.root = ReactDOM.createRoot(this);
+ this.renderIsland(config);
+ });
}
- connectedCallback() {
+ /**
+ * Extracts configuration needed for rendering
+ */
+ private extractRenderConfig(): IslandRenderConfig {
const output = this.querySelectorOrThrow(MarimoIslandElement.outputTagName);
const initialOutput = output.innerHTML;
-
const optionalEditor = this.getOptionalEditor();
const code = this.code;
- const codeCallback: () => string = optionalEditor
- ? () =>
- `${UI_ELEMENT_REGISTRY.lookupValue(
- optionalEditor.props[OBJECT_ID_ATTR],
- )}`
- : () => code;
-
- this.root = ReactDOM.createRoot(this);
- this.render(initialOutput, codeCallback, optionalEditor);
+ const cellId = this.cellId;
+
+ // Read objectId directly from the DOM before createRoot clears children.
+ // optionalEditor is a <RenderHTML> wrapper, so its .props don't carry the
+ // underlying element's attributes — we must grab objectId here instead.
+ const editorElement = this.querySelector(MarimoIslandElement.editorTagName);
+ const editorObjectId = (
+ editorElement?.parentElement as Element | null
+ )?.getAttribute(OBJECT_ID_ATTR) as UIElementId | null;
+
+ const codeCallback: () => string =
+ optionalEditor && editorObjectId
+ ? () => {
+ const val = UI_ELEMENT_REGISTRY.lookupValue(editorObjectId);
+ return val !== undefined ? String(val) : code;
+ }
+ : () => code;
+
+ return {
+ html: initialOutput,
+ codeCallback,
+ editor: optionalEditor,
+ cellId,
+ };
}
- private render(
- html: string,
- codeCallback: () => string,
- editor: JSX.Element | null,
- ) {
+ /**
+ * Renders the island with React
+ */
+ private renderIsland(config: IslandRenderConfig): void {
+ const { html, codeCallback, editor, cellId } = config;
const alwaysShowRun = !!editor;
- html = html.trim();
- const isEmpty = html === "<span></span>" || html === "";
- const initialHtml = isEmpty ? null : renderHTML({ html });
+ const trimmedHtml = html.trim();
+ const isEmpty = trimmedHtml === "<span></span>" || trimmedHtml === "";
+ const initialHtml = isEmpty ? null : renderHTML({ html: trimmedHtml });
+
+ // Non-reactive islands have no cell in the kernel — just render static HTML
+ if (!cellId) {
+ this.root?.render(
+ <ErrorBoundary>
+ <Provider store={store}>
+ <LocaleProvider>{initialHtml}</LocaleProvider>
+ </Provider>
+ </ErrorBoundary>,
+ );
+ return;
+ }
this.root?.render(
<ErrorBoundary>
@@ -85,7 +184,7 @@ export class MarimoIslandElement extends HTMLElement {
<LocaleProvider>
<TooltipProvider>
<MarimoOutputWrapper
- cellId={this.cellId}
+ cellId={cellId}
codeCallback={codeCallback}
alwaysShowRun={alwaysShowRun}
>
@@ -99,16 +198,30 @@ export class MarimoIslandElement extends HTMLElement {
);
}
+ /**
+ * Attempts to find and render an optional code editor.
+ *
+ * The DOM structure is:
+ * <marimo-cell-output>
+ * <div data-marimo-element> ← parent wrapper from Python render
+ * <marimo-code-editor .../>
+ * </div>
+ * </marimo-cell-output>
+ *
+ * We take the parent's outerHTML (the wrapper div) so that the rendered
+ * React element includes the UI element registration attributes.
+ *
+ * @returns A React element for the editor, or null if not found
+ */
private getOptionalEditor(): JSX.Element | null {
- // TODO: Maybe add specificity with a [editor=island] selector or something.
const optionalElement = this.querySelector(
MarimoIslandElement.editorTagName,
);
const html = (optionalElement?.parentNode as Element)?.outerHTML;
if (html) {
- // Push back to virtual dom.
+ // Convert HTML to virtual DOM
const virtualDom = renderHTML({ html });
- // and prove that it's an element.
+ // Verify it's a valid React element
if (isValidElement(virtualDom)) {
return virtualDom;
}
@@ -116,9 +229,24 @@ export class MarimoIslandElement extends HTMLElement {
return null;
}
- private querySelectorOrThrow(selector: string) {
+ /**
+ * Queries for an element and throws if not found
+ */
+ private querySelectorOrThrow(selector: string): Element {
const element = this.querySelector(selector);
invariant(element, `Missing ${selector} element`);
return element;
}
+
+ /**
+ * Cleanup when element is removed from DOM
+ */
+ disconnectedCallback(): void {
+ const root = this.root;
+ this.root = undefined;
+ // Defer unmount to avoid "unmount during render" race
+ if (root) {
+ queueMicrotask(() => root.unmount());
+ }
+ }
}
diff --git a/frontend/src/core/islands/constants.ts b/frontend/src/core/islands/constants.ts
new file mode 100644
index 0000000000..d163406f54
--- /dev/null
+++ b/frontend/src/core/islands/constants.ts
@@ -0,0 +1,28 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/**
+ * Custom element tag names for islands
+ */
+export const ISLAND_TAG_NAMES = {
+ ISLAND: "marimo-island",
+ CELL_OUTPUT: "marimo-cell-output",
+ CELL_CODE: "marimo-cell-code",
+ CODE_EDITOR: "marimo-code-editor",
+} as const;
+
+/**
+ * Data attributes for islands
+ */
+export const ISLAND_DATA_ATTRIBUTES = {
+ APP_ID: "data-app-id",
+ CELL_IDX: "data-cell-idx",
+ CELL_ID: "data-cell-id",
+ REACTIVE: "data-reactive",
+} as const;
+
+/**
+ * CSS classes for islands
+ */
+export const ISLAND_CSS_CLASSES = {
+ NAMESPACE: "marimo",
+} as const;
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index a3750bcf57..21dd168b8d 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -11,216 +11,18 @@ import "../../css/table.css";
import "iconify-icon";
-import { toast } from "@/components/ui/use-toast";
-import { renderHTML } from "@/plugins/core/RenderHTML";
-import {
- handleWidgetMessage,
- MODEL_MANAGER,
-} from "@/plugins/impl/anywidget/model";
-import { initializePlugins } from "@/plugins/plugins";
-import { logNever } from "@/utils/assertNever";
-import { Functions } from "@/utils/functions";
-import { safeExtractSetUIElementMessageBuffers } from "@/utils/json/base64";
-import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
import { Logger } from "@/utils/Logger";
-import {
- createNotebookActions,
- notebookAtom,
- notebookReducer,
-} from "../cells/cells";
-import { defineCustomElement } from "../dom/defineCustomElement";
-import { MarimoValueInputEvent } from "../dom/events";
-import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
-import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";
-import {
- handleCellNotificationeration,
- handleKernelReady,
- handleRemoveUIElements,
-} from "../kernel/handlers";
-import { queryParamHandlers } from "../kernel/queryParamHandlers";
-import { RuntimeState } from "../kernel/RuntimeState";
-import { initialModeAtom } from "../mode";
-import { requestClientAtom } from "../network/requests";
-import { store } from "../state/jotai";
-import { IslandsPyodideBridge } from "./bridge";
-import { MarimoIslandElement } from "./components/web-components";
-import {
- shouldShowIslandsWarningIndicatorAtom,
- userTriedToInteractWithIslandsAtom,
-} from "./state";
-import { dismissIslandsLoadingToast, toastIslandsLoading } from "./toast";
+import { initializeIslands } from "./bootstrap";
+import { getGlobalBridge } from "./bridge";
/**
* Main entry point for the js bundle for embedded marimo apps.
*/
-
-/**
- * Initialize the Marimo app.
- */
export async function initialize() {
- // Setup networking
- store.set(requestClientAtom, IslandsPyodideBridge.INSTANCE);
- store.set(initialModeAtom, "read");
-
- // This will display all the static HTML content.
- initializePlugins();
-
- // Find all `marimo-island` elements.
- const islands = document.querySelectorAll<HTMLElement>(
- MarimoIslandElement.tagName,
- );
-
- // If no islands are found, we can skip the rest of the initialization.
- if (islands.length === 0) {
- return;
- }
-
- // Add 'marimo' class name to all `marimo-island` elements.
- // This makes our styles apply to the islands.
- for (const island of islands) {
- island.classList.add(MarimoIslandElement.styleNamespace);
- }
-
- const actions = createNotebookActions((action) => {
- store.set(notebookAtom, (state) => notebookReducer(state, action));
- });
-
- // If the user has interacted with the islands before they are initialized,
- // we show the loading toast.
- store.sub(shouldShowIslandsWarningIndicatorAtom, () => {
- const showing = store.get(shouldShowIslandsWarningIndicatorAtom);
- if (showing) {
- toastIslandsLoading();
- // For each island, set the opacity to 0.5
- for (const island of islands) {
- island.style.setProperty("opacity", "0.5");
- }
- } else {
- dismissIslandsLoadingToast();
- // For each island, remove the opacity
- for (const island of islands) {
- island.style.removeProperty("opacity");
- }
- }
- });
-
- // Consume messages from the kernel
- IslandsPyodideBridge.INSTANCE.consumeMessages((message) => {
- const msg = jsonParseWithSpecialChar(message);
- switch (msg.data.op) {
- case "banner":
- case "missing-package-alert":
- case "installing-package-alert":
- case "completion-result":
- case "reload":
- case "focus-cell":
- case "variables":
- case "variable-values":
- case "data-column-preview":
- case "sql-table-preview":
- case "sql-table-list-preview":
- case "sql-schema-list-preview":
- case "datasets":
- case "data-source-connections":
- case "validate-sql-result":
- case "storage-namespaces":
- case "storage-entries":
- case "storage-download-ready":
- case "secret-keys-result":
- case "startup-logs":
- // Unsupported
- return;
- case "kernel-ready":
- handleKernelReady(msg.data, {
- autoInstantiate: true,
- setCells: actions.setCells,
- setLayoutData: Functions.NOOP,
- setAppConfig: Functions.NOOP,
- setCapabilities: Functions.NOOP,
- setKernelState: Functions.NOOP,
- onError: Logger.error,
- });
- // Define the custom element for the marimo-island tag.
- // This comes after initializing since this reads from the store.
- defineCustomElement(MarimoIslandElement.tagName, MarimoIslandElement);
- return;
- case "completed-run":
- return;
- case "interrupted":
- return;
- case "send-ui-element-message":
- UI_ELEMENT_REGISTRY.broadcastMessage(
- msg.data.ui_element,
- msg.data.message,
- safeExtractSetUIElementMessageBuffers(msg.data),
- );
- return;
-
- case "remove-ui-elements":
- handleRemoveUIElements(msg.data);
- return;
- case "function-call-result":
- FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);
- return;
- case "cell-op":
- handleCellNotificationeration(msg.data, actions.handleCellMessage);
- return;
- case "alert":
- // TODO: support toast with islands
- toast({
- title: msg.data.title,
- description: renderHTML({
- html: msg.data.description,
- }),
- variant: msg.data.variant,
- });
- return;
- case "query-params-append":
- queryParamHandlers.append(msg.data);
- return;
- case "query-params-set":
- queryParamHandlers.set(msg.data);
- return;
- case "query-params-delete":
- queryParamHandlers.delete(msg.data);
- return;
- case "query-params-clear":
- queryParamHandlers.clear();
- return;
- case "reconnected":
- return;
- case "cache-cleared":
- return;
- case "cache-info":
- return;
- case "kernel-startup-error":
- return;
- case "notebook-document-transaction":
- return;
- case "model-lifecycle":
- handleWidgetMessage(MODEL_MANAGER, msg.data);
- return;
- default:
- logNever(msg.data);
- }
- });
-
- // Set the user tried to interact with islands
- // before they are initialized.
- document.addEventListener(
- MarimoValueInputEvent.TYPE,
- () => {
- store.set(userTriedToInteractWithIslandsAtom, true);
- },
- {
- once: true,
- },
- );
-
- // Start the runtime
- RuntimeState.INSTANCE.start(
- IslandsPyodideBridge.INSTANCE.sendComponentValues,
- );
+ await initializeIslands({ bridge: getGlobalBridge() });
}
-initialize();
+// Auto-initialize on module load
+void initialize().catch((error) => {
+ Logger.error("Failed to initialize islands:", error);
+});
diff --git a/frontend/src/core/islands/parse.ts b/frontend/src/core/islands/parse.ts
index 5f59f531f5..2518e372d0 100644
--- a/frontend/src/core/islands/parse.ts
+++ b/frontend/src/core/islands/parse.ts
@@ -1,6 +1,9 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { MarimoIslandElement } from "@/core/islands/components/web-components";
+import {
+ ISLAND_DATA_ATTRIBUTES,
+ ISLAND_TAG_NAMES,
+} from "@/core/islands/constants";
import { Logger } from "@/utils/Logger";
/**
@@ -41,53 +44,94 @@ interface MarimoIslandCell {
idx: number;
}
-export function parseMarimoIslandApps(): MarimoIslandApp[] {
- const apps = new Map<string, MarimoIslandApp>();
-
- const embeds = document.querySelectorAll<HTMLElement>(
- MarimoIslandElement.tagName,
- );
+/**
+ * Parses marimo island apps from the DOM
+ * @param root - Root element to search within (defaults to document)
+ */
+export function parseMarimoIslandApps(
+ root: Document | Element = document,
+): MarimoIslandApp[] {
+ const embeds = root.querySelectorAll<HTMLElement>(ISLAND_TAG_NAMES.ISLAND);
if (embeds.length === 0) {
Logger.warn("No embedded marimo apps found.");
return [];
}
+ // eslint-disable-next-line prefer-spread
+ return parseIslandElementsIntoApps(Array.from(embeds));
+}
+
+/**
+ * Pure function to parse island elements into app structures
+ * @param embeds - Array of island HTML elements
+ */
+export function parseIslandElementsIntoApps(
+ embeds: HTMLElement[],
+): MarimoIslandApp[] {
+ const apps = new Map<string, MarimoIslandApp>();
+
for (const embed of embeds) {
- const id = embed.dataset.appId;
- if (!id) {
+ const appId = embed.getAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID);
+ if (!appId) {
Logger.warn("Embedded marimo cell missing data-app-id attribute.");
continue;
}
- const cellOutput = embed.querySelector<HTMLElement>(
- MarimoIslandElement.outputTagName,
- );
- const code = extractIslandCodeFromEmbed(embed);
+ // Non-reactive islands are static — they don't participate in the kernel
+ const reactive =
+ embed.getAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE) === "true";
+ if (!reactive) {
+ continue;
+ }
- if (!cellOutput || !code) {
- Logger.warn(`Embedded marimo app ${id} missing cell output or code.`);
+ const cellData = parseIslandElement(embed);
+ if (!cellData) {
+ Logger.warn(`Embedded marimo app ${appId} missing cell output or code.`);
continue;
}
- if (!apps.has(id)) {
- apps.set(id, { id, cells: [] });
+ if (!apps.has(appId)) {
+ apps.set(appId, { id: appId, cells: [] });
}
- // oxlint-disable-next-line typescript/no-non-null-assertion
- const app = apps.get(id)!;
+
+ const app = apps.get(appId)!;
const idx = app.cells.length;
app.cells.push({
- output: cellOutput.innerHTML,
- code: code,
+ output: cellData.output,
+ code: cellData.code,
idx: idx,
});
// Add data-cell-idx attribute to the island element
- embed.dataset.cellIdx = idx.toString();
+ embed.setAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX, idx.toString());
}
return [...apps.values()];
}
+/**
+ * Parses a single island element into cell data
+ * @param embed - The island HTML element
+ * @returns Cell data or null if invalid
+ */
+export function parseIslandElement(
+ embed: HTMLElement,
+): { output: string; code: string } | null {
+ const cellOutput = embed.querySelector<HTMLElement>(
+ ISLAND_TAG_NAMES.CELL_OUTPUT,
+ );
+ const code = extractIslandCodeFromEmbed(embed);
+
+ if (!cellOutput || !code) {
+ return null;
+ }
+
+ return {
+ output: cellOutput.innerHTML,
+ code: code,
+ };
+}
+
export function createMarimoFile(app: { cells: { code: string }[] }): string {
const lines = [
"import marimo",
@@ -134,7 +178,8 @@ export function parseIslandCode(code: string | undefined | null): string {
}
export function extractIslandCodeFromEmbed(embed: HTMLElement): string {
- const reactive = embed.dataset.reactive === "true";
+ const reactive =
+ embed.getAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE) === "true";
// Non-reactive cells are not guaranteed to have code, and should be treated as
// such.
if (!reactive) {
@@ -142,17 +187,19 @@ export function extractIslandCodeFromEmbed(embed: HTMLElement): string {
}
const cellCodeElement = embed.querySelector<HTMLElement>(
- MarimoIslandElement.codeTagName,
+ ISLAND_TAG_NAMES.CELL_CODE,
);
if (cellCodeElement) {
return parseIslandCode(cellCodeElement.textContent);
}
const editorCodeElement = embed.querySelector<HTMLElement>(
- MarimoIslandElement.editorTagName,
+ ISLAND_TAG_NAMES.CODE_EDITOR,
);
if (editorCodeElement) {
- return parseIslandEditor(editorCodeElement.dataset.initialValue);
+ return parseIslandEditor(
+ editorCodeElement.getAttribute("data-initial-value"),
+ );
}
return "";
diff --git a/frontend/src/core/islands/worker-factory.ts b/frontend/src/core/islands/worker-factory.ts
new file mode 100644
index 0000000000..08279f07e8
--- /dev/null
+++ b/frontend/src/core/islands/worker-factory.ts
@@ -0,0 +1,86 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { getMarimoVersion } from "../meta/globals";
+import workerUrl from "./worker/worker.tsx?worker&url";
+
+/**
+ * Interface for creating Web Workers for islands
+ */
+export interface WorkerFactory {
+ /**
+ * Creates a new worker instance
+ */
+ create(): Worker;
+}
+
+/**
+ * Configuration for the default worker factory
+ */
+export interface DefaultWorkerFactoryConfig {
+ /**
+ * The URL to the worker script
+ * Defaults to the bundled worker
+ */
+ workerUrl?: string;
+
+ /**
+ * The name to give the worker (shows in DevTools)
+ * Defaults to the marimo version
+ */
+ workerName?: string;
+}
+
+/**
+ * Default implementation of WorkerFactory that creates Pyodide workers
+ * for islands mode.
+ */
+export class DefaultWorkerFactory implements WorkerFactory {
+ private readonly url: string;
+ private readonly name: string;
+
+ constructor(config: DefaultWorkerFactoryConfig = {}) {
+ this.url = config.workerUrl || this.getDefaultWorkerUrl();
+ this.name = config.workerName || getMarimoVersion();
+ }
+
+ /**
+ * Creates a new Pyodide worker
+ */
+ create(): Worker {
+ const js = `import ${JSON.stringify(new URL(this.url, import.meta.url))}`;
+ const blob = new Blob([js], { type: "application/javascript" });
+ const objURL = URL.createObjectURL(blob);
+
+ const worker = new Worker(objURL, {
+ type: "module",
+ /* @vite-ignore */
+ name: this.name,
+ });
+
+ // Blob URL can be revoked once the worker has loaded the script
+ URL.revokeObjectURL(objURL);
+
+ return worker;
+ }
+
+ /**
+ * Gets the default worker URL based on environment
+ */
+ private getDefaultWorkerUrl(): string {
+ const url = import.meta.env.DEV
+ ? workerUrl
+ : makeRelativeWorkerUrl(workerUrl);
+ return url;
+ }
+}
+
+/**
+ * Makes worker URLs relative for production builds
+ */
+function makeRelativeWorkerUrl(url: string): string {
+ return url.startsWith("./")
+ ? url
+ : url.startsWith("/")
+ ? `.${url}`
+ : `./${url}`;
+}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 1f3d997c78..016404b272 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -68,6 +68,7 @@ import {
import { slotsController } from "@/core/slots/slots";
import { store } from "@/core/state/jotai";
import { isStaticNotebook } from "@/core/static/static-state";
+import { isIslands } from "@/core/islands/utils";
import { isInVscodeExtension } from "@/core/vscode/is-in-vscode";
import { useAsyncData } from "@/hooks/useAsyncData";
import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
@@ -1006,6 +1007,7 @@ const DataTableComponent = ({
const canShowColumnExplorer = showColumnExplorer && !!preview_column;
const isInVscode = isInVscodeExtension();
+ const isIslandsMode = isIslands();
return (
<>
@@ -1091,13 +1093,15 @@ const DataTableComponent = ({
onCellSelectionChange={handleCellSelectionChange}
getRowIds={get_row_ids}
toggleDisplayHeader={toggleDisplayHeader}
- showChartBuilder={showChartBuilder}
+ showChartBuilder={showChartBuilder && !isIslandsMode}
isChartBuilderOpen={isChartBuilderOpen}
showPageSizeSelector={showPageSizeSelector}
- // Hidden in VSCode (for now) because we don't have a panel to show
+ // Hidden in VSCode and islands because there's no panel to show
// the table explorer.
showTableExplorer={
- (showRowExplorer || canShowColumnExplorer) && !isInVscode
+ (showRowExplorer || canShowColumnExplorer) &&
+ !isInVscode &&
+ !isIslandsMode
}
togglePanel={togglePanel}
isPanelOpen={isPanelOpen}
diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.py
index 39bf46ed9d..acbacc17d3 100644
--- a/marimo/_islands/_island_generator.py
+++ b/marimo/_islands/_island_generator.py
@@ -411,10 +411,13 @@ class MarimoIslandGenerator:
base_url = _development_url
return dedent(
f"""
- <script
- type="module"
- src="{base_url}/src/core/islands/main.ts"
- ></script>
+ <script type="module" src="{base_url}/dist/main.js"></script>
+ <link
+ href="{base_url}/dist/style.css"
+ rel="stylesheet"
+ title="marimo-islands"
+ crossorigin="anonymous"
+ />
{fonts}
"""
).strip()
@@ -429,6 +432,7 @@ class MarimoIslandGenerator:
<link
href="{base_url}/dist/style.css"
rel="stylesheet"
+ title="marimo-islands"
crossorigin="anonymous"
/>
{fonts}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 635e7e86c2..691a61fa09 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -545,9 +545,9 @@ importers:
postcss:
specifier: ^8.5.6
version: 8.5.6
- postcss-plugin-namespace:
- specifier: ^0.0.3
- version: 0.0.3
+ postcss-prefix-selector:
+ specifier: ^2.1.1
+ version: 2.1.1([email protected])
react:
specifier: ^19.2.4
version: 19.2.4
@@ -7625,9 +7625,6 @@ packages:
resolution: {integrity: sha512-ESj2+eBxhGrcA1azgHs7lARG5+5iLakc/6nlfbpjcLl00HuuUOIuORhYXN4D1HfvMSKuVtFQjAlnwi1JHEeDIw==}
- resolution: {integrity: sha512-cMlDqaLEqfSaW8Z7N5Jw+lyIW869EzT73/F5lhtY9cLGoVxSXznfgfXMO0Z5K0o0Q2TkTXq+0KFsdnSe3jDViA==}
-
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -7856,8 +7853,10 @@ packages:
peerDependencies:
postcss: ^8.4.32
- resolution: {integrity: sha512-tDPJ7pF2ekL5OvdQXJgRIiAwV7148PEVQfSymIahO0DzyRruDCpgeJXrQXHdDVnNm/Qkip5FxNJUkUvUadrEew==}
+ resolution: {integrity: sha512-ZBgf427Et6+XnrnJ9VXtJEKCjJwTvn2wn/qMg+wvvlRhIeFIAxdbrlZZ0CSsWYMJfcyPLBh8ogj5O1kb/Mcx3g==}
+ peerDependencies:
+ postcss: ^8.0.0
resolution: {integrity: sha512-RHagHLidG8hTZcnr4FpyMB2jtgd/OcyAazjMhoy5qmWJOx1uxKh4ntk0Pb46ajKM0rkf32lRH4C8c9qQiPR6IA==}
@@ -7903,10 +7902,6 @@ packages:
resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}
- resolution: {integrity: sha512-yioayjNbHn6z1/Bywyb2Y4s3yvDAeXGOyxqD+LnVOinq6Mdmd++SW2wUNVzavyyHxd6+DxzWGIuosg6P1Rj8uA==}
- engines: {node: '>=6.0.0'}
-
resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
engines: {node: ^10 || ^12 || >=14}
@@ -18090,8 +18085,6 @@ snapshots:
-
@@ -18336,9 +18329,9 @@ snapshots:
postcss: 8.5.6
postcss-value-parser: 4.2.0
dependencies:
- postcss: 7.0.39
+ postcss: 8.5.6
dependencies:
@@ -18380,11 +18373,6 @@ snapshots:
- dependencies:
- picocolors: 0.2.1
- source-map: 0.6.1
-
dependencies:
nanoid: 3.3.11
diff --git a/tests/_islands/snapshots/header.txt b/tests/_islands/snapshots/header.txt
index 2b012b6c71..c15d2c9aa7 100644
--- a/tests/_islands/snapshots/header.txt
+++ b/tests/_islands/snapshots/header.txt
@@ -2,6 +2,7 @@
<link
href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"
rel="stylesheet"
+ title="marimo-islands"
crossorigin="anonymous"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
diff --git a/tests/_islands/snapshots/html.txt b/tests/_islands/snapshots/html.txt
index 33fd1e8801..3071707d42 100644
--- a/tests/_islands/snapshots/html.txt
+++ b/tests/_islands/snapshots/html.txt
@@ -7,6 +7,7 @@
<link
href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"
rel="stylesheet"
+ title="marimo-islands"
crossorigin="anonymous"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />