A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
[experimental] marimo islands (#1195)
Myles Scolnick1923ab01f376
diff --git a/.github/workflows/dev-release.yml b/.github/workflows/dev-release.ymlindex a670c8c831..dcb64b44f0 100644--- a/.github/workflows/dev-release.yml+++ b/.github/workflows/dev-release.yml@@ -85,7 +85,33 @@ jobs:echo "Updating package.json version to ${{ env.MARIMO_VERSION }}"npm version ${{ env.MARIMO_VERSION }} --no-git-tag-version- - name: 📤 Upload to npm+ - name: 📤 Upload wasm to npm+ working-directory: frontend+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}+ run: npm publish --access public++ - name: 📦 Update package.json name to @marimo-team/islands+ working-directory: frontend+ env:+ VITE_MARIMO_ISLANDS: "true"+ VITE_MARIMO_VERSION: ${{ env.NPM_TOKEN }}+ run: |+ echo "Updating package.json name to @marimo-team/islands"+ npm version ${{ env.MARIMO_VERSION }} --no-git-tag-version+ sed -i 's/"name": "@marimo-team\/frontend"/"name": "@marimo-team\/islands"/' package.json++ - name: 📦 Rebuild frontend+ working-directory: frontend+ env:+ VITE_MARIMO_ISLANDS: "true"+ VITE_MARIMO_VERSION: ${{ env.MARIMO_VERSION }}+ run: |+ pnpm turbo build:islands+ ./islands/validate.sh++ - name: 📤 Upload islands to npmworking-directory: frontendenv:NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yamlindex 13a115c2d2..79f0c846a9 100644--- a/.github/workflows/test.yaml+++ b/.github/workflows/test.yaml@@ -63,6 +63,15 @@ jobs:- name: 📦 Buildrun: pnpm turbo build+ - name: 📦 Build islands frontend+ env:+ VITE_MARIMO_ISLANDS: "true"+ VITE_MARIMO_VERSION: "0.0.0"+ run: |+ npm version 0.0.0 --no-git-tag-version+ pnpm turbo build:islands+ ./islands/validate.sh+test_python:name: Tests on ${{ matrix.os }}, Python ${{ matrix.python-version }} with ${{ matrix.dependencies }} dependenciesruns-on: ${{ matrix.os }}diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.cjssimilarity index 100%rename from frontend/.eslintrc.jsrename to frontend/.eslintrc.cjsdiff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsxindex 20a53b2c6e..8432060c2d 100644--- a/frontend/.storybook/preview.tsx+++ b/frontend/.storybook/preview.tsx@@ -1,6 +1,6 @@import type { Preview, Decorator } from "@storybook/react";import "../src/css/index.css";-import "../src/css/App.css";+import "../src/css/app/App.css";import "./sb.css";import "tailwindcss/tailwind.css";import React, { useEffect } from "react";diff --git a/frontend/.stylelintrc.js b/frontend/.stylelintrc.cjssimilarity index 100%rename from frontend/.stylelintrc.jsrename to frontend/.stylelintrc.cjsdiff --git a/frontend/e2e-tests/components.spec.ts b/frontend/e2e-tests/components.spec.tsindex add1c7b5a3..531b4447cc 100644--- a/frontend/e2e-tests/components.spec.ts+++ b/frontend/e2e-tests/components.spec.ts@@ -2,6 +2,9 @@import { test, expect, Page } from "@playwright/test";import { getAppUrl } from "../playwright.config";import { takeScreenshot } from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);const appUrl = getAppUrl("components.py");test.beforeEach(async ({ page }, info) => {diff --git a/frontend/e2e-tests/disabled.spec.ts b/frontend/e2e-tests/disabled.spec.tsindex 4c0338e68e..8154db6ddc 100644--- a/frontend/e2e-tests/disabled.spec.ts+++ b/frontend/e2e-tests/disabled.spec.ts@@ -2,6 +2,9 @@import { test, expect } from "@playwright/test";import { getAppUrl, resetFile } from "../playwright.config";import { takeScreenshot } from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);const appUrl = getAppUrl("cells.py");test.beforeEach(async ({ page }, info) => {diff --git a/frontend/e2e-tests/kitchen-sink.spec.ts b/frontend/e2e-tests/kitchen-sink.spec.tsindex 5ec54608da..916e8b05dc 100644--- a/frontend/e2e-tests/kitchen-sink.spec.ts+++ b/frontend/e2e-tests/kitchen-sink.spec.ts@@ -6,6 +6,9 @@ import {exportAsPNG,takeScreenshot,} from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);const appUrl = getAppUrl("kitchen_sink.py//edit");diff --git a/frontend/e2e-tests/layout-grid.spec.ts b/frontend/e2e-tests/layout-grid.spec.tsindex 443c57de71..8f939267aa 100644--- a/frontend/e2e-tests/layout-grid.spec.ts+++ b/frontend/e2e-tests/layout-grid.spec.ts@@ -2,6 +2,9 @@import { test, expect, Page } from "@playwright/test";import { getAppUrl } from "../playwright.config";import { takeScreenshot } from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);const runUrl = getAppUrl("layout_grid.py//run");const runMaxWidthUrl = getAppUrl("layout_grid_max_width.py//run");diff --git a/frontend/e2e-tests/mode.spec.ts b/frontend/e2e-tests/mode.spec.tsindex 841e32f952..a03c84158e 100644--- a/frontend/e2e-tests/mode.spec.ts+++ b/frontend/e2e-tests/mode.spec.ts@@ -2,6 +2,9 @@import { test, expect } from "@playwright/test";import { getAppUrl } from "../playwright.config";import { takeScreenshot } from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);test("page renders edit feature in edit mode", async ({ page }) => {const appUrl = getAppUrl("title.py");diff --git a/frontend/e2e-tests/output.spec.ts b/frontend/e2e-tests/output.spec.tsindex 0747f5ac97..cdba73bf0f 100644--- a/frontend/e2e-tests/output.spec.ts+++ b/frontend/e2e-tests/output.spec.ts@@ -2,6 +2,9 @@import { test, expect } from "@playwright/test";import { getAppUrl } from "../playwright.config";import { takeScreenshot } from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);test("it can clear and append output", async ({ page }) => {const appUrl = getAppUrl("output.py//run");diff --git a/frontend/e2e-tests/shutdown.spec.ts b/frontend/e2e-tests/shutdown.spec.tsindex a6cef26594..4076c1d683 100644--- a/frontend/e2e-tests/shutdown.spec.ts+++ b/frontend/e2e-tests/shutdown.spec.ts@@ -2,6 +2,9 @@import { test, expect } from "@playwright/test";import { getAppUrl, startServer } from "../playwright.config";import { takeScreenshot } from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);test("can resume a session", async ({ page }) => {const appUrl = getAppUrl("shutdown.py");diff --git a/frontend/islands/__demo__/index.html b/frontend/islands/__demo__/index.htmlnew file mode 100644index 0000000000..0ed22e6b27--- /dev/null+++ b/frontend/islands/__demo__/index.html@@ -0,0 +1,166 @@+<!doctype html>+<html lang="en">+ <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>my demo app</title>+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="" />+ <link+ href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap"+ rel="stylesheet"+ />+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"+ crossorigin="anonymous"+ />+ <script type="module" src="../src/core/islands/main.ts"></script>++ <style type="text/css">+ marimo-island {+ display: block;+ margin: 2rem;+ }+ </style>+ </head>+ <body>+ <marimo-island data-app-id="main" data-cell-id="Hbol">+ <marimo-cell-output> </marimo-cell-output>+ <marimo-cell-code hidden> import%20marimo%20as%20mo </marimo-cell-code>+ </marimo-island>+ <marimo-island data-app-id="main" data-cell-id="MJUe">+ <marimo-cell-output>+ <span class="markdown"+ ><span class="paragraph">Hello, islands!</span></span+ >+ </marimo-cell-output>+ <marimo-cell-code hidden> mo.md('Hello%2C%20islands!') </marimo-cell-code>+ </marimo-island>+ <marimo-island data-app-id="main" data-cell-id="vblA">+ <marimo-cell-output>+ <marimo-ui-element+ object-id="vblA-0"+ random-id="3fa4b908-82a9-40b2-af66-f7ba633f5f9e"+ >+ <marimo-slider+ data-initial-value="0"+ data-label="null"+ data-start="0"+ data-stop="100"+ data-step="2"+ data-debounce="false"+ data-orientation='"horizontal"'+ data-show-value="false"+ data-full-width="false"+ ></marimo-slider>+ </marimo-ui-element>+ </marimo-cell-output>+ <marimo-cell-code hidden>+ %0A%20%20%20%20slider%20%3D%20mo.ui.slider(0%2C%20100%2C%202)%0A%20%20%20%20slider%0A%20%20%20%20+ </marimo-cell-code>+ </marimo-island>+ <marimo-island data-app-id="main" data-cell-id="bkHC">+ <marimo-cell-output>+ <span class="markdown">+ <span class="paragraph">+ Slider value: <span class="code">0</span>+ </span>+ </span>+ </marimo-cell-output>+ <marimo-cell-code hidden>+ %0A%20%20%20%20mo.md(f%22Slider%20value%3A%20%7Bslider.value%7D%22)%0A%20%20%20%20+ </marimo-cell-code>+ </marimo-island>+ <marimo-island data-app-id="main" data-cell-id="lEQa">+ <marimo-cell-output>+ <span class="markdown">+ <h1 id="hello-markdown">Hello, Markdown!</h1>+ <span class="paragraph"+ >Use marimo's "<code>md</code>" function to embed rich text into+ your marimo apps. This function compiles Markdown into HTML that+ marimo can display.</span+ >+ <span class="paragraph"+ >For example, here's the code that rendered the above title and+ paragraph:</span+ >+ <div class="codehilite">+ <pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span>+<span class="w"> </span><span class="sd">'''</span>+<span class="sd"> # Hello, Markdown!</span>+<span class="sd"> Use marimo's "`md`" function to embed rich text into your marimo</span>+<span class="sd"> apps. This function compiles your Markdown into HTML that marimo</span>+<span class="sd"> can display.</span>+<span class="sd"> '''</span>+<span class="p">)</span>+</code></pre>+ </div>+ </span>+ </marimo-cell-output>+ <marimo-cell-code hidden>+ %0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20%22%22%22%0A%20%20%20%20%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20%20%20%20%20Use%20marimo's%20%22%60md%60%22%20function%20to%20embed%20rich%20text%20into%20your%20marimo%0A%20%20%20%20%20%20%20%20apps.%20This%20function%20compiles%20Markdown%20into%20HTML%20that%20marimo%0A%20%20%20%20%20%20%20%20can%20display.%0A%0A%20%20%20%20%20%20%20%20For%20example%2C%20here's%20the%20code%20that%20rendered%20the%20above%20title%20and%0A%20%20%20%20%20%20%20%20paragraph%3A%0A%0A%20%20%20%20%20%20%20%20%60%60%60python3%0A%20%20%20%20%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20%20%20%20%20'''%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20Use%20marimo's%20%22%60md%60%22%20function%20to%20embed%20rich%20text%20into%20your%20marimo%0A%20%20%20%20%20%20%20%20%20%20%20%20apps.%20This%20function%20compiles%20your%20Markdown%20into%20HTML%20that%20marimo%0A%20%20%20%20%20%20%20%20%20%20%20%20can%20display.%0A%20%20%20%20%20%20%20%20%20%20%20%20'''%0A%20%20%20%20%20%20%20%20)%0A%20%20%20%20%20%20%20%20%60%60%60%0A%20%20%20%20%20%20%20%20%22%22%22%0A%20%20%20%20)%0A%20%20%20%20+ </marimo-cell-code>+ </marimo-island>+ <marimo-island data-app-id="main" data-cell-id="PKri">+ <marimo-cell-output>+ <span class="markdown">+ <h2 id="latex">LaTeX</h2>+ <span class="paragraph">You can embed LaTeX in Markdown.</span>+ <span class="paragraph">For example,</span>+ <div class="codehilite">+ <pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span><span class="sa">r</span><span class="s1">'$f : \mathbf</span><span class="si">{R}</span><span class="s1"> o \mathbf</span><span class="si">{R}</span><span class="s1">$'</span><span class="p">)</span>+</code></pre>+ </div>+ <span class="paragraph">+ renders+ <marimo-tex class="arithmatex"+ >||(f : \mathbf{R} o \mathbf{R}||)</marimo-tex+ >+ , while+ </span>+ <div class="codehilite">+ <pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span>+<span class="w"> </span><span class="sa">r</span><span class="sd">'''</span>+<span class="sd"> \[</span>+<span class="sd"> f: \mathbf{R} o \mathbf{R}</span>+<span class="sd"> \]</span>+<span class="sd"> '''</span>+<span class="p">)</span>+</code></pre>+ </div>+ <span class="paragraph">renders the display math</span>+ <marimo-tex class="arithmatex"+ >||[ f: \mathbf{R} o \mathbf{R}. ||]</marimo-tex+ >+ </span>+ </marimo-cell-output>+ <marimo-cell-code hidden>+ %0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20r%22%22%22%0A%20%20%20%20%20%20%20%20%23%23%20LaTeX%0A%20%20%20%20%20%20%20%20You%20can%20embed%20LaTeX%20in%20Markdown.%0A%0A%20%20%20%20%20%20%20%20For%20example%2C%0A%0A%20%20%20%20%20%20%20%20%60%60%60python3%0A%20%20%20%20%20%20%20%20mo.md(r'%24f%20%3A%20%5Cmathbf%7BR%7D%20%09o%20%5Cmathbf%7BR%7D%24')%0A%20%20%20%20%20%20%20%20%60%60%60%0A%0A%20%20%20%20%20%20%20%20renders%20%24f%20%3A%20%5Cmathbf%7BR%7D%20%09o%20%5Cmathbf%7BR%7D%24%2C%20while%0A%0A%20%20%20%20%20%20%20%20%60%60%60python3%0A%20%20%20%20%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20%20%20%20%20r'''%0A%20%20%20%20%20%20%20%20%20%20%20%20%5C%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20f%3A%20%5Cmathbf%7BR%7D%20%09o%20%5Cmathbf%7BR%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20%5C%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20'''%0A%20%20%20%20%20%20%20%20)%0A%20%20%20%20%20%20%20%20%60%60%60%0A%0A%20%20%20%20%20%20%20%20renders%20the%20display%20math%0A%0A%20%20%20%20%20%20%20%20%5C%5B%0A%20%20%20%20%20%20%20%20f%3A%20%5Cmathbf%7BR%7D%20%09o%20%5Cmathbf%7BR%7D.%0A%20%20%20%20%20%20%20%20%5C%5D%0A%20%20%20%20%20%20%20%20%22%22%22%0A%20%20%20%20)%0A%20%20%20%20+ </marimo-cell-code>+ </marimo-island>+ <br />+ <br />+ <br />+ <br />+ <hr />+ <div class="bg-blue-500 p-4 border-2 border-red-500 bg-background">+ this should not be affected by global tailwind styles+ </div>+ <div class="marimo">+ <div class="bg-background p-4 border-2 border-red-500 text-foreground">+ this should be affected by global tailwind styles+ </div>+ </div>+ <div class="marimo">+ <div class="dark">+ <div class="bg-background p-4 border-2 border-red-500 text-foreground">+ this should be affected by global tailwind styles (dark)+ </div>+ </div>+ </div>+ </body>+</html>diff --git a/frontend/islands/development.md b/frontend/islands/development.mdnew file mode 100644index 0000000000..a26050ff16--- /dev/null+++ b/frontend/islands/development.md@@ -0,0 +1,20 @@+# Marimo Islands++marimo islands are a way to render HTML "islands" each with static outputs and code. This differs from the normal "app mode" int that there is no top-level app. In "island mode", we do not have access to the HTML of the parent page.++## Development++**Islands demo page**++```bash+pnpm dev:islands+```++**Generate an HTML page with islands**++```bash+# Generate+python3 ./islands/generate.py > islands/__demo__/index.html+# Run the Vite server+pnpm dev:islands+```diff --git a/frontend/islands/generate.py b/frontend/islands/generate.pynew file mode 100644index 0000000000..918e4f9253--- /dev/null+++ b/frontend/islands/generate.py@@ -0,0 +1,130 @@+import asyncio+from textwrap import dedent+import marimo++generator = marimo.experimental_MarimoIslandGenerator()++stubs = [+ generator.add_code("import marimo as mo"),+ generator.add_code("mo.md('Hello, islands!')"),+ generator.add_code(+ """+ slider = mo.ui.slider(0, 100, 2)+ slider+ """+ ),+ generator.add_code(+ """+ mo.md(f"Slider value: {slider.value}")+ """+ ),+ generator.add_code(+ """+ mo.md(+ \"\"\"+ # Hello, Markdown!++ Use marimo's "`md`" function to embed rich text into your marimo+ apps. This function compiles Markdown into HTML that marimo+ can display.++ For example, here's the code that rendered the above title and+ paragraph:++ ```python3+ mo.md(+ '''+ # Hello, Markdown!++ Use marimo's "`md`" function to embed rich text into your marimo+ apps. This function compiles your Markdown into HTML that marimo+ can display.+ '''+ )+ ```+ \"\"\"+ )+ """+ ),+ generator.add_code(+ """+ mo.md(+ r\"\"\"+ ## LaTeX+ You can embed LaTeX in Markdown.++ For example,++ ```python3+ mo.md(r'$f : \mathbf{R} \to \mathbf{R}$')+ ```++ renders $f : \mathbf{R} \to \mathbf{R}$, while++ ```python3+ mo.md(+ r'''+ \[+ f: \mathbf{R} \to \mathbf{R}+ \]+ '''+ )+ ```++ renders the display math++ \[+ f: \mathbf{R} \to \mathbf{R}.+ \]+ \"\"\"+ )+ """+ ),+]++app = asyncio.run(generator.build())++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(_development_url=True)}+ </head>+ <body>++{dedent(NEW_LINE.join([stub.render() for stub in stubs]))}+++ <br />+ <br />+ <br />+ <br />+ <hr />+ <div class="bg-blue-500 p-4 border-2 border-red-500 bg-background">+ this should not be affected by global tailwind styles+ </div>+ <div class="marimo">+ <div class="bg-background p-4 border-2 border-red-500 text-foreground">+ this should be affected by global tailwind styles+ </div>+ </div>+ <div class="marimo">+ <div class="dark">+ <div class="bg-background p-4 border-2 border-red-500 text-foreground">+ this should be affected by global tailwind styles (dark)+ </div>+ </div>+ </div>++ </body>+</html>+"""++print(output)diff --git a/frontend/islands/validate.sh b/frontend/islands/validate.shnew file mode 100755index 0000000000..943bece381--- /dev/null+++ b/frontend/islands/validate.sh@@ -0,0 +1,31 @@+#!/bin/sh++# Validate+# - no process.env variables in any of the js files+# - version does not equal 0.0.0-placeholder+# - files dist/main.js and dist/style.css exist++OUT_DIR=$(pwd)/dist+echo "validating $OUT_DIR"++echo "[validate: no process.env variables in any of the js files]"+grep -R "process.env" $(pwd)/dist+if [ $? -eq 0 ]; then+ echo "process.env variables found in js files"+ exit 1+fi++echo "[validate: version does not equal 0.0.0-placeholder]"+grep -R "0.0.0-placeholder" $(pwd)/dist+if [ $? -eq 0 ]; then+ echo "version is 0.0.0-placeholder"+ exit 1+fi++echo "[validate: files dist/main.js and dist/style.css exist]"+if [ ! -f "$OUT_DIR/main.js" ] || [ ! -f "$OUT_DIR/style.css" ]; then+ echo "dist/main.js or dist/style.css does not exist"+ exit 1+fi++echo "validation passed"diff --git a/frontend/islands/vite.config.mts b/frontend/islands/vite.config.mtsnew file mode 100644index 0000000000..d57117758f--- /dev/null+++ b/frontend/islands/vite.config.mts@@ -0,0 +1,56 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Plugin, defineConfig } from "vite";+import fs from "fs";+import path from "path";+import react from "@vitejs/plugin-react-swc";+import tsconfigPaths from "vite-tsconfig-paths";+import packageJson from "../package.json";++const htmlDevPlugin = (): Plugin => {+ return {+ apply: "serve",+ name: "html-transform",+ transformIndexHtml: async () => {+ const indexHtml = await fs.promises.readFile(+ path.resolve(__dirname, "__demo__", "index.html"),+ "utf-8",+ );++ return "<!DOCTYPE html>\n" + indexHtml;+ },+ };+};++// https://vitejs.dev/config/+export default defineConfig({+ resolve: {+ dedupe: ["react", "react-dom", "@emotion/react", "@emotion/cache"],+ },+ worker: {+ plugins: () => [tsconfigPaths()],+ },+ define: {+ "process.env": {+ NODE_ENV: JSON.stringify(process.env.NODE_ENV),+ },+ "import.meta.env.VITE_MARIMO_ISLANDS": JSON.stringify(true),+ "import.meta.env.VITE_MARIMO_VERSION":+ process.env.NODE_ENV === "production"+ ? JSON.stringify(packageJson.version)+ : JSON.stringify("latest"),+ },+ plugins: [htmlDevPlugin(), react({ tsDecorators: true }), tsconfigPaths()],+ build: {+ emptyOutDir: true,+ lib: {+ entry: path.resolve(__dirname, "../src/core/islands/main.ts"),+ formats: ["es"],+ },+ rollupOptions: {+ output: {+ // Remove hash from entry file name, so it's easier to import+ entryFileNames: "[name].js",+ },+ },+ },+});diff --git a/frontend/package.json b/frontend/package.jsonindex 348b98af0a..d95bc3c018 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -1,8 +1,9 @@{"name": "@marimo-team/frontend","version": "0.0.0-placeholder",- "main": "lib/marimo.js",- "types": "lib/index.d.ts",+ "main": "dist/main.js",+ "types": "dist/index.d.ts",+ "type": "module","license": "Apache-2.0","sideEffects": ["*.css",@@ -144,6 +145,8 @@"lint:prettier:fix": "prettier --write src/ e2e-tests/","format": "prettier --write src/ e2e-tests/","preview": "vite preview",+ "dev:islands": "VITE_MARIMO_ISLANDS=true vite --config islands/vite.config.mts",+ "build:islands": "VITE_MARIMO_ISLANDS=true vite --config islands/vite.config.mts build","storybook": "storybook dev -p 6006","build-storybook": "storybook build"},@@ -185,6 +188,7 @@"jsdom": "^24.0.0","npm-run-all2": "^6.1.2","postcss": "^8.4.35",+ "postcss-plugin-namespace": "^0.0.3","prettier": "^3.2.5","react": "^18.2.0","react-dom": "^18.2.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 6b447dc02e..ed0b4da7ba 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -442,6 +442,9 @@ devDependencies:postcss:specifier: ^8.4.35version: 8.4.38+ postcss-plugin-namespace:+ specifier: ^0.0.3+ version: 0.0.3prettier:specifier: ^3.2.5version: 3.2.5@@ -14896,6 +14899,10 @@ packages:resolution: {integrity: sha512-ESj2+eBxhGrcA1azgHs7lARG5+5iLakc/6nlfbpjcLl00HuuUOIuORhYXN4D1HfvMSKuVtFQjAlnwi1JHEeDIw==}dev: false+ resolution: {integrity: sha512-cMlDqaLEqfSaW8Z7N5Jw+lyIW869EzT73/F5lhtY9cLGoVxSXznfgfXMO0Z5K0o0Q2TkTXq+0KFsdnSe3jDViA==}+ dev: true+resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==}@@ -15400,6 +15407,12 @@ packages:postcss-value-parser: 4.2.0dev: false+ resolution: {integrity: sha512-tDPJ7pF2ekL5OvdQXJgRIiAwV7148PEVQfSymIahO0DzyRruDCpgeJXrQXHdDVnNm/Qkip5FxNJUkUvUadrEew==}+ dependencies:+ postcss: 7.0.39+ dev: true+resolution: {integrity: sha512-YGKalhNlCLcjcLvjU5nF8FyeCTkCO5UtvJEt0hrPZVCTtRLSOH4z00T1UntQPj4dUmIYZgMj8qK77JbSX95hSw==}engines: {node: ^14 || ^16 || >=18.0}@@ -15465,6 +15478,14 @@ packages:resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}+ resolution: {integrity: sha512-yioayjNbHn6z1/Bywyb2Y4s3yvDAeXGOyxqD+LnVOinq6Mdmd++SW2wUNVzavyyHxd6+DxzWGIuosg6P1Rj8uA==}+ engines: {node: '>=6.0.0'}+ dependencies:+ picocolors: 0.2.1+ source-map: 0.6.1+ dev: true+resolution: {integrity: sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A==}engines: {node: ^10 || ^12 || >=14}diff --git a/frontend/postcss.config.cjs b/frontend/postcss.config.cjsnew file mode 100644index 0000000000..0b5c3217fa--- /dev/null+++ b/frontend/postcss.config.cjs@@ -0,0 +1,16 @@+/* Copyright 2024 Marimo. All rights reserved. */+const config = {+ plugins: [+ require("tailwindcss/nesting"),+ require("tailwindcss"),+ process.env.VITE_MARIMO_ISLANDS === "true"+ ? require("postcss-plugin-namespace")(".marimo", {+ ignore: [".marimo", "html", "body"],+ })+ : undefined,+ process.env.NODE_ENV === "production" ? require("cssnano") : undefined,+ require("autoprefixer"),+ ],+};++module.exports = config;diff --git a/frontend/postcss.config.js b/frontend/postcss.config.jsdeleted file mode 100644index 9ccc3652cf..0000000000--- a/frontend/postcss.config.js+++ /dev/null@@ -1,9 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-module.exports = {- plugins: {- "tailwindcss/nesting": {},- tailwindcss: {},- ...(process.env.NODE_ENV === "production" ? { cssnano: {} } : {}),- autoprefixer: {},- },-};diff --git a/frontend/src/components/editor/chrome/state.ts b/frontend/src/components/editor/chrome/state.tsindex f1f9b754a5..19ad82157f 100644--- a/frontend/src/components/editor/chrome/state.ts+++ b/frontend/src/components/editor/chrome/state.ts@@ -1,7 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import { createReducer } from "@/utils/createReducer";-import { atom, useAtomValue, useSetAtom } from "jotai";-import { useMemo } from "react";+import { createReducerAndAtoms } from "@/utils/createReducer";+import { useAtomValue } from "jotai";import { PanelType } from "./types";export interface ChromeState {@@ -18,7 +17,12 @@ function initialState(): ChromeState {};}-const { reducer, createActions } = createReducer(initialState, {+const {+ reducer,+ createActions,+ valueAtom: chromeAtom,+ useActions,+} = createReducerAndAtoms(initialState, {openApplication: (state, selectedPanel: PanelType) => ({...state,selectedPanel,@@ -36,7 +40,6 @@ const { reducer, createActions } = createReducer(initialState, {}),});-const chromeAtom = atom<ChromeState>(initialState());export const useChromeState = () => {const state = useAtomValue(chromeAtom);if (state.isOpen) {@@ -49,14 +52,7 @@ export const useChromeState = () => {};export function useChromeActions() {- const setState = useSetAtom(chromeAtom);-- return useMemo(() => {- const actions = createActions((action) => {- setState((state) => reducer(state, action));- });- return actions;- }, [setState]);+ return useActions();}/**diff --git a/frontend/src/components/editor/file-tree/upload.tsx b/frontend/src/components/editor/file-tree/upload.tsxindex 305a5eb930..6cee2eff08 100644--- a/frontend/src/components/editor/file-tree/upload.tsx+++ b/frontend/src/components/editor/file-tree/upload.tsx@@ -5,6 +5,7 @@ import { FilePath } from "@/utils/paths";import { serializeBlob } from "@/utils/blob";import { DropzoneOptions, useDropzone } from "react-dropzone";import { refreshRoot } from "./state";+import { Logger } from "@/utils/Logger";const MAX_SIZE = 1024 * 1024 * 50; // 50MB@@ -13,7 +14,7 @@ export function useFileExplorerUpload(options: DropzoneOptions = {}) {multiple: true,maxSize: MAX_SIZE,onError: (error) => {- console.error(error);+ Logger.error(error);toast({title: "File upload failed",description: error.message,diff --git a/frontend/src/components/ui/popover.tsx b/frontend/src/components/ui/popover.tsxindex e4fab4f348..31264c670d 100644--- a/frontend/src/components/ui/popover.tsx+++ b/frontend/src/components/ui/popover.tsx@@ -3,6 +3,7 @@ import * as React from "react";import * as PopoverPrimitive from "@radix-ui/react-popover";import { cn } from "@/utils/cn";+import { StyleNamespace } from "@/theme/namespace";const Popover = PopoverPrimitive.Root;@@ -19,16 +20,18 @@ const PopoverContent = React.forwardRef<ref,) => {const content = (- <PopoverPrimitive.Content- ref={ref}- align={align}- sideOffset={sideOffset}- className={cn(- "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",- className,- )}- {...props}- />+ <StyleNamespace>+ <PopoverPrimitive.Content+ ref={ref}+ align={align}+ sideOffset={sideOffset}+ className={cn(+ "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className,+ )}+ {...props}+ />+ </StyleNamespace>);if (portal) {return <PopoverPrimitive.Portal>{content}</PopoverPrimitive.Portal>;diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsxindex 0bf58504f9..b59cd17764 100644--- a/frontend/src/components/ui/tooltip.tsx+++ b/frontend/src/components/ui/tooltip.tsx@@ -3,6 +3,7 @@ import * as React from "react";import * as TooltipPrimitive from "@radix-ui/react-tooltip";import { cn } from "@/utils/cn";+import { StyleNamespace } from "@/theme/namespace";const TooltipProvider = TooltipPrimitive.Provider;@@ -14,15 +15,17 @@ const TooltipContent = React.forwardRef<React.ElementRef<typeof TooltipPrimitive.Content>,React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>>(({ className, sideOffset = 4, ...props }, ref) => (- <TooltipPrimitive.Content- ref={ref}- sideOffset={sideOffset}- className={cn(- "z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-xs data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1",- className,- )}- {...props}- />+ <StyleNamespace>+ <TooltipPrimitive.Content+ ref={ref}+ sideOffset={sideOffset}+ className={cn(+ "z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-xs data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1",+ className,+ )}+ {...props}+ />+ </StyleNamespace>));TooltipContent.displayName = TooltipPrimitive.Content.displayName;diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsxindex 58f7c466b4..55fefbfe70 100644--- a/frontend/src/core/App.tsx+++ b/frontend/src/core/App.tsx@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import "../css/App.css";+import "../css/app/App.css";import { HourglassIcon, UnlinkIcon } from "lucide-react";import { useCallback, useEffect, useState } from "react";diff --git a/frontend/src/core/alerts/state.ts b/frontend/src/core/alerts/state.tsindex 385778c450..8aa4025a8a 100644--- a/frontend/src/core/alerts/state.ts+++ b/frontend/src/core/alerts/state.ts@@ -1,10 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */import { PackageInstallationStatus } from "@/core/kernel/messages";-import { createReducer } from "@/utils/createReducer";+import { createReducerAndAtoms } from "@/utils/createReducer";import { generateUUID } from "@/utils/uuid";-import { atom, useAtomValue, useSetAtom } from "jotai";-import { useMemo } from "react";+import { useAtomValue } from "jotai";type Identified<T> = { id: string } & T;@@ -42,7 +41,7 @@ interface AlertState {| null;}-const { reducer, createActions } = createReducer(+const { valueAtom: alertAtom, useActions } = createReducerAndAtoms(() => ({ packageAlert: null }) as AlertState,{addPackageAlert: (@@ -63,10 +62,6 @@ const { reducer, createActions } = createReducer(},);-const alertAtom = atom<AlertState>({- packageAlert: null,-});-/*** React hook to get the Alert state.*/@@ -76,11 +71,5 @@ export const useAlerts = () => useAtomValue(alertAtom);* React hook to get the Alerts actions.*/export function useAlertActions() {- const setState = useSetAtom(alertAtom);- return useMemo(() => {- const actions = createActions((action) => {- setState((state) => reducer(state, action));- });- return actions;- }, [setState]);+ return useActions();}diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex fe7546c9d5..12ffc1166b 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -273,15 +273,12 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(10).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(10).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("queued");@@ -293,15 +290,12 @@ describe("cell reducer", () => {// Receive running messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "running",- stale_inputs: null,- timestamp: new Date(20).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "running",+ stale_inputs: null,+ timestamp: new Date(20).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("running");@@ -313,20 +307,17 @@ describe("cell reducer", () => {// Console messages shouldn't transition statusactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: {- channel: "stdout",- mimetype: "text/plain",- data: "hello!",- timestamp: 0,- },- status: null,- stale_inputs: null,- timestamp: new Date(22).getTime() as Seconds,+ cell_id: firstCellId,+ output: null,+ console: {+ channel: "stdout",+ mimetype: "text/plain",+ data: "hello!",+ timestamp: 0,},+ status: null,+ stale_inputs: null,+ timestamp: new Date(22).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("running");@@ -337,25 +328,22 @@ describe("cell reducer", () => {// Receive output messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: {- channel: "output",- mimetype: "text/plain",- data: "ok",- timestamp: 0,- },- console: {- channel: "stdout",- mimetype: "text/plain",- data: "hello!",- timestamp: 0,- },- status: "idle",- stale_inputs: null,- timestamp: new Date(33).getTime() as Seconds,+ cell_id: firstCellId,+ output: {+ channel: "output",+ mimetype: "text/plain",+ data: "ok",+ timestamp: 0,},+ console: {+ channel: "stdout",+ mimetype: "text/plain",+ data: "hello!",+ timestamp: 0,+ },+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(33).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("idle");@@ -409,50 +397,41 @@ describe("cell reducer", () => {expect(cell.output).not.toBe(null); // keep old output// Queueactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(40).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(40).getTime() as Seconds,});cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Runningactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "running",- stale_inputs: null,- timestamp: new Date(50).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "running",+ stale_inputs: null,+ timestamp: new Date(50).getTime() as Seconds,});cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Receive erroractions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: {- channel: "marimo-error",- mimetype: "application/vnd.marimo+error",- data: [- { type: "exception", exception_type: "ValueError", msg: "Oh no!" },- ],- timestamp: 0,- },- console: null,- status: "idle",- stale_inputs: null,- timestamp: new Date(61).getTime() as Seconds,+ cell_id: firstCellId,+ output: {+ channel: "marimo-error",+ mimetype: "application/vnd.marimo+error",+ data: [+ { type: "exception", exception_type: "ValueError", msg: "Oh no!" },+ ],+ timestamp: 0,},+ console: null,+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(61).getTime() as Seconds,});cell = cells[0];expect(cell.output).not.toBe(null); // keep old output@@ -473,48 +452,39 @@ describe("cell reducer", () => {expect(cell.output).not.toBe(null); // keep old output// Queueactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(40).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(40).getTime() as Seconds,});cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Runningactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "running",- stale_inputs: null,- timestamp: new Date(50).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "running",+ stale_inputs: null,+ timestamp: new Date(50).getTime() as Seconds,});cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Receive erroractions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: {- channel: "marimo-error",- mimetype: "application/vnd.marimo+error",- data: [{ type: "interruption" }],- timestamp: 0,- },- console: null,- status: "idle",- stale_inputs: null,- timestamp: new Date(61).getTime() as Seconds,+ cell_id: firstCellId,+ output: {+ channel: "marimo-error",+ mimetype: "application/vnd.marimo+error",+ data: [{ type: "interruption" }],+ timestamp: 0,},+ console: null,+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(61).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("idle");@@ -552,15 +522,12 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({- cellId: secondCell,- message: {- cell_id: secondCell,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(10).getTime() as Seconds,- },+ cell_id: secondCell,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(10).getTime() as Seconds,});let cell = cells[1];expect(cell.status).toBe("queued");@@ -572,15 +539,12 @@ describe("cell reducer", () => {// Receive stale messageactions.handleCellMessage({- cellId: secondCell,- message: {- cell_id: secondCell,- output: null,- console: null,- status: null,- stale_inputs: true,- timestamp: new Date(20).getTime() as Seconds,- },+ cell_id: secondCell,+ output: null,+ console: null,+ status: null,+ stale_inputs: true,+ timestamp: new Date(20).getTime() as Seconds,});cell = cells[1];expect(cell.status).toBe("queued");@@ -608,25 +572,22 @@ describe("cell reducer", () => {cellId: firstCellId,});actions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: {- channel: "output",- mimetype: "text/plain",- data: "ok",- timestamp: 0,- },- console: {- channel: "stdout",- mimetype: "text/plain",- data: "hello!",- timestamp: 0,- },- status: "idle",- stale_inputs: null,- timestamp: new Date(33).getTime() as Seconds,+ cell_id: firstCellId,+ output: {+ channel: "output",+ mimetype: "text/plain",+ data: "ok",+ timestamp: 0,+ },+ console: {+ channel: "stdout",+ mimetype: "text/plain",+ data: "hello!",+ timestamp: 0,},+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(33).getTime() as Seconds,});// Check steady state@@ -684,15 +645,12 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(10).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(10).getTime() as Seconds,});let cell = cells[0];expect(cell.status).toBe("queued");@@ -706,41 +664,35 @@ describe("cell reducer", () => {// Receive idle messageactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "idle",- stale_inputs: null,- timestamp: new Date(20).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(20).getTime() as Seconds,});cell = cells[0];expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Receive stop outputactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: {- channel: "marimo-error",- mimetype: "application/vnd.marimo+error",- data: [- {- msg: "This cell wasn't run because an ancestor was stopped with `mo.stop`: ",- raising_cell: "2" as CellId,- type: "ancestor-stopped",- },- ],- timestamp: new Date(20).getTime() as Seconds,- },- console: null,- status: "idle",- stale_inputs: null,+ cell_id: firstCellId,+ output: {+ channel: "marimo-error",+ mimetype: "application/vnd.marimo+error",+ data: [+ {+ msg: "This cell wasn't run because an ancestor was stopped with `mo.stop`: ",+ raising_cell: "2" as CellId,+ type: "ancestor-stopped",+ },+ ],timestamp: new Date(20).getTime() as Seconds,},+ console: null,+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(20).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("idle");@@ -753,15 +705,12 @@ describe("cell reducer", () => {// Receive queued messageactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(30).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(30).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("queued");@@ -770,15 +719,12 @@ describe("cell reducer", () => {// Receive running messageactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "running",- stale_inputs: null,- timestamp: new Date(40).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "running",+ stale_inputs: null,+ timestamp: new Date(40).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("running");@@ -824,15 +770,12 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(10).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(10).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("queued");@@ -840,15 +783,12 @@ describe("cell reducer", () => {// Receive running messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "running",- stale_inputs: null,- timestamp: new Date(20).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "running",+ stale_inputs: null,+ timestamp: new Date(20).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("running");@@ -856,15 +796,12 @@ describe("cell reducer", () => {// Add consoleactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: STDOUT,- status: null,- stale_inputs: null,- timestamp: new Date(22).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: STDOUT,+ status: null,+ stale_inputs: null,+ timestamp: new Date(22).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("running");@@ -877,15 +814,12 @@ describe("cell reducer", () => {// Ask via stdinactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: STD_IN_1,- status: null,- stale_inputs: null,- timestamp: new Date(22).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: STD_IN_1,+ status: null,+ stale_inputs: null,+ timestamp: new Date(22).getTime() as Seconds,});cell = cells[0];expect(cell.consoleOutputs).toEqual([STDOUT, STD_IN_1]);@@ -911,15 +845,12 @@ describe("cell reducer", () => {// Ask via stdin, againactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: STD_IN_2,- status: null,- stale_inputs: null,- timestamp: new Date(22).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: STD_IN_2,+ status: null,+ stale_inputs: null,+ timestamp: new Date(22).getTime() as Seconds,});cell = cells[0];expect(cell.consoleOutputs).toEqual([@@ -932,20 +863,17 @@ describe("cell reducer", () => {// Interrupt, so we respond with ""actions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: {- channel: "marimo-error",- mimetype: "application/vnd.marimo+error",- data: [{ type: "interruption" }],- timestamp: 0,- },- console: null,- status: "idle",- stale_inputs: null,- timestamp: new Date(61).getTime() as Seconds,+ cell_id: firstCellId,+ output: {+ channel: "marimo-error",+ mimetype: "application/vnd.marimo+error",+ data: [{ type: "interruption" }],+ timestamp: 0,},+ console: null,+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(61).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("idle");@@ -978,15 +906,12 @@ describe("cell reducer", () => {// Add consoleactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: [OLD_STDOUT],- status: null,- stale_inputs: null,- timestamp: new Date(1).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: [OLD_STDOUT],+ status: null,+ stale_inputs: null,+ timestamp: new Date(1).getTime() as Seconds,});// Prepare for run@@ -1000,15 +925,12 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: null,- status: "queued",- stale_inputs: null,- timestamp: new Date(10).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ stale_inputs: null,+ timestamp: new Date(10).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("queued");@@ -1017,15 +939,12 @@ describe("cell reducer", () => {// Receive running messagesactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: [], // Backend sends an empty array to clearu- status: "running",- stale_inputs: null,- timestamp: new Date(20).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: [], // Backend sends an empty array to clearu+ status: "running",+ stale_inputs: null,+ timestamp: new Date(20).getTime() as Seconds,});cell = cells[0];expect(cell.status).toBe("running");@@ -1034,15 +953,12 @@ describe("cell reducer", () => {// Add consoleactions.handleCellMessage({- cellId: firstCellId,- message: {- cell_id: firstCellId,- output: null,- console: [STDOUT],- status: "idle",- stale_inputs: null,- timestamp: new Date(22).getTime() as Seconds,- },+ cell_id: firstCellId,+ output: null,+ console: [STDOUT],+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(22).getTime() as Seconds,});cell = cells[0];expect(cell.consoleOutputs).toEqual([STDOUT]);diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 92e205b038..35fefb8a8e 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";-import { ReducerWithoutAction, createRef, useMemo } from "react";+import { atom, useAtom, useAtomValue } from "jotai";+import { ReducerWithoutAction, createRef } from "react";import { CellMessage } from "../kernel/messages";import {CellConfig,@@ -18,7 +18,7 @@ import { arrayMove } from "@dnd-kit/sortable";import { CellId } from "./ids";import { prepareCellForExecution, transitionCell } from "./cell";import { store } from "../state/jotai";-import { createReducer } from "../../utils/createReducer";+import { createReducerAndAtoms } from "../../utils/createReducer";import { arrayInsert, arrayDelete, arrayShallowEquals } from "@/utils/arrays";import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";import { mergeOutlines } from "../dom/outline";@@ -145,7 +145,12 @@ function initialNotebookState(): NotebookState {/*** Actions and reducer for the notebook state.*/-const { reducer, createActions } = createReducer(initialNotebookState, {+const {+ reducer,+ createActions,+ useActions,+ valueAtom: notebookAtom,+} = createReducerAndAtoms(initialNotebookState, {createNewCell: (state,action: { cellId: CellId | "__end__"; before: boolean; code?: string },@@ -430,11 +435,8 @@ const { reducer, createActions } = createReducer(initialNotebookState, {};});},- handleCellMessage: (- state,- action: { cellId: CellId; message: CellMessage },- ) => {- const { cellId, message } = action;+ handleCellMessage: (state, message: CellMessage) => {+ const cellId = message.cell_id;const nextState = updateCellRuntimeState(state, cellId, (cell) => {return transitionCell(cell, message);});@@ -642,9 +644,13 @@ function updateCellData(};}-/// ATOMS+export {+ createActions as createNotebookActions,+ reducer as notebookReducer,+ notebookAtom,+};-export const notebookAtom = atom<NotebookState>(initialNotebookState());+/// ATOMSconst cellIdsAtom = atom((get) => get(notebookAtom).cellIds);@@ -872,14 +878,7 @@ export function flattenNotebookCells(state: NotebookState) {* when cells change.*/export function useCellActions() {- const setState = useSetAtom(notebookAtom);-- return useMemo(() => {- const actions = createActions((action) => {- setState((state) => reducer(state, action));- });- return actions;- }, [setState]);+ return useActions();}/**diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 64201c9247..c141c29573 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -1,10 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { z } from "zod";import { Logger } from "@/utils/Logger";-import {- getRawMarimoAppConfig,- getRawMarimoUserConfig,-} from "../dom/marimo-tag";+import { getMarimoAppConfig, getMarimoUserConfig } from "../dom/marimo-tag";// This has to be defined in the same file as the zod schema to satisfy zodexport const PackageManagerNames = [@@ -111,7 +108,7 @@ export type AppConfig = z.infer<typeof AppConfigSchema>;export function parseAppConfig() {try {- return AppConfigSchema.parse(JSON.parse(getRawMarimoAppConfig()));+ return AppConfigSchema.parse(getMarimoAppConfig());} catch (error) {Logger.error(`Marimo got an unexpected value in the configuration file: ${error}`,@@ -122,7 +119,7 @@ export function parseAppConfig() {export function parseUserConfig(): UserConfig {try {- const parsed = UserConfigSchema.parse(JSON.parse(getRawMarimoUserConfig()));+ const parsed = UserConfigSchema.parse(getMarimoUserConfig());for (const [key, value] of Object.entries(parsed.experimental)) {if (value === true) {Logger.log(`🧪 Experimental feature "${key}" is enabled.`);@@ -133,6 +130,10 @@ export function parseUserConfig(): UserConfig {Logger.error(`Marimo got an unexpected value in the configuration file: ${error}`,);- return UserConfigSchema.parse({});+ return defaultUserConfig();}}++export function defaultUserConfig(): UserConfig {+ return UserConfigSchema.parse({});+}diff --git a/frontend/src/core/dom/marimo-tag.ts b/frontend/src/core/dom/marimo-tag.tsindex 1281563631..df95660476 100644--- a/frontend/src/core/dom/marimo-tag.ts+++ b/frontend/src/core/dom/marimo-tag.ts@@ -1,29 +1,73 @@/* Copyright 2024 Marimo. All rights reserved. */-+import { assertExists } from "@/utils/assertExists";import { invariant } from "@/utils/invariant";-export function getMarimoVersion(): string {- return getMarimoDOMValue("marimo-version", "version");+interface MarimoSettings {+ getMarimoVersion: () => string;+ getMarimoServerToken: () => string;+ getMarimoAppConfig: () => unknown;+ getMarimoUserConfig: () => unknown;+ getMarimoCode: () => string;}-export function getMarimoServerToken(): string {- return getMarimoDOMValue("marimo-server-token", "token");-}+const domBasedMarimoSettings: MarimoSettings = {+ getMarimoVersion: () => {+ return getMarimoDOMValue("marimo-version", "version");+ },+ getMarimoServerToken: () => {+ return getMarimoDOMValue("marimo-server-token", "token");+ },+ getMarimoAppConfig: () => {+ return JSON.parse(getMarimoDOMValue("marimo-app-config", "config"));+ },+ getMarimoUserConfig: () => {+ return JSON.parse(getMarimoDOMValue("marimo-user-config", "config"));+ },+ getMarimoCode: () => {+ const tag = document.querySelector("marimo-code");+ invariant(tag, "internal-error: marimo-code not tag not found");+ const inner = tag.innerHTML;+ return decodeURIComponent(inner).trim();+ },+};-export function getRawMarimoAppConfig(): string {- return getMarimoDOMValue("marimo-app-config", "config");-}+// We don't control the DOM so we need to use a different method to get the values+const islandsBasedMarimoSettings: MarimoSettings = {+ getMarimoVersion: () => {+ assertExists(import.meta.env.VITE_MARIMO_VERSION);+ return import.meta.env.VITE_MARIMO_VERSION;+ },+ getMarimoServerToken: () => {+ return "";+ },+ getMarimoAppConfig: () => {+ return {};+ },+ getMarimoUserConfig: () => {+ return {};+ },+ getMarimoCode: () => {+ return "";+ },+};-export function getRawMarimoUserConfig(): string {- return getMarimoDOMValue("marimo-user-config", "config");-}+const {+ getMarimoVersion,+ getMarimoServerToken,+ getMarimoAppConfig,+ getMarimoUserConfig,+ getMarimoCode,+} = import.meta.env.VITE_MARIMO_ISLANDS+ ? islandsBasedMarimoSettings+ : domBasedMarimoSettings;-export function getMarimoCode(): string {- const tag = document.querySelector("marimo-code");- invariant(tag, "internal-error: marimo-code not tag not found");- const inner = tag.innerHTML;- return decodeURIComponent(inner).trim();-}+export {+ getMarimoVersion,+ getMarimoServerToken,+ getMarimoAppConfig,+ getMarimoUserConfig,+ getMarimoCode,+};function getMarimoDOMValue(tagName: string, key: string) {const tag = document.querySelector(tagName);diff --git a/frontend/src/core/errors/state.ts b/frontend/src/core/errors/state.tsindex 5d7e8cf4ee..b2da92ef76 100644--- a/frontend/src/core/errors/state.ts+++ b/frontend/src/core/errors/state.ts@@ -1,8 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */-import { createReducer } from "@/utils/createReducer";-import { atom, useAtomValue, useSetAtom } from "jotai";-import { useMemo } from "react";+import { createReducerAndAtoms } from "@/utils/createReducer";+import { useAtomValue } from "jotai";interface Banner {id: string;@@ -16,7 +15,7 @@ interface BannerState {banners: Banner[];}-const { reducer, createActions } = createReducer(+const { valueAtom: bannersAtom, useActions } = createReducerAndAtoms(() => ({ banners: [] }) as BannerState,{addBanner: (state, banner: Banner) => {@@ -34,8 +33,6 @@ const { reducer, createActions } = createReducer(},);-const bannersAtom = atom<BannerState>({ banners: [] });-/*** React hook to get the Banner state.*/@@ -45,11 +42,5 @@ export const useBanners = () => useAtomValue(bannersAtom);* React hook to get the Banners actions.*/export function useBannersActions() {- const setState = useSetAtom(bannersAtom);- return useMemo(() => {- const actions = createActions((action) => {- setState((state) => reducer(state, action));- });- return actions;- }, [setState]);+ return useActions();}diff --git a/frontend/src/core/islands/__tests__/parse.test.ts b/frontend/src/core/islands/__tests__/parse.test.tsnew file mode 100644index 0000000000..9c0767c842--- /dev/null+++ b/frontend/src/core/islands/__tests__/parse.test.ts@@ -0,0 +1,64 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, expect, it } from "vitest";+import { createMarimoFile } from "../parse";++describe("createMarimoFile", () => {+ it("should return a string", () => {+ const app = {+ cells: [+ {+ code: 'print("Hello, World!")',+ },+ ],+ };+ const result = createMarimoFile(app);+ expect(typeof result).toBe("string");+ });++ it("should correctly format a single cell", () => {+ const app = {+ cells: [+ {+ code: 'print("Hello, World!")',+ },+ ],+ };+ const result = createMarimoFile(app);+ const expected = [+ "import marimo",+ "app = marimo.App()",+ "@app.cell",+ "def __():",+ ' print("Hello, World!")',+ " return",+ ].join("\n");+ expect(result).toBe(expected);+ });++ it("should correctly format multiple cells", () => {+ const app = {+ cells: [+ {+ code: 'print("Hello, World!")',+ },+ {+ code: 'print("Goodbye, World!")',+ },+ ],+ };+ 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);+ });+});diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsnew file mode 100644index 0000000000..c525700dda--- /dev/null+++ b/frontend/src/core/islands/bridge.ts@@ -0,0 +1,133 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */+import {+ EditRequests,+ InstantiateRequest,+ RunRequests,+ SendFunctionRequest,+ ValueUpdate,+} from "../network/types";+import { Deferred } from "@/utils/Deferred";+import { getMarimoVersion } from "../dom/marimo-tag";+import { getWorkerRPC } from "./rpc";+import { OperationMessage } from "../kernel/messages";+import { JsonString } from "@/utils/json/base64";+import InlineWorker from "./worker/worker.ts?worker&inline";+import { CellId } from "@/core/cells/ids";+import { throwNotImplemented } from "@/utils/functions";+import { isIslands } from "@/core/islands/utils";++export class IslandsPyodideBridge implements RunRequests, EditRequests {+ /**+ * Lazy singleton instance of the IslandsPyodideBridge.+ */+ private static _instance: IslandsPyodideBridge | undefined;+ public static get INSTANCE() {+ if (!IslandsPyodideBridge._instance) {+ IslandsPyodideBridge._instance = new IslandsPyodideBridge();+ }+ return IslandsPyodideBridge._instance;+ }++ private rpc: ReturnType<typeof getWorkerRPC>;+ private messageConsumer:+ | ((message: JsonString<OperationMessage>) => void)+ | undefined;++ public initialized = new Deferred<void>();++ private constructor() {+ // Create a worker, must be inline to work with CORS restrictions+ const worker = new InlineWorker({+ // Pass the version to the worker+ /* @vite-ignore */+ name: isIslands() ? getMarimoVersion() : "dev",+ });++ // Create the RPC+ this.rpc = getWorkerRPC(worker);++ // Listeners+ this.rpc.addMessageListener("initialized", () => {+ this.initialized.resolve();+ });+ this.rpc.addMessageListener("initializedError", ({ error }) => {+ this.initialized.reject(new Error(error));+ });+ this.rpc.addMessageListener("kernelMessage", ({ message }) => {+ this.messageConsumer?.(message);+ });+ }++ async startSession(opts: { code: string; appId: string }) {+ await this.rpc.proxy.request.startSession(opts);+ }++ consumeMessages(consumer: (message: JsonString<OperationMessage>) => void) {+ this.messageConsumer = consumer;+ this.rpc.proxy.send.consumerReady({});+ }++ sendComponentValues = async (valueUpdates: ValueUpdate[]): Promise<null> => {+ await this.putControlRequest({+ ids_and_values: valueUpdates.map((update) => [+ update.objectId,+ update.value,+ ]),+ });+ return null;+ };+ sendInstantiate = async (request: InstantiateRequest): Promise<null> => {+ return null;+ };+ sendFunctionRequest = async (request: SendFunctionRequest): Promise<null> => {+ await this.putControlRequest(request);+ return null;+ };+ sendRun = async (cellIds: CellId[], codes: string[]): Promise<null> => {+ await this.rpc.proxy.request.loadPackages(codes.join("\n"));++ await this.putControlRequest({+ execution_requests: cellIds.map((cellId, index) => ({+ cell_id: cellId,+ code: codes[index],+ })),+ });+ return null;+ };++ sendRename = throwNotImplemented;+ sendSave = throwNotImplemented;+ sendStdin = throwNotImplemented;+ sendInterrupt = throwNotImplemented;+ sendShutdown = throwNotImplemented;+ sendFormat = throwNotImplemented;+ sendDeleteCell = throwNotImplemented;+ sendInstallMissingPackages = throwNotImplemented;+ sendCodeCompletionRequest = throwNotImplemented;+ saveUserConfig = throwNotImplemented;+ saveAppConfig = throwNotImplemented;+ saveCellConfig = throwNotImplemented;+ sendRestart = throwNotImplemented;+ readCode = throwNotImplemented;+ readSnippets = throwNotImplemented;+ openFile = throwNotImplemented;+ sendListFiles = throwNotImplemented;+ sendCreateFileOrFolder = throwNotImplemented;+ sendDeleteFileOrFolder = throwNotImplemented;+ sendRenameFileOrFolder = throwNotImplemented;+ sendUpdateFile = throwNotImplemented;+ sendFileDetails = throwNotImplemented;+ exportHTML = throwNotImplemented;+ getRecentFiles = throwNotImplemented;+ getWorkspaceFiles = throwNotImplemented;+ getRunningNotebooks = throwNotImplemented;+ shutdownSession = throwNotImplemented;++ private async putControlRequest(operation: object) {+ await this.rpc.proxy.request.bridge({+ functionName: "put_control_request",+ payload: operation,+ });+ }+}diff --git a/frontend/src/core/islands/components/output-wrapper.tsx b/frontend/src/core/islands/components/output-wrapper.tsxnew file mode 100644index 0000000000..0b98cef55f--- /dev/null+++ b/frontend/src/core/islands/components/output-wrapper.tsx@@ -0,0 +1,107 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { formatOutput } from "@/components/editor/Output";+import { Button } from "@/components/ui/button";+import { Tooltip } from "@/components/ui/tooltip";+import { NotebookState, notebookAtom } from "@/core/cells/cells";+import { CellId } from "@/core/cells/ids";+import { CellRuntimeState } from "@/core/cells/types";+import { RuntimeState } from "@/core/kernel/RuntimeState";+import { sendRun } from "@/core/network/requests";+import { useEventListener } from "@/hooks/useEventListener";+import { Logger } from "@/utils/Logger";+import { useAtomValue } from "jotai";+import { selectAtom } from "jotai/utils";+import { CopyIcon, Loader2Icon, PlayIcon } from "lucide-react";+import React, { PropsWithChildren, useCallback, useState } from "react";++interface Props {+ cellId: CellId;+ code: string;+ children: React.ReactNode;+}++export const MarimoOutputWrapper: React.FC<Props> = ({+ cellId,+ code,+ children,+}) => {+ const [pressed, setPressed] = useState<boolean>(false);+ const selector = useCallback(+ (s: NotebookState) => s.cellRuntime[cellId],+ [cellId],+ );+ const runtime = useAtomValue(selectAtom(notebookAtom, selector));++ useEventListener(document, "keydown", (e) => {+ if (e.metaKey || e.ctrlKey) {+ setPressed(true);+ }+ });++ useEventListener(document, "keyup", (e) => {+ if (e.metaKey || e.ctrlKey || e.key === "Meta" || e.key === "Control") {+ setPressed(false);+ }+ });++ if (!runtime?.output) {+ return children;+ }++ return (+ <div className="relative min-h-6">+ {formatOutput({ 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" }}+ >+ <Tooltip content="Copy code">+ <Button+ size="icon"+ variant="outline"+ className="bg-background h-5 w-5 mb-0"+ onClick={() => navigator.clipboard.writeText(code)}+ >+ <CopyIcon className="size-3" />+ </Button>+ </Tooltip>+ <Tooltip content="Re-run cell">+ <Button+ size="icon"+ variant="outline"+ className="bg-background h-5 w-5 mb-0"+ onClick={async () => {+ RuntimeState.INSTANCE.registerRunStart();+ await sendRun([cellId], [code]).catch((error) => {+ Logger.error(error);+ RuntimeState.INSTANCE.registerRunEnd();+ });+ }}+ >+ <PlayIcon className="size-3" />+ </Button>+ </Tooltip>+ </div>+ </div>+ );+};++const Indicator: React.FC<{ state: CellRuntimeState }> = ({ state }) => {+ if (state.status === "running") {+ return (+ <DelayRender>+ <div className="absolute top-1 right-1">+ <Loader2Icon className="animate-spin size-4" />+ </div>+ </DelayRender>+ );+ }++ return null;+};++// Render delay for children 200ms, using only css+const DelayRender: React.FC<PropsWithChildren> = ({ children }) => {+ return <div className="animate-delayed-show-200">{children}</div>;+};diff --git a/frontend/src/core/islands/components/web-components.tsx b/frontend/src/core/islands/components/web-components.tsxnew file mode 100644index 0000000000..2cfd9e0f38--- /dev/null+++ b/frontend/src/core/islands/components/web-components.tsx@@ -0,0 +1,77 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { invariant } from "@/utils/invariant";+import { CellId } from "../../cells/ids";+import { store } from "../../state/jotai";+import { notebookAtom } from "../../cells/cells";+import ReactDOM, { Root } from "react-dom/client";+import { parseIslandCode } from "../parse";+import { MarimoOutputWrapper } from "./output-wrapper";+import { Provider } from "jotai";+import { renderHTML } from "@/plugins/core/RenderHTML";+import { TooltipProvider } from "@/components/ui/tooltip";+import { ErrorBoundary } from "@/components/editor/boundary/ErrorBoundary";++/**+ * A custom element that renders the output of a marimo cell+ */+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 styleNamespace = "marimo";++ constructor() {+ super();+ this.classList.add(MarimoIslandElement.styleNamespace);+ }++ get appId(): string {+ invariant(this.dataset.appId, "Missing data-app-id attribute");+ return this.dataset.appId;+ }++ get cellId(): CellId {+ // Get the cell ID from the code+ invariant(this.dataset.cellIdx, "Missing data-cell-idx attribute");+ const { cellIds } = store.get(notebookAtom);+ const idx = Number.parseInt(this.dataset.cellIdx, 10);+ invariant(cellIds[idx], `Cell ID not found for index ${idx}`);+ return cellIds[idx];+ }++ get code(): string {+ const codeElement = this.querySelectorOrThrow(+ MarimoIslandElement.codeTagName,+ );+ return parseIslandCode(codeElement.textContent || "");+ }++ connectedCallback() {+ const output = this.querySelectorOrThrow(MarimoIslandElement.outputTagName);+ const initialOutput = output.innerHTML;+ this.root = ReactDOM.createRoot(this);+ this.render(initialOutput);+ }++ private render(html: string) {+ this.root?.render(+ <ErrorBoundary>+ <Provider store={store}>+ <TooltipProvider>+ <MarimoOutputWrapper cellId={this.cellId} code={this.code}>+ {renderHTML({ html })}+ </MarimoOutputWrapper>+ </TooltipProvider>+ </Provider>+ </ErrorBoundary>,+ );+ }++ private querySelectorOrThrow(selector: string) {+ const element = this.querySelector(selector);+ invariant(element, `Missing ${selector} element`);+ return element;+ }+}diff --git a/frontend/src/core/islands/islands.css b/frontend/src/core/islands/islands.cssnew file mode 100644index 0000000000..f9a4f81109--- /dev/null+++ b/frontend/src/core/islands/islands.css@@ -0,0 +1,6 @@+@import url("../../css/common.css");+@import url("../../css/globals.css");+@import url("../../css/codehilite.css");+@import url("../../css/katex.min.css");+@import url("../../css/table.css");+@import url("../../css/md.css");diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsnew file mode 100644index 0000000000..398e9eae82--- /dev/null+++ b/frontend/src/core/islands/main.ts@@ -0,0 +1,139 @@+/* Copyright 2024 Marimo. All rights reserved. */+import "./islands.css";+import "iconify-icon";++import { initializePlugins } from "@/plugins/plugins";+import { createMarimoFile, parseMarimoIslandApps } from "./parse";+import { IslandsPyodideBridge } from "./bridge";+import { store } from "../state/jotai";+import {+ createNotebookActions,+ notebookAtom,+ notebookReducer,+} from "../cells/cells";+import { toast } from "@/components/ui/use-toast";+import { renderHTML } from "@/plugins/core/RenderHTML";+import { logNever } from "@/utils/assertNever";+import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";+import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";+import {+ handleKernelReady,+ handleCompletedRun,+ handleInterrupted,+ handleRemoveUIElements,+ handleCellOperation,+} from "../kernel/handlers";+import { queryParamHandlers } from "../kernel/queryParamHandlers";+import { Logger } from "@/utils/Logger";+import { Functions } from "@/utils/functions";+import { defineCustomElement } from "../dom/defineCustomElement";+import { MarimoIslandElement } from "./components/web-components";+import { RuntimeState } from "../kernel/RuntimeState";++/**+ * Main entry point for the js bundle for embedded marimo apps.+ */++/**+ * Initialize the Marimo app.+ */+export async function initialize() {+ // Add 'marimo' class name to all `marimo-island` elements.+ const islands = document.querySelectorAll<HTMLElement>(+ MarimoIslandElement.tagName,+ );+ for (const island of islands) {+ island.classList.add(MarimoIslandElement.styleNamespace);+ }++ // This will display all the static HTML content.+ initializePlugins();++ // Find all "applications" which consist of snippets of code that are inside <marimo-island> tags.+ const apps = parseMarimoIslandApps();++ // Initialize each app+ for (const app of apps) {+ await IslandsPyodideBridge.INSTANCE.startSession({+ code: createMarimoFile(app),+ appId: app.id,+ });+ }++ const actions = createNotebookActions((action) => {+ store.set(notebookAtom, (state) => notebookReducer(state, action));+ });++ // Consume messages from the kernel+ IslandsPyodideBridge.INSTANCE.consumeMessages((message) => {+ const msg = jsonParseWithSpecialChar(message);+ switch (msg.op) {+ case "banner":+ case "missing-package-alert":+ case "installing-package-alert":+ case "completion-result":+ case "reload":+ // Unsupported+ return;+ case "kernel-ready":+ handleKernelReady(msg.data, {+ autoInstantiate: true,+ setCells: actions.setCells,+ setLayoutData: Functions.NOOP,+ setAppConfig: 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":+ handleCompletedRun();+ return;+ case "interrupted":+ handleInterrupted();+ 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":+ handleCellOperation(msg.data, actions.handleCellMessage);+ return;+ case "variables":+ case "variable-values":+ 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;+ default:+ logNever(msg);+ }+ });++ // Start the runtime+ RuntimeState.INSTANCE.start();+}++initialize();diff --git a/frontend/src/core/islands/parse.ts b/frontend/src/core/islands/parse.tsnew file mode 100644index 0000000000..5058522e03--- /dev/null+++ b/frontend/src/core/islands/parse.ts@@ -0,0 +1,130 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { MarimoIslandElement } from "@/core/islands/components/web-components";+import { Logger } from "@/utils/Logger";+import dedent from "string-dedent";++/**+ * DOM elements look like this:+ * <marimo-island data-app-id="{self._app_id}">+ * <marimo-cell-output>+ * <div> Hello, world! </div>+ * </marimo-cell-output>+ * <marimo-cell-code>+ * encoded(print("Hello, world!"))+ * </marimo-cell-code>+ * </marimo-island>+ */++export interface MarimoIslandApp {+ /**+ * ID since we allow multiple apps on the same page.+ */+ id: string;+ /**+ * Cells in the app.+ */+ cells: MarimoIslandCell[];+}++interface MarimoIslandCell {+ /**+ * Output of the cell.+ */+ output: string;+ /**+ * Code of the cell.+ */+ code: string;+ /**+ * Index of the cell.+ */+ idx: number;+}++export function parseMarimoIslandApps(): MarimoIslandApp[] {+ const apps = new Map<string, MarimoIslandApp>();++ const embeds = document.querySelectorAll<HTMLElement>(+ MarimoIslandElement.tagName,+ );+ if (embeds.length === 0) {+ Logger.warn("No embedded marimo apps found.");+ return [];+ }++ for (const embed of embeds) {+ const id = embed.dataset.appId;+ if (!id) {+ Logger.warn("Embedded marimo cell missing data-app-id attribute.");+ continue;+ }++ const cellOutput = embed.querySelector<HTMLElement>(+ MarimoIslandElement.outputTagName,+ );+ const cellCode = embed.querySelector<HTMLElement>(+ MarimoIslandElement.codeTagName,+ );++ if (!cellOutput || !cellCode) {+ Logger.warn(`Embedded marimo app ${id} missing cell output or code.`);+ continue;+ }++ if (!apps.has(id)) {+ apps.set(id, { id, cells: [] });+ }+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion+ const app = apps.get(id)!;+ const idx = app.cells.length;+ app.cells.push({+ output: cellOutput.innerHTML,+ code: parseIslandCode(cellCode.textContent),+ idx: idx,+ });++ // Add data-cell-idx attribute to the island element+ embed.dataset.cellIdx = idx.toString();+ }++ return [...apps.values()];+}++export function createMarimoFile(app: {+ cells: Array<{ code: string }>;+}): string {+ const lines = [+ "import marimo",+ "app = marimo.App()",+ app.cells+ .map((cell) => {+ // Add 4 spaces to each line+ const code = cell.code+ .split("\n")+ .map((line) => ` ${line}`)+ .join("\n");++ // TODO: Handle async cells better+ // This is probably not the best way to check if the code is async+ // Ideally this is pushed into the Python code+ const isAsync = code.includes("await ");+ const prefix = isAsync ? "async def" : "def";++ // Wrap in a function+ return `@app.cell\n${prefix} __():\n${code}\n return`;+ })+ .join("\n"),+ ];++ return lines.join("\n");+}++export function parseIslandCode(code: string | undefined | null): string {+ if (!code) {+ return "";+ }+ code = decodeURIComponent(code);+ // string-dedent expects the first and last line to be empty / contain only whitespace, so we pad with \n+ return dedent(`\n${code}\n`).trim();+}diff --git a/frontend/src/core/islands/rpc.ts b/frontend/src/core/islands/rpc.tsnew file mode 100644index 0000000000..4c110f1e06--- /dev/null+++ b/frontend/src/core/islands/rpc.ts@@ -0,0 +1,29 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { createWorkerTransport, createRPC, type RPCSchema } from "rpc-anywhere";++import type { WorkerSchema } from "./worker/worker";+import { Logger } from "../../utils/Logger";+import { TRANSPORT_ID } from "../pyodide/worker/constants";++export type ParentSchema = RPCSchema<{+ messages: {+ consumerReady: {};+ };+}>;++export function getWorkerRPC(worker: Worker) {+ return createRPC<ParentSchema, WorkerSchema>({+ transport: createWorkerTransport(worker, {+ transportId: TRANSPORT_ID,+ }),+ maxRequestTime: 20_000, // 20 seconds+ _debugHooks: {+ onSend: (message) => {+ Logger.debug("[rpc] Parent -> Worker", message);+ },+ onReceive: (message) => {+ Logger.debug("[rpc] Worker -> Parent", message);+ },+ },+ });+}diff --git a/frontend/src/core/islands/utils.ts b/frontend/src/core/islands/utils.tsnew file mode 100644index 0000000000..810ce2849f--- /dev/null+++ b/frontend/src/core/islands/utils.ts@@ -0,0 +1,4 @@+/* Copyright 2024 Marimo. All rights reserved. */+export function isIslands() {+ return import.meta.env.VITE_MARIMO_ISLANDS === true;+}diff --git a/frontend/src/core/islands/worker/controller.ts b/frontend/src/core/islands/worker/controller.tsnew file mode 100644index 0000000000..3ec0933400--- /dev/null+++ b/frontend/src/core/islands/worker/controller.ts@@ -0,0 +1,61 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { PyodideInterface } from "pyodide";+import { Logger } from "../../../utils/Logger";+import { defaultUserConfig } from "@/core/config/config-schema";+import { getFS } from "@/core/pyodide/worker/getFS";+import { SerializedBridge } from "@/core/pyodide/worker/types";+import { OperationMessage } from "@/core/kernel/messages";+import { JsonString } from "@/utils/json/base64";+import { DefaultWasmController } from "@/core/pyodide/worker/bootstrap";+import { invariant } from "@/utils/invariant";++export class ReadonlyWasmController extends DefaultWasmController {+ private MOUNT_POINT = "/marimo";++ override async bootstrap(opts: {+ version: string;+ }): Promise<PyodideInterface> {+ const pyodide = await super.bootstrap(opts);++ // Make dir and change to it+ const fs = getFS(pyodide);+ fs.mkdir(this.MOUNT_POINT);+ fs.chdir(this.MOUNT_POINT);++ return pyodide;+ }++ protected override mountFilesystem(opts: {+ code: string;+ filename: string | null;+ }) {+ const { code, filename } = opts;+ invariant(filename, "Filename is required");++ // Write file+ try {+ const fs = getFS(this.requirePyodide);+ fs.writeFile(`${this.MOUNT_POINT}/${filename}`, code);+ } catch (error) {+ Logger.error(error);+ }++ return Promise.resolve({ content: code, filename });+ }++ override async startSession(opts: {+ code: string;+ filename: string | null;+ onMessage: (message: JsonString<OperationMessage>) => void;+ }): Promise<SerializedBridge> {+ const bridge = super.startSession({+ queryParameters: {},+ code: opts.code,+ filename: opts.filename,+ onMessage: opts.onMessage,+ userConfig: defaultUserConfig(),+ });++ return bridge;+ }+}diff --git a/frontend/src/core/islands/worker/worker.ts b/frontend/src/core/islands/worker/worker.tsnew file mode 100644index 0000000000..6854e07687--- /dev/null+++ b/frontend/src/core/islands/worker/worker.ts@@ -0,0 +1,159 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { PyodideInterface } from "pyodide";+import { Deferred } from "../../../utils/Deferred";+import { prettyError } from "../../../utils/errors";+import {+ createWorkerParentTransport,+ createRPC,+ createRPCRequestHandler,+ type RPCSchema,+} from "rpc-anywhere";+import { invariant } from "../../../utils/invariant";+import { ParentSchema } from "@/core/pyodide/rpc";+import { TRANSPORT_ID } from "@/core/pyodide/worker/constants";+import { MessageBuffer } from "@/core/pyodide/worker/message-buffer";+import { SerializedBridge, RawBridge } from "@/core/pyodide/worker/types";+import { ReadonlyWasmController } from "./controller";+import { OperationMessage } from "@/core/kernel/messages";+import { JsonString } from "@/utils/json/base64";+import { Logger } from "@/utils/Logger";++declare const self: Window & {+ pyodide: PyodideInterface;+ controller: ReadonlyWasmController;+};++// Initialize pyodide+async function loadPyodideAndPackages() {+ // @ts-expect-error ehh TypeScript+ await import("https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js");+ try {+ self.controller = new ReadonlyWasmController();+ self.pyodide = await self.controller.bootstrap({+ version: getMarimoVersion(),+ });+ } catch (error) {+ console.error("Error bootstrapping", error);+ rpc.send.initializedError({+ error: prettyError(error),+ });+ }+}++const pyodideReadyPromise = loadPyodideAndPackages();+const messageBuffer = new MessageBuffer(+ (message: JsonString<OperationMessage>) => {+ rpc.send.kernelMessage({ message });+ },+);+const bridgeReady = new Deferred<SerializedBridge>();++// Handle RPC requests+const requestHandler = createRPCRequestHandler({+ /**+ * Start the session+ */+ startSession: async (opts: { code: string; appId: string }) => {+ await pyodideReadyPromise; // Make sure loading is done++ try {+ invariant(self.controller, "Controller not loaded");+ const bridge = await self.controller.startSession({+ code: opts.code,+ filename: `app-${opts.appId}.py`,+ onMessage: messageBuffer.push,+ });+ bridgeReady.resolve(bridge);+ rpc.send.initialized({});+ } catch (error) {+ rpc.send.initializedError({+ error: prettyError(error),+ });+ }+ return;+ },++ /**+ * Load packages+ */+ loadPackages: async (packages: string) => {+ await pyodideReadyPromise; // Make sure loading is done++ await self.pyodide.loadPackagesFromImports(packages, {+ messageCallback: Logger.log,+ errorCallback: Logger.error,+ });+ },++ /**+ * Call a function on the bridge+ */+ bridge: async (opts: {+ functionName: keyof RawBridge;+ payload: {} | undefined | null;+ }) => {+ await pyodideReadyPromise; // Make sure loading is done++ const { functionName, payload } = opts;++ // Perform the function call to the Python bridge+ const bridge = await bridgeReady.promise;++ // Serialize the payload+ const payloadString =+ payload == null+ ? null+ : typeof payload === "string"+ ? payload+ : JSON.stringify(payload);++ // Make the request+ const response =+ payloadString == null+ ? // @ts-expect-error ehh TypeScript+ await bridge[functionName]()+ : // @ts-expect-error ehh TypeScript+ await bridge[functionName](payloadString);++ // Post the response back to the main thread+ return typeof response === "string" ? JSON.parse(response) : response;+ },+});++// create the iframe's schema+export type WorkerSchema = RPCSchema<+ {+ messages: {+ // Emitted when the worker is ready+ ready: {};+ // Emitted when the kernel sends a message+ kernelMessage: { message: JsonString<OperationMessage> };+ // Emitted when the Pyodide is initialized+ initialized: {};+ // Emitted when the Pyodide fails to initialize+ initializedError: { error: string };+ };+ },+ typeof requestHandler+>;++const rpc = createRPC<WorkerSchema, ParentSchema>({+ transport: createWorkerParentTransport({+ transportId: TRANSPORT_ID,+ }),+ requestHandler,+});++rpc.send("ready", {});++/// Listeners+// When the consumer is ready, start the message buffer+rpc.addMessageListener("consumerReady", async () => {+ await pyodideReadyPromise; // Make sure loading is done+ messageBuffer.start();+});++function getMarimoVersion() {+ return self.name; // We store the version in the worker name+}diff --git a/frontend/src/core/kernel/__tests__/handlers.test.ts b/frontend/src/core/kernel/__tests__/handlers.test.tsnew file mode 100644index 0000000000..9abd9e9495--- /dev/null+++ b/frontend/src/core/kernel/__tests__/handlers.test.ts@@ -0,0 +1,62 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/unbound-method */+import { describe, it, expect, vi } from "vitest";+import { queryParamHandlers } from "../queryParamHandlers";++// Helper to set up URL and searchParams+function setupURL(search = "") {+ const url = new URL("http://localhost:3000");+ url.search = search;+ window.history.pushState({}, "", `${url.pathname}${url.search}`);+ return url;+}++vi.spyOn(window.history, "pushState");++describe("queryParamHandlers", () => {+ it("should append a query parameter", () => {+ setupURL();+ queryParamHandlers.append({ key: "test", value: "123" });+ expect(window.location.href).toContain("test=123");+ expect(window.history.pushState).toHaveBeenCalled();+ });++ it("should set a query parameter", () => {+ setupURL();+ queryParamHandlers.set({ key: "test", value: "123" });+ expect(window.location.href).toContain("test=123");+ expect(window.history.pushState).toHaveBeenCalled();+ });++ it("should delete a specific query parameter", () => {+ setupURL("?test=123&sample=456");+ queryParamHandlers.delete({ key: "test", value: "123" });+ expect(window.location.href).not.toContain("test=123");+ expect(window.location.href).toContain("sample=456");+ expect(window.history.pushState).toHaveBeenCalled();+ });++ it("shouldn't delete a specific query parameter if the value doesn't match", () => {+ setupURL("?test=abc&sample=456");+ queryParamHandlers.delete({ key: "test", value: "123" });+ expect(window.location.href).toContain("test=abc");+ expect(window.location.href).toContain("sample=456");+ expect(window.history.pushState).toHaveBeenCalled();+ });++ it("should delete all instances of a query parameter", () => {+ setupURL("?test=123&test=456");+ queryParamHandlers.delete({ key: "test", value: null });+ expect(window.location.href).not.toContain("test=123");+ expect(window.location.href).not.toContain("test=456");+ expect(window.history.pushState).toHaveBeenCalled();+ });++ it("should clear all query parameters", () => {+ setupURL("?test=123&sample=456");+ queryParamHandlers.clear();+ expect(window.location.href).not.toContain("test=123");+ expect(window.location.href).not.toContain("sample=456");+ expect(window.history.pushState).toHaveBeenCalled();+ });+});diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsnew file mode 100644index 0000000000..2f815e52cc--- /dev/null+++ b/frontend/src/core/kernel/handlers.ts@@ -0,0 +1,151 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { deserializeLayout } from "@/components/editor/renderers/plugins";+import { Objects } from "@/utils/objects";+import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";+import { LayoutData, LayoutState, initialLayoutState } from "../layout/layout";+import { sendInstantiate } from "../network/requests";+import { RuntimeState } from "./RuntimeState";+import { CellMessage, OperationMessage } from "./messages";+import { LayoutType } from "@/components/editor/renderers/types";+import { AppConfig } from "../config/config-schema";+import { CellData, createCell } from "../cells/types";+import { VirtualFileTracker } from "../static/virtual-file-tracker";++export type OperationMessageData<T extends OperationMessage["op"]> = Extract<+ OperationMessage,+ { op: T }+>;++export function handleKernelReady(+ data: OperationMessageData<"kernel-ready">["data"],+ opts: {+ autoInstantiate: boolean;+ setCells: (cells: CellData[], layout: LayoutState) => void;+ setLayoutData: (payload: {+ layoutView: LayoutType;+ data: LayoutData;+ }) => void;+ setAppConfig: (config: AppConfig) => void;+ onError: (error: Error) => void;+ },+) {+ const { autoInstantiate, setCells, setLayoutData, onError, setAppConfig } =+ opts;++ const {+ codes,+ names,+ layout,+ configs,+ resumed,+ ui_values,+ cell_ids,+ last_executed_code = {},+ app_config,+ } = data;++ // Set the layout, initial codes, cells+ const cells = codes.map((code, i) => {+ const cellId = cell_ids[i];++ // A cell is stale if we did not auto-instantiate (i.e. nothing has run yet)+ // or if the code has changed since the last time it was run.+ let edited = false;+ if (autoInstantiate || resumed) {+ const lastCodeRun = last_executed_code[cellId];+ if (lastCodeRun) {+ edited = lastCodeRun !== code;+ }+ } else {+ edited = true;+ }++ return createCell({+ id: cellId,+ code,+ edited: edited,+ name: names[i],+ lastCodeRun: last_executed_code[cellId] ?? null,+ config: configs[i],+ });+ });++ const layoutState = initialLayoutState();+ if (layout) {+ const layoutData = deserializeLayout(layout.type, layout.data, cells);+ layoutState.selectedLayout = layout.type;+ layoutState.layoutData[layout.type] = layoutData;+ setLayoutData({ layoutView: layout.type, data: layoutData });+ }+ setCells(cells, layoutState);+ setAppConfig(app_config);++ // If resumed, we don't need to instantiate the UI elements,+ // and we should read in th existing values from the kernel.+ if (resumed) {+ for (const [objectId, value] of Objects.entries(ui_values || {})) {+ UI_ELEMENT_REGISTRY.set(objectId, value);+ }+ return;+ }++ // Auto-instantiate, in future this can be configurable+ // or include initial values+ const objectIds: string[] = [];+ const values: unknown[] = [];+ // If we already have values for some objects, we should+ // send them to the kernel. This may happen after re-connecting+ // to the kernel after the computer wakes from sleep.+ UI_ELEMENT_REGISTRY.entries.forEach((entry, objectId) => {+ objectIds.push(objectId);+ values.push(entry.value);+ });+ // Send the instantiate message+ if (autoInstantiate) {+ // Start the run+ RuntimeState.INSTANCE.registerRunStart();+ sendInstantiate({ objectIds, values }).catch((error) => {+ RuntimeState.INSTANCE.registerRunEnd();+ onError(new Error("Failed to instantiate", { cause: error }));+ });+ }+}++export function handleRemoveUIElements(+ data: OperationMessageData<"remove-ui-elements">["data"],+) {+ // This removes the element from the registry to (1) clean-up+ // memory and (2) make sure that the old value doesn't get re-used+ // if the same cell-id is later reused for another element.+ const { cell_id } = data;+ UI_ELEMENT_REGISTRY.removeElementsByCell(cell_id);+ VirtualFileTracker.INSTANCE.removeForCellId(cell_id);+}++export function handleInterrupted() {+ if (!RuntimeState.INSTANCE.running()) {+ RuntimeState.INSTANCE.flushUpdates();+ }+}++export function handleCompletedRun() {+ RuntimeState.INSTANCE.registerRunEnd();+ if (!RuntimeState.INSTANCE.running()) {+ RuntimeState.INSTANCE.flushUpdates();+ }+}++export function handleCellOperation(+ data: OperationMessageData<"cell-op">["data"],+ handleCellMessage: (message: CellMessage) => void,+) {+ /* Register a state transition for a cell.+ *+ * The cell may have a new output, a new console output,+ * it may have been queued, it may have started running, or+ * it may have stopped running. Each of these things+ * affects how the cell should be rendered.+ */+ handleCellMessage(data);+ VirtualFileTracker.INSTANCE.track(data);+}diff --git a/frontend/src/core/kernel/queryParamHandlers.ts b/frontend/src/core/kernel/queryParamHandlers.tsnew file mode 100644index 0000000000..ec750256c2--- /dev/null+++ b/frontend/src/core/kernel/queryParamHandlers.ts@@ -0,0 +1,38 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { OperationMessageData } from "./handlers";++export const queryParamHandlers = {+ append: (data: OperationMessageData<"query-params-append">["data"]) => {+ const url = new URL(window.location.href);+ url.searchParams.append(data.key, data.value);+ window.history.pushState({}, "", `${url.pathname}${url.search}`);+ return;+ },+ set: (data: OperationMessageData<"query-params-set">["data"]) => {+ const url = new URL(window.location.href);+ if (Array.isArray(data.value)) {+ url.searchParams.delete(data.key);+ data.value.forEach((v) => url.searchParams.append(data.key, v));+ } else {+ url.searchParams.set(data.key, data.value);+ }+ window.history.pushState({}, "", `${url.pathname}${url.search}`);+ return;+ },+ delete: (data: OperationMessageData<"query-params-delete">["data"]) => {+ const url = new URL(window.location.href);+ if (data.value == null) {+ url.searchParams.delete(data.key);+ } else {+ url.searchParams.delete(data.key, data.value);+ }+ window.history.pushState({}, "", `${url.pathname}${url.search}`);+ return;+ },+ clear: () => {+ const url = new URL(window.location.href);+ url.search = "";+ window.history.pushState({}, "", `${url.pathname}${url.search}`);+ return;+ },+};diff --git a/frontend/src/core/layout/layout.ts b/frontend/src/core/layout/layout.tsindex 11984b5435..e2ec6dff51 100644--- a/frontend/src/core/layout/layout.ts+++ b/frontend/src/core/layout/layout.ts@@ -1,9 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */import { GridLayout } from "@/components/editor/renderers/grid-layout/types";import { LayoutType } from "@/components/editor/renderers/types";-import { atom, useAtomValue, useSetAtom } from "jotai";-import { createReducer } from "@/utils/createReducer";-import { useMemo } from "react";+import { useAtomValue } from "jotai";+import { createReducerAndAtoms } from "@/utils/createReducer";import { cellRendererPlugins } from "@/components/editor/renderers/plugins";import { getNotebook, notebookCells } from "../cells/cells";import { store } from "../state/jotai";@@ -23,52 +22,46 @@ export function initialLayoutState(): LayoutState {};}-const { reducer, createActions } = createReducer(initialLayoutState, {- setLayoutView: (state, payload: LayoutType) => {- return {- ...state,- selectedLayout: payload,- };+const { valueAtom: layoutStateAtom, useActions } = createReducerAndAtoms(+ initialLayoutState,+ {+ setLayoutView: (state, payload: LayoutType) => {+ return {+ ...state,+ selectedLayout: payload,+ };+ },+ setLayoutData: (+ state,+ payload: { layoutView: LayoutType; data: LayoutData },+ ) => {+ return {+ ...state,+ selectedLayout: payload.layoutView,+ layoutData: {+ ...state.layoutData,+ [payload.layoutView]: payload.data,+ },+ };+ },+ setCurrentLayoutData: (state, payload: LayoutData) => {+ return {+ ...state,+ layoutData: {+ ...state.layoutData,+ [state.selectedLayout]: payload,+ },+ };+ },},- setLayoutData: (- state,- payload: { layoutView: LayoutType; data: LayoutData },- ) => {- return {- ...state,- selectedLayout: payload.layoutView,- layoutData: {- ...state.layoutData,- [payload.layoutView]: payload.data,- },- };- },- setCurrentLayoutData: (state, payload: LayoutData) => {- return {- ...state,- layoutData: {- ...state.layoutData,- [state.selectedLayout]: payload,- },- };- },-});--const layoutStateAtom = atom<LayoutState>(initialLayoutState());+);export const useLayoutState = () => {return useAtomValue(layoutStateAtom);};export const useLayoutActions = () => {- const setState = useSetAtom(layoutStateAtom);-- return useMemo(() => {- const actions = createActions((action) => {- setState((state) => reducer(state, action));- });- return actions;- }, [setState]);+ return useActions();};/**diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 503ffd7004..d8e9c8b67c 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -1,4 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */+import { IslandsPyodideBridge } from "../islands/bridge";+import { isIslands } from "../islands/utils";import { PyodideBridge } from "../pyodide/bridge";import { isPyodide } from "../pyodide/utils";import { isStaticNotebook } from "../static/static-state";@@ -7,6 +9,12 @@ import { createStaticRequests } from "./requests-static";import { createErrorToastingRequests } from "./requests-toasting";function getRequest() {+ if (isIslands()) {+ // We don't wrap in error toasting, since we don't currently mount+ // the ToastProvider in islands+ return IslandsPyodideBridge.INSTANCE;+ }+const base = isPyodide()? PyodideBridge.INSTANCE: isStaticNotebook()diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsindex bc6a8aa3d9..315f581564 100644--- a/frontend/src/core/pyodide/bridge.ts+++ b/frontend/src/core/pyodide/bridge.ts@@ -39,6 +39,7 @@ import { getWorkerRPC } from "./rpc";import { API } from "../network/api";import { RuntimeState } from "@/core/kernel/RuntimeState";import { parseUserConfig } from "../config/config-schema";+import { throwNotImplemented } from "@/utils/functions";export class PyodideBridge implements RunRequests, EditRequests {static INSTANCE = new PyodideBridge();@@ -49,7 +50,7 @@ export class PyodideBridge implements RunRequests, EditRequests {public initialized = new Deferred<void>();- constructor() {+ private constructor() {if (isPyodide()) {// Create a workerconst worker = new Worker(@@ -101,8 +102,7 @@ export class PyodideBridge implements RunRequests, EditRequests {await this.rpc.proxy.request.startSession({queryParameters: queryParameters,- code,- fallbackCode: fallbackCode || "",+ code: code || fallbackCode || "",filename,userConfig,});@@ -390,10 +390,6 @@ export class PyodideBridge implements RunRequests, EditRequests {}}-function throwNotImplemented(): never {- throw new Error("Not implemented");-}-export class PyodideWebsocket implements IReconnectingWebSocket {CONNECTING = WebSocket.CONNECTING;OPEN = WebSocket.OPEN;@@ -415,7 +411,7 @@ export class PyodideWebsocket implements IReconnectingWebSocket {messageSubscriptions = new Set<(event: MessageEvent) => void>();errorSubscriptions = new Set<(event: Event) => void>();- constructor(private bridge: PyodideBridge) {}+ constructor(private bridge: Pick<PyodideBridge, "consumeMessages">) {}private consumeMessages() {this.bridge.consumeMessages((message) => {diff --git a/frontend/src/core/pyodide/worker/bootstrap.ts b/frontend/src/core/pyodide/worker/bootstrap.tsindex bffe6529ad..e48577c76e 100644--- a/frontend/src/core/pyodide/worker/bootstrap.ts+++ b/frontend/src/core/pyodide/worker/bootstrap.ts@@ -5,6 +5,9 @@ import { Logger } from "../../../utils/Logger";import { SerializedBridge, WasmController } from "./types";import { invariant } from "../../../utils/invariant";import { UserConfig } from "@/core/config/config-schema";+import { getMarimoWheel } from "./getMarimoWheel";+import { OperationMessage } from "@/core/kernel/messages";+import { JsonString } from "@/utils/json/base64";declare let loadPyodide: (opts: {packages: string[];@@ -12,7 +15,12 @@ declare let loadPyodide: (opts: {}) => Promise<PyodideInterface>;export class DefaultWasmController implements WasmController {- private pyodide: PyodideInterface | null = null;+ protected pyodide: PyodideInterface | null = null;++ get requirePyodide() {+ invariant(this.pyodide, "Pyodide not loaded");+ return this.pyodide;+ }async bootstrap(opts: { version: string }): Promise<PyodideInterface> {const pyodide = await this.loadPyoideAndPackages();@@ -79,20 +87,24 @@ export class DefaultWasmController implements WasmController {`);}+ protected mountFilesystem(opts: { code: string; filename: string | null }) {+ return mountFilesystem({+ pyodide: this.requirePyodide,+ ...opts,+ });+ }+async startSession(opts: {queryParameters: Record<string, string | string[]>;- code: string | null;- fallbackCode: string;+ code: string;filename: string | null;- onMessage: (message: string) => void;+ onMessage: (message: JsonString<OperationMessage>) => void;userConfig: UserConfig;}): Promise<SerializedBridge> {- invariant(this.pyodide, "Pyodide not loaded");-// Set up the filesystem- const { filename, content } = await mountFilesystem({- pyodide: this.pyodide,- ...opts,+ const { filename, content } = await this.mountFilesystem({+ code: opts.code,+ filename: opts.filename,});// We pass down a messenger object to the code@@ -108,12 +120,12 @@ export class DefaultWasmController implements WasmController {self.user_config = opts.userConfig;// Load packages from the code- await this.pyodide.loadPackagesFromImports(content, {+ await this.requirePyodide.loadPackagesFromImports(content, {messageCallback: Logger.log,errorCallback: Logger.error,});- const bridge = await this.pyodide.runPythonAsync(+ const bridge = await this.requirePyodide.runPythonAsync(`print("[py] Starting marimo...")import asyncio@@ -138,13 +150,3 @@ export class DefaultWasmController implements WasmController {return bridge;}}--function getMarimoWheel(version: string) {- if (!version) {- return "marimo >= 0.3.0";- }- if (version === "local") {- return "http://localhost:8000/dist/marimo-0.4.2-py3-none-any.whl";- }- return `marimo==${version}`;-}diff --git a/frontend/src/core/pyodide/worker/fs.ts b/frontend/src/core/pyodide/worker/fs.tsindex f2362d4c6e..f853a78f00 100644--- a/frontend/src/core/pyodide/worker/fs.ts+++ b/frontend/src/core/pyodide/worker/fs.ts@@ -1,22 +1,18 @@/* Copyright 2024 Marimo. All rights reserved. */import type { PyodideInterface } from "pyodide";+import { getFS } from "./getFS";-const FALLBACK_FILE = "notebook.py";--export function getFS(pyodide: PyodideInterface): typeof FS {- return pyodide.FS;-}+const NOTEBOOK_FILENAME = "notebook.py";export async function mountFilesystem(opts: {pyodide: PyodideInterface;- code: string | null;- fallbackCode: string;+ code: string;filename: string | null;}): Promise<{content: string;filename: string;}> {- const { pyodide, filename, code, fallbackCode } = opts;+ const { pyodide, filename, code } = opts;const FS = getFS(pyodide);// This is our home directory@@ -38,11 +34,9 @@ export async function mountFilesystem(opts: {}};- const content = code || fallbackCode;-// If there is a filename, read the file if it exists// We don't want to change the contents of the file if it already exists- if (filename && filename !== FALLBACK_FILE) {+ if (filename && filename !== NOTEBOOK_FILENAME) {const existingContent = readIfExist(filename);if (existingContent) {return {@@ -50,20 +44,13 @@ export async function mountFilesystem(opts: {filename,};}-- // If the filename does not exist in the FS, write the content to the file- FS.writeFile(filename, content);- return {- content,- filename,- };}// If there is no filename, write the code to the last used file- FS.writeFile(FALLBACK_FILE, content);+ FS.writeFile(NOTEBOOK_FILENAME, code);return {- content: content,- filename: FALLBACK_FILE,+ content: code,+ filename: NOTEBOOK_FILENAME,};}diff --git a/frontend/src/core/pyodide/worker/getFS.ts b/frontend/src/core/pyodide/worker/getFS.tsnew file mode 100644index 0000000000..28364ce610--- /dev/null+++ b/frontend/src/core/pyodide/worker/getFS.ts@@ -0,0 +1,9 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { PyodideInterface } from "pyodide";++/**+ * Wrapper around pyodide.FS to add type safety.+ */+export function getFS(pyodide: PyodideInterface): typeof FS {+ return pyodide.FS;+}diff --git a/frontend/src/core/pyodide/worker/getMarimoWheel.ts b/frontend/src/core/pyodide/worker/getMarimoWheel.tsnew file mode 100644index 0000000000..3756b2660a--- /dev/null+++ b/frontend/src/core/pyodide/worker/getMarimoWheel.ts@@ -0,0 +1,13 @@+/* Copyright 2024 Marimo. All rights reserved. */+export function getMarimoWheel(version: string) {+ if (!version) {+ return "marimo >= 0.3.0";+ }+ if (version === "local") {+ return "http://localhost:8000/dist/marimo-0.4.2-py3-none-any.whl";+ }+ if (version === "latest") {+ return "marimo";+ }+ return `marimo==${version}`;+}diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.tsindex 1fd010ed4c..92fb1de4e3 100644--- a/frontend/src/core/pyodide/worker/types.ts+++ b/frontend/src/core/pyodide/worker/types.ts@@ -18,6 +18,9 @@ import type {SaveUserConfigRequest,SnippetsResponse,} from "../../network/types";+import { OperationMessage } from "@/core/kernel/messages";+import { JsonString } from "@/utils/json/base64";+import { UserConfig } from "@/core/config/config-schema";export interface WasmController {/**@@ -33,10 +36,10 @@ export interface WasmController {*/startSession(opts: {queryParameters: Record<string, string | string[]>;- code: string | null;- fallbackCode: string;+ code: string;filename: string | null;- onMessage: (message: string) => void;+ userConfig: UserConfig | null;+ onMessage: (message: JsonString<OperationMessage>) => void;}): Promise<SerializedBridge>;}diff --git a/frontend/src/core/pyodide/worker/worker.ts b/frontend/src/core/pyodide/worker/worker.tsindex dc86cf531f..1e703a5114 100644--- a/frontend/src/core/pyodide/worker/worker.ts+++ b/frontend/src/core/pyodide/worker/worker.ts@@ -17,12 +17,13 @@ import { ParentSchema } from "../rpc";import { Logger } from "../../../utils/Logger";import { TRANSPORT_ID } from "./constants";import { invariant } from "../../../utils/invariant";-import { UserConfig } from "vite";+import { OperationMessage } from "@/core/kernel/messages";+import { JsonString } from "@/utils/json/base64";+import { UserConfig } from "@/core/config/config-schema";declare const self: Window & {pyodide: PyodideInterface;controller: WasmController;- rpc: ReturnType<typeof createRPC>;};// Initialize pyodide@@ -58,9 +59,11 @@ async function getController(version: string) {}const pyodideReadyPromise = loadPyodideAndPackages();-const messageBuffer = new MessageBuffer((message: string) => {- rpc.send.kernelMessage({ message });-});+const messageBuffer = new MessageBuffer(+ (message: JsonString<OperationMessage>) => {+ rpc.send.kernelMessage({ message });+ },+);const bridgeReady = new Deferred<SerializedBridge>();let started = false;@@ -71,8 +74,7 @@ const requestHandler = createRPCRequestHandler({*/startSession: async (opts: {queryParameters: Record<string, string | string[]>;- code: string | null;- fallbackCode: string;+ code: string;filename: string | null;userConfig: UserConfig | null;}) => {@@ -87,7 +89,10 @@ const requestHandler = createRPCRequestHandler({try {invariant(self.controller, "Controller not loaded");const bridge = await self.controller.startSession({- ...opts,+ code: opts.code,+ filename: opts.filename,+ queryParameters: opts.queryParameters,+ userConfig: opts.userConfig,onMessage: messageBuffer.push,});bridgeReady.resolve(bridge);@@ -192,7 +197,7 @@ export type WorkerSchema = RPCSchema<// Emitted when the worker is readyready: {};// Emitted when the kernel sends a message- kernelMessage: { message: string };+ kernelMessage: { message: JsonString<OperationMessage> };// Emitted when the Pyodide is initializedinitialized: {};// Emitted when the Pyodide fails to initialize@@ -209,7 +214,6 @@ const rpc = createRPC<WorkerSchema, ParentSchema>({requestHandler,});-self.rpc = rpc;rpc.send("ready", {});/// Listenersdiff --git a/frontend/src/core/variables/state.ts b/frontend/src/core/variables/state.tsindex 0ec5da9f7c..64c48df258 100644--- a/frontend/src/core/variables/state.ts+++ b/frontend/src/core/variables/state.ts@@ -1,15 +1,19 @@/* Copyright 2024 Marimo. All rights reserved. */-import { createReducer } from "@/utils/createReducer";+import { createReducerAndAtoms } from "@/utils/createReducer";import { Variable, VariableName, Variables } from "./types";-import { atom, useAtomValue, useSetAtom } from "jotai";-import { useMemo } from "react";+import { useAtomValue } from "jotai";function initialState(): Variables {return {};}-const { reducer, createActions } = createReducer(initialState, {+const {+ reducer,+ createActions,+ valueAtom: variablesAtom,+ useActions,+} = createReducerAndAtoms(initialState, {setVariables: (state, variables: Variable[]) => {// start with empty state, but keep the old state's metadataconst oldVariables = { ...state };@@ -52,8 +56,6 @@ const { reducer, createActions } = createReducer(initialState, {},});-const variablesAtom = atom(initialState());-/*** React hook to get the variables state.*/@@ -63,13 +65,7 @@ export const useVariables = () => useAtomValue(variablesAtom);* React hook to get the variables actions.*/export function useVariablesActions() {- const setState = useSetAtom(variablesAtom);- return useMemo(() => {- const actions = createActions((action) => {- setState((state) => reducer(state, action));- });- return actions;- }, [setState]);+ return useActions();}export const exportedForTesting = {diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 0bd73016f1..4cb8afd1ff 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -5,21 +5,12 @@ import { connectionAtom } from "../network/connection";import { useWebSocket } from "@/core/websocket/useWebSocket";import { logNever } from "@/utils/assertNever";import { useCellActions } from "@/core/cells/cells";-import { RuntimeState } from "@/core/kernel/RuntimeState";import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";-import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";import { OperationMessage } from "@/core/kernel/messages";-import { sendInstantiate } from "../network/requests";import { CellData } from "../cells/types";-import { createCell } from "../cells/types";import { useErrorBoundary } from "react-error-boundary";import { Logger } from "@/utils/Logger";-import {- LayoutState,- initialLayoutState,- useLayoutActions,-} from "../layout/layout";-import { deserializeLayout } from "@/components/editor/renderers/plugins";+import { LayoutState, useLayoutActions } from "../layout/layout";import { useVariablesActions } from "../variables/state";import { toast } from "@/components/ui/use-toast";import { renderHTML } from "@/plugins/core/RenderHTML";@@ -28,14 +19,21 @@ import { prettyError } from "@/utils/errors";import { isStaticNotebook } from "../static/static-state";import { useRef } from "react";import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";-import { VirtualFileTracker } from "../static/virtual-file-tracker";-import { Objects } from "@/utils/objects";import { SessionId } from "../kernel/session";import { useBannersActions } from "../errors/state";import { useAlertActions } from "../alerts/state";import { generateUUID } from "@/utils/uuid";import { createWsUrl } from "./createWsUrl";import { useSetAppConfig } from "../config/config";+import {+ handleCellOperation,+ handleCompletedRun,+ handleInterrupted,+ handleKernelReady,+ handleRemoveUIElements,+} from "../kernel/handlers";+import { queryParamHandlers } from "../kernel/queryParamHandlers";+import { JsonString } from "@/utils/json/base64";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -58,130 +56,43 @@ export function useMarimoWebSocket(opts: {const { addBanner } = useBannersActions();const { addPackageAlert } = useAlertActions();- const handleMessage = (e: MessageEvent<string>) => {- const msg = jsonParseWithSpecialChar<OperationMessage>(e.data);+ const handleMessage = (e: MessageEvent<JsonString<OperationMessage>>) => {+ const msg = jsonParseWithSpecialChar(e.data);switch (msg.op) {case "reload":window.location.reload();return;- case "kernel-ready": {- const {- codes,- names,- layout,- configs,- resumed,- ui_values,- cell_ids,- last_executed_code = {},- app_config,- } = msg.data;-- // Set the layout, initial codes, cells- const cells = codes.map((code, i) => {- const cellId = cell_ids[i];-- // A cell is stale if we did not auto-instantiate (i.e. nothing has run yet)- // or if the code has changed since the last time it was run.- let edited = false;- if (autoInstantiate || resumed) {- const lastCodeRun = last_executed_code[cellId];- if (lastCodeRun) {- edited = lastCodeRun !== code;- }- } else {- edited = true;- }-- return createCell({- id: cellId,- code,- edited: edited,- name: names[i],- lastCodeRun: last_executed_code[cellId] ?? null,- config: configs[i],- });+ case "kernel-ready":+ handleKernelReady(msg.data, {+ autoInstantiate,+ setCells,+ setLayoutData,+ setAppConfig,+ onError: showBoundary,});-- const layoutState = initialLayoutState();- if (layout) {- const layoutData = deserializeLayout(layout.type, layout.data, cells);- layoutState.selectedLayout = layout.type;- layoutState.layoutData[layout.type] = layoutData;- setLayoutData({ layoutView: layout.type, data: layoutData });- }- setCells(cells, layoutState);- setAppConfig(app_config);-- // If resumed, we don't need to instantiate the UI elements,- // and we should read in th existing values from the kernel.- if (resumed) {- for (const [objectId, value] of Objects.entries(ui_values || {})) {- UI_ELEMENT_REGISTRY.set(objectId, value);- }- return;- }-- // Auto-instantiate, in future this can be configurable- // or include initial values- const objectIds: string[] = [];- const values: unknown[] = [];- // If we already have values for some objects, we should- // send them to the kernel. This may happen after re-connecting- // to the kernel after the computer wakes from sleep.- UI_ELEMENT_REGISTRY.entries.forEach((entry, objectId) => {- objectIds.push(objectId);- values.push(entry.value);- });- // Send the instantiate message- if (autoInstantiate) {- // Start the run- RuntimeState.INSTANCE.registerRunStart();- sendInstantiate({ objectIds, values }).catch((error) => {- RuntimeState.INSTANCE.registerRunEnd();- showBoundary(new Error("Failed to instantiate", { cause: error }));- });- }return;- }+case "completed-run":+ handleCompletedRun();+ return;case "interrupted":- if (msg.op === "completed-run") {- RuntimeState.INSTANCE.registerRunEnd();- }-- if (!RuntimeState.INSTANCE.running()) {- RuntimeState.INSTANCE.flushUpdates();- }+ handleInterrupted();return;- case "remove-ui-elements": {- // This removes the element from the registry to (1) clean-up- // memory and (2) make sure that the old value doesn't get re-used- // if the same cell-id is later reused for another element.- const { cell_id } = msg.data;- UI_ELEMENT_REGISTRY.removeElementsByCell(cell_id);- VirtualFileTracker.INSTANCE.removeForCellId(cell_id);++ case "remove-ui-elements":+ handleRemoveUIElements(msg.data);return;- }+case "completion-result":AUTOCOMPLETER.resolve(msg.data.completion_id, msg.data);return;case "function-call-result":FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);return;- case "cell-op": {- /* Register a state transition for a cell.- *- * The cell may have a new output, a new console output,- * it may have been queued, it may have started running, or- * it may have stopped running. Each of these things- * affects how the cell should be rendered.- */- const body = msg.data;- handleCellMessage({ cellId: body.cell_id, message: body });- VirtualFileTracker.INSTANCE.track(body);+ case "cell-op":+ handleCellOperation(msg.data, handleCellMessage);return;- }+case "variables":setVariables(msg.data.variables.map((v) => ({@@ -227,41 +138,22 @@ export function useMarimoWebSocket(opts: {kind: "installing",});return;- case "query-params-append": {- const url = new URL(window.location.href);- url.searchParams.append(msg.data.key, msg.data.value);- window.history.pushState({}, "", `${url.pathname}${url.search}`);+ case "query-params-append":+ queryParamHandlers.append(msg.data);return;- }- case "query-params-set": {- const url = new URL(window.location.href);- if (Array.isArray(msg.data.value)) {- url.searchParams.delete(msg.data.key);- msg.data.value.forEach((v) =>- url.searchParams.append(msg.data.key, v),- );- } else {- url.searchParams.set(msg.data.key, msg.data.value);- }- window.history.pushState({}, "", `${url.pathname}${url.search}`);++ case "query-params-set":+ queryParamHandlers.set(msg.data);return;- }- case "query-params-delete": {- const url = new URL(window.location.href);- if (msg.data.value == null) {- url.searchParams.delete(msg.data.key);- } else {- url.searchParams.delete(msg.data.key, msg.data.value);- }- window.history.pushState({}, "", `${url.pathname}${url.search}`);++ case "query-params-delete":+ queryParamHandlers.delete(msg.data);return;- }- case "query-params-clear": {- const url = new URL(window.location.href);- url.search = "";- window.history.pushState({}, "", `${url.pathname}${url.search}`);++ case "query-params-clear":+ queryParamHandlers.clear();return;- }+default:logNever(msg);}diff --git a/frontend/src/css/App.css b/frontend/src/css/app/App.csssimilarity index 83%rename from frontend/src/css/App.cssrename to frontend/src/css/app/App.cssindex 3d7cf0b854..af01520896 100644--- a/frontend/src/css/App.css+++ b/frontend/src/css/app/App.css@@ -1,8 +1,9 @@-@import url("./Header.css");+@import url("./reset.css");@import url("./Cell.css");-@import url("./md.css");-@import url("./table.css");@import url("./codemirror.css");+@import url("./fonts.css");+@import url("./Header.css");+@import url("./print.css");/* stylelint-disable unit-allowed-list */@@ -21,9 +22,6 @@ html {:root {--content-width: 740px;--content-width-medium: 1110px;- --monospace-font: "Fira Mono";- --text-font: "PT Sans", sans-serif;- --heading-font: "Lora", serif;}#App {@@ -45,7 +43,7 @@ html {/* Use an image because hard to get consistent result across browsers with* css gradients. */- background-image: url("../assets/gradient.png");+ background-image: url("../../assets/gradient.png");background-repeat: no-repeat;/* Scale gradient with zoom in/out. */@@ -59,7 +57,7 @@ html {width: 100vw;height: 100vh;z-index: -1;- background-image: url("../assets/noise.png");+ background-image: url("../../assets/noise.png");background-repeat: repeat;opacity: 0.5;}diff --git a/frontend/src/css/Cell.css b/frontend/src/css/app/Cell.csssimilarity index 100%rename from frontend/src/css/Cell.cssrename to frontend/src/css/app/Cell.cssdiff --git a/frontend/src/css/Header.css b/frontend/src/css/app/Header.csssimilarity index 100%rename from frontend/src/css/Header.cssrename to frontend/src/css/app/Header.cssdiff --git a/frontend/src/css/codemirror.css b/frontend/src/css/app/codemirror.csssimilarity index 100%rename from frontend/src/css/codemirror.cssrename to frontend/src/css/app/codemirror.cssdiff --git a/frontend/src/css/fonts.css b/frontend/src/css/app/fonts.csssimilarity index 66%rename from frontend/src/css/fonts.cssrename to frontend/src/css/app/fonts.cssindex 4d14f0aead..a0f311879e 100644--- a/frontend/src/css/fonts.css+++ b/frontend/src/css/app/fonts.css@@ -6,7 +6,7 @@ see frontend/src/core/static/download-html.ts */font-style: normal;font-weight: 400;font-display: block;- src: url("../fonts/Lora/Lora-VariableFont_wght.ttf") format("truetype");+ src: url("../../fonts/Lora/Lora-VariableFont_wght.ttf") format("truetype");}@font-face {@@ -14,7 +14,7 @@ see frontend/src/core/static/download-html.ts */font-style: normal;font-weight: 400;font-display: block;- src: url("../fonts/PT_Sans/PTSans-Regular.ttf") format("truetype");+ src: url("../../fonts/PT_Sans/PTSans-Regular.ttf") format("truetype");}@font-face {@@ -22,7 +22,7 @@ see frontend/src/core/static/download-html.ts */font-style: normal;font-weight: 700;font-display: block;- src: url("../fonts/PT_Sans/PTSans-Bold.ttf") format("truetype");+ src: url("../../fonts/PT_Sans/PTSans-Bold.ttf") format("truetype");}@font-face {@@ -30,7 +30,7 @@ see frontend/src/core/static/download-html.ts */font-style: normal;font-weight: 400;font-display: block;- src: url("../fonts/Fira_Mono/FiraMono-Regular.ttf") format("truetype");+ src: url("../../fonts/Fira_Mono/FiraMono-Regular.ttf") format("truetype");}@font-face {@@ -38,7 +38,7 @@ see frontend/src/core/static/download-html.ts */font-style: normal;font-weight: 500;font-display: block;- src: url("../fonts/Fira_Mono/FiraMono-Medium.ttf") format("truetype");+ src: url("../../fonts/Fira_Mono/FiraMono-Medium.ttf") format("truetype");}@font-face {@@ -46,5 +46,5 @@ see frontend/src/core/static/download-html.ts */font-style: normal;font-weight: 700;font-display: block;- src: url("../fonts/Fira_Mono/FiraMono-Bold.ttf") format("truetype");+ src: url("../../fonts/Fira_Mono/FiraMono-Bold.ttf") format("truetype");}diff --git a/frontend/src/css/app/print.css b/frontend/src/css/app/print.cssnew file mode 100644index 0000000000..d37c75db07--- /dev/null+++ b/frontend/src/css/app/print.css@@ -0,0 +1,18 @@+/* Hide on print+To hide an element on print, add the class `no-print` to it.+When printing, the class `printing` is added to the body element to enable this rule. */+body.printing .no-print {+ display: none !important;+}++body.printing #App {+ /* Full screen print */+ height: fit-content !important;+}++/* When printing the output of a cell, this unset the max-height set by the notebook to capture the full output */+.printing-output {+ max-height: none !important;++ @apply bg-background;+}diff --git a/frontend/src/css/app/reset.css b/frontend/src/css/app/reset.cssnew file mode 100644index 0000000000..db1d1a0cb0--- /dev/null+++ b/frontend/src/css/app/reset.css@@ -0,0 +1,32 @@+html {+ box-sizing: border-box;+}++*,+*::before,+*::after {+ box-sizing: inherit;+}++body {+ margin: 0;+ font-family: var(--text-font);+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+}++#root {+ width: 100%;+ display: flex;+ flex-direction: column;+ min-height: 100vh;+}++code {+ font-family: var(--monospace-font);+}++button {+ padding: 0;+ margin: 0;+}diff --git a/frontend/src/css/common.css b/frontend/src/css/common.cssindex 9604e78d39..0da4a45976 100644--- a/frontend/src/css/common.css+++ b/frontend/src/css/common.css@@ -20,30 +20,3 @@.hover-action {display: inline-flex !important;}--/* Hide on print-To hide an element on print, add the class `no-print` to it.-When printing, the class `printing` is added to the body element to enable this rule. */-body.printing .no-print {- display: none !important;-}--body.printing #App {- /* Full screen print */- height: fit-content !important;-}--/* When printing the output of a cell, this unset the max-height set by the notebook to capture the full output */-.printing-output {- max-height: none !important;-- @apply bg-background;-}--a.hyperlink {- @apply text-link;-}--a.hyperlink:hover {- text-decoration: underline;-}diff --git a/frontend/src/css/globals.css b/frontend/src/css/globals.cssindex b1ce021102..1e60b4de5a 100644--- a/frontend/src/css/globals.css+++ b/frontend/src/css/globals.css@@ -24,9 +24,14 @@@tailwind utilities;@layer base {- :root {+ :root,+ .marimo {color-scheme: light;+ --monospace-font: "Fira Mono";+ --text-font: "PT Sans", sans-serif;+ --heading-font: "Lora", serif;+/* Radix light colors for reference: https://github.com/radix-ui/colors/blob/main/src/light.ts */--background: 0 0% 100%;@@ -171,16 +176,20 @@@apply border-border;}- body {+ body,+ .marimo {@apply bg-background text-foreground;font-feature-settings:"rlig" 1,"calt" 1;}-}-button {- padding: 0;- margin: 0;+ a.hyperlink {+ @apply text-link;+ }++ a.hyperlink:hover {+ text-decoration: underline;+ }}diff --git a/frontend/src/css/index.css b/frontend/src/css/index.cssindex 4e8931bba2..5ccc2e8910 100644--- a/frontend/src/css/index.css+++ b/frontend/src/css/index.css@@ -1,33 +1,7 @@-@import url("./fonts.css");-@import url("./common.css");@import url("./globals.css");@import url("./codehilite.css");+@import url("./common.css");+@import url("./katex-fonts.css");@import url("./katex.min.css");--html {- box-sizing: border-box;-}--*,-*::before,-*::after {- box-sizing: inherit;-}--body {- margin: 0;- font-family: var(--text-font);- -webkit-font-smoothing: antialiased;- -moz-osx-font-smoothing: grayscale;-}--#root {- width: 100%;- display: flex;- flex-direction: column;- min-height: 100vh;-}--code {- font-family: var(--monospace-font);-}+@import url("./md.css");+@import url("./table.css");diff --git a/frontend/src/css/katex-fonts.css b/frontend/src/css/katex-fonts.cssnew file mode 100644index 0000000000..82e2f6e68c--- /dev/null+++ b/frontend/src/css/katex-fonts.css@@ -0,0 +1,214 @@+@font-face {+ font-family: "KaTeX_AMS";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_AMS-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_AMS-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_AMS-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Caligraphic";+ font-style: normal;+ font-display: block;+ font-weight: 700;+ src:+ url("../fonts/KaTeX/KaTeX_Caligraphic-Bold.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Caligraphic-Bold.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Caligraphic-Bold.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Caligraphic";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Caligraphic-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Caligraphic-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Caligraphic-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Fraktur";+ font-style: normal;+ font-display: block;+ font-weight: 700;+ src:+ url("../fonts/KaTeX/KaTeX_Fraktur-Bold.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Fraktur-Bold.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Fraktur-Bold.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Fraktur";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Fraktur-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Fraktur-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Fraktur-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Main";+ font-style: normal;+ font-display: block;+ font-weight: 700;+ src:+ url("../fonts/KaTeX/KaTeX_Main-Bold.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Main-Bold.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Main-Bold.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Main";+ font-style: italic;+ font-weight: 700;+ src:+ url("../fonts/KaTeX/KaTeX_Main-BoldItalic.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Main-BoldItalic.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Main-BoldItalic.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Main";+ font-style: italic;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Main-Italic.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Main-Italic.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Main-Italic.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Main";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Main-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Main-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Main-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Math";+ font-style: italic;+ font-weight: 700;+ src:+ url("../fonts/KaTeX/KaTeX_Math-BoldItalic.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Math-BoldItalic.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Math-BoldItalic.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Math";+ font-style: italic;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Math-Italic.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Math-Italic.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Math-Italic.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_SansSerif";+ font-style: normal;+ font-display: block;+ font-weight: 700;+ src:+ url("../fonts/KaTeX/KaTeX_SansSerif-Bold.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_SansSerif-Bold.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_SansSerif-Bold.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_SansSerif";+ font-style: italic;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_SansSerif-Italic.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_SansSerif-Italic.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_SansSerif-Italic.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_SansSerif";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_SansSerif-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_SansSerif-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_SansSerif-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Script";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Script-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Script-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Script-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Size1";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Size1-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Size1-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Size1-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Size2";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Size2-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Size2-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Size2-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Size3";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Size3-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Size3-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Size3-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Size4";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Size4-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Size4-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Size4-Regular.ttf") format("truetype");+}++@font-face {+ font-family: "KaTeX_Typewriter";+ font-style: normal;+ font-display: block;+ font-weight: 400;+ src:+ url("../fonts/KaTeX/KaTeX_Typewriter-Regular.woff2") format("woff2"),+ url("../fonts/KaTeX/KaTeX_Typewriter-Regular.woff") format("woff"),+ url("../fonts/KaTeX/KaTeX_Typewriter-Regular.ttf") format("truetype");+}diff --git a/frontend/src/css/katex.min.css b/frontend/src/css/katex.min.cssindex 558936fc2b..45cf558d0d 100644--- a/frontend/src/css/katex.min.css+++ b/frontend/src/css/katex.min.css@@ -1,220 +1,5 @@/* Slightly adapted from https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css */-@font-face {- font-family: "KaTeX_AMS";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_AMS-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_AMS-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_AMS-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Caligraphic";- font-style: normal;- font-display: block;- font-weight: 700;- src:- url("../fonts/KaTeX/KaTeX_Caligraphic-Bold.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Caligraphic-Bold.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Caligraphic-Bold.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Caligraphic";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Caligraphic-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Caligraphic-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Caligraphic-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Fraktur";- font-style: normal;- font-display: block;- font-weight: 700;- src:- url("../fonts/KaTeX/KaTeX_Fraktur-Bold.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Fraktur-Bold.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Fraktur-Bold.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Fraktur";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Fraktur-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Fraktur-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Fraktur-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Main";- font-style: normal;- font-display: block;- font-weight: 700;- src:- url("../fonts/KaTeX/KaTeX_Main-Bold.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Main-Bold.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Main-Bold.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Main";- font-style: italic;- font-weight: 700;- src:- url("../fonts/KaTeX/KaTeX_Main-BoldItalic.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Main-BoldItalic.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Main-BoldItalic.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Main";- font-style: italic;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Main-Italic.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Main-Italic.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Main-Italic.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Main";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Main-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Main-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Main-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Math";- font-style: italic;- font-weight: 700;- src:- url("../fonts/KaTeX/KaTeX_Math-BoldItalic.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Math-BoldItalic.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Math-BoldItalic.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Math";- font-style: italic;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Math-Italic.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Math-Italic.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Math-Italic.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_SansSerif";- font-style: normal;- font-display: block;- font-weight: 700;- src:- url("../fonts/KaTeX/KaTeX_SansSerif-Bold.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_SansSerif-Bold.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_SansSerif-Bold.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_SansSerif";- font-style: italic;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_SansSerif-Italic.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_SansSerif-Italic.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_SansSerif-Italic.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_SansSerif";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_SansSerif-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_SansSerif-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_SansSerif-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Script";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Script-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Script-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Script-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Size1";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Size1-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Size1-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Size1-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Size2";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Size2-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Size2-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Size2-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Size3";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Size3-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Size3-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Size3-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Size4";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Size4-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Size4-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Size4-Regular.ttf") format("truetype");-}--@font-face {- font-family: "KaTeX_Typewriter";- font-style: normal;- font-display: block;- font-weight: 400;- src:- url("../fonts/KaTeX/KaTeX_Typewriter-Regular.woff2") format("woff2"),- url("../fonts/KaTeX/KaTeX_Typewriter-Regular.woff") format("woff"),- url("../fonts/KaTeX/KaTeX_Typewriter-Regular.ttf") format("truetype");-}-.katex {text-rendering: auto;font-family: "KaTeX_Main", "Times New Roman", serif;diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex a317977271..ccb72f4108 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -43,6 +43,7 @@ import { PluginFunctions } from "./rpc";import { ZodSchema } from "zod";import useEvent from "react-use-event-hook";import { Functions } from "@/utils/functions";+import { StyleNamespace } from "@/theme/namespace";export interface PluginSlotHandle {/**@@ -188,18 +189,20 @@ function PluginSlotInternal<T>(// Render the pluginreturn (- <div className={`contents ${theme}`}>- <Suspense fallback={<div />}>- {plugin.render({- setValue: setValueAndSendInput,- value,- data: parsedResult.data,- children: childNodes,- host: hostElement,- functions: functionMethods,- })}- </Suspense>- </div>+ <StyleNamespace>+ <div className={`contents ${theme}`}>+ <Suspense fallback={<div />}>+ {plugin.render({+ setValue: setValueAndSendInput,+ value,+ data: parsedResult.data,+ children: childNodes,+ host: hostElement,+ functions: functionMethods,+ })}+ </Suspense>+ </div>+ </StyleNamespace>);}@@ -341,6 +344,9 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {invariant(shadowRoot, "Shadow root should exist");// If we don't support adopted stylesheets, we need to copy the stylesif (!this.isAdoptedStyleSheetsSupported()) {+ Logger.warn(+ "adoptedStyleSheets not supported, copying stylesheets in a less performance way. Please consider upgrading your browser.",+ );this.copyStylesFallback();return;}@@ -444,7 +450,7 @@ function shouldCopyStyleSheet(sheet: CSSStyleSheet): boolean {return true;}- if (sheet.href.includes("@marimo-team/frontend")) {+ if (sheet.href.includes("/@marimo-team/")) {return true;}diff --git a/frontend/src/plugins/impl/FileBrowserPlugin.tsx b/frontend/src/plugins/impl/FileBrowserPlugin.tsxindex 5991c908e7..429ceaacbe 100644--- a/frontend/src/plugins/impl/FileBrowserPlugin.tsx+++ b/frontend/src/plugins/impl/FileBrowserPlugin.tsx@@ -15,6 +15,7 @@ import {import { renderHTML } from "../core/RenderHTML";import { PathBuilder, Paths } from "@/utils/paths";import { CornerLeftUp } from "lucide-react";+import { Logger } from "@/utils/Logger";/*** Arguments for a file browser component.@@ -128,7 +129,7 @@ export const FileBrowser = ({);if (error) {- console.error(error);+ Logger.error(error);toast({title: `Could not load files in directory ${path}`,description: error.message,diff --git a/frontend/src/plugins/impl/FileUploadPlugin.tsx b/frontend/src/plugins/impl/FileUploadPlugin.tsxindex be86380fe5..96c232e680 100644--- a/frontend/src/plugins/impl/FileUploadPlugin.tsx+++ b/frontend/src/plugins/impl/FileUploadPlugin.tsx@@ -10,6 +10,7 @@ import { buttonVariants } from "../../components/ui/button";import { renderHTML } from "../core/RenderHTML";import { toast } from "@/components/ui/use-toast";import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";+import { Logger } from "@/utils/Logger";type FileUploadType = "button" | "area";@@ -132,7 +133,7 @@ export const FileUpload = (props: FileUploadProps): JSX.Element => {multiple: multiple,maxSize: MAX_SIZE,onError: (error) => {- console.error(error);+ Logger.error(error);toast({title: "File upload failed",description: error.message,@@ -161,7 +162,7 @@ export const FileUpload = (props: FileUploadProps): JSX.Element => {setValue(value);}).catch((error) => {- console.error(error);+ Logger.error(error);toast({title: "File upload failed",description: "Failed to convert file to base64.",diff --git a/frontend/src/plugins/impl/data-explorer/state/reducer.ts b/frontend/src/plugins/impl/data-explorer/state/reducer.tsindex baed3f636c..026c62eafd 100644--- a/frontend/src/plugins/impl/data-explorer/state/reducer.ts+++ b/frontend/src/plugins/impl/data-explorer/state/reducer.ts@@ -1,10 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */import { SpecificEncoding } from "../encoding";-import { createReducer } from "@/utils/createReducer";+import { createReducerAndAtoms } from "@/utils/createReducer";import { ChartSpec } from "./types";import { SHORT_WILDCARD } from "compassql/build/src/wildcard";-import { atom, useSetAtom } from "jotai";-import { useMemo } from "react";+import { atom } from "jotai";import {mainViewResult,allRelatedViewResults,@@ -31,44 +30,36 @@ function initialState(): ChartSpec {};}-const { reducer, createActions } = createReducer(initialState, {- setSchema: (state, schema: Schema) => {- return { ...state, schema };- },- setMark: (state, mark: SpecMark) => {- return { ...state, mark };- },- setEncoding: (state, encoding: SpecificEncoding) => {- // Merge and remove undefined values- const nextEncoding = removeUndefined({- ...state.encoding,- ...encoding,- });+const { valueAtom: chartSpecAtom, useActions } = createReducerAndAtoms(+ initialState,+ {+ setSchema: (state, schema: Schema) => {+ return { ...state, schema };+ },+ setMark: (state, mark: SpecMark) => {+ return { ...state, mark };+ },+ setEncoding: (state, encoding: SpecificEncoding) => {+ // Merge and remove undefined values+ const nextEncoding = removeUndefined({+ ...state.encoding,+ ...encoding,+ });- return { ...state, encoding: nextEncoding };- },- set: (state, next: ChartSpec) => {- // remove schema- const { schema, ...rest } = next;- return { ...state, ...rest };+ return { ...state, encoding: nextEncoding };+ },+ set: (state, next: ChartSpec) => {+ // remove schema+ const { schema, ...rest } = next;+ return { ...state, ...rest };+ },},-});--export const chartSpecAtom = atom<ChartSpec>(initialState());+);-export function useChartSpecActions(onChange?: (spec: ChartSpec) => void) {- const setState = useSetAtom(chartSpecAtom);+export { chartSpecAtom };- return useMemo(() => {- const actions = createActions((action) => {- setState((state) => {- const newState = reducer(state, action);- onChange?.(newState);- return newState;- });- });- return actions;- }, [setState, onChange]);+export function useChartSpecActions() {+ return useActions();}export const relatedChartSpecsAtom = atom<Partial<ResultingCharts>>((get) => {diff --git a/frontend/src/theme/namespace.tsx b/frontend/src/theme/namespace.tsxnew file mode 100644index 0000000000..f911d16252--- /dev/null+++ b/frontend/src/theme/namespace.tsx@@ -0,0 +1,18 @@+/* Copyright 2024 Marimo. All rights reserved. */+import React, { PropsWithChildren } from "react";++const style = {+ display: "contents",+};++/**+ * Adds the 'marimo' className which serves as a namespace to its children,+ * so that the styles are scoped to the DOM subtree.+ */+export const StyleNamespace: React.FC<PropsWithChildren> = ({ children }) => {+ return (+ <div className="marimo" style={style}>+ {children}+ </div>+ );+};diff --git a/frontend/src/theme/useTheme.ts b/frontend/src/theme/useTheme.tsindex 548a0505eb..d9bbe062fd 100644--- a/frontend/src/theme/useTheme.ts+++ b/frontend/src/theme/useTheme.ts@@ -18,6 +18,9 @@ function setupThemeListener(): void {if (typeof window === "undefined") {return;}+ if (!window.matchMedia) {+ return;+ }const media = window.matchMedia("(prefers-color-scheme: dark)");store.set(prefersDarkModeAtom, media.matches);diff --git a/frontend/src/utils/createReducer.ts b/frontend/src/utils/createReducer.tsindex c6b1eeecf0..f81dc67f06 100644--- a/frontend/src/utils/createReducer.ts+++ b/frontend/src/utils/createReducer.ts@@ -2,7 +2,8 @@/* eslint-disable @typescript-eslint/no-explicit-any */import { Logger } from "@/utils/Logger";import { NoInfer } from "@tanstack/react-table";-import { Reducer } from "react";+import { atom, useSetAtom } from "jotai";+import { Reducer, useMemo } from "react";interface ReducerAction<T> {type: string;@@ -66,3 +67,25 @@ export function createReducer<},};}++export function createReducerAndAtoms<+ State,+ RH extends ReducerHandlers<NoInfer<State>>,+>(initialState: () => State, reducers: RH) {+ const { reducer, createActions } = createReducer(initialState, reducers);++ const valueAtom = atom(initialState());++ function useActions() {+ const setState = useSetAtom(valueAtom);++ return useMemo(() => {+ const actions = createActions((action) => {+ setState((state) => reducer(state, action));+ });+ return actions;+ }, [setState]);+ }++ return { reducer, createActions, valueAtom, useActions };+}diff --git a/frontend/src/utils/functions.ts b/frontend/src/utils/functions.tsindex aa9cb3d810..15c7ba6bf9 100644--- a/frontend/src/utils/functions.ts+++ b/frontend/src/utils/functions.ts@@ -15,3 +15,7 @@ export const Functions = {: () => updater;},};++export function throwNotImplemented(): never {+ throw new Error("Not implemented");+}diff --git a/frontend/src/utils/json/json-parser.ts b/frontend/src/utils/json/json-parser.tsindex e257b6f8b3..0a63ed0456 100644--- a/frontend/src/utils/json/json-parser.ts+++ b/frontend/src/utils/json/json-parser.ts@@ -1,10 +1,14 @@/* Copyright 2024 Marimo. All rights reserved. */+import { JsonString } from "./base64";+/*** Parse an attribute value as JSON.* This also handles NaN, Infinity, and -Infinity.*/-export function jsonParseWithSpecialChar<T>(value: string): T {+export function jsonParseWithSpecialChar<T = unknown>(+ value: JsonString<T> | string,+): T {// This regex handling is expensive and often not needed.// We try to parse with JSON.parse first, and if that fails, we use the regex.try {diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.jsindex 9eea6af4dd..85fd5c4796 100644--- a/frontend/tailwind.config.js+++ b/frontend/tailwind.config.js@@ -118,10 +118,17 @@ module.exports = {from: { height: "var(--radix-accordion-content-height)" },to: { height: 0 },},+ "delayed-show": {+ "0%": { opacity: 0 },+ "99%": { opacity: 0 },+ "100%": { opacity: 1 },+ },},animation: {"accordion-down": "accordion-down 0.2s ease-out","accordion-up": "accordion-up 0.2s ease-out",+ "delayed-show-200": "delayed-show 200ms ease-out",+ "delayed-show-400": "delayed-show 400ms ease-out",},},},diff --git a/frontend/turbo.json b/frontend/turbo.jsonindex 6a6a8d3f90..9a2b8c47a8 100644--- a/frontend/turbo.json+++ b/frontend/turbo.json@@ -2,7 +2,8 @@"$schema": "https://turbo.build/schema.json","pipeline": {"build": {- "outputs": ["dist/**"]+ "outputs": ["dist/**"],+ "env": ["VITE_MARIMO_ISLANDS"]},"typecheck": {},"test": {},@@ -10,6 +11,10 @@"build-storybook": {"outputs": ["storybook-static/**"]},+ "build:islands": {+ "outputs": ["dist/**"],+ "env": ["VITE_MARIMO_ISLANDS", "VITE_MARIMO_VERSION"]+ },"dev": {"cache": false,"persistent": truediff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 8f042dd78b..a9a9a2355a 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -108,6 +108,9 @@ export default defineConfig({resolve: {dedupe: ["react", "react-dom", "@emotion/react", "@emotion/cache"],},+ worker: {+ plugins: () => [tsconfigPaths()],+ },plugins: [htmlDevPlugin(),react({diff --git a/marimo/__init__.py b/marimo/__init__.pyindex 15937eaa69..4f37b4f8c9 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -17,6 +17,7 @@ __all__ = ["Cell","MarimoStopError","create_asgi_app",+ "experimental_MarimoIslandGenerator","accordion","carousel","as_html",@@ -62,6 +63,9 @@ __version__ = "0.4.2"from marimo._ast.app import Appfrom marimo._ast.cell import Cell+from marimo._islands.island_generator import (+ MarimoIslandGenerator as experimental_MarimoIslandGenerator,+)from marimo._output.doc import docfrom marimo._output.formatting import as_htmlfrom marimo._output.hypertext import Htmldiff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 9ff9161fac..e7437ab4d3 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -497,6 +497,15 @@ class CellManager:def cell_data_at(self, cell_id: CellId_t) -> CellData:return self._cell_data[cell_id]+ def get_cell_id_by_code(self, code: str) -> Optional[CellId_t]:+ """+ Finds the first cell with the given code and returns its cell ID.+ """+ for cell_id, cell_data in self._cell_data.items():+ if cell_data.code == code:+ return cell_id+ return None+class InternalApp:"""diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 0e8d8a6e79..9fc6164270 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport dataclassesimport inspect-from typing import TYPE_CHECKING, Any, Callable, Literal, Mapping, Optional+from typing import TYPE_CHECKING, Any, Literal, Mapping, Optionalfrom marimo._ast.visitor import ImportData, Name, VariableDatafrom marimo._utils.deep_merge import deep_merge@@ -215,7 +215,7 @@ class Cell:"""# Function from which this cell was created- _f: Callable[..., Any]+ _name: str# Internal cell representation_cell: CellImpl@@ -225,7 +225,7 @@ class Cell:@propertydef name(self) -> str:- return self._f.__name__+ return self._name@propertydef refs(self) -> set[str]:diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 3ec4a84961..daba7ca28c 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import astimport inspectimport io@@ -220,4 +222,6 @@ def cell_factory(# handle return written on same line as last statement in cellcell_code += "\n" + lines[end_line][:return_offset]- return Cell(_f=f, _cell=compile_cell(cell_code, cell_id=cell_id))+ return Cell(+ _name=f.__name__, _cell=compile_cell(cell_code, cell_id=cell_id)+ )diff --git a/marimo/_islands/island_generator.py b/marimo/_islands/island_generator.pynew file mode 100644index 0000000000..72bac1da3c--- /dev/null+++ b/marimo/_islands/island_generator.py@@ -0,0 +1,249 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from textwrap import dedent+from typing import List, Optional, cast++from marimo import __version__, _loggers+from marimo._ast.app import App, InternalApp+from marimo._ast.cell import Cell, CellConfig+from marimo._ast.compiler import compile_cell+from marimo._output.utils import uri_encode_component+from marimo._server.export.utils import run_app_until_completion+from marimo._server.file_manager import AppFileManager+from marimo._server.sessions import Session++LOGGER = _loggers.marimo_logger()+++class MarimoIslandStub:+ def __init__(self, *, cell_id: str, app_id: str, code: str):+ self._cell_id = cell_id+ self._app_id = app_id+ self._code = code+ self._internal_app: Optional[InternalApp] = None+ self._session: Optional[Session] = None++ @property+ def code(self) -> str:+ return self._code++ def render(+ self, include_code: bool = True, include_output: bool = True+ ) -> str:+ """+ Render the HTML island code for the cell.++ *Args:*++ - include_code (bool): Whether to include the code in the HTML.+ - include_output (bool): Whether to include the output in the HTML.++ *Returns:*++ - str: The HTML code.+ """+ assert (+ self._internal_app is not None+ ), "You must call build() before rendering"+ assert (+ self._session is not None+ ), "You must call build() before rendering"++ if include_code is False and include_output is False:+ raise ValueError("You must include either code or output")++ outputs = self._session.session_view.get_cell_outputs([self._cell_id])+ output = outputs.get(self._cell_id, None)++ # Cell may not have output+ # (e.g. imports, but still needs to be included)+ return remove_empty_lines(+ dedent(+ f"""+ <marimo-island+ data-app-id="{self._app_id}"+ data-cell-id="{self._cell_id}"+ >+ <marimo-cell-output>+ {output.data if output and include_output else ""}+ </marimo-cell-output>+ <marimo-cell-code hidden>+ {uri_encode_component(self.code) if include_code else ""}+ </marimo-cell-code>+ </marimo-island>+ """+ ).strip()+ )+++class MarimoIslandGenerator:+ """+ Generates Marimo islands for embedding in other pages.++ This is a great way to use another SSG framework that converts+ Python code to HTML using marimo-islands.++ Generally you will want to:++ 1. Find all the code snippets and add them to the generator.+ 2. Build the app.+ 3. Replace all code snippets with the rendered HTML.+ 4. Include the header in the <head> tag.++ # Example++ ```python+ from marimo import MarimoIslandGenerator++ generator = MarimoIslandGenerator()+ block1 = generator.add_code("import marimo as mo")+ block2 = generator.add_code("mo.md('Hello, islands!')")++ # Build the app+ app = await generator.build()++ # Render the app+ output = f\"\"\"+ <html>+ <head>+ {generator.render_head()}+ </head>+ <body>+ {block1.render(include_output=False)}+ {block2.render()}+ </body>+ </html>+ \"\"\"+ ```+ """++ def __init__(self, app_id: str = "main"):+ self.has_run = False+ self._app_id = app_id+ self._app = InternalApp(App())+ self._stubs: List[MarimoIslandStub] = []++ def add_code(+ self,+ code: str,+ ) -> MarimoIslandStub:+ """Add a code cell to the app.++ *Args:*++ - code (str): The code to add to the app.+ """++ cell_id = self._app.cell_manager.create_cell_id()+ cell_impl = compile_cell(dedent(code), cell_id)+ cell_impl.configure(CellConfig(disabled=False, hide_code=False))+ cell = Cell(_name="__", _cell=cell_impl)++ self._app.cell_manager._register_cell(+ cell,+ app=self._app,+ )++ stub = MarimoIslandStub(+ cell_id=cell_id,+ app_id=self._app_id,+ code=code,+ )+ self._stubs.append(stub)++ return stub++ async def build(self) -> App:+ """+ Build the app. This should be called after adding all the code cells.++ *Returns:*++ - App: The built app.+ """++ if self.has_run:+ raise ValueError("You can only call build() once")++ session = await run_app_until_completion(+ file_manager=AppFileManager.from_app(self._app),+ cli_args={},+ )+ self.has_run = True++ for stub in self._stubs:+ stub._internal_app = self._app+ stub._session = session++ return cast(App, self._app)++ def render_head(+ self,+ *,+ version_override: str = __version__,+ _development_url: bool = False,+ ) -> str:+ """+ Render the header for the app.+ This should be included in the <head> tag of the page.+ """++ # This loads:+ # - The marimo islands js+ # - The marimo islands css+ # - Preconnects to Google Fonts (https://stackoverflow.com/questions/73838138)+ # - Fonts from Google Fonts+ # (otherwise they would get bundled in the css)+ # - Fonts from KaTeX+ # (otherwise they would get bundled in the css)++ base_url = f"https://cdn.jsdelivr.net/npm/@marimo-team/islands@{version_override}"+ # This should be kept in sync fonts.css in the frontend+ # Since this is embedded on other pages, we want display=swap+ # for the most compatible font loading+ font_url = "https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap"++ fonts = f"""+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link+ rel="preconnect"+ href="https://fonts.gstatic.com"+ crossorigin+ />+ <link href="{font_url}" rel="stylesheet" />+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"+ crossorigin="anonymous"+ />+ """.strip()++ if _development_url:+ base_url = "http://localhost:5174"+ return dedent(+ f"""+ <script+ type="module"+ src="{base_url}/src/core/islands/main.ts"+ ></script>+ {fonts}+ """+ ).strip()++ return dedent(+ f"""+ <script src="{base_url}/dist/main.js"></script>+ <link+ href="{base_url}/dist/styles.css"+ rel="stylesheet"+ crossorigin="anonymous"+ />+ {fonts}+ """+ ).strip()+++def remove_empty_lines(text: str) -> str:+ return "\n".join([line for line in text.split("\n") if line.strip() != ""])diff --git a/marimo/_output/utils.py b/marimo/_output/utils.pyindex e592b3c301..4e9e92307c 100644--- a/marimo/_output/utils.py+++ b/marimo/_output/utils.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import urllib.parsefrom typing import Optional, Unionfrom marimo._messaging.mimetypes import KnownMimeType@@ -22,3 +23,8 @@ def create_style(return Nonereturn ";".join([f"{k}: {v}" for k, v in pairs.items() if v is not None])+++def uri_encode_component(code: str) -> str:+ """Equivalent to `encodeURIComponent` in JavaScript."""+ return urllib.parse.quote(code, safe="~()*!.'")diff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.pyindex 0d231bb886..c2d0c5a8dc 100644--- a/marimo/_server/export/utils.py+++ b/marimo/_server/export/utils.py@@ -9,6 +9,7 @@ from marimo._messaging.ops import MessageOperationfrom marimo._messaging.types import KernelMessagefrom marimo._runtime.requests import AppMetadata, SerializedCLIArgsfrom marimo._server.export.exporter import Exporter+from marimo._server.file_manager import AppFileManagerfrom marimo._server.file_router import AppFileRouterfrom marimo._server.model import ConnectionState, SessionConsumer, SessionModefrom marimo._server.models.export import ExportAsHTMLRequest@@ -19,7 +20,7 @@ from marimo._server.sessions import Sessionasync def run_app_then_export_as_html(filename: str,include_code: bool,- cli_args: SerializedCLIArgs | None = None,+ cli_args: SerializedCLIArgs,) -> tuple[str, str]:# Create a file router and file managerfile_router = AppFileRouter.from_filename(filename)@@ -27,6 +28,28 @@ async def run_app_then_export_as_html(assert file_key is not Nonefile_manager = file_router.get_file_manager(file_key)+ config = UserConfigManager()+ session = await run_app_until_completion(file_manager, cli_args)++ # Export the session as HTML+ html, filename = Exporter().export_as_html(+ file_manager=session.app_file_manager,+ session_view=session.session_view,+ display_config=config.get_config()["display"],+ request=ExportAsHTMLRequest(+ include_code=include_code,+ download=False,+ files=[],+ ),+ )++ return html, filename+++async def run_app_until_completion(+ file_manager: AppFileManager,+ cli_args: SerializedCLIArgs,+) -> Session:instantiated_event = asyncio.Event()# Create a no-op session consumer@@ -56,13 +79,14 @@ async def run_app_then_export_as_html(# Create a sessionsession = Session.create(- initialization_id=file_key,+ # Any initialization ID will do+ initialization_id="_any_",session_consumer=NoopSessionConsumer(),mode=SessionMode.RUN,app_metadata=AppMetadata(query_params={},filename=file_manager.path,- cli_args=cli_args if cli_args is not None else {},+ cli_args=cli_args,),app_file_manager=file_manager,user_config_manager=config,@@ -73,16 +97,4 @@ async def run_app_then_export_as_html(session.instantiate(InstantiateRequest(object_ids=[], values=[]))await instantiated_event.wait()- # Export the session as HTML- html, filename = Exporter().export_as_html(- file_manager=session.app_file_manager,- session_view=session.session_view,- display_config=config.get_config()["display"],- request=ExportAsHTMLRequest(- include_code=include_code,- download=False,- files=[],- ),- )-- return html, filename+ return sessiondiff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 1978d3c3e8..72b83ef3c3 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport base64import json-import urllib.parsefrom typing import List, Optionalfrom marimo import __version__@@ -11,6 +10,7 @@ from marimo._ast.app import _AppConfigfrom marimo._ast.cell import CellConfig, CellId_tfrom marimo._config.config import MarimoConfigfrom marimo._messaging.cell_output import CellOutput+from marimo._output.utils import uri_encode_componentfrom marimo._server.api.utils import parse_titlefrom marimo._server.model import SessionMode@@ -124,7 +124,7 @@ def static_notebook_template(code_block = f"""<marimo-code hidden="">- {urllib.parse.quote(code)}+ {uri_encode_component(code)}</marimo-code>"""if not code:@@ -148,7 +148,7 @@ def static_notebook_template(def _serialize_to_base64(value: str) -> str:# Encode the JSON string to URL-encoded format- url_encoded = urllib.parse.quote(value)+ url_encoded = uri_encode_component(value)# Encode the URL-encoded string to Base64base64_encoded = base64.b64encode(url_encoded.encode()).decode()return base64_encodeddiff --git a/pyproject.toml b/pyproject.tomlindex 6657442aad..6cba8a639a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -282,5 +282,7 @@ wheres = "wheres"[tool.typos.files]extend-exclude = ["MultiSelectPlugin.test.ts",- "module_name_to_pypi_name.py"+ "module_name_to_pypi_name.py",+ "**/snapshots/*",+ "**/__demo__/index.html",]diff --git a/tests/_ast/test_app_cell.py b/tests/_ast/test_app_cell.pyindex ca45997f0a..f3d4a46f08 100644--- a/tests/_ast/test_app_cell.py+++ b/tests/_ast/test_app_cell.py@@ -1,7 +1,6 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import inspectfrom collections.abc import Awaitablefrom marimo._ast.app import App@@ -77,7 +76,7 @@ async def test_decorator_async() -> None:cell = app.cell(__)assert cell is not None- assert inspect.iscoroutinefunction(cell._f)+ assert cell._cell.is_coroutine()assert cell._cell.config.disabled is Falseassert cell.name == "__"diff --git a/tests/_islands/snapshots/header.txt b/tests/_islands/snapshots/header.txtnew file mode 100644index 0000000000..9881349565--- /dev/null+++ b/tests/_islands/snapshots/header.txt@@ -0,0 +1,19 @@+<script src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/main.js"></script>+<link+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/styles.css"+ rel="stylesheet"+ crossorigin="anonymous"+/>+<link rel="preconnect" href="https://fonts.googleapis.com" />+<link+ rel="preconnect"+ href="https://fonts.gstatic.com"+ crossorigin+/>+<link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />+<link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"+ crossorigin="anonymous"+/>\ No newline at end of filediff --git a/tests/_islands/snapshots/islan d-no-code.txt b/tests/_islands/snapshots/islan d-no-code.txtnew file mode 100644index 0000000000..809313e832--- /dev/null+++ b/tests/_islands/snapshots/islan d-no-code.txt@@ -0,0 +1,10 @@+<marimo-island+ data-app-id="main"+ data-cell-id="MJUe"+>+ <marimo-cell-output>+ <span class="markdown"><span class="paragraph">Hello, islands!</span></span>+ </marimo-cell-output>+ <marimo-cell-code hidden>+ </marimo-cell-code>+</marimo-island>\ No newline at end of filediff --git a/tests/_islands/snapshots/island-no-output.txt b/tests/_islands/snapshots/island-no-output.txtnew file mode 100644index 0000000000..fa38e19533--- /dev/null+++ b/tests/_islands/snapshots/island-no-output.txt@@ -0,0 +1,10 @@+<marimo-island+ data-app-id="main"+ data-cell-id="MJUe"+>+ <marimo-cell-output>+ </marimo-cell-output>+ <marimo-cell-code hidden>+ mo.md('Hello%2C%20islands!')+ </marimo-cell-code>+</marimo-island>\ No newline at end of filediff --git a/tests/_islands/snapshots/island.txt b/tests/_islands/snapshots/island.txtnew file mode 100644index 0000000000..47b31199cc--- /dev/null+++ b/tests/_islands/snapshots/island.txt@@ -0,0 +1,11 @@+<marimo-island+ data-app-id="main"+ data-cell-id="MJUe"+>+ <marimo-cell-output>+ <span class="markdown"><span class="paragraph">Hello, islands!</span></span>+ </marimo-cell-output>+ <marimo-cell-code hidden>+ mo.md('Hello%2C%20islands!')+ </marimo-cell-code>+</marimo-island>\ No newline at end of filediff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.pynew file mode 100644index 0000000000..8770aff443--- /dev/null+++ b/tests/_islands/test_island_generator.py@@ -0,0 +1,70 @@+from __future__ import annotations++import pytest++from marimo import __version__+from marimo._islands.island_generator import MarimoIslandGenerator+from tests.mocks import snapshotter++snapshot = snapshotter(__file__)+++def test_add_code():+ generator = MarimoIslandGenerator()+ generator.add_code("print('Hello, World!')")++ # Check if the cell was added+ assert len(list(generator._app.cell_manager.cells())) == 1+++async def test_build():+ generator = MarimoIslandGenerator()+ generator.add_code("print('Hello, World!')")++ # Check if the app is built successfully+ app = await generator.build()+ assert app is not None+ assert generator.has_run is True++ # Check if build() raises an error when called more than once+ with pytest.raises(ValueError):+ await generator.build()+++async def test_render():+ generator = MarimoIslandGenerator()+ block1 = generator.add_code("import marimo as mo")+ block2 = generator.add_code("mo.md('Hello, islands!')")++ # Check if render raises an error when build() is not called+ with pytest.raises(AssertionError) as e:+ block1.render()+ assert "You must call build() before rendering" in str(e.value)++ with pytest.raises(AssertionError) as e:+ block2.render(include_code=False)+ assert "You must call build() before rendering" in str(e.value)++ await generator.build()++ with pytest.raises(ValueError) as e:+ block1.render(include_code=False, include_output=False)+ assert str(e.value) == "You must include either code or output"++ # Check if render works after build() is called+ snapshot("island.txt", block2.render())++ snapshot("islan d-no-code.txt", block2.render(include_code=False))++ snapshot("island-no-output.txt", block2.render(include_output=False))+++async def test_render_head():+ generator = MarimoIslandGenerator()+ generator.add_code("print('Hello, islands!')")+ await generator.build()++ # Check if render_head works after build() is called+ snapshot(+ "header.txt", generator.render_head().replace(__version__, "0.0.0")+ )diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex 433a27656b..d3ce5a46bc 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -66,7 +66,7 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAxJTI3JTI5", "cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAyJTI3JTI5"], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA=="}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA==", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJFcnJvciUyMGluJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"]}};+ window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};</script>@@ -75,7 +75,7 @@<div id="root"></div><marimo-code hidden="">- print%28%27Hello%2C%20World%21%27%29+ print('Hello%2C%20World!')</marimo-code></body></html>diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 2e999704df..df6f09a459 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -66,7 +66,7 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAxJTI3JTI5", "cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAyJTI3JTI5"], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA=="}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA==", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJFcnJvciUyMGluJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"]}};+ window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};</script>@@ -75,7 +75,7 @@<div id="root"></div><marimo-code hidden="">- print%28%27Hello%2C%20World%21%27%29+ print('Hello%2C%20World!')</marimo-code></body></html>