Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: improve loading states while islands are initializing (#2682)

Myles Scolnickf996ffb71bdd
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.md
index ae6ed7d0cb..a9578c4429 100644
--- a/docs/guides/exporting.md
+++ b/docs/guides/exporting.md
@@ -8,7 +8,6 @@ marimo export
## Export to static HTML
-
### Export from a running notebook
Export the current view your notebook to static HTML via the notebook
@@ -111,10 +110,7 @@ In order to use marimo islands, you need to import the necessary JS/CSS headers
```html
<head>
<!-- marimo js/ccs -->
- <script
- type="module"
- src="https://cdn.jsdelivr.net/npm/@marimo-team/islands@<version>/dist/main.js"
- ></script>
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@marimo-team/islands@<version>/dist/main.js"></script>
<link
href="https://cdn.jsdelivr.net/npm/@marimo-team/islands@<version>/dist/style.css"
rel="stylesheet"
diff --git a/frontend/islands/__demo__/index.html b/frontend/islands/__demo__/index.html
index 86113aa90e..8f5c93d3a2 100644
--- a/frontend/islands/__demo__/index.html
+++ b/frontend/islands/__demo__/index.html
@@ -1,94 +1,131 @@
-<!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>
- <script type="module" src="../src/core/islands/main.ts"></script>
+ <!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>
- <style type="text/css">
- marimo-island {
- display: block;
- margin: 2rem;
- }
- </style>
+ <script type="module" 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/style.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&amp;family=Lora&amp;family=PT+Sans:wght@400;700&amp;display=swap"
- rel="stylesheet"
+ rel="preconnect"
+ href="https://fonts.gstatic.com"
+ crossorigin
/>
+ <link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&amp;family=Lora&amp;family=PT+Sans:wght@400;700&amp;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"
+ rel="stylesheet"
+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"
+ crossorigin="anonymous"
/>
- </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="f9c89741-c82c-4139-90a7-5a7408c73a0d"
- ><marimo-slider
- data-initial-value="0"
- data-label="null"
- data-start="0"
- data-stop="100"
- data-step="2"
- data-steps="[]"
- 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>
- %0Aslider%20%3D%20mo.ui.slider(0%2C%20100%2C%202)%0Aslider%0A
- </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: 0</span></span
+ <marimo-filename hidden></marimo-filename>
+<marimo-mode data-mode='read' hidden></marimo-mode>
+
+ <!-- If running a local server of the production build -->
+ <!-- <script type="module" src="http://127.0.0.1:8001/main.js"></script>
+ <link
+ href="http://127.0.0.1:8001/style.css"
+ rel="stylesheet"
+ crossorigin="anonymous"
+ /> -->
+
+ <!-- If running from Vite -->
+ <!-- <script type="module" src="/src/core/islands/main.ts"></script> -->
+ </head>
+ <body>
+
+ <marimo-island
+ data-app-id="main"
+ data-cell-id="Hbol"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <span></span>
+ </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"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <span class="markdown prose dark:prose-invert"><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"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <marimo-ui-element object-id='vblA-0' random-id='eb5f2816-d9cf-4b03-bae6-6c67925d4253'><marimo-slider data-initial-value='0' data-label='null' data-start='0' data-stop='100' data-step='2' data-steps='[]' data-debounce='false' data-orientation='&quot;horizontal&quot;' data-show-value='false' data-full-width='false'></marimo-slider></marimo-ui-element>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%0Aslider%20%3D%20mo.ui.slider(0%2C%20100%2C%202)%0Aslider%0A</marimo-cell-code>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="bkHC"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <span class="markdown prose dark:prose-invert"><span class="paragraph">Slider value: 0</span></span>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%0Amo.md(f%22Slider%20value%3A%20%7Bslider.value%7D%22)%0A</marimo-cell-code>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="lEQa"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <span class="markdown prose dark:prose-invert"><span class="paragraph">We can also show the island code!</span></span>
+ </marimo-cell-output>
+ <marimo-ui-element object-id='135dcce7-6c7f-49fe-853d-fbcb784342fa' random-id='135dcce7-6c7f-49fe-853d-fbcb784342fa'><marimo-code-editor data-initial-value='&quot;mo.md(&#92;&quot;We can also show the island code!&#92;&quot;)&quot;' data-label='null' data-language='&quot;python&quot;' data-placeholder='&quot;&quot;' data-disabled='false'></marimo-code-editor></marimo-ui-element>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="PKri"
+ data-reactive="false"
+>
+ <marimo-cell-output>
+ <marimo-mime-renderer data-mime='&quot;application/vnd.marimo+error&quot;' data-data='[{&quot;msg&quot;: &quot;This cell raised an exception: ModuleNotFoundError(&#x27;No module named &#x27;matplotlib&#x27;&#x27;)&quot;, &quot;exception_type&quot;: &quot;ModuleNotFoundError&quot;, &quot;raising_cell&quot;: null, &quot;type&quot;: &quot;exception&quot;}]'></marimo-mime-renderer>
+ </marimo-cell-output>
+ <marimo-ui-element object-id='332c9909-e441-462a-9faa-6a60625e808b' random-id='332c9909-e441-462a-9faa-6a60625e808b'><marimo-code-editor data-initial-value='&quot;# Also run expensive outputs without performing them in the browser&#92;nimport matplotlib.pyplot as plt&#92;nimport numpy as np&#92;nx = np.linspace(0, 2*np.pi, 100)&#92;ny = np.sin(x)&#92;nplt.plot(x, y)&#92;nplt.gca()&quot;' data-label='null' data-language='&quot;python&quot;' data-placeholder='&quot;&quot;' data-disabled='false'></marimo-code-editor></marimo-ui-element>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="Xref"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <marimo-mime-renderer data-mime='&quot;application/vnd.marimo+error&quot;' data-data='[{&quot;msg&quot;: &quot;This cell raised an exception: ModuleNotFoundError(&#x27;No module named &#x27;idk_package&#x27;&#x27;)&quot;, &quot;exception_type&quot;: &quot;ModuleNotFoundError&quot;, &quot;raising_cell&quot;: null, &quot;type&quot;: &quot;exception&quot;}]'></marimo-mime-renderer>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%0Aimport%20idk_package%0A%22Should%20raise%20an%20error%22%0A</marimo-cell-code>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="SFPL"
+ data-reactive="true"
>
- </marimo-cell-output>
- <marimo-cell-code hidden>
- %0Amo.md(f%22Slider%20value%3A%20%7Bslider.value%7D%22)%0A
- </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>
+ <marimo-cell-output>
+ <span class="markdown prose dark:prose-invert"><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">&#39;&#39;&#39;</span>
<span class="sd"> # Hello, Markdown!</span>
<span class="sd"> Use marimo&#39;s &quot;`md`&quot; function to embed rich text into your marimo</span>
@@ -96,70 +133,61 @@
<span class="sd"> can display.</span>
<span class="sd"> &#39;&#39;&#39;</span>
<span class="p">)</span>
-</code></pre>
- </div></span
+</code></pre></div></span>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%0Amo.md(%0A%20%20%20%20%22%22%22%0A%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20Use%20marimo's%20%22%60md%60%22%20function%20to%20embed%20rich%20text%20into%20your%20marimo%0A%20%20%20%20apps.%20This%20function%20compiles%20Markdown%20into%20HTML%20that%20marimo%0A%20%20%20%20can%20display.%0A%0A%20%20%20%20For%20example%2C%20here's%20the%20code%20that%20rendered%20the%20above%20title%20and%0A%20%20%20%20paragraph%3A%0A%0A%20%20%20%20%60%60%60python3%0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20'''%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%20your%20Markdown%20into%20HTML%20that%20marimo%0A%20%20%20%20%20%20%20%20can%20display.%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20)%0A%20%20%20%20%60%60%60%0A%20%20%20%20%22%22%22%0A)%0A</marimo-cell-code>
+ </marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="BYtC"
+ data-reactive="true"
>
- </marimo-cell-output>
- <marimo-cell-code hidden>
- %0Amo.md(%0A%20%20%20%20%22%22%22%0A%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20Use%20marimo's%20%22%60md%60%22%20function%20to%20embed%20rich%20text%20into%20your%20marimo%0A%20%20%20%20apps.%20This%20function%20compiles%20Markdown%20into%20HTML%20that%20marimo%0A%20%20%20%20can%20display.%0A%0A%20%20%20%20For%20example%2C%20here's%20the%20code%20that%20rendered%20the%20above%20title%20and%0A%20%20%20%20paragraph%3A%0A%0A%20%20%20%20%60%60%60python3%0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20'''%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%20your%20Markdown%20into%20HTML%20that%20marimo%0A%20%20%20%20%20%20%20%20can%20display.%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20)%0A%20%20%20%20%60%60%60%0A%20%20%20%20%22%22%22%0A)%0A
- </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">&#39;$f : \mathbf</span><span class="si">{R}</span><span class="s1"> o \mathbf</span><span class="si">{R}</span><span class="s1">$&#39;</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>
+ <marimo-cell-output>
+ <span class="markdown prose dark:prose-invert"><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">&#39;$f : \mathbf</span><span class="si">{R}</span><span class="s1"> o \mathbf</span><span class="si">{R}</span><span class="s1">$&#39;</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">&#39;&#39;&#39;</span>
<span class="sd"> \[</span>
<span class="sd"> f: \mathbf{R} o \mathbf{R}</span>
<span class="sd"> \]</span>
<span class="sd"> &#39;&#39;&#39;</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>
- %0Amo.md(%0A%20%20%20%20r%22%22%22%0A%20%20%20%20%23%23%20LaTeX%0A%20%20%20%20You%20can%20embed%20LaTeX%20in%20Markdown.%0A%0A%20%20%20%20For%20example%2C%0A%0A%20%20%20%20%60%60%60python3%0A%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%60%60%60%0A%0A%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%60%60%60python3%0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20r'''%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'''%0A%20%20%20%20)%0A%20%20%20%20%60%60%60%0A%0A%20%20%20%20renders%20the%20display%20math%0A%0A%20%20%20%20%5C%5B%0A%20%20%20%20f%3A%20%5Cmathbf%7BR%7D%20%09o%20%5Cmathbf%7BR%7D.%0A%20%20%20%20%5C%5D%0A%20%20%20%20%22%22%22%0A)%0A
- </marimo-cell-code>
- </marimo-island>
+</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>%0Amo.md(%0A%20%20%20%20r%22%22%22%0A%20%20%20%20%23%23%20LaTeX%0A%20%20%20%20You%20can%20embed%20LaTeX%20in%20Markdown.%0A%0A%20%20%20%20For%20example%2C%0A%0A%20%20%20%20%60%60%60python3%0A%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%60%60%60%0A%0A%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%60%60%60python3%0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20r'''%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'''%0A%20%20%20%20)%0A%20%20%20%20%60%60%60%0A%0A%20%20%20%20renders%20the%20display%20math%0A%0A%20%20%20%20%5C%5B%0A%20%20%20%20f%3A%20%5Cmathbf%7BR%7D%20%09o%20%5Cmathbf%7BR%7D.%0A%20%20%20%20%5C%5D%0A%20%20%20%20%22%22%22%0A)%0A</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)
+
+ <br />
+ <br />
+ <br />
+ <br />
+ <hr />
+ <div class="bg-background p-4 border-2 text-primary font-bold bg-background">
+ this should not be affected by global tailwind styles
+ </div>
+ <div class="marimo">
+ <div class="bg-background p-4 border-2 text-primary font-bold text-foreground">
+ this should be affected by global tailwind styles
+ </div>
+ </div>
+ <div class="marimo">
+ <div class="dark">
+ <div class="bg-background p-4 border-2 text-primary font-bold text-foreground">
+ this should be affected by global tailwind styles (dark)
+ </div>
</div>
- </div>
- </div>
- </body>
-</html>
+ </div>
+ </div>
+
+ </body>
+ </html>
+
diff --git a/frontend/islands/development.md b/frontend/islands/development.md
index a26050ff16..3e607b3d82 100644
--- a/frontend/islands/development.md
+++ b/frontend/islands/development.md
@@ -14,7 +14,7 @@ pnpm dev:islands
```bash
# Generate
-python3 ./islands/generate.py > islands/__demo__/index.html
+uv run ./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.py
index 8a898aed78..73358632b2 100644
--- a/frontend/islands/generate.py
+++ b/frontend/islands/generate.py
@@ -1,26 +1,45 @@
-#!/usr/bin/env python3
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "marimo",
+# ]
+# [tool.uv.sources]
+# marimo = { path = "../../", editable = true }
+# ///
import asyncio
from textwrap import dedent
-from marimo import experimental_MarimoIslandGenerator
+import marimo
-generator = experimental_MarimoIslandGenerator()
+generator = marimo.MarimoIslandGenerator()
def run():
stubs = [
+ # Basic
generator.add_code("import marimo as mo"),
generator.add_code("mo.md('Hello, islands!')"),
+
+ # Slider
generator.add_code(
"""
slider = mo.ui.slider(0, 100, 2)
slider
"""
),
+ generator.add_code(
+ """
+ mo.md(f"Slider value: {slider.value}")
+ """
+ ),
+
+ # display_code=True
generator.add_code("""
mo.md("We can also show the island code!")
""", display_code=True),
+
+ # is_reactive=False
generator.add_code("""
# Also run expensive outputs without performing them in the browser
import matplotlib.pyplot as plt
@@ -30,11 +49,16 @@ def run():
plt.plot(x, y)
plt.gca()
""", display_code=True, is_reactive=False),
+
+ # Error
generator.add_code(
- """
- mo.md(f"Slider value: {slider.value}")
+ """
+ import idk_package
+ "Should raise an error"
"""
),
+
+ # Markdown
generator.add_code(
"""
mo.md(
@@ -63,6 +87,8 @@ def run():
)
"""
),
+
+ # LaTeX
generator.add_code(
"""
mo.md(
@@ -121,6 +147,9 @@ def run():
rel="stylesheet"
crossorigin="anonymous"
/> -->
+
+ <!-- If running from Vite -->
+ <!-- <script type="module" src="/src/core/islands/main.ts"></script> -->
</head>
<body>
@@ -132,21 +161,22 @@ def run():
<br />
<br />
<hr />
- <div class="bg-blue-500 p-4 border-2 border-red-500 bg-background">
+ <div class="bg-background p-4 border-2 text-primary font-bold bg-background">
this should not be affected by global tailwind styles
</div>
<div class="marimo">
- <div class="bg-background p-4 border-2 border-red-500 text-foreground">
+ <div class="bg-background p-4 border-2 text-primary font-bold 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">
+ <div class="bg-background p-4 border-2 text-primary font-bold text-foreground">
this should be affected by global tailwind styles (dark)
</div>
</div>
</div>
+ </div>
</body>
</html>
diff --git a/frontend/islands/validate.sh b/frontend/islands/validate.sh
index dd2f65c8ce..d7f26cd9b7 100755
--- a/frontend/islands/validate.sh
+++ b/frontend/islands/validate.sh
@@ -23,7 +23,7 @@ if [ $? -eq 0 ]; then
exit 1
fi
-echo "[validate: data uri does not convert data:video/mp2t]"
+echo "[validate: data uri does not contain data:video/mp2t]"
grep -R "data:video/mp2t" $(pwd)/dist
if [ $? -eq 0 ]; then
echo "mininification misencoded typescript data uri."
diff --git a/frontend/islands/vite.config.mts b/frontend/islands/vite.config.mts
index 2c4ab55be4..471d8cc72c 100644
--- a/frontend/islands/vite.config.mts
+++ b/frontend/islands/vite.config.mts
@@ -41,6 +41,12 @@ export default defineConfig({
? JSON.stringify(packageJson.version)
: JSON.stringify("latest"),
},
+ server: {
+ headers: {
+ "Cross-Origin-Opener-Policy": "same-origin",
+ "Cross-Origin-Embedder-Policy": "require-corp",
+ },
+ },
plugins: [htmlDevPlugin(), react({ tsDecorators: true }), tsconfigPaths()],
build: {
emptyOutDir: true,
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index b62e528e8d..25bb31257b 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -12,6 +12,8 @@ import workerUrl from "./worker/worker.tsx?worker&url";
import { createMarimoFile, parseMarimoIslandApps } from "./parse";
import { Logger } from "@/utils/Logger";
+import { store } from "../state/jotai";
+import { islandsInitializedAtom } from "./state";
export class IslandsPyodideBridge implements RunRequests, EditRequests {
/**
@@ -36,11 +38,9 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
// TODO: abstract out into a worker constructor
// . in front of workerUrl is necessary to make it a relative import
- const url = workerUrl.startsWith("./")
+ const url = import.meta.env.DEV
? workerUrl
- : workerUrl.startsWith("/")
- ? `.${workerUrl}`
- : `./${workerUrl}`;
+ : makeRelativeWorkerUrl(workerUrl);
const js = `import ${JSON.stringify(new URL(url, import.meta.url))}`;
const blob = new Blob([js], { type: "application/javascript" });
const objURL = URL.createObjectURL(blob);
@@ -64,8 +64,8 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
this.rpc = getWorkerRPC<WorkerSchema>(worker);
// Listeners
+ const apps = parseMarimoIslandApps();
this.rpc.addMessageListener("ready", () => {
- const apps = parseMarimoIslandApps();
for (const app of apps) {
Logger.debug("Starting session for app", app.id);
const file = createMarimoFile(app);
@@ -77,9 +77,11 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
}
});
this.rpc.addMessageListener("initialized", () => {
+ store.set(islandsInitializedAtom, true);
this.initialized.resolve();
});
this.rpc.addMessageListener("initializedError", ({ error }) => {
+ store.set(islandsInitializedAtom, error);
this.initialized.reject(new Error(error));
});
this.rpc.addMessageListener("kernelMessage", ({ message }) => {
@@ -169,3 +171,11 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
});
}
}
+
+function makeRelativeWorkerUrl(url: string) {
+ return url.startsWith("./")
+ ? url
+ : url.startsWith("/")
+ ? `.${url}`
+ : `./${url}`;
+}
diff --git a/frontend/src/core/islands/components/output-wrapper.tsx b/frontend/src/core/islands/components/output-wrapper.tsx
index 5e8f961fe3..0a6967da6a 100644
--- a/frontend/src/core/islands/components/output-wrapper.tsx
+++ b/frontend/src/core/islands/components/output-wrapper.tsx
@@ -28,7 +28,7 @@ interface IconButtonProps {
}
const IconButton: React.FC<IconButtonProps> = ({ tooltip, icon, action }) => (
- <Tooltip content={tooltip}>
+ <Tooltip content={tooltip} delayDuration={200}>
<Button
size="icon"
variant="outline"
@@ -81,9 +81,12 @@ export const MarimoOutputWrapper: React.FC<Props> = ({
}
}),
);
+ // Set pressed to false if the window loses focus
+ useEventListener(window, "blur", () => setPressed(false));
+ useEventListener(window, "mouseleave", () => setPressed(false));
if (!runtime?.output) {
- return children;
+ return <div className="relative min-h-6 empty:hidden">{children}</div>;
}
// No output to display
diff --git a/frontend/src/core/islands/components/web-components.tsx b/frontend/src/core/islands/components/web-components.tsx
index 626f7179fd..aea1145292 100644
--- a/frontend/src/core/islands/components/web-components.tsx
+++ b/frontend/src/core/islands/components/web-components.tsx
@@ -2,7 +2,6 @@
import { invariant } from "@/utils/invariant";
import type { CellId } from "../../cells/ids";
import { store } from "../../state/jotai";
-import { notebookAtom } from "../../cells/cells";
import ReactDOM, { type Root } from "react-dom/client";
import { isValidElement } from "react";
import { extractIslandCodeFromEmbed } from "../parse";
@@ -12,6 +11,7 @@ import { renderHTML } from "@/plugins/core/RenderHTML";
import { TooltipProvider } from "@/components/ui/tooltip";
import { ErrorBoundary } from "@/components/editor/boundary/ErrorBoundary";
import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";
+import { shouldShowIslandsWarningIndicatorAtom } from "../state";
/**
* A custom element that renders the output of a marimo cell
@@ -28,6 +28,16 @@ export class MarimoIslandElement extends HTMLElement {
constructor() {
super();
this.classList.add(MarimoIslandElement.styleNamespace);
+
+ // If we warn that islands are still loading, we fade them out.
+ store.sub(shouldShowIslandsWarningIndicatorAtom, () => {
+ const loading = store.get(shouldShowIslandsWarningIndicatorAtom);
+ if (loading) {
+ this.style.setProperty("opacity", "0.5");
+ } else {
+ this.style.removeProperty("opacity");
+ }
+ });
}
get appId(): string {
@@ -36,13 +46,8 @@ export class MarimoIslandElement extends HTMLElement {
}
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);
- const cellId = cellIds.inOrderIds.at(idx);
- invariant(cellId, "Missing cell ID");
- return cellId;
+ invariant(this.dataset.cellId, "Missing data-cell-id attribute");
+ return this.dataset.cellId as CellId;
}
get code(): string {
@@ -72,6 +77,10 @@ export class MarimoIslandElement extends HTMLElement {
editor: JSX.Element | null,
) {
const alwaysShowRun = !!editor;
+ html = html.trim();
+ const isEmpty = html === "<span></span>" || html === "";
+ const initialHtml = isEmpty ? null : renderHTML({ html });
+
this.root?.render(
<ErrorBoundary>
<Provider store={store}>
@@ -81,7 +90,7 @@ export class MarimoIslandElement extends HTMLElement {
codeCallback={codeCallback}
alwaysShowRun={alwaysShowRun}
>
- {renderHTML({ html })}
+ {initialHtml}
</MarimoOutputWrapper>
{editor}
</TooltipProvider>
diff --git a/frontend/src/core/islands/islands.css b/frontend/src/core/islands/islands.css
index 3277270fe6..743faff129 100644
--- a/frontend/src/core/islands/islands.css
+++ b/frontend/src/core/islands/islands.css
@@ -1,10 +1,12 @@
-@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");
-@import url("../../css/md-tooltip.css");
+@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');
+@import url('../../css/admonition.css');
+@import url('../../css/md-tooltip.css');
+@import url('../../css/table.css');
.marimo {
@apply bg-background text-foreground;
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 7b41c2dae5..052a5836ba 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -30,6 +30,12 @@ import { sendComponentValues } from "../network/requests";
import type { RequestId } from "../network/DeferredRequestRegistry";
import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
import type { UIElementId } from "../cells/ids";
+import { MarimoValueInputEvent } from "../dom/events";
+import {
+ shouldShowIslandsWarningIndicatorAtom,
+ userTriedToInteractWithIslandsAtom,
+} from "./state";
+import { dismissIslandsLoadingToast, toastIslandsLoading } from "./toast";
/**
* Main entry point for the js bundle for embedded marimo apps.
@@ -42,7 +48,7 @@ export async function initialize() {
// This will display all the static HTML content.
initializePlugins();
- // Add 'marimo' class name to all `marimo-island` elements.
+ // Find all `marimo-island` elements.
const islands = document.querySelectorAll<HTMLElement>(
MarimoIslandElement.tagName,
);
@@ -52,6 +58,7 @@ export async function initialize() {
return;
}
+ // Add 'marimo' class name to all `marimo-island` elements.
for (const island of islands) {
island.classList.add(MarimoIslandElement.styleNamespace);
}
@@ -60,6 +67,22 @@ export async function initialize() {
store.set(notebookAtom, (state) => notebookReducer(state, action));
});
+ // Define the custom element for the marimo-island tag.
+ requestAnimationFrame(() => {
+ defineCustomElement(MarimoIslandElement.tagName, MarimoIslandElement);
+ });
+
+ // If the user has interacted with the islands before they are initialized,
+ // we show the loading toast.
+ store.sub(shouldShowIslandsWarningIndicatorAtom, () => {
+ const showing = store.get(shouldShowIslandsWarningIndicatorAtom);
+ if (showing) {
+ toastIslandsLoading();
+ } else {
+ dismissIslandsLoadingToast();
+ }
+ });
+
// Consume messages from the kernel
IslandsPyodideBridge.INSTANCE.consumeMessages((message) => {
const msg = jsonParseWithSpecialChar(message);
@@ -87,9 +110,6 @@ export async function initialize() {
setCapabilities: Functions.NOOP,
onError: Logger.error,
});
- // Define the custom element for the marimo-island tag.
- // This comes after initializing since this reads from the store.
- defineCustomElement(MarimoIslandElement.tagName, MarimoIslandElement);
return;
case "completed-run":
return;
@@ -144,6 +164,18 @@ export async function initialize() {
}
});
+ // Set the user tried to interact with islands
+ // before they are initialized.
+ document.addEventListener(
+ MarimoValueInputEvent.TYPE,
+ () => {
+ store.set(userTriedToInteractWithIslandsAtom, true);
+ },
+ {
+ once: true,
+ },
+ );
+
// Start the runtime
RuntimeState.INSTANCE.start(sendComponentValues);
}
diff --git a/frontend/src/core/islands/state.ts b/frontend/src/core/islands/state.ts
new file mode 100644
index 0000000000..a99ad0d80b
--- /dev/null
+++ b/frontend/src/core/islands/state.ts
@@ -0,0 +1,30 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { atom } from "jotai";
+
+/**
+ * Whether the islands have been initialized.
+ *
+ * false: Islands have not been initialized.
+ * true: Islands have been initialized.
+ * string: If there was an error initializing the islands, the string will
+ * contain the error message.
+ */
+export const islandsInitializedAtom = atom<boolean | string>(false);
+
+/**
+ * Whether the user has tried to interact with the islands.
+ */
+export const userTriedToInteractWithIslandsAtom = atom(false);
+
+/**
+ * Whether to show the islands warning indicator.
+ *
+ * This only happens if the user has tried to interact with the islands, but
+ * they haven't been initialized yet.
+ */
+export const shouldShowIslandsWarningIndicatorAtom = atom((get) => {
+ return (
+ get(userTriedToInteractWithIslandsAtom) &&
+ get(islandsInitializedAtom) === false
+ );
+});
diff --git a/frontend/src/core/islands/toast.ts b/frontend/src/core/islands/toast.ts
new file mode 100644
index 0000000000..5c00ae532b
--- /dev/null
+++ b/frontend/src/core/islands/toast.ts
@@ -0,0 +1,41 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+let didToast = false;
+let toastElement: HTMLDivElement | undefined;
+
+/**
+ * Show a toast message in the center of the screen.
+ *
+ * Intentionally outside React and not using our styles since we place
+ * this in the global scope.
+ *
+ * We only show this once.
+ */
+export function toastIslandsLoading() {
+ if (didToast) {
+ return;
+ }
+ didToast = true;
+ toastElement = document.createElement("div");
+ toastElement.classList.add("marimo-islands-loading-toast");
+ toastElement.textContent = "⚡ reactivity initializing...";
+ toastElement.style.position = "fixed";
+ toastElement.style.top = "0.5rem";
+ toastElement.style.left = "50%";
+ toastElement.style.transform = "translateX(-50%)";
+ toastElement.style.zIndex = "1000";
+ toastElement.style.backgroundColor = "#0f172a";
+ toastElement.style.color = "#f8fafc";
+ toastElement.style.padding = "0.25rem 0.5rem";
+ toastElement.style.borderRadius = "0.5rem";
+ toastElement.style.fontSize = "0.875rem";
+ document.body.append(toastElement);
+}
+
+/**
+ * Remove the toast message from the screen.
+ */
+export function dismissIslandsLoadingToast() {
+ if (toastElement) {
+ toastElement.remove();
+ }
+}
diff --git a/frontend/src/css/index.css b/frontend/src/css/index.css
index da4a70a7db..06d721f19d 100644
--- a/frontend/src/css/index.css
+++ b/frontend/src/css/index.css
@@ -1,9 +1,9 @@
-@import url("./globals.css");
-@import url("./codehilite.css");
-@import url("./common.css");
-@import url("./katex-fonts.css");
-@import url("./katex.min.css");
-@import url("./md.css");
-@import url("./md-tooltip.css");
-@import url("./admonition.css");
-@import url("./table.css");
+@import url('./globals.css');
+@import url('./codehilite.css');
+@import url('./common.css');
+@import url('./katex-fonts.css');
+@import url('./katex.min.css');
+@import url('./md.css');
+@import url('./md-tooltip.css');
+@import url('./admonition.css');
+@import url('./table.css');
diff --git a/frontend/src/plugins/layout/MimeRenderPlugin.tsx b/frontend/src/plugins/layout/MimeRenderPlugin.tsx
index 54335400ac..648a2178d5 100644
--- a/frontend/src/plugins/layout/MimeRenderPlugin.tsx
+++ b/frontend/src/plugins/layout/MimeRenderPlugin.tsx
@@ -18,7 +18,12 @@ export class MimeRendererPlugin implements IStatelessPlugin<Data> {
validator = z.object({
mime: z.string().transform((val) => val as OutputMessage["mimetype"]),
- data: z.union([z.string(), z.null(), z.record(z.unknown())]),
+ data: z.union([
+ z.string(),
+ z.null(),
+ z.record(z.unknown()),
+ z.array(z.any()),
+ ]),
});
render({ data }: IStatelessPluginProps<Data>): JSX.Element {
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 2999de2e04..4bb9849f45 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -27,6 +27,7 @@ __all__ = [
# Other namespaces
"ai",
"ui",
+ "islands",
# Application elements
"accordion",
"app_meta",
@@ -82,6 +83,7 @@ __all__ = [
]
__version__ = "0.9.11"
+import marimo._islands as islands
from marimo._ast.app import App
from marimo._ast.cell import Cell
from marimo._islands.island_generator import MarimoIslandGenerator
diff --git a/marimo/_islands/__init__.py b/marimo/_islands/__init__.py
new file mode 100644
index 0000000000..61acf554fa
--- /dev/null
+++ b/marimo/_islands/__init__.py
@@ -0,0 +1,11 @@
+from __future__ import annotations
+
+__all__ = [
+ "MarimoIslandGenerator",
+ "MarimoIslandStub",
+]
+
+from marimo._islands.island_generator import (
+ MarimoIslandGenerator,
+ MarimoIslandStub,
+)
diff --git a/marimo/_islands/island_generator.py b/marimo/_islands/island_generator.py
index 7cb8e5f699..8ef8946e3f 100644
--- a/marimo/_islands/island_generator.py
+++ b/marimo/_islands/island_generator.py
@@ -106,7 +106,9 @@ class MarimoIslandStub:
# make it present for reactivity, unless reactivity is disabled.
if display_code:
# TODO: Allow for non-disabled code editors.
- code_block = as_html(code_editor(self.code, disabled=False)).text
+ code_block = as_html(
+ code_editor(self.code.strip(), disabled=False)
+ ).text
else:
code_block = (
"<marimo-cell-code hidden>"
@@ -125,13 +127,13 @@ class MarimoIslandStub:
data-reactive="{json.dumps(is_reactive)}"
>
<marimo-cell-output>
- {output if output and display_output else ""}
+ {output.text if output and display_output else ""}
</marimo-cell-output>
{code_block}
</marimo-island>
"""
- ).strip()
- )
+ )
+ ).strip()
class MarimoIslandGenerator:
@@ -151,7 +153,7 @@ class MarimoIslandGenerator:
# Example
```python
- from marimo import MarimoIslandGenerator
+ from marimo.islands import MarimoIslandGenerator
generator = MarimoIslandGenerator()
block1 = generator.add_code("import marimo as mo")
@@ -370,10 +372,9 @@ class MarimoIslandGenerator:
"""
init_cell_id = self._app.cell_manager.create_cell_id()
- init_input = "<marimo-cell-code hidden> '' </marimo-cell-code>"
init_output = """
- <div class="marimo" style="--tw-bg-opacity: 0;">
- <div class="flex flex-col items-center justify-center">
+ <div class="marimo">
+ <div class="flex flex-col flex-1 items-center justify-center">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
@@ -397,12 +398,12 @@ class MarimoIslandGenerator:
<marimo-island
data-app-id="{self._app_id}"
data-cell-id="{init_cell_id}"
- data-reactive="{json.dumps(True)}"
+ data-reactive="{json.dumps(False)}"
>
<marimo-cell-output>
{init_output}
</marimo-cell-output>
- {init_input}
+ <marimo-cell-code hidden></marimo-cell-code>
</marimo-island>
"""
).strip()
diff --git a/tests/_islands/snapshots/html.txt b/tests/_islands/snapshots/html.txt
new file mode 100644
index 0000000000..1b7ca3fb03
--- /dev/null
+++ b/tests/_islands/snapshots/html.txt
@@ -0,0 +1,80 @@
+<!doctype html>
+ <html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title> main </title>
+ <script type="module" 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/style.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&amp;family=Lora&amp;family=PT+Sans:wght@400;700&amp;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"
+ />
+ <marimo-filename hidden></marimo-filename>
+<marimo-mode data-mode='read' hidden></marimo-mode>
+ </head>
+ <body>
+ <div style="margin: auto; max-width: 740px;">
+ <marimo-island
+ data-app-id="main"
+ data-cell-id="vblA"
+ data-reactive="false"
+ >
+ <marimo-cell-output>
+
+<div class="marimo">
+ <div class="flex flex-col flex-1 items-center justify-center">
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ class="size-20 animate-spin text-primary"
+ >
+ <path d="M21 12a9 9 0 1 1-6.219-8.56"></path>
+ </svg>
+ <div>Initializing...</div>
+ </div>
+</div>
+
+ </marimo-cell-output>
+ <marimo-cell-code hidden></marimo-cell-code>
+ </marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="Hbol"
+ data-reactive="true"
+>
+ <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"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>mo.md('Hello%2C%20HTML!')</marimo-cell-code>
+</marimo-island>
+ </div>
+ </body>
+ </html>
\ No newline at end of file
diff --git a/tests/_islands/snapshots/markdown.txt b/tests/_islands/snapshots/markdown.txt
new file mode 100644
index 0000000000..4e64d414ca
--- /dev/null
+++ b/tests/_islands/snapshots/markdown.txt
@@ -0,0 +1,18 @@
+<marimo-island
+ data-app-id="main"
+ data-cell-id="Hbol"
+ data-reactive="true"
+ >
+ <marimo-cell-output>
+ <span class="markdown prose dark:prose-invert"><h1 id="hello-markdown">Hello, Markdown!</h1>
+<span class="paragraph">This is a paragsraph.</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">&#39;&#39;&#39;</span>
+<span class="sd"> # Hello, Markdown!</span>
+<span class="sd"> This is a paragraph.</span>
+<span class="sd"> &#39;&#39;&#39;</span>
+<span class="p">)</span>
+</code></pre></div></span>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%0Aimport%20marimo%20as%20mo%0Amo.md(%0A%20%20%20%20%22%22%22%0A%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20This%20is%20a%20paragsraph.%0A%0A%20%20%20%20%60%60%60python3%0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20%20%20%20%20This%20is%20a%20paragraph.%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20)%0A%20%20%20%20%60%60%60%0A%20%20%20%20%22%22%22%0A)%0A</marimo-cell-code>
+ </marimo-island>
\ No newline at end of file
diff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.py
index 8da94ca350..912d2bd7e8 100644
--- a/tests/_islands/test_island_generator.py
+++ b/tests/_islands/test_island_generator.py
@@ -1,13 +1,19 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
import pytest
from marimo import __version__
+from marimo._ast.app import _AppConfig
from marimo._islands.island_generator import (
MarimoIslandGenerator,
)
from tests.mocks import snapshotter
+if TYPE_CHECKING:
+ from pathlib import Path
+
snapshot = snapshotter(__file__)
@@ -71,12 +77,147 @@ async def test_render():
)
-async def test_render_head():
+async def test_render_multiline_markdown():
generator = MarimoIslandGenerator()
- generator.add_code("print('Hello, islands!')")
+ stub = generator.add_code(
+ """
+ import marimo as mo
+ mo.md(
+ \"\"\"
+ # Hello, Markdown!
+
+ This is a paragsraph.
+
+ ```python3
+ mo.md(
+ '''
+ # Hello, Markdown!
+
+ This is a paragraph.
+ '''
+ )
+ ```
+ \"\"\"
+ )
+ """
+ )
await generator.build()
+ snapshot("markdown.txt", stub.render())
+
+
+async def test_from_file(tmp_path: Path):
+ # Create a temporary marimo file
+ marimo_file = tmp_path / "temp_marimo_file.py"
+ marimo_file.write_text(
+ """
+import marimo
+
+app = marimo.App()
+
+def __():
+ import marimo as mo
+ mo.md("# Hello, Marimo!")
+ return (mo,)
+
+def __(mo):
+ x = 42
+ mo.md(f"The answer is {x}")
+ return (x,)
+ """
+ )
- # Check if render_head works after build() is called
- snapshot(
- "header.txt", generator.render_head().replace(__version__, "0.0.0")
+ generator = MarimoIslandGenerator.from_file(str(marimo_file))
+
+ # Check if stubs were created correctly
+ assert len(generator._stubs) == 2
+ assert (
+ generator._stubs[0].code.strip()
+ == 'import marimo as mo\nmo.md("# Hello, Marimo!")'
+ )
+ assert (
+ generator._stubs[1].code.strip()
+ == 'x = 42\nmo.md(f"The answer is {x}")'
)
+
+ # Build and check outputs
+ await generator.build()
+ stub1 = generator._stubs[0]
+ stub2 = generator._stubs[1]
+ assert stub1.output is not None
+ assert stub2.output is not None
+ assert "Hello, Marimo!" in stub1.output.data
+ assert "The answer is 42" in stub2.output.data
+
+
+def test_render_head():
+ generator = MarimoIslandGenerator()
+ head_html = generator.render_head()
+
+ assert (
+ '<script type="module" src="https://cdn.jsdelivr.net/npm/@marimo-team/islands@'
+ in head_html
+ )
+ assert (
+ 'href="https://cdn.jsdelivr.net/npm/@marimo-team/islands@' in head_html
+ )
+ assert (
+ '<link rel="preconnect" href="https://fonts.googleapis.com" />'
+ in head_html
+ )
+ assert 'href="https://cdn.jsdelivr.net/npm/katex@' in head_html
+
+ snapshot("header.txt", head_html.replace(__version__, "0.0.0"))
+
+
+def test_render_init_island():
+ generator = MarimoIslandGenerator()
+ init_island = generator.render_init_island()
+
+ assert "<marimo-island" in init_island
+ assert 'data-reactive="false"' in init_island
+ assert "Initializing..." in init_island
+
+
+def test_render_body():
+ generator = MarimoIslandGenerator()
+ generator.add_code("import marimo as mo")
+ generator.add_code("mo.md('Hello, World!')")
+
+ body_html = generator.render_body()
+
+ assert "<marimo-island" in body_html
+ assert 'data-reactive="true"' in body_html
+ assert "Hello%2C%20World!" in body_html
+ assert "Initializing..." in body_html # Check for init island
+
+ # Test without init island
+ body_html_no_init = generator.render_body(include_init_island=False)
+ assert "Initializing..." not in body_html_no_init
+
+
+async def test_render_html():
+ generator = MarimoIslandGenerator()
+ generator.add_code("import marimo as mo")
+ generator.add_code("mo.md('Hello, HTML!')")
+
+ html = generator.render_html()
+
+ assert "<!doctype html>" in html
+ assert '<html lang="en">' in html
+ assert "<head>" in html
+ assert "<body>" in html
+ assert "Hello%2C%20HTML!" in html
+ snapshot("html.txt", html)
+
+
+def test_app_config():
+ generator = MarimoIslandGenerator()
+ generator._config = _AppConfig(width="medium", app_title="Test App")
+
+ body_html = generator.render_body()
+ assert 'style="margin: auto; max-width: 1110px;"' in body_html
+
+ html = generator.render_html()
+ assert "<title> Test App </title>" in html