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.

[experimental] Grid Layout (#103)

Myles Scolnick9c6a982c14e2
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml
index a78a18003f..10aa1c0efa 100644
--- a/.github/workflows/playwright.yml
+++ b/.github/workflows/playwright.yml
@@ -14,7 +14,7 @@ jobs:
shell: bash
env:
NODE_ENV: test
- DEBUG: "pw:webserver"
+ DEBUG: 'pw:webserver'
steps:
- name: 🛑 Cancel Previous Runs
@@ -23,6 +23,11 @@ jobs:
- name: ⬇️ Checkout repo
uses: actions/checkout@v3
+ - name: Write TOML
+ run: |
+ echo "[experimental]" > .marimo.toml
+ echo "layouts=true" >> .marimo.toml
+
- uses: pnpm/action-setup@v2
with:
version: 8
@@ -31,8 +36,8 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: 18
- cache: "pnpm"
- cache-dependency-path: "**/pnpm-lock.yaml"
+ cache: 'pnpm'
+ cache-dependency-path: '**/pnpm-lock.yaml'
- name: 📥 Install pnpm dependencies
working-directory: ./frontend
@@ -44,7 +49,7 @@ jobs:
- name: 🐍 Setup Python 3.10
uses: actions/setup-python@v4
with:
- python-version: "3.10"
+ python-version: '3.10'
- name: 🐍 Install marimo
run: |
@@ -95,9 +100,9 @@ jobs:
continue-on-error: true
with:
base-branch: main
- api-endpoint: "https://marimo.io/api"
+ api-endpoint: 'https://marimo.io/api'
api-token: ${{ secrets.VISUAL_SNAPSHOT_SECRET }}
- gcs-bucket: "marimo-oss-visual-snapshots"
+ gcs-bucket: 'marimo-oss-visual-snapshots'
snapshot-path: frontend/e2e-tests/screenshots
- name: 📊 Upload snapshots
diff --git a/frontend/e2e-tests/layout-grid.spec.ts b/frontend/e2e-tests/layout-grid.spec.ts
new file mode 100644
index 0000000000..fd42e2e821
--- /dev/null
+++ b/frontend/e2e-tests/layout-grid.spec.ts
@@ -0,0 +1,93 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { test, expect, Page } from "@playwright/test";
+import { getAppUrl } from "../playwright.config";
+
+const runUrl = getAppUrl("layout_grid.py//run");
+const editUrl = getAppUrl("layout_grid.py//edit");
+
+test("can run Grid layout", async ({ page }) => {
+ await page.goto(runUrl);
+ // wait 500ms to render
+ await page.waitForTimeout(500);
+
+ // Verify markdown "Grid Layout"
+ await expect(page.getByText("Grid Layout")).toBeVisible();
+
+ // Type in search box
+ await page.fill("input", "hello");
+
+ // Verify dependent output updated
+ await expect(page.getByText("Searching hello")).toBeVisible();
+
+ // Verify text 1 have the same y coordinate as text 2, but text 2 is further left
+ const bb1 = await bbForText(page, "text 1");
+ const bb2 = await bbForText(page, "text 2");
+ await expect(bb1.y).toBe(bb2.y);
+ await expect(bb1.x).toBeGreaterThan(bb2.x);
+});
+
+test("can edit Grid layout", async ({ page }) => {
+ await page.goto(editUrl);
+
+ // Verify text 1 bounding box is above text 2
+ let bb1 = await bbForText(page, "text 1");
+ let bb2 = await bbForText(page, "text 2");
+ await expect(bb1.y).toBeLessThan(bb2.y);
+
+ // Toggle preview-button
+ await page.locator("#preview-button").click();
+ // Wait 500ms to allow preview to render
+ await page.waitForTimeout(500);
+
+ // Verify text 1 have the same y coordinate as text 2, but text 2 is further left
+ bb1 = await bbForText(page, "text 1");
+ bb2 = await bbForText(page, "text 2");
+ await expect(bb1.y).toBe(bb2.y);
+ await expect(bb1.x).toBeGreaterThan(bb2.x);
+
+ // Can still use interactive elements
+ await page.fill("input", "hello");
+ await expect(page.getByText("Searching hello")).toBeVisible();
+
+ // Can toggle to Vertical layout
+ const layoutSelect = page.getByTestId("layout-select");
+ await expect(layoutSelect).toBeVisible();
+ await layoutSelect.click();
+ await page.getByText("Vertical").click();
+ // Wait 500ms to allow preview to render
+ await page.waitForTimeout(500);
+
+ // Verify bounding boxes are back to vertical
+ bb1 = await bbForText(page, "text 1");
+ bb2 = await bbForText(page, "text 2");
+ await expect(bb1.x).toBe(bb2.x);
+ await expect(bb1.y).toBeLessThan(bb2.y);
+});
+
+interface BoundingBox {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+function expectValidBoundingBox(
+ bb: BoundingBox | null
+): asserts bb is BoundingBox {
+ expect(bb).toBeDefined();
+ if (!bb) {
+ throw new Error("bb is null");
+ }
+ expect(bb.x).toBeGreaterThan(0);
+ expect(bb.y).toBeGreaterThan(0);
+ expect(bb.width).toBeGreaterThan(0);
+ expect(bb.height).toBeGreaterThan(0);
+}
+
+async function bbForText(page: Page, text: string) {
+ const el = page.getByText(text).first();
+ await expect(el).toBeVisible();
+ const bb = await el.boundingBox();
+ expectValidBoundingBox(bb);
+ return bb;
+}
diff --git a/frontend/e2e-tests/mode.spec.ts b/frontend/e2e-tests/mode.spec.ts
index 109b927f81..6af44ce205 100644
--- a/frontend/e2e-tests/mode.spec.ts
+++ b/frontend/e2e-tests/mode.spec.ts
@@ -16,7 +16,7 @@ test("page renders edit feature in edit mode", async ({ page }) => {
await takeScreenshot(page, __filename);
});
-test("can toggle to read mode", async ({ page }) => {
+test("can toggle to presenter mode", async ({ page }) => {
const appUrl = getAppUrl("title.py");
await page.goto(appUrl);
diff --git a/frontend/e2e-tests/py/layout_grid.py b/frontend/e2e-tests/py/layout_grid.py
new file mode 100644
index 0000000000..10c23231be
--- /dev/null
+++ b/frontend/e2e-tests/py/layout_grid.py
@@ -0,0 +1,45 @@
+import marimo
+
+__generated_with = "0.1.2"
+app = marimo.App(layout_file="layouts/layout_grid.grid.json")
+
+
+def __(mo):
+ mo.md("# Grid Layout")
+ return
+
+
+def __(mo, search):
+ mo.md(f"Searching {search.value}")
+ return
+
+
+def __(mo):
+ search = mo.ui.text(label="Search")
+ search
+ return search,
+
+
+def __(mo):
+ mo.md("text 1")
+ return
+
+
+def __(mo):
+ mo.md("text 2")
+ return
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/e2e-tests/py/layouts/layout_grid.grid.json b/frontend/e2e-tests/py/layouts/layout_grid.grid.json
new file mode 100644
index 0000000000..951bb82f71
--- /dev/null
+++ b/frontend/e2e-tests/py/layouts/layout_grid.grid.json
@@ -0,0 +1,27 @@
+{
+ "type": "grid",
+ "data": {
+ "columns": 12,
+ "rowHeight": 40,
+ "cells": [
+ {
+ "position": [0, 0, 5, 2]
+ },
+ {
+ "position": [0, 2, 4, 2]
+ },
+ {
+ "position": [5, 0, 5, 2]
+ },
+ {
+ "position": [3, 4, 3, 2]
+ },
+ {
+ "position": [0, 4, 3, 2]
+ },
+ {
+ "position": null
+ }
+ ]
+ }
+}
diff --git a/frontend/package.json b/frontend/package.json
index 1a13bd75ac..ae2a1603ac 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -55,6 +55,7 @@
"@tanstack/react-table": "^8.10.0",
"@textea/json-viewer": "^3.1.1",
"@types/js-cookie": "^3.0.4",
+ "@types/react-grid-layout": "^1.3.2",
"class-variance-authority": "^0.7.0",
"clsx": "^1.2.1",
"cmdk": "^0.2.0",
@@ -73,6 +74,7 @@
"react-day-picker": "^8.8.2",
"react-dropzone": "^14.2.3",
"react-error-boundary": "^4.0.11",
+ "react-grid-layout": "^1.3.4",
"react-hook-form": "^7.46.1",
"react-resizable-panels": "^0.0.53",
"react-use-event-hook": "^0.9.6",
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index a6d0ae703b..f13cee760c 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -31,6 +31,8 @@ const appToOptions = {
"components.py": { port: port(), command: "run" },
"cells.py": { port: port(), command: "edit" },
"bugs.py": { port: port(), command: "edit" },
+ "layout_grid.py//edit": { port: port(), command: "edit" },
+ "layout_grid.py//run": { port: port(), command: "run" },
} satisfies Record<string, ServerOptions>;
export type ApplicationNames = keyof typeof appToOptions;
@@ -119,6 +121,8 @@ const config: PlaywrightTestConfig = {
// Run marimo servers before starting the tests, one for each app/test
webServer: Object.entries(appToOptions).map(([app, options]) => {
+ app = app.replace("//edit", "").replace("//run", "");
+
const { command, port } = options;
const pathToApp = path.join(pydir, app);
const marimoCmd = `marimo -q ${command} ${pathToApp} -p ${port} --headless`;
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 786ae448a3..fe1fd185cb 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -137,6 +137,9 @@ dependencies:
'@types/js-cookie':
specifier: ^3.0.4
version: 3.0.4
+ '@types/react-grid-layout':
+ specifier: ^1.3.2
+ version: 1.3.2
class-variance-authority:
specifier: ^0.7.0
version: 0.7.0
@@ -191,6 +194,9 @@ dependencies:
react-error-boundary:
specifier: ^4.0.11
version: 4.0.11([email protected])
+ react-grid-layout:
+ specifier: ^1.3.4
react-hook-form:
specifier: ^7.46.1
version: 7.46.1([email protected])
@@ -483,7 +489,7 @@ packages:
'@babel/compat-data': 7.22.9
'@babel/core': 7.21.8
'@babel/helper-validator-option': 7.22.5
- browserslist: 4.21.10
+ browserslist: 4.21.9
lru-cache: 5.1.1
semver: 6.3.1
dev: true
@@ -497,7 +503,7 @@ packages:
'@babel/compat-data': 7.22.9
'@babel/core': 7.22.9
'@babel/helper-validator-option': 7.22.5
- browserslist: 4.21.10
+ browserslist: 4.21.9
lru-cache: 5.1.1
semver: 6.3.1
dev: true
@@ -590,11 +596,19 @@ packages:
'@babel/types': 7.22.5
dev: true
+ resolution: {integrity: sha512-orajc5T2PsRYUN3ZryCEFeMDYwyw09c/pZeaQEZPH0MpKzSvn3e0uXsDBu3k03VI+9DBiRo+l22BfKTpKwa/Wg==}
+ engines: {node: '>=6.9.0'}
+ dependencies:
+ '@babel/types': 7.22.5
+ dev: false
+
resolution: {integrity: sha512-8Dl6+HD/cKifutF5qGd/8ZJi84QeAKh+CEe1sBzz8UayBBGg1dAIJrdHOcOM5b2MpzWL2yuotJTtGjETq0qjXg==}
engines: {node: '>=6.9.0'}
dependencies:
'@babel/types': 7.22.5
+ dev: true
resolution: {integrity: sha512-t+WA2Xn5K+rTeGtC8jCsdAH52bjggG5TKRuRrAGNM/mjIbO4GxvlLMFOEz9wXY5I2XQ60PMFsAG2WIcG82dQMQ==}
@@ -759,7 +773,6 @@ packages:
resolution: {integrity: sha512-cumfXOF0+nzZrrN8Rf0t7M+tF6sZc7vhQwYQck9q1/5w2OExlD+b4v4RpMJFaV1Z7WcDRgO6FqvxqxGlwo+RHQ==}
engines: {node: '>=6.9.0'}
- deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
peerDependencies:
'@babel/core': ^7.0.0-0
dependencies:
@@ -786,7 +799,6 @@ packages:
resolution: {integrity: sha512-wQxQzxYeJqHcfppzBDnm1yAY0jSRkUXR2z8RePZYrKwMKgMlE8+Z6LUno+bd6LvbGh8Gltvy74+9pIYkr+XkKA==}
engines: {node: '>=6.9.0'}
- deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
peerDependencies:
'@babel/core': ^7.0.0-0
dependencies:
@@ -809,7 +821,6 @@ packages:
resolution: {integrity: sha512-p4zeefM72gpmEe2fkUr/OnOXpWEf8nAgk7ZYVqqfFiyIG7oFfVZcCrU64hWn5xp4tQ9LkV4bTIa5rD0KANpKNA==}
engines: {node: '>=6.9.0'}
- deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
peerDependencies:
'@babel/core': ^7.0.0-0
dependencies:
@@ -833,7 +844,6 @@ packages:
resolution: {integrity: sha512-ha4zfehbJjc5MmXBlHec1igel5TJXXLDDRbuJ4+XT2TJcyD9/V1919BA8gMvsdHcNMBy4WBUBiRb3nw/EQUtBw==}
engines: {node: '>=6.9.0'}
- deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-property-in-object instead.
peerDependencies:
'@babel/core': ^7.0.0-0
dependencies:
@@ -856,7 +866,6 @@ packages:
resolution: {integrity: sha512-2BShG/d5yoZyXZfVePH91urL5wTG6ASZU9M4o03lKK8u8UW1y08OMttBSOADTcJrnPMpvDXRG3G8fyLh4ovs8w==}
engines: {node: '>=4'}
- deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-unicode-property-regex instead.
peerDependencies:
'@babel/core': ^7.0.0-0
dependencies:
@@ -2121,7 +2130,7 @@ packages:
/@emotion/[email protected]:
resolution: {integrity: sha512-m4HEDZleaaCH+XgDDsPF15Ht6wTLsgDTeR3WYj9Q/k76JtWhrJjcP4+/XlG8LGT/Rol9qUfOIztXeA84ATpqPQ==}
dependencies:
- '@babel/helper-module-imports': 7.22.5
+ '@babel/helper-module-imports': 7.21.4
'@babel/runtime': 7.22.5
'@emotion/hash': 0.9.1
'@emotion/memoize': 0.8.1
@@ -2416,7 +2425,7 @@ packages:
eslint: ^6.0.0 || ^7.0.0 || >=8.0.0
dependencies:
eslint: 8.49.0
- eslint-visitor-keys: 3.4.3
+ eslint-visitor-keys: 3.4.2
/@eslint-community/[email protected]:
resolution: {integrity: sha512-Z5ba73P98O1KUYCCJTUeVpja9RcGoMdncZ6T49FCUl2lN38JtCJ+3WgIDBv0AuY4WChU5PmtJmOCTlN6FZTFKQ==}
@@ -5884,6 +5893,12 @@ packages:
dependencies:
'@types/react': 18.2.21
+ resolution: {integrity: sha512-ZzpBEOC1JTQ7MGe1h1cPKSLP4jSWuxc+yvT4TsAlEW9+EFPzAf8nxQfFd7ea9gL17Em7PbwJZAsiwfQQBUklZQ==}
+ dependencies:
+ '@types/react': 18.2.21
+ dev: false
+
resolution: {integrity: sha512-wyUkmaaSZEzFZivD8F2ftSyAfk6L+DfFliVj/mYdOXbVjRcS87fQJLTnhk6dRZPuJjI+9g6RZJO4PNCngUrmyw==}
dependencies:
@@ -6150,7 +6165,7 @@ packages:
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dependencies:
'@typescript-eslint/types': 5.29.0
- eslint-visitor-keys: 3.4.2
+ eslint-visitor-keys: 3.4.1
dev: true
/@typescript-eslint/[email protected]:
@@ -6951,6 +6966,16 @@ packages:
node-releases: 2.0.13
update-browserslist-db: 1.0.11([email protected])
+ resolution: {integrity: sha512-M0MFoZzbUrRU4KNfCrDLnvyE7gub+peetoTid3TBIqtunaDJyXlwhakT+/VkvSXcfIzFfK/nkCs4nmyTmxdNSg==}
+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
+ hasBin: true
+ dependencies:
+ caniuse-lite: 1.0.30001517
+ electron-to-chromium: 1.4.468
+ node-releases: 2.0.13
+ update-browserslist-db: 1.0.11([email protected])
+
resolution: {integrity: sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==}
dependencies:
@@ -7047,12 +7072,15 @@ packages:
resolution: {integrity: sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==}
dependencies:
- browserslist: 4.21.10
- caniuse-lite: 1.0.30001522
+ browserslist: 4.21.9
+ caniuse-lite: 1.0.30001517
lodash.memoize: 4.1.2
lodash.uniq: 4.5.0
dev: false
+ resolution: {integrity: sha512-Vdhm5S11DaFVLlyiKu4hiUTkpZu+y1KA/rZZqVQfOD5YdDT/eQKlkt7NaE0WGOFgX32diqt9MiP9CAiFeRklaA==}
+
resolution: {integrity: sha512-TKiyTVZxJGhsTszLuzb+6vUZSjVOAhClszBr2Ta2k9IwtNBT/4dzmL6aywt0HCgEZlmwJzXJd8yNiob6HgwTRg==}
@@ -7398,7 +7426,7 @@ packages:
resolution: {integrity: sha512-wIDWd2s5/5aJSdpOJHfSibxNODxoGoWOBHt8JSPB41NOE94M7kuTPZCYLOlTtuoXTsBPKobpJ6T+y0SSy5L9SA==}
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
dev: true
@@ -7911,6 +7939,9 @@ packages:
jake: 10.8.7
dev: true
+ resolution: {integrity: sha512-6M1qyhaJOt7rQtNti1lBA0GwclPH+oKCmsra/hkcWs5INLxfXXD/dtdnaKUYQu/pjOBP/8Osoe4mAcNvvzoFag==}
+
resolution: {integrity: sha512-qeXC3Zbykq44RCrBa4kr8v/dWzYJA8rAwpyh9Qd+NKWoJfjG5vvJqy9XOJ9H4P/lqulZBCgUWAYi+FeK5AuJ8g==}
@@ -8417,7 +8448,6 @@ packages:
resolution: {integrity: sha512-8drBzUEyZ2llkpCA67iYrgEssKDUu68V8ChqqOfFupIaG/LCVPUT+CoGJpT77zJprs4T/W7p07LP7zAIMuweVw==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
- dev: true
resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==}
@@ -10124,6 +10154,10 @@ packages:
resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}
dev: true
+ resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}
+ dev: false
+
resolution: {integrity: sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==}
dev: false
@@ -11052,7 +11086,7 @@ packages:
peerDependencies:
postcss: ^8.2.15
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
caniuse-api: 3.0.0
colord: 2.9.3
postcss: 8.4.29
@@ -11065,7 +11099,7 @@ packages:
peerDependencies:
postcss: ^8.2.15
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
postcss: 8.4.29
postcss-value-parser: 4.2.0
dev: false
@@ -11174,7 +11208,7 @@ packages:
peerDependencies:
postcss: ^8.2.15
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
caniuse-api: 3.0.0
cssnano-utils: 4.0.0([email protected])
postcss: 8.4.29
@@ -11209,7 +11243,7 @@ packages:
peerDependencies:
postcss: ^8.2.15
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
cssnano-utils: 4.0.0([email protected])
postcss: 8.4.29
postcss-value-parser: 4.2.0
@@ -11340,7 +11374,7 @@ packages:
peerDependencies:
postcss: ^8.2.15
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
postcss: 8.4.29
postcss-value-parser: 4.2.0
dev: false
@@ -11382,7 +11416,7 @@ packages:
peerDependencies:
postcss: ^8.2.15
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
caniuse-api: 3.0.0
postcss: 8.4.29
dev: false
@@ -11688,6 +11722,18 @@ packages:
react: 18.2.0
scheduler: 0.23.0
+ resolution: {integrity: sha512-OMHzJdyJbYTZo4uQE393fHcqqPYsEtkjfMgvCHr6rejT+Ezn4OZbNyGH50vv+SunC1RMvwOTSWkEODQLzw1M9g==}
+ peerDependencies:
+ react: '>= 16.3.0'
+ react-dom: '>= 16.3.0'
+ dependencies:
+ clsx: 1.2.1
+ prop-types: 15.8.1
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-O3om8I+PkFKbxCukfIR3QAGftYXDZfOE2N1mr/7qebQJHs7U+/RSL/9xomJNpRg9kM5h9soQSdf0Gc7OHF5Fug==}
engines: {node: '>= 10.13'}
@@ -11722,6 +11768,21 @@ packages:
react: 18.2.0
dev: false
+ resolution: {integrity: sha512-sB3rNhorW77HUdOjB4JkelZTdJGQKuXLl3gNg+BI8gJkTScspL1myfZzW/EM0dLEn+1eH+xW+wNqk0oIM9o7cw==}
+ peerDependencies:
+ react: '>= 16.3.0'
+ react-dom: '>= 16.3.0'
+ dependencies:
+ clsx: 1.2.1
+ lodash.isequal: 4.5.0
+ prop-types: 15.8.1
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ react-draggable: 4.4.5([email protected])([email protected])
+ react-resizable: 3.0.5([email protected])([email protected])
+ dev: false
+
resolution: {integrity: sha512-0GfI31LRTBd5tqbXMGXT1Rdsv3rnvy0FjEk8Gn9/4tp6+s77T7DPZuGEpBRXOauL+NhyGT5iaXzdIM2R6F/E+w==}
engines: {node: '>=12.22.0'}
@@ -11824,6 +11885,18 @@ packages:
react-dom: 18.2.0([email protected])
dev: false
+ resolution: {integrity: sha512-vKpeHhI5OZvYn82kXOs1bC8aOXktGU5AmKAgaZS4F5JPburCtbmDPqE7Pzp+1kN4+Wb81LlF33VpGwWwtXem+w==}
+ peerDependencies:
+ react: '>= 16.3'
+ dependencies:
+ prop-types: 15.8.1
+ react: 18.2.0
+ react-draggable: 4.4.5([email protected])([email protected])
+ transitivePeerDependencies:
+ - react-dom
+ dev: false
+
resolution: {integrity: sha512-ZWj0fHEMyWkHzKYUr2Bs/4zU6XLmq9HsgBURm7g5pAVfyn49DgUiNgY2d4lXRlYSiCif9YBGpQleewkcqddc7g==}
engines: {node: '>=10'}
@@ -12669,7 +12742,7 @@ packages:
peerDependencies:
postcss: ^8.2.15
dependencies:
- browserslist: 4.21.10
+ browserslist: 4.21.9
postcss: 8.4.29
postcss-selector-parser: 6.0.13
dev: false
@@ -13303,6 +13376,16 @@ packages:
escalade: 3.1.1
picocolors: 1.0.0
+ resolution: {integrity: sha512-dCwEFf0/oT85M1fHBg4F0jtLwJrutGoHSQXCh7u4o2t1drG+c0a9Flnqww6XUKSfQMPpJBRjU8d4RXB09qtvaA==}
+ hasBin: true
+ peerDependencies:
+ browserslist: '>= 4.21.0'
+ dependencies:
+ browserslist: 4.21.9
+ escalade: 3.1.1
+ picocolors: 1.0.0
+
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
dependencies:
diff --git a/frontend/public/mockServiceWorker.js b/frontend/public/mockServiceWorker.js
index d8bc3ace34..0f24d51586 100644
--- a/frontend/public/mockServiceWorker.js
+++ b/frontend/public/mockServiceWorker.js
@@ -2,7 +2,7 @@
/* tslint:disable */
/**
- * Mock Service Worker (1.3.0).
+ * Mock Service Worker (1.3.1).
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d3317731d6..861ad87fc8 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -43,6 +43,8 @@ import { CellConfig } from "./core/model/cells";
import { getFilenameFromDOM } from "./core/dom/htmlUtils";
import { CellArray } from "./editor/renderers/CellArray";
import { RuntimeState } from "./core/RuntimeState";
+import { CellsRenderer } from "./editor/renderers/cells-renderer";
+import { getSerializedLayout } from "./core/state/layout";
import { useAtom } from "jotai";
import { useRunStaleCells } from "./editor/cell/useRunCells";
@@ -131,7 +133,13 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
}
Logger.log("saving to ", filename);
- sendSave({ codes, names: cellNames, filename, configs })
+ sendSave({
+ codes,
+ names: cellNames,
+ filename,
+ configs,
+ layout: getSerializedLayout(),
+ })
.then(() => {
if (showToast) {
toast({ title: "Notebook saved" });
@@ -208,7 +216,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
// Toggle the array's presenting state, and sets a cell to anchor scrolling to
const togglePresenting = useCallback(() => {
- const outputAreas = document.getElementsByClassName("OutputArea");
+ const outputAreas = document.getElementsByClassName("output-area");
const viewportEnd =
window.innerHeight || document.documentElement.clientHeight;
let cellAnchor: CellId | null = null;
@@ -270,7 +278,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
);
});
- const cellsArray = (
+ const editableCellsArray = (
<CellArray
cells={cells}
connStatus={connStatus}
@@ -286,6 +294,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
className={clsx(
connStatus.state === WebSocketState.CLOSED && "disconnected",
"bg-background w-full h-full text-textColor",
+ "flex flex-col",
appConfig.width === "full" && "config-width-full"
)}
>
@@ -313,9 +322,11 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
{/* Don't render until we have a single cell */}
{cells.present.length > 0 && (
- <SortableCellsProvider disabled={!isEditing}>
- {cellsArray}
- </SortableCellsProvider>
+ <CellsRenderer appConfig={appConfig} mode={viewState.mode}>
+ <SortableCellsProvider disabled={!isEditing}>
+ {editableCellsArray}
+ </SortableCellsProvider>
+ </CellsRenderer>
)}
{(isEditing || isPresenting) && (
diff --git a/frontend/src/components/data-table/mime-cell.tsx b/frontend/src/components/data-table/mime-cell.tsx
index 77984feb7b..88790682dc 100644
--- a/frontend/src/components/data-table/mime-cell.tsx
+++ b/frontend/src/components/data-table/mime-cell.tsx
@@ -20,7 +20,7 @@ export const MimeCell = ({ value }: MimeCellProps) => {
<div className={cn("flex items-center space-x-2")}>
{formatOutput({
message: {
- channel: "",
+ channel: "output",
data: value.data,
mimetype: value.mimetype,
timestamp: "",
diff --git a/frontend/src/components/ui/select.tsx b/frontend/src/components/ui/select.tsx
index 530f3c34a8..1eb6f400f3 100644
--- a/frontend/src/components/ui/select.tsx
+++ b/frontend/src/components/ui/select.tsx
@@ -1,7 +1,7 @@
/* Copyright 2023 Marimo. All rights reserved. */
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
-import { Check, ChevronDown } from "lucide-react";
+import { CheckIcon, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
@@ -18,7 +18,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
- "flex h-7 mb-1 items-center justify-between rounded-md border border-input bg-transparent px-2 py-1 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
+ "flex h-7 items-center justify-between rounded-md border border-input shadow-sm bg-transparent px-2 py-1 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
@@ -39,8 +39,9 @@ const SelectContent = React.forwardRef<
<SelectPrimitive.Content
ref={ref}
className={cn(
- "relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md animate-in fade-in-80",
- position === "popper" && "translate-y-1",
+ "relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
@@ -66,7 +67,7 @@ const SelectLabel = React.forwardRef<
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
- className={cn("py-1 pl-7 pr-2 text-sm font-semibold", className)}
+ className={cn("px-2 py-1.5 text-sm font-semibold", className)}
{...props}
/>
));
@@ -79,17 +80,16 @@ const SelectItem = React.forwardRef<
<SelectPrimitive.Item
ref={ref}
className={cn(
- "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-7 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
- <Check className="h-3 w-3" />
+ <CheckIcon className="h-3 w-3" />
</SelectPrimitive.ItemIndicator>
</span>
-
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.ts
index b15861413c..7cd70a9d21 100644
--- a/frontend/src/core/config/config.ts
+++ b/frontend/src/core/config/config.ts
@@ -22,6 +22,7 @@ export const UserConfigSchema = z
experimental: z
.object({
theming: z.boolean().optional(),
+ layouts: z.boolean().optional(),
})
// Pass through so that we don't remove any extra keys that the user has added.
.passthrough()
diff --git a/frontend/src/core/config/feature-flag.ts b/frontend/src/core/config/feature-flag.ts
index 3dbb94fe1e..4ac8c5be30 100644
--- a/frontend/src/core/config/feature-flag.ts
+++ b/frontend/src/core/config/feature-flag.ts
@@ -7,10 +7,15 @@ export interface ExperimentalFeatures {
* Allows the user to switch between light and dark themes.
*/
theming: boolean;
+ /**
+ * Allows the user to switch between different layouts.
+ */
+ layouts: boolean;
}
const defaultValues: ExperimentalFeatures = {
theming: false,
+ layouts: false,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
diff --git a/frontend/src/core/kernel/messages.tsx b/frontend/src/core/kernel/messages.tsx
index 99fd590ff5..ed67833e6b 100644
--- a/frontend/src/core/kernel/messages.tsx
+++ b/frontend/src/core/kernel/messages.tsx
@@ -1,8 +1,17 @@
/* Copyright 2023 Marimo. All rights reserved. */
+import { LayoutType } from "@/editor/renderers/types";
import { CellConfig, CellStatus } from "../model/cells";
import { CellId } from "../model/ids";
+export type OutputChannel =
+ | "output"
+ | "console"
+ | "media"
+ | "marimo-error"
+ | "stderr"
+ | "stdout";
+
export type MarimoError =
| { type: "syntax"; msg?: string }
| { type: "interruption"; msg?: string }
@@ -20,13 +29,13 @@ export type MarimoError =
export type OutputMessage =
| {
- channel: string;
+ channel: OutputChannel;
mimetype: "application/vnd.marimo+error";
data: MarimoError[];
timestamp: string;
}
| {
- channel: string;
+ channel: OutputChannel;
mimetype:
| "text/plain"
| "text/html"
@@ -44,7 +53,7 @@ export type OutputMessage =
timestamp: string;
}
| {
- channel: string;
+ channel: OutputChannel;
mimetype: "application/json";
data: unknown;
timestamp: string;
@@ -115,6 +124,22 @@ export type OperationMessage =
* The cell codes. Will be empty in Read mode.
*/
codes: string[];
+ /**
+ * The layout of the notebook
+ * May be undefined if there is no layout set.
+ */
+ layout:
+ | {
+ /**
+ * The type of the layout
+ */
+ type: LayoutType;
+ /**
+ * The serialized layout
+ */
+ data: unknown;
+ }
+ | undefined;
/**
* The cell configs.
*/
diff --git a/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.ts b/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.ts
index 849c173b55..3b431e1d8a 100644
--- a/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.ts
+++ b/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.ts
@@ -7,8 +7,18 @@ import { OutputMessage } from "@/core/kernel/messages";
describe("collapseConsoleOutputs", () => {
it("should collapse last two text/plain outputs on the same channel", () => {
const consoleOutputs: OutputMessage[] = [
- { mimetype: "text/plain", channel: "1", data: "Hello ", timestamp: "" },
- { mimetype: "text/plain", channel: "1", data: "World", timestamp: "" },
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "Hello ",
+ timestamp: "",
+ },
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "World",
+ timestamp: "",
+ },
];
const result = collapseConsoleOutputs(consoleOutputs);
expect(result[0].data).toMatchInlineSnapshot('"Hello World"');
@@ -16,8 +26,18 @@ describe("collapseConsoleOutputs", () => {
it("should not collapse outputs on different channels", () => {
const consoleOutputs: OutputMessage[] = [
- { mimetype: "text/plain", channel: "1", data: "Hello ", timestamp: "" },
- { mimetype: "text/plain", channel: "2", data: "World", timestamp: "" },
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "Hello ",
+ timestamp: "",
+ },
+ {
+ mimetype: "text/plain",
+ channel: "console",
+ data: "World",
+ timestamp: "",
+ },
];
const result = collapseConsoleOutputs(consoleOutputs);
expect(result).toEqual(consoleOutputs);
@@ -25,8 +45,18 @@ describe("collapseConsoleOutputs", () => {
it("should not collapse outputs of different mimetypes", () => {
const consoleOutputs: OutputMessage[] = [
- { mimetype: "text/plain", channel: "1", data: "Hello ", timestamp: "" },
- { mimetype: "text/html", channel: "1", data: "World", timestamp: "" },
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "Hello ",
+ timestamp: "",
+ },
+ {
+ mimetype: "text/html",
+ channel: "output",
+ data: "World",
+ timestamp: "",
+ },
];
const result = collapseConsoleOutputs(consoleOutputs);
expect(result).toEqual(consoleOutputs);
@@ -36,7 +66,7 @@ describe("collapseConsoleOutputs", () => {
const consoleOutputs: OutputMessage[] = [
{
mimetype: "text/plain",
- channel: "1",
+ channel: "output",
data: "Hello\rWorld",
timestamp: "",
},
@@ -49,7 +79,7 @@ describe("collapseConsoleOutputs", () => {
const consoleOutputs: OutputMessage[] = [
{
mimetype: "text/plain",
- channel: "1",
+ channel: "output",
data: "Hello\rWorld\r!",
timestamp: "",
},
@@ -62,7 +92,7 @@ describe("collapseConsoleOutputs", () => {
const consoleOutputs: OutputMessage[] = [
{
mimetype: "text/plain",
- channel: "1",
+ channel: "output",
data: "Hello\nWorld\r!",
timestamp: "",
},
diff --git a/frontend/src/core/model/ids.ts b/frontend/src/core/model/ids.ts
index 18933ec90a..09d468a3d6 100644
--- a/frontend/src/core/model/ids.ts
+++ b/frontend/src/core/model/ids.ts
@@ -1,6 +1,8 @@
/* Copyright 2023 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-redeclare */
+import { invariant } from "@/utils/invariant";
+
export type TypedNumber<T> = number & { __type__: T };
export type TypedString<T> = string & { __type__: T };
@@ -35,6 +37,8 @@ export const HTMLCellId = {
* Create a new HTMLCellId
*/
create(cellId: CellId): HTMLCellId {
+ invariant(cellId != null, "cellId is required");
+
return `cell-${cellId}` as HTMLCellId;
},
parse(htmlCellId: HTMLCellId): CellId {
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 0e03b55e14..a5f2e4e3f3 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -1,5 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { AppConfig, UserConfig } from "../config/config";
+import { LayoutType } from "@/editor/renderers/types";
import { CellId } from "../../core/model/ids";
import { CellConfig } from "../model/cells";
@@ -40,6 +41,12 @@ export interface SaveKernelRequest {
filename: string;
codes: string[];
names: string[];
+ layout:
+ | {
+ type: LayoutType;
+ data: unknown;
+ }
+ | undefined;
configs: CellConfig[];
}
diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.ts
index 4363651385..ed28795345 100644
--- a/frontend/src/core/state/cells.ts
+++ b/frontend/src/core/state/cells.ts
@@ -378,6 +378,8 @@ const cellsAtom = atom<CellsAndHistory>(initialCellState());
*/
export const useCells = () => useAtomValue(cellsAtom);
+export const getCells = () => store.get(cellsAtom).present;
+
/**
* Get the editor views for all cells.
*/
diff --git a/frontend/src/core/state/layout.ts b/frontend/src/core/state/layout.ts
new file mode 100644
index 0000000000..ae7bd80406
--- /dev/null
+++ b/frontend/src/core/state/layout.ts
@@ -0,0 +1,46 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { GridLayout } from "@/editor/renderers/grid-layout/types";
+import { LayoutType } from "@/editor/renderers/types";
+import { cellRendererPlugins } from "@/editor/renderers/plugins";
+import { Logger } from "@/utils/Logger";
+import { atom } from "jotai";
+import { getCells } from "./cells";
+import { store } from "./jotai";
+
+/**
+ * The currently selected layout type to show.
+ */
+export const layoutViewAtom = atom<LayoutType>("vertical");
+
+/**
+ * The layout data
+ */
+export const layoutDataAtom = atom<GridLayout | undefined>(undefined);
+
+/**
+ * Get the serialized layout data, to be used when saving.
+ */
+export function getSerializedLayout() {
+ const cells = getCells();
+ const layoutData = store.get(layoutDataAtom);
+ const layoutViewType = store.get(layoutViewAtom);
+
+ if (layoutData === undefined) {
+ return undefined;
+ }
+ // Vertical layout has no data, as it is the default.
+ if (layoutViewType === "vertical") {
+ return undefined;
+ }
+ const plugin = cellRendererPlugins.find(
+ (plugin) => plugin.type === layoutViewType
+ );
+ if (plugin === undefined) {
+ Logger.error(`Unknown layout type: ${layoutViewType}`);
+ return undefined;
+ }
+ return {
+ type: layoutViewType,
+ data: plugin.serializeLayout(layoutData, cells),
+ };
+}
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index 0fcb5be8eb..5721c3a202 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -1,6 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { WebSocketClosedReason, WebSocketState } from "./types";
-import { useAtom } from "jotai";
+import { useAtom, useSetAtom } from "jotai";
import { connectionAtom } from "../state/connection";
import { useWebSocket } from "@/core/websocket/useWebSocket";
import { logNever } from "@/utils/assertNever";
@@ -15,6 +15,8 @@ import { CellConfig } from "../model/cells";
import { CellState, createCell } from "../model/cells";
import { useErrorBoundary } from "react-error-boundary";
import { Logger } from "@/utils/Logger";
+import { layoutDataAtom, layoutViewAtom } from "../state/layout";
+import { deserializeLayout } from "@/editor/renderers/plugins";
/**
* WebSocket that connects to the Marimo kernel and handles incoming messages.
@@ -29,6 +31,8 @@ export function useMarimoWebSocket(opts: {
const { showBoundary } = useErrorBoundary();
const { handleCellMessage } = useCellActions();
+ const setLayoutView = useSetAtom(layoutViewAtom);
+ const setLayoutData = useSetAtom(layoutDataAtom);
const [connStatus, setConnStatus] = useAtom(connectionAtom);
const ws = useWebSocket({
@@ -51,13 +55,13 @@ export function useMarimoWebSocket(opts: {
const msg = JSON.parse(e.data) as OperationMessage;
switch (msg.op) {
case "kernel-ready": {
- const { codes, names, configs } = msg.data;
+ const { codes, names, layout, configs } = msg.data;
// TODO(akshayka): Get rid of this once the kernel sends cell IDs in
// kernel-ready.
CellId.reset();
- // Set the initial codes and cells
+ // Set the layout, initial codes, cells
const cells = codes.map((code, i) =>
createCell({
key: CellId.create(),
@@ -67,6 +71,10 @@ export function useMarimoWebSocket(opts: {
config: configs[i],
})
);
+ if (layout) {
+ setLayoutView(layout.type);
+ setLayoutData(deserializeLayout(layout.type, layout.data, cells));
+ }
setCells(cells);
setInitialCodes(codes);
setInitialConfigs(configs);
diff --git a/frontend/src/css/App.css b/frontend/src/css/App.css
index c4bbf92456..607130be69 100644
--- a/frontend/src/css/App.css
+++ b/frontend/src/css/App.css
@@ -81,7 +81,8 @@ html {
opacity: 0.5;
}
-#App.disconnected {
+#App.disconnected,
+#App.disconnected .transparent-when-disconnected {
background: none;
}
diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.css
index e6e92bc8f4..062f90720b 100644
--- a/frontend/src/css/Cell.css
+++ b/frontend/src/css/Cell.css
@@ -14,17 +14,34 @@
@apply border-border;
}
-#App.disconnected .Cell {
- /* Background determined by disconnected gradient/noise. */
+/* Background determined by disconnected gradient/noise. */
+#App.disconnected .Cell,
+#App.disconnected .console-output-area,
+#App.disconnected .cm .cm-gutters,
+#App.disconnected .Cell .cm-editor.cm-focused .cm-activeLineGutter,
+#App.disconnected .Cell .cm-editor.cm-focused .cm-activeLine,
+#App.disconnected .Cell .ShoulderButton {
background-color: transparent;
}
+/* Hide when disconnected. */
+#App.disconnected .cell-running-icon,
+#App.disconnected .cell-queued-icon,
+#App.disconnected .elapsed-time {
+ visibility: hidden;
+ animation: none;
+}
+
+#App.disconnected .console-output-area {
+ border-color: transparent;
+}
+
.Cell:not(.disabled):hover {
box-shadow: var(--medium-shadow);
}
-.Cell.disabled .OutputArea,
-.Cell.disabled.stale .OutputArea,
+.Cell.disabled .output-area,
+.Cell.disabled.stale .output-area,
.Cell.disabled .cm-gutters,
.Cell.disabled.stale .cm-gutters,
.Cell.disabled .cm,
@@ -33,7 +50,7 @@
opacity: 0.5;
}
-.Cell.stale .OutputArea,
+.Cell.stale .output-area,
.Cell.stale .cm,
.Cell.stale .cm-gutters {
background-color: var(--gray-1);
@@ -144,10 +161,6 @@
vertical-align: bottom;
}
-#App.disconnected .Cell .ShoulderButton {
- background-color: transparent;
-}
-
.Cell .shoulder-right {
display: inline-flex;
flex-direction: column;
@@ -207,11 +220,6 @@
background: hsl(210deg 100% 2% / 75%);
}
-#App.disconnected .Cell .cm-editor.cm-focused .cm-activeLineGutter,
-#App.disconnected .Cell .cm-editor.cm-focused .cm-activeLine {
- background: transparent;
-}
-
.Cell .cm-editor .cm-activeLine {
background: transparent;
@@ -231,10 +239,6 @@
background-color: transparent;
}
-.disconnected .cm .cm-gutters {
- background-color: transparent !important;
-}
-
.cm-scroller {
overflow: auto;
}
@@ -300,16 +304,10 @@
content: "κ";
}
-#App.disconnected .cell-running-icon,
-#App.disconnected .cell-queued-icon {
- visibility: hidden;
- animation: none;
-}
-
/* ------------------------------ Output Areas ------------------------------ */
-.OutputArea,
-.ConsoleOutputArea {
+.output-area,
+.console-output-area {
max-width: inherit;
width: 100%;
@@ -324,27 +322,27 @@
}
/* Only restrain output length in edit mode. */
-.Cell:not(.published) .OutputArea,
-.ConsoleOutputArea {
+.Cell:not(.published) .output-area,
+.console-output-area {
max-height: 600px;
overflow: auto;
}
.marimo-output-stale,
-.Cell.stale .OutputArea.marimo-output-stale,
-.Cell.stale .ConsoleOutputArea.marimo-output-stale {
+.Cell.stale .output-area.marimo-output-stale,
+.Cell.stale .console-output-area.marimo-output-stale {
opacity: 0.2;
transition: opacity 300ms;
transition-delay: 200ms;
}
-.OutputArea {
+.output-area {
padding: 0.25rem 1.85rem;
border: 1px solid transparent;
border-bottom: 1px solid var(--gray-5);
}
-.ConsoleOutputArea {
+.console-output-area {
padding: 20px;
border-radius: 0 0 8px 8px;
border-top: 1px solid var(--gray-5);
@@ -354,15 +352,9 @@
background-color: var(--gray-1);
}
-#App.disconnected .ConsoleOutputArea {
- /* Background determined by disconnected gradient/noise. */
- background-color: transparent;
- border: 1px solid transparent;
-}
-
/* ------------------------------- Published -------------------------------- */
-.Cell.published .OutputArea {
+.Cell.published .output-area {
/* flow-root interferes with margin collapsing, but appears to be unneeded
* when cell outlines are hidden; clear:both is sufficient.
*
@@ -396,12 +388,17 @@
}
.Cell.published,
-.Cell.published .OutputArea,
-.Cell.published .ConsoleOutputArea {
+.Cell.published .output-area,
+.Cell.published .console-output-area {
border: none;
box-shadow: none;
}
+.Cell .cm-content {
+ font-size: 0.875rem;
+ font-family: var(--monospace-font);
+}
+
/* ------------------------------ Needs Run---------------------------------- */
.Cell.needs-run {
box-shadow: var(--light-shadow-stale);
@@ -421,91 +418,10 @@
border-radius: 0;
}
-.Cell.needs-run .OutputArea {
+.Cell.needs-run .output-area {
border-bottom: 1px solid var(--stale-color);
}
-/* ------------------------ Output Formatting ---------------------------- */
-.output,
-.media,
-.stdout,
-.stderr,
-.return,
-.marimo-error {
- width: 100%;
-}
-
-.output {
- margin-top: 1rem;
- margin-bottom: 1rem;
-}
-
-.marimo-error a {
- @apply text-link;
-}
-
-.output > * {
- max-width: 100%;
-}
-
-.stdout,
-.stderr,
-.marimo-error,
-.Cell .cm-content {
- font-family: var(--monospace-font);
-}
-
-.stdout,
-.stderr {
- font-size: 0.813rem;
-}
-
-.Cell .cm-content {
- font-size: 0.875rem;
-}
-
-.marimo-error,
-.stderr {
- font-weight: bold;
-
- @apply text-error;
-}
-
-.marimo-error {
- background: #ffc0cb30;
- padding: 3%;
- font-size: 0.8125rem;
- border-radius: 20px;
- white-space: pre-wrap; /* respect newlines */
-}
-
-.return {
- display: block;
-}
-
-.text-plain {
- white-space: pre-wrap; /* respect newlines */
-}
-
-.output.text-plain {
- font-family: var(--text-font);
-}
-
-.marimo-json-output {
- padding-top: 2px;
- padding-bottom: 2px;
-
- /* content-visiblity is set by material UI;
- * when set on an element that has overflow auto, causes abrupt jumps when
- * scrolling in Chrome */
- content-visibility: unset;
-
- /* Coarse hack to stop children from overflowing; doesn't seem to affect
- * margin collapse. */
- overflow: auto;
-}
-
-.marimo-json-output .data-key-pair:not(:last-child) {
- margin-top: 0.2rem;
- margin-bottom: 0.2rem;
+.Cell.needs-run .RunButton {
+ visibility: visible;
}
diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsx
index 794f5a2059..7708ca3731 100644
--- a/frontend/src/editor/Cell.tsx
+++ b/frontend/src/editor/Cell.tsx
@@ -22,7 +22,8 @@ import { UserConfig } from "../core/config/config";
import { CellState } from "../core/model/cells";
import { CellActions, useCellActions } from "../core/state/cells";
import { derefNotNull } from "../utils/dereference";
-import { ConsoleOutputArea, OutputArea } from "./Output";
+import { OutputArea } from "./Output";
+import { ConsoleOutput } from "./output/ConsoleOutput";
import { CreateCellButton } from "./cell/CreateCellButton";
import { RunButton } from "./cell/RunButton";
import { DeleteButton } from "./cell/DeleteButton";
@@ -374,6 +375,7 @@ const CellComponent = (
const outputArea = (
<OutputArea
output={output}
+ className="output-area"
cellId={cellId}
stale={(loading || edited || status === "stale") && !interrupted}
/>
@@ -486,9 +488,8 @@ const CellComponent = (
) : null}
</div>
</div>
- <ConsoleOutputArea
+ <ConsoleOutput
consoleOutputs={consoleOutputs}
- cellId={cellId}
stale={
(status === "queued" || edited || status === "stale") && !interrupted
}
diff --git a/frontend/src/editor/Controls.styles.ts b/frontend/src/editor/Controls.styles.ts
index 2f9cf50ab4..3a5689bad3 100644
--- a/frontend/src/editor/Controls.styles.ts
+++ b/frontend/src/editor/Controls.styles.ts
@@ -1,6 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
export const topRightControls =
- "fixed top-3 right-3 m-0 flex items-center space-x-3 no-print";
+ "fixed top-3 right-3 m-0 flex items-center space-x-3 min-h-[28px] no-print";
export const bottomRightControls =
"fixed bottom-4 right-4 flex items-center space-x-3 no-print";
diff --git a/frontend/src/editor/Controls.tsx b/frontend/src/editor/Controls.tsx
index c364405ce0..1aea9369f3 100644
--- a/frontend/src/editor/Controls.tsx
+++ b/frontend/src/editor/Controls.tsx
@@ -19,6 +19,7 @@ import { renderShortcut } from "../components/shortcuts/renderShortcut";
import { useCellActions } from "../core/state/cells";
import { AppConfigButton } from "../components/app-config/app-config-button";
import { useState, useEffect } from "react";
+import { LayoutSelect } from "./renderers/layout-select";
import { NotebookMenuDropdown } from "@/editor/notebook-menu-dropdown";
import { FindReplace } from "@/components/find-replace/find-replace";
@@ -83,6 +84,7 @@ export const Controls = ({
{!closed && (
<div className={styles.topRightControls}>
+ {presenting && <LayoutSelect />}
<NotebookMenuDropdown filename={filename} />
<AppConfigButton />
<ShutdownButton onShutdown={onShutdown} />
diff --git a/frontend/src/editor/Output.tsx b/frontend/src/editor/Output.tsx
index 23a18785b1..aad430c68c 100644
--- a/frontend/src/editor/Output.tsx
+++ b/frontend/src/editor/Output.tsx
@@ -13,6 +13,8 @@ import { VideoOutput } from "./output/VideoOutput";
import { CellId } from "@/core/model/ids";
import { cn } from "@/lib/utils";
+import "./output/Outputs.css";
+
/**
* Renders an output based on an OutputMessage.
*/
@@ -24,20 +26,20 @@ export function formatOutput({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
parsedJsonData?: Record<string, any>;
}): React.ReactNode {
- const outputCls: string = message.channel;
+ const channel = message.channel;
// TODO(akshayka): audio; pdf; text/csv; excel?; text/css; text/javascript
switch (message.mimetype) {
case "text/html":
- return <HtmlOutput className={outputCls} html={message.data} />;
+ return <HtmlOutput className={channel} html={message.data} />;
case "text/plain":
- return <TextOutput className={outputCls} text={message.data} />;
+ return <TextOutput channel={channel} text={message.data} />;
case "application/json":
// TODO: format is 'auto', but should make configurable once cells can
// support config
return (
- <JsonOutput className={outputCls} data={parsedJsonData} format="auto" />
+ <JsonOutput className={channel} data={parsedJsonData} format="auto" />
);
case "image/png":
case "image/svg+xml":
@@ -46,11 +48,11 @@ export function formatOutput({
case "image/bmp":
case "image/gif":
case "image/jpeg":
- return <ImageOutput className={outputCls} src={message.data} alt="" />;
+ return <ImageOutput className={channel} src={message.data} alt="" />;
case "video/mp4":
case "video/mpeg":
- return <VideoOutput className={outputCls} src={message.data} />;
+ return <VideoOutput className={channel} src={message.data} />;
case "application/vnd.marimo+error":
return <MarimoErrorOutput errors={message.data} />;
@@ -62,7 +64,12 @@ export function formatOutput({
}
export const OutputArea = React.memo(
- (props: { output: OutputMessage | null; cellId: CellId; stale: boolean }) => {
+ (props: {
+ output: OutputMessage | null;
+ cellId: CellId;
+ stale: boolean;
+ className?: string;
+ }) => {
// Memoize parsing the json data
const parsedJsonData = useMemo(() => {
if (!props.output) {
@@ -92,7 +99,7 @@ export const OutputArea = React.memo(
<div
title={title}
id={`output-${props.cellId}`}
- className={cn("OutputArea", props.stale && "marimo-output-stale")}
+ className={cn(props.stale && "marimo-output-stale", props.className)}
>
{formatOutput({
message: props.output,
@@ -105,25 +112,3 @@ export const OutputArea = React.memo(
}
);
OutputArea.displayName = "OutputArea";
-
-export const ConsoleOutputArea = (props: {
- consoleOutputs: OutputMessage[];
- cellId: CellId;
- stale: boolean;
-}): React.ReactNode => {
- if (props.consoleOutputs.length === 0) {
- return null;
- }
-
- const cls = `ConsoleOutputArea${props.stale ? " marimo-output-stale" : ""}`;
- const title = props.stale ? "This console output is stale" : undefined;
- return (
- <div title={title} className={cls}>
- {props.consoleOutputs.map((output) =>
- formatOutput({
- message: output,
- })
- )}
- </div>
- );
-};
diff --git a/frontend/src/editor/cell/CellStatus.tsx b/frontend/src/editor/cell/CellStatus.tsx
index deb66e46f7..787270e259 100644
--- a/frontend/src/editor/cell/CellStatus.tsx
+++ b/frontend/src/editor/cell/CellStatus.tsx
@@ -52,7 +52,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({
data-status="stale"
>
<MultiIcon>
- <BanIcon className="h-4 w-4" strokeWidth={1.5} />
+ <BanIcon className="h-5 w-5" strokeWidth={1.5} />
<RefreshCwIcon className="h-3 w-3" strokeWidth={2.5} />
</MultiIcon>
</div>
@@ -69,7 +69,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({
data-testid="cell-status"
data-status="disabled"
>
- <BanIcon className="h-4 w-4" strokeWidth={1.5} />
+ <BanIcon className="h-5 w-5" strokeWidth={1.5} />
</div>
</Tooltip>
);
@@ -161,7 +161,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({
data-testid="cell-status"
data-status="outdated"
>
- <RefreshCwIcon className="h-4 w-4" strokeWidth={1.5} />
+ <RefreshCwIcon className="h-5 w-5" strokeWidth={1.5} />
</div>
</Tooltip>
);
diff --git a/frontend/src/editor/cell/TinyCode.tsx b/frontend/src/editor/cell/TinyCode.tsx
new file mode 100644
index 0000000000..ea75c04908
--- /dev/null
+++ b/frontend/src/editor/cell/TinyCode.tsx
@@ -0,0 +1,29 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import React from "react";
+
+interface Props {
+ code: string;
+}
+
+export const TinyCode: React.FC<Props> = ({ code }) => {
+ return (
+ <div
+ className="text-gray-500 flex flex-col overflow-hidden"
+ style={{
+ fontSize: "8px",
+ lineHeight: "10px",
+ }}
+ >
+ {code
+ .trim()
+ .split("\n")
+ .map((line, idx) => {
+ return (
+ <code className="whitespace-pre min-h-[10px]" key={idx}>
+ {line}
+ </code>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/frontend/src/editor/cell/cell-status.css b/frontend/src/editor/cell/cell-status.css
index 115b27428a..c4a92fefe3 100644
--- a/frontend/src/editor/cell/cell-status.css
+++ b/frontend/src/editor/cell/cell-status.css
@@ -1,5 +1,7 @@
.cell-status-icon {
+ margin-top: 4px;
margin-left: 3px;
+ margin-bottom: auto;
}
.elapsed-time {
diff --git a/frontend/src/editor/output/ConsoleOutput.tsx b/frontend/src/editor/output/ConsoleOutput.tsx
new file mode 100644
index 0000000000..bd286191d0
--- /dev/null
+++ b/frontend/src/editor/output/ConsoleOutput.tsx
@@ -0,0 +1,26 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import React from "react";
+import { OutputMessage } from "@/core/kernel/messages";
+import { formatOutput } from "../Output";
+import { cn } from "@/lib/utils";
+
+interface Props {
+ consoleOutputs: OutputMessage[];
+ stale: boolean;
+}
+
+export const ConsoleOutput = (props: Props): React.ReactNode => {
+ const { consoleOutputs, stale } = props;
+ if (consoleOutputs.length === 0) {
+ return null;
+ }
+
+ return (
+ <div
+ title={stale ? "This console output is stale" : undefined}
+ className={cn("console-output-area", stale && "marimo-output-stale")}
+ >
+ {consoleOutputs.map((output) => formatOutput({ message: output }))}
+ </div>
+ );
+};
diff --git a/frontend/src/editor/output/Outputs.css b/frontend/src/editor/output/Outputs.css
new file mode 100644
index 0000000000..633494ab06
--- /dev/null
+++ b/frontend/src/editor/output/Outputs.css
@@ -0,0 +1,67 @@
+.output,
+.media,
+.stdout,
+.stderr,
+.return,
+.marimo-error {
+ width: 100%;
+}
+
+/* Just applied to vertical layout */
+.output-area .output {
+ margin-top: 1rem;
+ margin-bottom: 1rem;
+}
+
+.marimo-error a {
+ @apply text-link;
+}
+
+.output > * {
+ max-width: 100%;
+}
+
+.stdout,
+.stderr,
+.marimo-error {
+ font-family: var(--monospace-font);
+}
+
+.stdout,
+.stderr {
+ font-size: 0.813rem;
+}
+
+.marimo-error,
+.stderr {
+ font-weight: bold;
+
+ @apply text-error;
+}
+
+.marimo-error {
+ background: #ffc0cb30;
+ padding: 3%;
+ font-size: 0.8125rem;
+ border-radius: 20px;
+ white-space: pre-wrap; /* respect newlines */
+}
+
+.marimo-json-output {
+ padding-top: 2px;
+ padding-bottom: 2px;
+
+ /* content-visiblity is set by material UI;
+ * when set on an element that has overflow auto, causes abrupt jumps when
+ * scrolling in Chrome */
+ content-visibility: unset;
+
+ /* Coarse hack to stop children from overflowing; doesn't seem to affect
+ * margin collapse. */
+ overflow: auto;
+}
+
+.marimo-json-output .data-key-pair:not(:last-child) {
+ margin-top: 0.2rem;
+ margin-bottom: 0.2rem;
+}
diff --git a/frontend/src/editor/output/TextOutput.tsx b/frontend/src/editor/output/TextOutput.tsx
index b6011c2098..3606b7bdce 100644
--- a/frontend/src/editor/output/TextOutput.tsx
+++ b/frontend/src/editor/output/TextOutput.tsx
@@ -1,10 +1,23 @@
/* Copyright 2023 Marimo. All rights reserved. */
+import { OutputChannel } from "@/core/kernel/messages";
+import { cn } from "@/lib/utils";
+
interface Props {
text: string;
- className?: string;
+ channel?: OutputChannel;
}
-export const TextOutput = ({ text, className }: Props): JSX.Element => {
- return <span className={`${className} text-plain`}>{text}</span>;
+export const TextOutput = ({ text, channel }: Props): JSX.Element => {
+ return (
+ <span
+ className={cn(
+ "whitespace-pre",
+ channel === "output" && "font-prose",
+ channel
+ )}
+ >
+ {text}
+ </span>
+ );
};
diff --git a/frontend/src/editor/output/types.ts b/frontend/src/editor/output/types.ts
deleted file mode 100644
index 88d84ef9ff..0000000000
--- a/frontend/src/editor/output/types.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/* Copyright 2023 Marimo. All rights reserved. */
-export interface OutputElement {
- new (): HTMLElement;
- tagName: string;
-}
diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsx
index b41a591da1..cfaad3da9a 100644
--- a/frontend/src/editor/renderers/CellArray.tsx
+++ b/frontend/src/editor/renderers/CellArray.tsx
@@ -1,6 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
+import { useEffect } from "react";
import { EditorView } from "@codemirror/view";
-import { useEffect, useState } from "react";
import { sendDeleteCell } from "@/core/network/requests";
import { Cell } from "editor/Cell";
import { RuntimeState } from "../../core/RuntimeState";
@@ -12,8 +12,9 @@ import { useHotkey } from "../../hooks/useHotkey";
import { useEvent } from "../../hooks/useEvent";
import { CellId } from "../../core/model/ids";
import { formatEditorViews } from "../../core/codemirror/format";
-import { cn } from "../../lib/utils";
import { useTheme } from "../../theme/useTheme";
+import { VerticalLayoutWrapper } from "./vertical-layout/vertical-layout-wrapper";
+import { useDelayVisibility } from "./vertical-layout/useDelayVisiblity";
interface CellArrayProps {
cells: CellsAndHistory;
@@ -51,23 +52,7 @@ export const CellArray: React.FC<CellArrayProps> = ({
} = useCellActions();
const { theme } = useTheme();
- // Start the app as invisible and delay proportional to the number of cells,
- // to avoid most of the flickering when the app is loaded (b/c it is
- // streamed). Delaying also helps prevent cell editors from stealing focus.
- const [invisible, setInvisible] = useState(true);
- useEffect(() => {
- const delay = Math.max(Math.min((cells.present.length - 1) * 15, 100), 0);
- const timeout = setTimeout(() => {
- setInvisible(false);
- // After 1 frame, focus on the first cell if it's been mounted
- requestAnimationFrame(() => {
- cells.present[0]?.ref.current?.editorView.focus();
- });
- }, delay);
- return () => clearTimeout(timeout);
- // Delay only when app is first loaded
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ const { invisible } = useDelayVisibility(cells.present);
// HOTKEYS
useHotkey("global.focusTop", focusTopCell);
@@ -98,49 +83,40 @@ export const CellArray: React.FC<CellArrayProps> = ({
}, [cells.present, cells.scrollKey, scrollToTarget]);
return (
- <div className="px-2 sm:px-18">
- <div
- className={cn(
- "m-auto pb-12",
- appConfig.width !== "full" && "max-w-contentWidth",
- // Hide the cells for a fake loading effect, to avoid flickering
- invisible && "invisible"
- )}
- >
- {cells.present.map((cell) => (
- <Cell
- key={cell.key.toString()}
- theme={theme}
- showPlaceholder={cells.present.length === 1}
- allowFocus={!invisible}
- cellId={cell.key}
- initialContents={cell.initialContents}
- output={cell.output}
- consoleOutputs={cell.consoleOutputs}
- status={cell.status}
- updateCellCode={updateCellCode}
- prepareForRun={prepareForRun}
- edited={cell.edited}
- interrupted={cell.interrupted}
- errored={cell.errored}
- stopped={cell.stopped}
- runElapsedTimeMs={cell.runElapsedTimeMs}
- registerRunStart={registerRunStart}
- serializedEditorState={cell.serializedEditorState}
- showDeleteButton={cells.present.length > 1}
- createNewCell={createNewCell}
- deleteCell={onDeleteCell}
- focusCell={focusCell}
- moveToNextCell={moveToNextCell}
- moveCell={moveCell}
- editing={mode === "edit"}
- appClosed={connStatus.state !== WebSocketState.OPEN}
- ref={cell.ref}
- userConfig={userConfig}
- config={cell.config}
- />
- ))}
- </div>
- </div>
+ <VerticalLayoutWrapper invisible={invisible} appConfig={appConfig}>
+ {cells.present.map((cell) => (
+ <Cell
+ key={cell.key.toString()}
+ theme={theme}
+ showPlaceholder={cells.present.length === 1}
+ allowFocus={!invisible}
+ cellId={cell.key}
+ initialContents={cell.initialContents}
+ output={cell.output}
+ consoleOutputs={cell.consoleOutputs}
+ status={cell.status}
+ updateCellCode={updateCellCode}
+ prepareForRun={prepareForRun}
+ edited={cell.edited}
+ interrupted={cell.interrupted}
+ errored={cell.errored}
+ stopped={cell.stopped}
+ runElapsedTimeMs={cell.runElapsedTimeMs}
+ registerRunStart={registerRunStart}
+ serializedEditorState={cell.serializedEditorState}
+ showDeleteButton={cells.present.length > 1}
+ createNewCell={createNewCell}
+ deleteCell={onDeleteCell}
+ focusCell={focusCell}
+ moveToNextCell={moveToNextCell}
+ moveCell={moveCell}
+ editing={mode === "edit"}
+ appClosed={connStatus.state !== WebSocketState.OPEN}
+ ref={cell.ref}
+ userConfig={userConfig}
+ config={cell.config}
+ />
+ ))}
+ </VerticalLayoutWrapper>
);
};
diff --git a/frontend/src/editor/renderers/cells-renderer.tsx b/frontend/src/editor/renderers/cells-renderer.tsx
new file mode 100644
index 0000000000..c526cc1fcb
--- /dev/null
+++ b/frontend/src/editor/renderers/cells-renderer.tsx
@@ -0,0 +1,47 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { useCells } from "@/core/state/cells";
+import React, { PropsWithChildren, memo } from "react";
+import { cellRendererPlugins } from "./plugins";
+import { AppConfig } from "@/core/config/config";
+import { AppMode } from "@/core/mode";
+import { layoutDataAtom, layoutViewAtom } from "@/core/state/layout";
+import { useAtom } from "jotai";
+
+interface Props {
+ appConfig: AppConfig;
+ mode: AppMode;
+}
+
+export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
+ ({ appConfig, mode, children }) => {
+ const cells = useCells();
+ const [layoutData, setLayoutData] = useAtom(layoutDataAtom);
+ const [layoutType] = useAtom(layoutViewAtom);
+
+ // Just render children if we are in edit mode
+ if (mode === "edit") {
+ return children;
+ }
+
+ const plugin = cellRendererPlugins.find((p) => p.type === layoutType);
+
+ // Just render children if there is no plugin
+ if (!plugin) {
+ return children;
+ }
+
+ const Renderer = plugin.Component;
+ const body = (
+ <Renderer
+ appConfig={appConfig}
+ mode={mode}
+ cells={cells.present}
+ layout={layoutData || plugin.getInitialLayout(cells.present)}
+ setLayout={setLayoutData}
+ />
+ );
+
+ return body;
+ }
+);
+CellsRenderer.displayName = "CellsRenderer";
diff --git a/frontend/src/editor/renderers/grid-layout/grid-layout.tsx b/frontend/src/editor/renderers/grid-layout/grid-layout.tsx
new file mode 100644
index 0000000000..3295c70592
--- /dev/null
+++ b/frontend/src/editor/renderers/grid-layout/grid-layout.tsx
@@ -0,0 +1,297 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import React, { memo } from "react";
+import { Responsive, WidthProvider } from "react-grid-layout";
+import { ICellRendererPlugin, ICellRendererProps } from "../types";
+import {
+ GridLayout,
+ SerializedGridLayout,
+ SerializedGridLayoutCell,
+} from "./types";
+import { OutputArea } from "@/editor/Output";
+import { CellState } from "@/core/model/cells";
+
+import "react-grid-layout/css/styles.css";
+import "./styles.css";
+import { Logger } from "@/utils/Logger";
+import { z } from "zod";
+import { Maps } from "@/utils/maps";
+import { CellId } from "@/core/model/ids";
+import { AppMode } from "@/core/mode";
+import { TinyCode } from "@/editor/cell/TinyCode";
+import { cn } from "@/lib/utils";
+import { XIcon } from "lucide-react";
+
+type Props = ICellRendererProps<GridLayout>;
+
+const ReactGridLayout = WidthProvider(Responsive);
+
+const cols = {
+ // we only allow 1 responsive breakpoint
+ // we can change this later if we want to support more,
+ // but this increases complexity to the user
+ lg: 12,
+};
+
+const GridLayoutRenderer: React.FC<Props> = ({
+ layout,
+ setLayout,
+ cells,
+ mode,
+}) => {
+ const isReading = mode === "read";
+ const [isDragging, setIsDragging] = React.useState(false);
+ const inGridIds = new Set(layout.cells.map((cell) => cell.i));
+ const [droppingItem, setDroppingItem] = React.useState<{
+ i: string;
+ w?: number;
+ h?: number;
+ } | null>(null);
+
+ const grid = (
+ <ReactGridLayout
+ breakpoint="lg"
+ layouts={{
+ lg: layout.cells,
+ }}
+ cols={cols}
+ isBounded={true}
+ allowOverlap={false}
+ autoSize={true}
+ className={cn(
+ !isReading && "min-w-[800px] min-h-[600px]",
+ isReading && "disable-animation"
+ )}
+ rowHeight={layout.rowHeight}
+ onLayoutChange={(cellLayouts) =>
+ setLayout({
+ ...layout,
+ cells: cellLayouts,
+ })
+ }
+ droppingItem={
+ droppingItem
+ ? {
+ i: droppingItem.i,
+ w: droppingItem.w || 2,
+ h: droppingItem.h || 2,
+ }
+ : undefined
+ }
+ onDrop={(cellLayouts, dropped, _event) => {
+ setIsDragging(false);
+ if (!dropped) {
+ return;
+ }
+ setLayout({
+ ...layout,
+ cells: [...cellLayouts, dropped],
+ });
+ }}
+ onDragStart={() => setIsDragging(true)}
+ onDragStop={() => setIsDragging(false)}
+ // When in read mode, disable dragging and resizing
+ isDraggable={!isReading}
+ isDroppable={!isReading}
+ isResizable={!isReading}
+ >
+ {cells
+ .filter((cell) => inGridIds.has(cell.key))
+ .map((cell) => (
+ <div
+ key={cell.key}
+ className={cn(
+ "relative transparent-when-disconnected",
+ !isReading &&
+ "hover:bg-[var(--sage-2)] border-transparent hover:border-border border hover:rounded hover-actions-parent",
+ isDragging && "bg-[var(--sage-2)] border-border rounded",
+ "overflow-hidden p-2"
+ )}
+ >
+ <GridCell
+ code={cell.code}
+ mode={mode}
+ cellId={cell.key}
+ output={cell.output}
+ status={cell.status}
+ />
+ {!isReading && (
+ <div className="absolute top-0 right-0 p-1 hover-action">
+ <XIcon
+ className="cursor-pointer h-4 w-4 opacity-60 hover:opacity-100"
+ onClick={() => {
+ setLayout({
+ ...layout,
+ cells: layout.cells.filter((c) => c.i !== cell.key),
+ });
+ }}
+ />
+ </div>
+ )}
+ </div>
+ ))}
+ </ReactGridLayout>
+ );
+
+ if (isReading) {
+ return grid;
+ }
+
+ const notInGrid = cells.filter((cell) => !inGridIds.has(cell.key));
+
+ return (
+ <div className={cn("flex h-full overflow-hidden gap-2 px-2 pb-2")}>
+ <div className="flex-grow overflow-auto border rounded bg-[var(--sage-1)] shadow-sm transparent-when-disconnected">
+ {grid}
+ </div>
+ <div className="flex-none flex flex-col w-[400px] p-3 gap-3 overflow-auto h-full bg-[var(--sage-3)] border rounded shadow-sm transparent-when-disconnected">
+ <div className="text font-bold text-[var(--sage-10)] overflow-auto flex-shrink-0">
+ Outputs
+ </div>
+ {notInGrid.map((cell) => (
+ <div
+ key={cell.key}
+ draggable={true}
+ unselectable="on"
+ data-cell-id={cell.key}
+ // Firefox requires some kind of initialization which we can do by adding this attribute
+ // @see https://bugzilla.mozilla.org/show_bug.cgi?id=568313
+ onDragStart={(e) => {
+ // get height of self
+ const height = e.currentTarget.offsetHeight;
+
+ setDroppingItem({
+ i: cell.key,
+ w: 3,
+ h: Math.ceil(height / layout.rowHeight) || 1,
+ });
+ e.dataTransfer.setData("text/plain", "");
+ }}
+ className="droppable-element bg-[var(--sage-2)] border-border border overflow-hidden p-2 rounded flex-shrink-0"
+ >
+ <GridCell
+ code={cell.code}
+ mode={mode}
+ cellId={cell.key}
+ output={cell.output}
+ status={cell.status}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+};
+
+interface GridCellProps extends Pick<CellState, "output" | "status" | "code"> {
+ cellId: CellId;
+ mode: AppMode;
+}
+
+const GridCell = memo(
+ ({ output, cellId, status, mode, code }: GridCellProps) => {
+ const loading = status === "running" || status === "queued";
+
+ const isOutputEmpty = output == null || output.data === "";
+ // If not reading, show code when there is no output
+ if (isOutputEmpty && mode !== "read") {
+ return <TinyCode code={code} />;
+ }
+
+ return (
+ <div>
+ <OutputArea output={output} cellId={cellId} stale={loading} />
+ </div>
+ );
+ }
+);
+GridCell.displayName = "GridCell";
+
+/**
+ * Plugin definition for the grid layout.
+ */
+export const GridLayoutPlugin: ICellRendererPlugin<
+ SerializedGridLayout,
+ GridLayout
+> = {
+ type: "grid",
+ name: "Grid",
+
+ validator: z.object({
+ columns: z.number().min(1).max(12),
+ rowHeight: z.number().min(1),
+ cells: z.array(
+ z.object({
+ position: z
+ .tuple([z.number(), z.number(), z.number(), z.number()])
+ .nullable(),
+ })
+ ),
+ }),
+
+ deserializeLayout: (serialized, cells): GridLayout => {
+ if (serialized.cells.length === 0) {
+ return {
+ columns: serialized.columns,
+ rowHeight: serialized.rowHeight,
+ cells: [],
+ };
+ }
+
+ if (serialized.cells.length !== cells.length) {
+ Logger.warn(
+ "Number of cells in layout does not match number of cells in notebook"
+ );
+ }
+
+ return {
+ columns: serialized.columns,
+ rowHeight: serialized.rowHeight,
+ cells: serialized.cells.flatMap((cellLayout, idx) => {
+ const position = cellLayout.position;
+ if (!position) {
+ return [];
+ }
+ const cell = cells[idx];
+ if (!cell) {
+ return [];
+ }
+ return {
+ i: cell.key,
+ x: position[0],
+ y: position[1],
+ w: position[2],
+ h: position[3],
+ };
+ }),
+ };
+ },
+
+ serializeLayout: (layout, cells): SerializedGridLayout => {
+ const layoutsByKey = Maps.keyBy(layout.cells, (cell) => cell.i);
+ const serializedCells: SerializedGridLayoutCell[] = cells.map((cell) => {
+ const layout = layoutsByKey.get(cell.key);
+ if (!layout) {
+ return {
+ position: null,
+ };
+ }
+ return {
+ position: [layout.x, layout.y, layout.w, layout.h],
+ };
+ });
+
+ return {
+ columns: layout.columns,
+ rowHeight: layout.rowHeight,
+ cells: serializedCells,
+ };
+ },
+
+ Component: GridLayoutRenderer,
+
+ getInitialLayout: () => ({
+ columns: 12,
+ rowHeight: 40,
+ cells: [],
+ }),
+};
diff --git a/frontend/src/editor/renderers/grid-layout/styles.css b/frontend/src/editor/renderers/grid-layout/styles.css
new file mode 100644
index 0000000000..e4202645a9
--- /dev/null
+++ b/frontend/src/editor/renderers/grid-layout/styles.css
@@ -0,0 +1,16 @@
+.react-grid-item.react-grid-placeholder {
+ background-color: var(--grass-9);
+}
+
+.react-resizable-handle {
+ visibility: hidden;
+}
+
+.react-grid-item:hover .react-resizable-handle {
+ visibility: visible;
+}
+
+.disable-animation .react-grid-item {
+ transition-property: none !important;
+ transition: none !important;
+}
diff --git a/frontend/src/editor/renderers/grid-layout/types.ts b/frontend/src/editor/renderers/grid-layout/types.ts
new file mode 100644
index 0000000000..7400a36580
--- /dev/null
+++ b/frontend/src/editor/renderers/grid-layout/types.ts
@@ -0,0 +1,61 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+/**
+ * The serialized form of a grid layout.
+ * This must be backwards-compatible as it is stored on the user's disk.
+ */
+export interface SerializedGridLayout {
+ /**
+ * The number of columns.
+ * @default 12
+ *
+ * This is currently hardcoded and not settable by the user.
+ * In future, we may want to allow the user to set this.
+ */
+ columns: number;
+
+ /**
+ * The height of a row, in pixels.
+ *
+ * This is currently hardcoded and not settable by the user.
+ * In future, we may want to allow the user to set this.
+ */
+ rowHeight: number;
+
+ /**
+ * The cells in the layout.
+ * Cells don't have IDs at rest but are indexed based.
+ *
+ * Once we load the layout, we assign IDs to the cells so that we can
+ * track as they move around.
+ */
+ cells: SerializedGridLayoutCell[];
+}
+
+export interface SerializedGridLayoutCell {
+ /**
+ * The cell position, as [x, y, w, h].
+ * If null, the cell is not in the layout.
+ */
+ position: SerializedGridLayoutCellPosition | null;
+}
+
+export interface GridLayout extends Omit<SerializedGridLayout, "cells"> {
+ /**
+ * The cells in the layout.
+ */
+ cells: Array<{
+ i: string;
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ }>;
+}
+
+export type SerializedGridLayoutCellPosition = [
+ x: number,
+ y: number,
+ w: number,
+ h: number
+];
diff --git a/frontend/src/editor/renderers/layout-select.tsx b/frontend/src/editor/renderers/layout-select.tsx
new file mode 100644
index 0000000000..c3920ad417
--- /dev/null
+++ b/frontend/src/editor/renderers/layout-select.tsx
@@ -0,0 +1,74 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import React from "react";
+import { layoutViewAtom } from "@/core/state/layout";
+import { useAtom } from "jotai";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { LayoutType } from "./types";
+import { SquareIcon, Grid3x3Icon, ListIcon } from "lucide-react";
+import { getFeatureFlag } from "@/core/config/feature-flag";
+
+export const LayoutSelect: React.FC = () => {
+ const [layoutType, setLayoutType] = useAtom(layoutViewAtom);
+ const layouts: LayoutType[] = ["vertical", "grid"];
+
+ if (!getFeatureFlag("layouts")) {
+ return null;
+ }
+
+ return (
+ <Select
+ value={layoutType}
+ onValueChange={(v) => setLayoutType(v as LayoutType)}
+ >
+ <SelectTrigger
+ className="min-w-[110px] border-border"
+ data-testid="layout-select"
+ >
+ <SelectValue placeholder="Select a view" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectLabel>View as</SelectLabel>
+ {layouts.map((layout) => (
+ <SelectItem key={layout} value={layout}>
+ <div className="flex items-center gap-1.5 leading-5">
+ {renderIcon(layout)}
+ <span>{displayName(layout)}</span>
+ </div>
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+};
+
+function renderIcon(layoutType: LayoutType) {
+ switch (layoutType) {
+ case "vertical":
+ return <ListIcon className="h-4 w-4" />;
+ case "grid":
+ return <Grid3x3Icon className="h-4 w-4" />;
+ default:
+ return <SquareIcon className="h-4 w-4" />;
+ }
+}
+
+function displayName(layoutType: LayoutType) {
+ switch (layoutType) {
+ case "vertical":
+ return "Vertical";
+ case "grid":
+ return "Grid";
+ default:
+ return "Unknown";
+ }
+}
diff --git a/frontend/src/editor/renderers/plugins.ts b/frontend/src/editor/renderers/plugins.ts
new file mode 100644
index 0000000000..194c6cf392
--- /dev/null
+++ b/frontend/src/editor/renderers/plugins.ts
@@ -0,0 +1,22 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { GridLayoutPlugin } from "./grid-layout/grid-layout";
+import { ICellRendererPlugin, LayoutType } from "./types";
+import { CellState } from "@/core/model/cells";
+
+// If more renderers are added, we may want to consider lazy loading them.
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export const cellRendererPlugins: Array<ICellRendererPlugin<any, any>> = [
+ GridLayoutPlugin,
+];
+
+export function deserializeLayout(
+ type: LayoutType,
+ data: unknown,
+ cells: CellState[]
+) {
+ const plugin = cellRendererPlugins.find((plugin) => plugin.type === type);
+ if (plugin === undefined) {
+ throw new Error(`Unknown layout type: ${type}`);
+ }
+ return plugin.deserializeLayout(data, cells);
+}
diff --git a/frontend/src/editor/renderers/types.ts b/frontend/src/editor/renderers/types.ts
new file mode 100644
index 0000000000..72ccd165f7
--- /dev/null
+++ b/frontend/src/editor/renderers/types.ts
@@ -0,0 +1,65 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { AppConfig } from "@/core/config/config";
+import { CellState } from "@/core/model/cells";
+import { ZodType, ZodTypeDef } from "zod";
+import { AppMode } from "@/core/mode";
+
+/**
+ * The props passed to a cell renderer.
+ */
+export interface ICellRendererProps<L> {
+ /**
+ * App Config
+ */
+ appConfig: AppConfig;
+
+ /**
+ * The cells to render.
+ */
+ cells: CellState[];
+
+ /**
+ * The layout configuration.
+ */
+ layout: L;
+
+ /**
+ * Application mode.
+ * As of now, this won't include 'edit' mode.
+ */
+ mode: AppMode;
+
+ /**
+ * Callback to set the layout.
+ * @param layout The new layout.
+ */
+ setLayout: (layout: L) => void;
+}
+
+export type LayoutType = "grid" | "vertical";
+
+/**
+ * A cell renderer plugin.
+ * @template S The layout as stored at rest, in its serialized form.
+ * @template L The layout as used by the renderer.
+ *
+ * We have 2 different forms since cells don't have IDs at rest.
+ * The mapping allows us to map between indexed-based cells and ID-based cells.
+ */
+export interface ICellRendererPlugin<S, L> {
+ type: LayoutType;
+
+ name: string;
+
+ /**
+ * Validate the layout data. Use [zod](https://zod.dev/) to validate the data.
+ */
+ validator: ZodType<S, ZodTypeDef, unknown>;
+
+ deserializeLayout: (layout: S, cells: CellState[]) => L;
+ serializeLayout: (layout: L, cells: CellState[]) => S;
+
+ Component: React.FC<ICellRendererProps<L>>;
+
+ getInitialLayout: (cells: CellState[]) => L;
+}
diff --git a/frontend/src/editor/renderers/vertical-layout/useDelayVisiblity.ts b/frontend/src/editor/renderers/vertical-layout/useDelayVisiblity.ts
new file mode 100644
index 0000000000..240451e2ba
--- /dev/null
+++ b/frontend/src/editor/renderers/vertical-layout/useDelayVisiblity.ts
@@ -0,0 +1,25 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { CellState } from "@/core/model/cells";
+import { useState, useEffect } from "react";
+
+export function useDelayVisibility(cells: CellState[]) {
+ // Start the app as invisible and delay proportional to the number of cells,
+ // to avoid most of the flickering when the app is loaded (b/c it is
+ // streamed). Delaying also helps prevent cell editors from stealing focus.
+ const [invisible, setInvisible] = useState(true);
+ useEffect(() => {
+ const delay = Math.max(Math.min((cells.length - 1) * 15, 100), 0);
+ const timeout = setTimeout(() => {
+ setInvisible(false);
+ // After 1 frame, focus on the first cell if it's been mounted
+ requestAnimationFrame(() => {
+ cells[0]?.ref.current?.editorView.focus();
+ });
+ }, delay);
+ return () => clearTimeout(timeout);
+ // Delay only when app is first loaded
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return { invisible };
+}
diff --git a/frontend/src/editor/renderers/vertical-layout/vertical-layout-wrapper.tsx b/frontend/src/editor/renderers/vertical-layout/vertical-layout-wrapper.tsx
new file mode 100644
index 0000000000..6e025767dd
--- /dev/null
+++ b/frontend/src/editor/renderers/vertical-layout/vertical-layout-wrapper.tsx
@@ -0,0 +1,30 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { PropsWithChildren } from "react";
+import { cn } from "@/lib/utils";
+import { AppConfig } from "@/core/config/config";
+
+interface Props {
+ appConfig: AppConfig;
+ invisible?: boolean;
+}
+
+export const VerticalLayoutWrapper: React.FC<PropsWithChildren<Props>> = ({
+ invisible,
+ appConfig,
+ children,
+}) => {
+ return (
+ <div className="px-18">
+ <div
+ className={cn(
+ "m-auto pb-12",
+ appConfig.width !== "full" && "max-w-contentWidth",
+ // Hide the cells for a fake loading effect, to avoid flickering
+ invisible && "invisible"
+ )}
+ >
+ {children}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/editor/renderers/vertical-layout/vertical-layout.tsx
new file mode 100644
index 0000000000..e195111660
--- /dev/null
+++ b/frontend/src/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -0,0 +1,90 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { memo, useRef } from "react";
+import { CellState } from "@/core/model/cells";
+import { CellId, HTMLCellId } from "@/core/model/ids";
+import { OutputArea } from "@/editor/Output";
+import clsx from "clsx";
+import { ICellRendererPlugin, ICellRendererProps } from "../types";
+import { VerticalLayoutWrapper } from "./vertical-layout-wrapper";
+import { z } from "zod";
+import { useDelayVisibility } from "./useDelayVisiblity";
+
+type VerticalLayout = null;
+type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;
+
+const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({
+ cells,
+ appConfig,
+}) => {
+ const { invisible } = useDelayVisibility(cells);
+ return (
+ <VerticalLayoutWrapper invisible={invisible} appConfig={appConfig}>
+ {cells.map((cell) => (
+ <VerticalCell
+ key={cell.key}
+ cellId={cell.key}
+ output={cell.output}
+ status={cell.status}
+ stopped={cell.stopped}
+ errored={cell.errored}
+ interrupted={cell.interrupted}
+ />
+ ))}
+ </VerticalLayoutWrapper>
+ );
+};
+
+interface VerticalCellProps
+ extends Pick<
+ CellState,
+ "output" | "key" | "status" | "stopped" | "errored" | "interrupted"
+ > {
+ cellId: CellId;
+}
+
+const VerticalCell = memo(
+ ({
+ output,
+ cellId,
+ status,
+ stopped,
+ errored,
+ interrupted,
+ }: VerticalCellProps) => {
+ const cellRef = useRef<HTMLDivElement>(null);
+ const loading = status === "running" || status === "queued";
+
+ const className = clsx("Cell", "hover-actions-parent", {
+ published: true,
+ "has-error": errored,
+ stopped: stopped,
+ });
+
+ const HTMLId = HTMLCellId.create(cellId);
+ const hidden = errored || interrupted || stopped;
+ return hidden ? null : (
+ <div tabIndex={-1} id={HTMLId} ref={cellRef} className={className}>
+ <OutputArea
+ output={output}
+ className="output-area"
+ cellId={cellId}
+ stale={loading && !interrupted}
+ />
+ </div>
+ );
+ }
+);
+VerticalCell.displayName = "VerticalCell";
+
+export const VerticalLayoutPlugin: ICellRendererPlugin<
+ VerticalLayout,
+ VerticalLayout
+> = {
+ type: "vertical",
+ name: "Vertical",
+ validator: z.any(),
+ Component: VerticalLayoutRenderer,
+ deserializeLayout: (serialized) => serialized,
+ serializeLayout: (layout) => layout,
+ getInitialLayout: () => null,
+};
diff --git a/frontend/src/plugins/types.ts b/frontend/src/plugins/types.ts
index ee64225cbb..1304941e40 100644
--- a/frontend/src/plugins/types.ts
+++ b/frontend/src/plugins/types.ts
@@ -56,9 +56,6 @@ export interface IPlugin<S, D = Record<string, never>> {
/**
* Validate the plugin data. Use [zod](https://zod.dev/) to validate the data.
- *
- * The data is input as a map of strings, but you can use
- * `zod.string().transform` to convert the string to the correct type.
*/
validator: ZodType<D, ZodTypeDef, unknown>;
diff --git a/frontend/src/utils/maps.ts b/frontend/src/utils/maps.ts
new file mode 100644
index 0000000000..dc7fd6745d
--- /dev/null
+++ b/frontend/src/utils/maps.ts
@@ -0,0 +1,31 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+type NoInfer<T> = [T][T extends any ? 0 : never];
+
+export const Maps = {
+ /**
+ * keyBy for Map, with duplicate key detection.
+ */
+ keyBy<V, K = string>(
+ items: Iterable<V>,
+ key: (item: NoInfer<V>) => K
+ ): Map<K, V> {
+ const map = new Map<K, V>();
+ const duplicateIds = new Set<K>();
+
+ for (const item of items) {
+ const k = key(item);
+ if (map.has(k)) {
+ duplicateIds.add(k);
+ }
+ map.set(k, item);
+ }
+
+ if (duplicateIds.size > 0) {
+ console.trace(`Duplicate keys: ${[...duplicateIds].join(", ")}`);
+ }
+
+ return map;
+ },
+};
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 46e9b4e438..1279502264 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -37,6 +37,9 @@ class _AppConfig:
width: Literal["normal", "full"] = "normal"
+ # The file path of the layout file, relative to the app file.
+ layout_file: Optional[str] = None
+
def asdict(self) -> dict[str, Any]:
return asdict(self)
@@ -80,7 +83,7 @@ class App:
self._config = _AppConfig()
for key in asdict(self._config):
if key in kwargs:
- self._config.__setattr__(key, kwargs.pop("width"))
+ self._config.__setattr__(key, kwargs.pop(key))
self._cell_data: dict[CellId_t, CellData] = {}
self._registration_order: list[CellId_t] = []
diff --git a/marimo/_ast/test_app.py b/marimo/_ast/test_app.py
index 76c2730b33..bb31acdcac 100644
--- a/marimo/_ast/test_app.py
+++ b/marimo/_ast/test_app.py
@@ -246,4 +246,4 @@ class TestApp:
@staticmethod
def test_app_config_extra_args_ignored() -> None:
app = App(width="full", fake_config="foo")
- assert app._config.asdict() == {"width": "full"}
+ assert app._config.asdict() == {"width": "full", "layout_file": None}
diff --git a/marimo/_messaging/message_types.py b/marimo/_messaging/message_types.py
index cac44a5eaf..14f3f20a5d 100644
--- a/marimo/_messaging/message_types.py
+++ b/marimo/_messaging/message_types.py
@@ -14,6 +14,7 @@ from marimo._ast.cell import CellConfig, CellId_t, CellStatusType
from marimo._messaging.cell_output import CellOutput
from marimo._messaging.completion_option import CompletionOption
from marimo._plugins.core.web_component import JSONType
+from marimo._server.layout import LayoutConfig
# A cell-op's data has three optional fields:
@@ -58,6 +59,7 @@ class KernelReady:
name: ClassVar[str] = "kernel-ready"
codes: tuple[str, ...]
names: tuple[str, ...]
+ layout: Optional[LayoutConfig]
configs: tuple[CellConfig, ...]
diff --git a/marimo/_server/api/save.py b/marimo/_server/api/save.py
index aecab78fd1..5811f188d3 100644
--- a/marimo/_server/api/save.py
+++ b/marimo/_server/api/save.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import os
from dataclasses import dataclass
-from typing import List
+from typing import Any, Dict, List, Optional
import tornado.web
@@ -13,6 +13,7 @@ from marimo._ast.cell import CellConfig
from marimo._server import sessions
from marimo._server.api.model import parse_raw
from marimo._server.api.status import HTTPStatus
+from marimo._server.layout import LayoutConfig, save_layout_config
from marimo._server.utils import canonicalize_filename
LOGGER = _loggers.marimo_logger()
@@ -28,6 +29,8 @@ class Save:
configs: List[CellConfig]
# path to app
filename: str
+ # layout of app
+ layout: Optional[Dict[str, Any]] = None
class SaveHandler(tornado.web.RequestHandler):
@@ -37,7 +40,12 @@ class SaveHandler(tornado.web.RequestHandler):
def post(self) -> None:
mgr = sessions.get_manager()
args = parse_raw(self.request.body, Save)
- codes, names, filename = args.codes, args.names, args.filename
+ codes, names, filename, layout = (
+ args.codes,
+ args.names,
+ args.filename,
+ args.layout,
+ )
filename = canonicalize_filename(filename)
if mgr.filename is not None and mgr.filename != filename:
raise tornado.web.HTTPError(
@@ -50,6 +58,15 @@ class SaveHandler(tornado.web.RequestHandler):
reason="File {0} already exists".format(filename),
)
else:
+ # save layout
+ if layout is not None:
+ app_dir = os.path.dirname(filename)
+ app_name = os.path.basename(filename)
+ layout_filename = save_layout_config(
+ app_dir, app_name, LayoutConfig(**layout)
+ )
+ mgr.update_app_config({"layout_file": layout_filename})
+
# try to save the app under the name `filename`
contents = codegen.generate_filecontents(
codes, names, cell_configs=args.configs, config=mgr.app_config
diff --git a/marimo/_server/layout.py b/marimo/_server/layout.py
new file mode 100644
index 0000000000..26c8572ecb
--- /dev/null
+++ b/marimo/_server/layout.py
@@ -0,0 +1,69 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass
+from typing import Any, Optional
+
+from marimo import _loggers
+
+LOGGER = _loggers.marimo_logger()
+
+
+@dataclass
+class LayoutConfig:
+ # type of layout
+ type: str
+ # data for layout
+ data: dict[str, Any]
+
+
+def save_layout_config(
+ directory: str, app_name: str, config: LayoutConfig
+) -> str:
+ """
+ Save the layout configuration to disk
+ at the given directory.
+
+ The layout is saved as a JSON file under
+ <directory>/layouts/<app_nam>.{type}.json
+ This allows:
+ - all layouts to be saved in the same directory
+ - multiple layouts to be saved for the same app
+ - multiple apps can live in the same directory
+
+ Returns: the path to the layout file
+ """
+
+ # remove py extension
+ app_name_without_ext = app_name.replace(".py", "")
+ # relative file path
+ filepath = f"layouts/{app_name_without_ext}.{config.type}.json"
+ # full file path
+ full_filepath = os.path.join(directory, filepath)
+ # create directory if it doesn't exist
+ os.makedirs(os.path.dirname(full_filepath), exist_ok=True)
+ with open(full_filepath, "w") as f:
+ json.dump(config.__dict__, f, indent=2)
+ return filepath
+
+
+def read_layout_config(
+ directory: str, filename: str
+) -> Optional[LayoutConfig]:
+ """
+ Read the layout configuration from disk.
+
+ Returns: the layout configuration
+ """
+ filepath = os.path.join(directory, filename)
+ if not os.path.exists(filepath):
+ LOGGER.warning("Layout file %s does not exist", filepath)
+ return None
+ if not filepath.endswith(".json"):
+ LOGGER.warning("Layout file %s is not a JSON file", filepath)
+ return None
+ with open(filepath) as f:
+ data = json.load(f)
+ return LayoutConfig(type=data["type"], data=data["data"])
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 0fe9c8ad06..4ecee59871 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -38,6 +38,7 @@ from marimo._messaging.message_types import KernelReady, serialize
from marimo._output.formatters.formatters import register_formatters
from marimo._runtime import requests, runtime
from marimo._server.api.status import HTTPStatus
+from marimo._server.layout import LayoutConfig, read_layout_config
from marimo._server.utils import print_tabbed
LOGGER = _loggers.marimo_logger()
@@ -94,6 +95,7 @@ class IOSocketHandler(tornado.websocket.WebSocketHandler):
names: tuple[str, ...]
configs: tuple[CellConfig, ...]
app = mgr.load_app()
+ layout: Optional[LayoutConfig] = None
if app is None:
codes = ("",)
names = ("__",)
@@ -118,10 +120,20 @@ class IOSocketHandler(tornado.websocket.WebSocketHandler):
)
)
+ if (
+ app
+ and app._config.layout_file is not None
+ and isinstance(mgr.filename, str)
+ ):
+ app_dir = os.path.dirname(mgr.filename)
+ layout = read_layout_config(app_dir, app._config.layout_file)
+
self.write_op(
op=KernelReady.name,
data=serialize(
- KernelReady(codes=codes, names=names, configs=configs)
+ KernelReady(
+ codes=codes, names=names, configs=configs, layout=layout
+ )
),
)
diff --git a/marimo/_smoke_tests/grid.py b/marimo/_smoke_tests/grid.py
new file mode 100644
index 0000000000..2ffc8bbb17
--- /dev/null
+++ b/marimo/_smoke_tests/grid.py
@@ -0,0 +1,79 @@
+# Copyright 2023 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.1.8"
+app = marimo.App(layout_file="layouts/grid.grid.json")
+
+
+def __(mo):
+ align = mo.ui.dropdown(
+ label="Align", options=["start", "end", "center", "stretch"]
+ )
+ justify = mo.ui.dropdown(
+ label="Justify",
+ options=["start", "center", "end", "space-between", "space-around"],
+ )
+ gap = mo.ui.number(label="Gap", start=0, stop=100, value=1)
+ size = mo.ui.slider(label="Size", start=60, stop=500)
+ wrap = mo.ui.checkbox(label="Wrap")
+
+ mo.hstack([align, justify, gap, size, wrap], gap=0.25)
+ return align, gap, justify, size, wrap
+
+
+def __(mo):
+ mo.md("# Horizontal Stack: `hstack`")
+ return
+
+
+def __(align, boxes, gap, justify, mo, wrap):
+ mo.hstack(
+ boxes,
+ align=align.value,
+ justify=justify.value,
+ gap=gap.value,
+ wrap=wrap.value,
+ )
+ return
+
+
+def __(mo):
+ mo.md("# Vertical Stack: `vstack`")
+ return
+
+
+def __(align, boxes, gap, mo):
+ mo.vstack(
+ boxes,
+ align=align.value,
+ gap=gap.value,
+ )
+ return
+
+
+def __(mo, size):
+ def create_box(num):
+ box_size = size.value + num * 10
+ return mo.Html(
+ f"<div style='min-width: {box_size}px; min-height: {box_size}px; background-color: orange; text-align: center; line-height: {box_size}px'>{str(num)}</div>"
+ )
+
+
+ boxes = [create_box(i) for i in range(1, 5)]
+ return boxes, create_box
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/layouts/grid.grid.json b/marimo/_smoke_tests/layouts/grid.grid.json
new file mode 100644
index 0000000000..5ad32b2c46
--- /dev/null
+++ b/marimo/_smoke_tests/layouts/grid.grid.json
@@ -0,0 +1,30 @@
+{
+ "type": "grid",
+ "data": {
+ "columns": 12,
+ "rowHeight": 40,
+ "cells": [
+ {
+ "position": [0, 0, 12, 1]
+ },
+ {
+ "position": [0, 1, 6, 3]
+ },
+ {
+ "position": [0, 4, 6, 13]
+ },
+ {
+ "position": [6, 1, 6, 3]
+ },
+ {
+ "position": [6, 4, 6, 13]
+ },
+ {
+ "position": null
+ },
+ {
+ "position": null
+ }
+ ]
+ }
+}