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.

feat: mo.lazy (#1052)

Myles Scolnicke7011671ac80
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.md
index 5568e77935..d6c8724ddd 100644
--- a/docs/api/layouts/index.md
+++ b/docs/api/layouts/index.md
@@ -9,6 +9,7 @@
carousel
callout
justify
+ lazy
stacks
tree
```
@@ -30,6 +31,7 @@ them but just render their children in a certain way.
marimo.callout
marimo.center
marimo.hstack
+ marimo.lazy
marimo.left
marimo.right
marimo.tree
diff --git a/docs/api/layouts/lazy.md b/docs/api/layouts/lazy.md
new file mode 100644
index 0000000000..d0254f3c03
--- /dev/null
+++ b/docs/api/layouts/lazy.md
@@ -0,0 +1,25 @@
+# Lazy
+
+```{eval-rst}
+.. marimo-embed::
+ @app.cell
+ def __():
+ mo.accordion({
+ "Open me": mo.lazy(expensive_number, show_loading_indicator=True)
+ })
+ return
+
+ @app.cell
+ def __():
+ import time
+
+ def expensive_number():
+ time.sleep(1)
+ num = random.randint(0, 100)
+ return num
+ return
+```
+
+```{eval-rst}
+.. autofunction:: marimo.lazy
+```
diff --git a/docs/guides/best_practices.md b/docs/guides/best_practices.md
index be081e8d72..23d794708b 100644
--- a/docs/guides/best_practices.md
+++ b/docs/guides/best_practices.md
@@ -53,29 +53,18 @@ l = [1, 2, 3]
```python
extended_list = l + [new_item()]
```
-:::
-
+:::
**Write idempotent cells.**
Write cells whose outputs and behavior are the same
when given the same inputs (references); such cells are called idempotent. This
will help you avoid bugs and cache expensive intermediate computations.
-**Cache computations with `@functools.cache`.**
-Use Python's builtin `functools` library to cache expensive computations.
-
-For example,
+```{admonition} Performance
+:class: tip
-```python
-import functools
-
-def compute_predictions(problem_parameters):
- ...
+For tips on writing
+performant notebooks (e.g., how to cache intermediate outputs), see the
+[performance guide](/guides/performance.md).
```
-
-Whenever `compute_predictions` is called with a value of `problem_parameters`
-it has not seen, it will compute the predictions and store them in a cache. The
-next time it is called with the same parameters, instead of recomputing the
-predictions, it will return the previously computed value from the cache.
diff --git a/docs/guides/index.md b/docs/guides/index.md
index f2d2b9cdc3..2968eae7a5 100644
--- a/docs/guides/index.md
+++ b/docs/guides/index.md
@@ -18,6 +18,7 @@
wasm
ai_completion
best_practices
+ performance
deploying/index
```
@@ -36,6 +37,7 @@ These guides cover marimo's core concepts.
| {doc}`apps` | Running notebooks as apps |
| {doc}`scripts` | Running notebooks as scripts |
| {doc}`best_practices` | Best practices when working with marimo |
+| {doc}`performance` | Writing performant notebooks |
| {doc}`wasm` | Running notebooks in the browser (no backend required!) |
| {doc}`ai_completion` | Using AI to speed up your coding |
| {doc}`deploying/index` | Deploying marimo notebooks and apps |
diff --git a/docs/guides/performance.md b/docs/guides/performance.md
new file mode 100644
index 0000000000..c671ccd007
--- /dev/null
+++ b/docs/guides/performance.md
@@ -0,0 +1,61 @@
+# Performance
+
+## Cache computations with `@functools.cache`
+
+Use Python's builtin `functools` library to cache expensive computations.
+
+For example,
+
+```python
+import functools
+
+def compute_predictions(problem_parameters):
+ ...
+```
+
+Whenever `compute_predictions` is called with a value of `problem_parameters`
+it has not seen, it will compute the predictions and store them in a cache. The
+next time it is called with the same parameters, instead of recomputing the
+predictions, it will return the previously computed value from the cache.
+
+## Disable expensive cells
+
+marimo lets you temporarily disable cells from automatically running. This is
+helpful when you want to edit one part of a notebook without triggering
+execution of other parts. See the
+[reactivity guide](/guides/reactivity.md#disabling-cells) for more info.
+
+## Lazy-load expensive elements or computations
+
+You can lazily render UI elements that are expensive to compute using `marimo.lazy`.
+
+For example,
+
+```python
+import marimo as mo
+
+data = db.query("SELECT * FROM data")
+mo.lazy(mo.ui.table(data))
+```
+
+In this example, `mo.ui.table(data)` will not be rendered on the frontend until is it in the viewport.
+For example, an element can be out of the viewport due to scroll, inside a tab that is not selected, or inside an accordion that is not open.
+
+However, in this example, data is eagerly computed, while only the rendering of the table is lazy. It is possible to lazily compute the data as well: see the next example.
+
+```python
+import marimo as mo
+
+def expensive_component():
+ import time
+ time.sleep(1)
+ data = db.query("SELECT * FROM data")
+ return mo.ui.table(data)
+
+accordion = mo.ui.accordion({
+ "Charts": mo.lazy(expensive_component)
+})
+```
+
+In this example, we pass a function to `mo.lazy` instead of a component. This function will only be called when the user opens the accordion. In this way, `expensive_component` lazily computed and we only query the database when the user needs to see the data. This can be useful when the data is expensive to compute and the user may not need to see it immediately.
diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.js
index 553a8dd65a..13eff60e81 100644
--- a/frontend/.eslintrc.js
+++ b/frontend/.eslintrc.js
@@ -84,6 +84,7 @@ module.exports = {
"jsx-a11y/no-static-element-interactions": "off",
"jsx-a11y/no-noninteractive-element-interactions": "off",
"jsx-a11y/click-events-have-key-events": "off",
+ "storybook/no-redundant-story-name": "off",
// Turn of unicorn rules that don't have autofixes or that we don't want
"unicorn/consistent-function-scoping": "off",
"unicorn/expiring-todo-comments": "off",
diff --git a/frontend/.pnpmfile.cjs b/frontend/.pnpmfile.cjs
new file mode 100644
index 0000000000..6966d8c36e
--- /dev/null
+++ b/frontend/.pnpmfile.cjs
@@ -0,0 +1,13 @@
+const IGNORE = ["vue", "solid-js", "svelte", "solid-swr-store"];
+
+module.exports = {
+ hooks: {
+ readPackage: (pkg) => {
+ for (const key of IGNORE) {
+ delete pkg.peerDependencies[key];
+ delete pkg.dependencies[key];
+ }
+ return pkg;
+ },
+ },
+};
diff --git a/frontend/package.json b/frontend/package.json
index 275432c192..0d179df26c 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -67,9 +67,10 @@
"@types/js-cookie": "^3.0.6",
"@types/jsdom": "^21.1.6",
"@types/react-grid-layout": "^1.3.5",
+ "@uidotdev/usehooks": "^2.4.1",
"@uiw/codemirror-extensions-langs": "^4.21.23",
"@uiw/react-codemirror": "^4.21.23",
- "ai": "^3.0.1",
+ "ai": "^3.0.17",
"ansi_up": "^6.0.2",
"blob-polyfill": "^7.0.20220408",
"class-variance-authority": "^0.7.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index b246786f18..2217043aaf 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -170,6 +170,9 @@ dependencies:
'@types/react-grid-layout':
specifier: ^1.3.5
version: 1.3.5
+ '@uidotdev/usehooks':
+ specifier: ^2.4.1
'@uiw/codemirror-extensions-langs':
specifier: ^4.21.23
version: 4.21.23(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
@@ -177,8 +180,8 @@ dependencies:
specifier: ^4.21.23
ai:
- specifier: ^3.0.1
+ specifier: ^3.0.17
ansi_up:
specifier: ^6.0.2
version: 6.0.2
@@ -486,6 +489,7 @@ packages:
dependencies:
'@jridgewell/gen-mapping': 0.3.5
'@jridgewell/trace-mapping': 0.3.25
+ dev: true
/@aw-web-design/[email protected]:
resolution: {integrity: sha512-Xk1sIhyNC/esHGGVjL/niHLowM0csl/kFO5uawBy4IrWwy0o1G8LGt3jP6nmWGz+USxeeqbihAmp/oVZju6wug==}
@@ -7051,6 +7055,17 @@ packages:
eslint-visitor-keys: 3.4.3
dev: true
+ resolution: {integrity: sha512-1I+RwWyS+kdv3Mv0Vmc+p0dPYH0DTRAo04HLyXReYBL9AeseDWUJyi4THuksBJcu9F0Pih69Ak150VDnqbVnXg==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ react: '>=18.0.0'
+ react-dom: '>=18.0.0'
+ dependencies:
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ dev: false
+
/@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected]):
resolution: {integrity: sha512-TJYKlPxNAVJNclW1EGumhC7I02jpdMgBon4jZvb5Aju9+tUzS44IwORxUx8BD8ZtH2UHmYS+04rE3kLk/BtnCQ==}
peerDependencies:
@@ -7211,79 +7226,6 @@ packages:
pretty-format: 29.7.0
dev: true
- resolution: {integrity: sha512-MjXawxZf2SbZszLPYxaFCjxfibYrzr3eYbKxwpLR9EQN+oaziSu3qKVbwBERj1IFIB8OLUewxB5m/BFzi613og==}
- dependencies:
- '@babel/parser': 7.24.1
- '@vue/shared': 3.4.21
- entities: 4.5.0
- estree-walker: 2.0.2
- source-map-js: 1.2.0
- dev: false
-
- resolution: {integrity: sha512-IZC6FKowtT1sl0CR5DpXSiEB5ayw75oT2bma1BEhV7RRR1+cfwLrxc2Z8Zq/RGFzJ8w5r9QtCOvTjQgdn0IKmA==}
- dependencies:
- '@vue/compiler-core': 3.4.21
- '@vue/shared': 3.4.21
- dev: false
-
- resolution: {integrity: sha512-me7epoTxYlY+2CUM7hy9PCDdpMPfIwrOvAXud2Upk10g4YLv9UBW7kL798TvMeDhPthkZ0CONNrK2GoeI1ODiQ==}
- dependencies:
- '@babel/parser': 7.24.1
- '@vue/compiler-core': 3.4.21
- '@vue/compiler-dom': 3.4.21
- '@vue/compiler-ssr': 3.4.21
- '@vue/shared': 3.4.21
- estree-walker: 2.0.2
- magic-string: 0.30.8
- postcss: 8.4.38
- source-map-js: 1.2.0
- dev: false
-
- resolution: {integrity: sha512-M5+9nI2lPpAsgXOGQobnIueVqc9sisBFexh5yMIMRAPYLa7+5wEJs8iqOZc1WAa9WQbx9GR2twgznU8LTIiZ4Q==}
- dependencies:
- '@vue/compiler-dom': 3.4.21
- '@vue/shared': 3.4.21
- dev: false
-
- resolution: {integrity: sha512-UhenImdc0L0/4ahGCyEzc/pZNwVgcglGy9HVzJ1Bq2Mm9qXOpP8RyNTjookw/gOCUlXSEtuZ2fUg5nrHcoqJcw==}
- dependencies:
- '@vue/shared': 3.4.21
- dev: false
-
- resolution: {integrity: sha512-pQthsuYzE1XcGZznTKn73G0s14eCJcjaLvp3/DKeYWoFacD9glJoqlNBxt3W2c5S40t6CCcpPf+jG01N3ULyrA==}
- dependencies:
- '@vue/reactivity': 3.4.21
- '@vue/shared': 3.4.21
- dev: false
-
- resolution: {integrity: sha512-gvf+C9cFpevsQxbkRBS1NpU8CqxKw0ebqMvLwcGQrNpx6gqRDodqKqA+A2VZZpQ9RpK2f9yfg8VbW/EpdFUOJw==}
- dependencies:
- '@vue/runtime-core': 3.4.21
- '@vue/shared': 3.4.21
- csstype: 3.1.3
- dev: false
-
- resolution: {integrity: sha512-aV1gXyKSN6Rz+6kZ6kr5+Ll14YzmIbeuWe7ryJl5muJ4uwSwY/aStXTixx76TwkZFJLm1aAlA/HSWEJ4EyiMkg==}
- peerDependencies:
- vue: 3.4.21
- dependencies:
- '@vue/compiler-ssr': 3.4.21
- '@vue/shared': 3.4.21
- vue: 3.4.21([email protected])
- dev: false
-
- resolution: {integrity: sha512-PuJe7vDIi6VYSinuEbUIQgMIRZGgM8e4R+G+/dQTk0X1NEdvgvvgv7m+rfmDH1gZzyA1OjjoWskvHlfRNfQf3g==}
- dev: false
-
/@webassemblyjs/[email protected]:
resolution: {integrity: sha512-EKfMUOPRRUTy5UII4qJDGPpqfwjOmZ5jeGFwid9mnoqIFK+e0vqoi1qH56JpmZSzEL53jKnNzScdmftJyG5xWg==}
dependencies:
@@ -7523,14 +7465,14 @@ packages:
indent-string: 4.0.0
dev: true
- resolution: {integrity: sha512-rzBJFhGQAMMzQEPCAWPc2XB4wQ4ce2k/fo9MTWkp2awPsZX2d11DsXF8BMDYFVO/xioEPTeix138jVQEZEpY7g==}
+ resolution: {integrity: sha512-GWVJ+Rb7Xt6oEk44aO2fpDYGMIoH3VL8toGKKQNq8sHKzxfBRYwOF9n8ir9YyU53STt7mAc1Kp3r9AEeWPePAA==}
engines: {node: '>=14.6'}
peerDependencies:
react: ^18.2.0
- solid-js: ^1.7.7
- svelte: ^3.0.0 || ^4.0.0
- vue: ^3.3.4
+ solid-js: '*'
+ svelte: '*'
+ vue: '*'
zod: ^3.0.0
peerDependenciesMeta:
react:
@@ -7544,18 +7486,15 @@ packages:
zod:
optional: true
dependencies:
- eventsource-parser: 1.0.0
+ eventsource-parser: 1.1.2
jsondiffpatch: 0.6.0
nanoid: 3.3.6
react: 18.2.0
- solid-js: 1.8.16
- solid-swr-store: 0.10.7([email protected])([email protected])
- sswr: 2.0.0([email protected])
- svelte: 4.2.12
+ secure-json-parse: 2.7.0
+ sswr: 2.0.0
swr: 2.2.0([email protected])
swr-store: 0.10.6
- swrv: 1.0.4([email protected])
- vue: 3.4.21([email protected])
+ swrv: 1.0.4
zod: 3.22.4
zod-to-json-schema: 3.22.4([email protected])
dev: false
@@ -7667,6 +7606,7 @@ packages:
resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
dependencies:
dequal: 2.0.3
+ dev: true
resolution: {integrity: sha512-8wdW3ZGk6UjMPJx/glyEt0sLzzwAE1bhToPsO1W2pbpR2gULyxe3BjSiuJFheP50T/GgODVPz2fuMUmIywt8cQ==}
@@ -7887,12 +7827,6 @@ packages:
dequal: 2.0.3
dev: true
- resolution: {integrity: sha512-+60uv1hiVFhHZeO+Lz0RYzsVHy5Wr1ayX0mwda9KPDVLNJgZ1T9Ny7VmFbLDzxsH0D87I86vgj3gFrjTJUYznw==}
- dependencies:
- dequal: 2.0.3
- dev: false
-
resolution: {integrity: sha512-poPX9mZH/5CSanm50Q+1toVci6pv5KSRv/5TWCwtzQS5XEwn40BcCrgIeMFWP9CKKIniKXNxoIOnOq4VVlGXhg==}
peerDependencies:
@@ -8425,16 +8359,6 @@ packages:
engines: {node: '>=0.10.0'}
dev: false
- resolution: {integrity: sha512-7qJWqItLA8/VPVlKJlFXU+NBlo/qyfs39aJcuMT/2ere32ZqvF5OSxgdM5xOfJJ7O429gg2HM47y8v9P+9wrNw==}
- dependencies:
- '@jridgewell/sourcemap-codec': 1.4.15
- '@types/estree': 1.0.5
- acorn: 8.11.3
- estree-walker: 3.0.3
- periscopic: 3.1.0
- dev: false
-
resolution: {integrity: sha512-IgNoyK7d4HJicqZMYMC1RgHlpR1pnSEgDHATKIuQrqW68o5QmD8IFZ26M/8UXNI+Usb00Vu4q0EtzMdm92pOAg==}
peerDependencies:
@@ -10350,11 +10274,13 @@ packages:
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
+ dev: true
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
dependencies:
'@types/estree': 1.0.5
+ dev: true
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
@@ -10375,8 +10301,8 @@ packages:
engines: {node: '>=0.8.x'}
dev: false
- resolution: {integrity: sha512-9jgfSCa3dmEme2ES3mPByGXfgZ87VbP97tng1G2nWwWx6bV2nYxm2AWCrbQjXToSe+yYlqaZNtxffR9IeQr95g==}
+ resolution: {integrity: sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA==}
engines: {node: '>=14.18'}
dev: false
@@ -11777,12 +11703,6 @@ packages:
resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
dev: true
- resolution: {integrity: sha512-v3rht/LgVcsdZa3O2Nqs+NMowLOxeOm7Ay9+/ARQ2F+qEoANRcqrjAZKGN0v8ymUetZGgkp26LTnGT7H0Qo9Pg==}
- dependencies:
- '@types/estree': 1.0.5
- dev: false
-
resolution: {integrity: sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==}
engines: {node: '>= 0.4'}
@@ -12432,10 +12352,6 @@ packages:
pkg-types: 1.0.3
dev: true
- resolution: {integrity: sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==}
- dev: false
-
resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==}
engines: {node: '>=6'}
@@ -12547,6 +12463,7 @@ packages:
engines: {node: '>=12'}
dependencies:
'@jridgewell/sourcemap-codec': 1.4.15
+ dev: true
resolution: {integrity: sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==}
@@ -13616,14 +13533,6 @@ packages:
resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==}
dev: false
- resolution: {integrity: sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==}
- dependencies:
- '@types/estree': 1.0.5
- estree-walker: 3.0.3
- is-reference: 3.0.2
- dev: false
-
resolution: {integrity: sha512-ESj2+eBxhGrcA1azgHs7lARG5+5iLakc/6nlfbpjcLl00HuuUOIuORhYXN4D1HfvMSKuVtFQjAlnwi1JHEeDIw==}
dev: false
@@ -15395,6 +15304,10 @@ packages:
ajv-keywords: 3.5.2([email protected])
dev: false
+ resolution: {integrity: sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==}
+ dev: false
+
resolution: {integrity: sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==}
hasBin: true
@@ -15437,20 +15350,6 @@ packages:
randombytes: 2.1.0
dev: false
- resolution: {integrity: sha512-8+pDC1vOedPXjKG7oz8o+iiHrtF2WswaMQJ7CKFpccvSYfrzmvKY9zOJWCg+881722wIHfwkdnRmiiDm9ym+zQ==}
- engines: {node: '>=10'}
- peerDependencies:
- seroval: ^1.0
- dependencies:
- seroval: 1.0.5
- dev: false
-
- resolution: {integrity: sha512-TM+Z11tHHvQVQKeNlOUonOWnsNM+2IBwZ4vwoi4j3zKzIpc5IDw8WPwCfcc8F17wy6cBcJGbZbFOR0UCuTZHQA==}
- engines: {node: '>=10'}
- dev: false
-
resolution: {integrity: sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==}
engines: {node: '>= 0.8.0'}
@@ -15566,25 +15465,6 @@ packages:
is-fullwidth-code-point: 3.0.0
dev: true
- resolution: {integrity: sha512-rja94MNU9flF3qQRLNsu60QHKBDKBkVE1DldJZPIfn2ypIn3NV2WpSbGTQIvsyGPBo+9E2IMjwqnqpbgfWuzeg==}
- dependencies:
- csstype: 3.1.3
- seroval: 1.0.5
- seroval-plugins: 1.0.5([email protected])
- dev: false
-
- resolution: {integrity: sha512-A6d68aJmRP471aWqKKPE2tpgOiR5fH4qXQNfKIec+Vap+MGQm3tvXlT8n0I8UgJSlNAsSAUuw2VTviH2h3Vv5g==}
- engines: {node: '>=10'}
- peerDependencies:
- solid-js: ^1.2
- swr-store: ^0.10
- dependencies:
- solid-js: 1.8.16
- swr-store: 0.10.6
- dev: false
-
resolution: {integrity: sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg==}
engines: {node: '>=0.10.0'}
@@ -15654,12 +15534,9 @@ packages:
tweetnacl: 0.14.5
dev: false
resolution: {integrity: sha512-mV0kkeBHcjcb0M5NqKtKVg/uTIYNlIIniyDfSGrSfxpEdM9C365jK0z55pl9K0xAkNTJi2OAOVFQpgMPUk+V0w==}
- peerDependencies:
- svelte: ^4.0.0
dependencies:
- svelte: 4.2.12
swrev: 4.0.0
dev: false
@@ -16062,26 +15939,6 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-d8+wsh5TfPwqVzbm4/HCXC783/KPHV60NvwitJnyTA5lWn1elhXMNWhXGCJ7PwPa8qFUnyJNIyuIRt2mT0WMug==}
- engines: {node: '>=16'}
- dependencies:
- '@ampproject/remapping': 2.3.0
- '@jridgewell/sourcemap-codec': 1.4.15
- '@jridgewell/trace-mapping': 0.3.25
- '@types/estree': 1.0.5
- acorn: 8.11.3
- aria-query: 5.3.0
- axobject-query: 4.0.0
- code-red: 1.0.4
- css-tree: 2.3.1
- estree-walker: 3.0.3
- is-reference: 3.0.2
- locate-character: 3.0.0
- magic-string: 0.30.8
- periscopic: 3.1.0
- dev: false
-
resolution: {integrity: sha512-djbJ/vZKZO+gPoSDThGNpKDO+o+bAeA4XQKovvkNCqnIS2t+S4qnLAGQhyyrulhCFRl1WWzAp0wUDV8PpTVU3g==}
dev: false
@@ -16148,12 +16005,8 @@ packages:
resolution: {integrity: sha512-LqVcOHSB4cPGgitD1riJ1Hh4vdmITOp+BkmfmXRh4hSF/t7EnS4iD+SOTmq7w5pPm/SiPeto4ADbKS6dHUDWFA==}
dev: false
resolution: {integrity: sha512-zjEkcP8Ywmj+xOJW3lIT65ciY/4AL4e/Or7Gj0MzU3zBJNMdJiT8geVZhINavnlHRMMCcJLHhraLTAiDOTmQ9g==}
- peerDependencies:
- vue: '>=3.2.26 < 4'
- dependencies:
- vue: 3.4.21([email protected])
dev: false
@@ -16740,6 +16593,7 @@ packages:
resolution: {integrity: sha512-KrPd3PKaCLr78MalgiwJnA25Nm8HAmdwN3mYUYZgG/wizIo9EainNVQI9/yDavtVFRN2h3k8uf3GLHuhDMgEHg==}
engines: {node: '>=14.17'}
hasBin: true
+ dev: true
resolution: {integrity: sha512-o+ORpgGwaYQXgqGDwd+hkS4PuZ3QnmqMMxRuajK/a38L6fTpcE5GPIfrf+L/KemFzfUpeUQc1rRS1iDBozvnFA==}
@@ -17566,22 +17420,6 @@ packages:
pbf: 3.2.1
dev: false
- resolution: {integrity: sha512-5hjyV/jLEIKD/jYl4cavMcnzKwjMKohureP8ejn3hhEjwhWIhWeuzL2kJAjzl/WyVsgPY56Sy4Z40C3lVshxXA==}
- peerDependencies:
- typescript: '*'
- peerDependenciesMeta:
- typescript:
- optional: true
- dependencies:
- '@vue/compiler-dom': 3.4.21
- '@vue/compiler-sfc': 3.4.21
- '@vue/runtime-dom': 3.4.21
- '@vue/server-renderer': 3.4.21([email protected])
- '@vue/shared': 3.4.21
- typescript: 5.4.3
- dev: false
-
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
dev: false
diff --git a/frontend/src/hooks/useAsyncData.ts b/frontend/src/hooks/useAsyncData.ts
index c214fd1360..dc47c21035 100644
--- a/frontend/src/hooks/useAsyncData.ts
+++ b/frontend/src/hooks/useAsyncData.ts
@@ -9,12 +9,16 @@ interface AsyncDataResponse<T> {
setData: Dispatch<SetStateAction<T | undefined>>;
}
+interface Context {
+ previous(): void;
+}
+
/**
* A hook that loads data asynchronously.
* Handles loading and error states, and prevents race conditions.
*/
export function useAsyncData<T>(
- loader: () => Promise<T>,
+ loader: (context: Context) => Promise<T>,
deps: DependencyList,
): AsyncDataResponse<T> {
const [data, setData] = useState<T | undefined>(undefined);
@@ -23,12 +27,21 @@ export function useAsyncData<T>(
useEffect(() => {
let isCancelled = false;
+ let keepPrevious = false;
+ const context = {
+ previous: () => {
+ keepPrevious = true;
+ },
+ };
setLoading(true);
- loader()
+ loader(context)
.then((data) => {
if (isCancelled) {
return;
}
+ if (keepPrevious) {
+ return;
+ }
setData(data);
setError(undefined);
})
diff --git a/frontend/src/plugins/layout/LazyPlugin.tsx b/frontend/src/plugins/layout/LazyPlugin.tsx
new file mode 100644
index 0000000000..c6f7321a26
--- /dev/null
+++ b/frontend/src/plugins/layout/LazyPlugin.tsx
@@ -0,0 +1,75 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { z } from "zod";
+
+import { createPlugin } from "@/plugins/core/builder";
+import { rpc } from "@/plugins/core/rpc";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { ErrorBanner } from "../impl/common/error-banner";
+import { renderHTML } from "../core/RenderHTML";
+import { useIntersectionObserver } from "@uidotdev/usehooks";
+import { useRef } from "react";
+import { Loader2Icon } from "lucide-react";
+
+interface Data {
+ showLoadingIndicator: boolean;
+}
+
+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+type PluginFunctions = {
+ load: (req: {}) => Promise<{
+ html: string;
+ }>;
+};
+
+type S = undefined;
+
+export const LazyPlugin = createPlugin<S>("marimo-lazy")
+ .withData(
+ z.object({
+ showLoadingIndicator: z.boolean().default(false),
+ }),
+ )
+ .withFunctions<PluginFunctions>({
+ load: rpc.input(z.object({})).output(
+ z.object({
+ html: z.string(),
+ }),
+ ),
+ })
+ .renderer((props) => <LazyComponent {...props.data} {...props.functions} />);
+
+type Props = PluginFunctions & Data;
+
+const LazyComponent = ({ load, showLoadingIndicator }: Props): JSX.Element => {
+ const [ref, entry] = useIntersectionObserver({
+ threshold: 0,
+ root: null,
+ rootMargin: "0px",
+ });
+
+ const hasIntersected = useRef<boolean>(false);
+ if (entry?.isIntersecting) {
+ hasIntersected.current = true;
+ }
+
+ const { data, loading, error } = useAsyncData(() => {
+ if (!hasIntersected.current) {
+ return Promise.resolve({ html: "" });
+ }
+ return load({});
+ }, [hasIntersected.current]);
+
+ if (error) {
+ return <ErrorBanner error={error} />;
+ }
+
+ return (
+ <div ref={ref} className="min-h-4">
+ {loading && showLoadingIndicator ? (
+ <Loader2Icon className="w-12 h-12 animate-spin text-primary my-4 mx-4" />
+ ) : (
+ data && renderHTML({ html: data.html })
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 4df777c2bc..8981b62eee 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -37,6 +37,7 @@ import { CodeEditorPlugin } from "./impl/CodeEditorPlugin";
import { DataExplorerPlugin } from "./impl/data-explorer/DataExplorerPlugin";
import { MermaidPlugin } from "./layout/mermaid/MermaidPlugin";
import { AnyWidgetPlugin } from "./impl/anywidget/AnyWidgetPlugin";
+import { LazyPlugin } from "./layout/LazyPlugin";
// List of UI plugins
export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -63,6 +64,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
new PlotlyPlugin(),
DataExplorerPlugin,
DataFramePlugin,
+ LazyPlugin,
new AnyWidgetPlugin(),
];
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 89bdd48cde..581d1aabf4 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -33,6 +33,7 @@ __all__ = [
"Html",
"icon",
"image",
+ "lazy",
"left",
"md",
"mermaid",
@@ -74,6 +75,7 @@ from marimo._plugins.stateless.download import download
from marimo._plugins.stateless.flex import hstack, vstack
from marimo._plugins.stateless.icon import icon
from marimo._plugins.stateless.image import image
+from marimo._plugins.stateless.lazy import lazy
from marimo._plugins.stateless.mermaid import mermaid
from marimo._plugins.stateless.pdf import pdf
from marimo._plugins.stateless.plain_text import plain_text
diff --git a/marimo/_plugins/stateless/accordion.py b/marimo/_plugins/stateless/accordion.py
index 4644ced2ac..a663752125 100644
--- a/marimo/_plugins/stateless/accordion.py
+++ b/marimo/_plugins/stateless/accordion.py
@@ -6,10 +6,13 @@ from marimo._output.hypertext import Html
from marimo._output.md import md
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import build_stateless_plugin
+from marimo._plugins.stateless.lazy import lazy as lazy_ui
@mddoc
-def accordion(items: dict[str, object], multiple: bool = False) -> Html:
+def accordion(
+ items: dict[str, object], multiple: bool = False, lazy: bool = False
+) -> Html:
"""
Accordion of one or more items.
@@ -21,24 +24,41 @@ def accordion(items: dict[str, object], multiple: bool = False) -> Html:
})
```
+ Accordion content can be lazily loaded:
+
+ ```python3
+ mo.accordion({
+ "View total": expensive_item
+ }, lazy=True)
+ ```
+
+ where `expensive_item` is the item to render, or a callable that
+ returns the item to render.
+
**Args.**
- `items`: a dictionary of item names to item content; strings are
interpreted as markdown
- `multiple`: whether to allow multiple items to be open simultaneously
+ - `lazy`: a boolean, whether to lazily load the accordion content.
+ This is a convenience that wraps each accordion in a `mo.lazy`
+ component.
**Returns.**
- An `Html` object.
"""
+
+ def render_content(tab: object) -> str:
+ if lazy:
+ return lazy_ui(tab).text
+ if isinstance(tab, str):
+ return md(tab).text
+ return as_html(tab).text
+
item_labels = list(md(label).text for label in items.keys())
item_content = "".join(
- [
- "<div>"
- + (md(item).text if isinstance(item, str) else as_html(item).text)
- + "</div>"
- for item in items.values()
- ]
+ ["<div>" + render_content(item) + "</div>" for item in items.values()]
)
return Html(
build_stateless_plugin(
diff --git a/marimo/_plugins/stateless/lazy.py b/marimo/_plugins/stateless/lazy.py
new file mode 100644
index 0000000000..28abff3275
--- /dev/null
+++ b/marimo/_plugins/stateless/lazy.py
@@ -0,0 +1,94 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Callable, Final, Union
+
+from marimo._output.formatting import as_html
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._runtime.functions import EmptyArgs, Function
+
+
+@dataclass
+class LoadResponse:
+ html: str
+
+
+@mddoc
+class lazy(UIElement[None, None]):
+ """Lazy load a component until it is visible.
+
+ Use `mo.lazy` to defer rendering of an item until it's visible. This is
+ useful for loading expensive components only when they are needed, e.g.,
+ only when an accordion or tab is opened.
+
+ The argument to `mo.lazy` can be an object to render lazily, or a function
+ that returns the object to render (that is, functions are lazily
+ evaluated). Using a function is useful when the item to render is
+ the result of a database query or some other expensive operation.
+
+ **Examples.**
+
+ Create a lazy-loaded tab:
+
+ ```python
+ tabs = mo.ui.tabs({
+ "Overview": tab1,
+ "Charts": mo.lazy(expensive_component)
+ })
+ ```
+
+ Create a lazy-loaded accordion:
+
+ ```python
+ accordion = mo.ui.accordion({
+ "Charts": mo.lazy(expensive_component)
+ })
+ ```
+
+ **Initialization Args.**
+
+ - `element`: object or callable that returns content to be lazily loaded
+ - `show_loading_indicator`: a boolean, whether to show a loading
+ indicator while the content is being loaded.
+ Default is `False`.
+ """
+
+ _name: Final[str] = "marimo-lazy"
+
+ def __init__(
+ self,
+ element: Union[Callable[[], object], object],
+ show_loading_indicator: bool = False,
+ ) -> None:
+ self._element = element
+
+ super().__init__(
+ component_name=self._name,
+ initial_value=None,
+ label="",
+ args={
+ "show-loading-indicator": show_loading_indicator,
+ },
+ on_change=lambda _: None,
+ functions=(
+ Function(
+ name=self.load.__name__,
+ arg_cls=EmptyArgs,
+ function=self.load,
+ ),
+ ),
+ )
+
+ def _convert_value(self, value: None) -> None:
+ return value
+
+ def load(self, _args: EmptyArgs) -> LoadResponse:
+ if callable(self._element) and not isinstance(
+ self._element, UIElement
+ ):
+ el = self._element()
+ return LoadResponse(html=as_html(el).text)
+ else:
+ return LoadResponse(html=as_html(self._element).text)
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index debe548079..62f69a5420 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -33,7 +33,6 @@ __all__ = [
"text",
]
-
from marimo._plugins.ui._impl.altair_chart import altair_chart
from marimo._plugins.ui._impl.array import array
from marimo._plugins.ui._impl.batch import batch
diff --git a/marimo/_plugins/ui/_impl/tabs.py b/marimo/_plugins/ui/_impl/tabs.py
index ed78195906..6992d4f922 100644
--- a/marimo/_plugins/ui/_impl/tabs.py
+++ b/marimo/_plugins/ui/_impl/tabs.py
@@ -6,6 +6,7 @@ from typing import Callable, Final, Optional
from marimo._output.formatting import as_html
from marimo._output.md import md
from marimo._output.rich_help import mddoc
+from marimo._plugins.stateless.lazy import lazy as lazy_ui
from marimo._plugins.ui._core.ui_element import UIElement
@@ -41,6 +42,15 @@ class tabs(UIElement[str, str]):
}, value="Heading 2")
```
+ Tab content can be lazily loaded:
+
+ ```python
+ tabs = mo.ui.tabs({
+ "Heading 1": tab1,
+ "Heading 2": expensive_component
+ }, lazy=True)
+ ```
+
**Attributes.**
- `value`: A string, the name of the selected tab.
@@ -50,6 +60,9 @@ class tabs(UIElement[str, str]):
- `tabs`: a dictionary of tab names to tab content; strings are interpreted
as markdown
- `value`: the name of the tab to open; defaults to the first tab
+ - `lazy`: a boolean, whether to lazily load the tab content.
+ This is a convenience that wraps each tab in a `mo.lazy`
+ component.
"""
_name: Final[str] = "marimo-tabs"
@@ -58,15 +71,21 @@ class tabs(UIElement[str, str]):
self,
tabs: dict[str, object],
value: Optional[str] = None,
+ lazy: bool = False,
*,
label: str = "",
on_change: Optional[Callable[[str], None]] = None,
) -> None:
+ def render_content(tab: object) -> str:
+ if lazy:
+ return lazy_ui(tab).text
+ if isinstance(tab, str):
+ return md(tab).text
+ return as_html(tab).text
+
tab_items = "".join(
[
- "<div data-kind='tab'>"
- + (md(tab).text if isinstance(tab, str) else as_html(tab).text)
- + "</div>"
+ "<div data-kind='tab'>" + render_content(tab) + "</div>"
for tab in tabs.values()
]
)
diff --git a/marimo/_smoke_tests/lazy.py b/marimo/_smoke_tests/lazy.py
new file mode 100644
index 0000000000..f8a1757f5f
--- /dev/null
+++ b/marimo/_smoke_tests/lazy.py
@@ -0,0 +1,73 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App(width="full")
+
+
+def __(generate_number, mo, table):
+ tabs = mo.ui.tabs(
+ {
+ "First": "",
+ "Second": mo.lazy(table),
+ "Third": mo.lazy(generate_number, show_loading_indicator=True),
+ }
+ )
+ tabs
+ return tabs,
+
+
+def __(generate_number, mo, table):
+ auto_lazy_tabs = mo.ui.tabs(
+ {
+ "First": "",
+ "Second": table,
+ "Third": generate_number,
+ },
+ lazy=True,
+ )
+ auto_lazy_tabs
+ return auto_lazy_tabs,
+
+
+def __(generate_number, mo):
+ mo.accordion({"Open me": mo.lazy(generate_number, show_loading_indicator=True)})
+ return
+
+
+def __(generate_number, mo):
+ mo.accordion({"Open me": generate_number}, lazy=True)
+ return
+
+
+def __(random, time):
+ def generate_number():
+ print("Loading...")
+ time.sleep(1)
+ print("Loaded!")
+ num = random.randint(0, 100)
+ return num
+ return generate_number,
+
+
+def __():
+ import marimo as mo
+ import pandas as pd
+ import random
+ import time
+ import vega_datasets
+
+ cars = vega_datasets.data.cars()
+ table = mo.ui.table(cars)
+ return cars, mo, pd, random, table, time, vega_datasets
+
+
+if __name__ == "__main__":
+ app.run()