A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: resizable columns in notebook (#4698)
Shahmir Varqha86f8ef542d07
diff --git a/frontend/src/components/editor/columns/__tests__/storage.test.ts b/frontend/src/components/editor/columns/__tests__/storage.test.tsnew file mode 100644index 0000000000..956cdc59e4--- /dev/null+++ b/frontend/src/components/editor/columns/__tests__/storage.test.ts@@ -0,0 +1,104 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, it, expect, afterEach } from "vitest";+import { reorderColumnSizes, storageFn } from "../storage";++describe("setColumnWidth", () => {+ const { clearStorage, getColumnWidth, setColumnWidth } = storageFn;++ afterEach(() => {+ clearStorage();+ });++ it("should set width for an existing index", () => {+ // Setup initial state+ setColumnWidth(0, 100);+ setColumnWidth(1, 200);++ // Test+ setColumnWidth(0, 150);++ // Verify+ expect(getColumnWidth(0)).toBe(150);+ expect(getColumnWidth(1)).toBe(200);+ });++ it("should set width for a new index", () => {+ // Setup initial state+ setColumnWidth(0, 100);++ // Test+ setColumnWidth(1, 200);++ // Verify+ expect(getColumnWidth(0)).toBe(100);+ expect(getColumnWidth(1)).toBe(200);+ });++ it("should pad with contentWidth when setting width for out of bounds index", () => {+ // Setup initial state+ setColumnWidth(0, 100);++ // Test+ setColumnWidth(3, 300);++ // Verify+ expect(getColumnWidth(0)).toBe(100);+ expect(getColumnWidth(1)).toBe("contentWidth");+ expect(getColumnWidth(2)).toBe("contentWidth");+ expect(getColumnWidth(3)).toBe(300);+ });++ it("should handle empty initial state", () => {+ // Test+ setColumnWidth(2, 200);++ // Verify+ expect(getColumnWidth(0)).toBe("contentWidth");+ expect(getColumnWidth(1)).toBe("contentWidth");+ expect(getColumnWidth(2)).toBe(200);+ });++ it("should update multiple columns", () => {+ // Setup initial state+ setColumnWidth(0, 100);+ setColumnWidth(1, 200);+ setColumnWidth(2, 300);++ // Test+ setColumnWidth(0, 150);+ setColumnWidth(2, 350);++ // Verify+ expect(getColumnWidth(0)).toBe(150);+ expect(getColumnWidth(1)).toBe(200);+ expect(getColumnWidth(2)).toBe(350);+ });++ it("should set contentWidth directly", () => {+ // Setup initial state+ setColumnWidth(0, 100);+ setColumnWidth(1, 200);++ // Test+ setColumnWidth(0, "contentWidth");++ // Verify+ expect(getColumnWidth(0)).toBe("contentWidth");+ expect(getColumnWidth(1)).toBe(200);+ });++ it("should maintain correct widths after reordering", () => {+ // Setup initial state with 3 columns+ setColumnWidth(0, 100);+ setColumnWidth(1, 200);+ setColumnWidth(2, 300);++ // Reorder column 0 to position 2+ reorderColumnSizes(0, 2);++ // Verify the widths are in the correct order after reordering+ expect(getColumnWidth(0)).toBe(200); // Original column 1+ expect(getColumnWidth(1)).toBe(300); // Original column 2+ expect(getColumnWidth(2)).toBe(100); // Original column 0+ });+});diff --git a/frontend/src/components/editor/columns/cell-column.tsx b/frontend/src/components/editor/columns/cell-column.tsxindex 850f8eef69..45861b765d 100644--- a/frontend/src/components/editor/columns/cell-column.tsx+++ b/frontend/src/components/editor/columns/cell-column.tsx@@ -1,13 +1,15 @@/* Copyright 2024 Marimo. All rights reserved. */-import { cn } from "@/utils/cn";import { memo, useRef } from "react";import { SortableColumn } from "./sortable-column";import type { CellColumnId } from "@/utils/id-tree";import type { AppConfig } from "@/core/config/config-schema";+import { storageFn } from "./storage";+import { useResizeHandle } from "@/hooks/useResizeHandle";interface Props {className?: string;columnId: CellColumnId;+ index: number;children: React.ReactNode;width: AppConfig["width"];footer?: React.ReactNode;@@ -16,21 +18,24 @@ interface Props {canMoveRight: boolean;}+const { getColumnWidth, setColumnWidth } = storageFn;+export const Column = memo((props: Props) => {const columnRef = useRef<HTMLDivElement>(null);- const column = (- <div- className={cn(- "flex flex-col gap-5",- // box-content is needed so the column is width=contentWidth, but not affected by padding- props.width === "columns" &&- "w-contentWidth box-content min-h-[100px] px-11 py-6",- )}- >- {props.children}- </div>- );+ const column: React.ReactNode =+ props.width === "columns" ? (+ <ResizableComponent+ startingWidth={getColumnWidth(props.index)}+ onResize={(width: number) => {+ setColumnWidth(props.index, width);+ }}+ >+ {props.children}+ </ResizableComponent>+ ) : (+ <div className="flex flex-col gap-5">{props.children}</div>+ );if (props.width === "columns") {return (@@ -58,3 +63,38 @@ export const Column = memo((props: Props) => {});Column.displayName = "Column";++interface ResizableComponentProps {+ startingWidth: number | "contentWidth";+ onResize?: (width: number) => void;+ children: React.ReactNode;+}++const ResizableComponent = ({+ startingWidth,+ onResize,+ children,+}: ResizableComponentProps) => {+ const { resizableDivRef, handleRef, style } = useResizeHandle({+ startingWidth,+ onResize,+ });++ return (+ <div className="flex flex-row gap-2">+ <div+ ref={resizableDivRef}+ className="flex flex-col gap-5 box-content min-h-[100px] px-11 py-6 min-w-[500px] z-1"+ style={style}+ >+ {children}+ </div>+ <div+ ref={handleRef}+ className="w-1 cursor-col-resize transition-colors duration-200 z-10+ group-hover/column:bg-[var(--slate-3)] dark:group-hover/column:bg-[var(--slate-5)]+ group-hover/column:hover:bg-primary/60 dark:group-hover/column:hover:bg-primary/60"+ />+ </div>+ );+};diff --git a/frontend/src/components/editor/columns/storage.ts b/frontend/src/components/editor/columns/storage.tsnew file mode 100644index 0000000000..38d97bcbc0--- /dev/null+++ b/frontend/src/components/editor/columns/storage.ts@@ -0,0 +1,53 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { arrayMove } from "@/utils/arrays";+import { NotebookScopedLocalStorage } from "@/utils/localStorage";+import { z } from "zod";++const BASE_KEY = "marimo:notebook-col-sizes";++interface ColumnSizes {+ widths: Array<number | "contentWidth">;+}++function initialState(): ColumnSizes {+ return { widths: [] };+}++const storage = new NotebookScopedLocalStorage<ColumnSizes>(+ BASE_KEY,+ z.object({+ widths: z.array(z.union([z.number(), z.literal("contentWidth")])),+ }),+ initialState,+);++export const storageFn = {+ // Default to "contentWidth" if the column width is not set.+ getColumnWidth: (index: number) => {+ const widths = storage.get().widths;+ return widths[index] ?? "contentWidth";+ },+ setColumnWidth: (index: number, width: number | "contentWidth") => {+ const widths = storage.get().widths;+ if (widths[index]) {+ widths[index] = width;+ } else {+ // If the index is out of bounds, add "contentWidth" until we reach the index+ while (widths.length <= index) {+ widths.push("contentWidth");+ }+ widths[index] = width;+ }+ storage.set({ widths });+ },+ clearStorage: () => {+ storage.remove();+ },+};++// When a column is reordered, we need to update the storage to reflect the new order.+export function reorderColumnSizes(fromIdx: number, toIdx: number) {+ const widths = storage.get().widths;+ const newWidths = arrayMove(widths, fromIdx, toIdx);+ storage.set({ widths: newWidths });+}diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 1e77e15237..2dba6dd346 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -197,6 +197,7 @@ const CellColumn: React.FC<{return (<ColumncolumnId={column.id}+ index={index}canMoveLeft={index > 0}canMoveRight={index < columnsLength - 1}width={appConfig.width}diff --git a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts b/frontend/src/core/codemirror/markdown/__tests__/commands.test.tsindex 09f03c3fd4..a9877e1050 100644--- a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts+++ b/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts@@ -21,7 +21,7 @@ import {insertUL,} from "../commands";import { sendCreateFileOrFolder } from "@/core/network/requests";-import { filenameAtom } from "@/core/saving/filename";+import { filenameAtom } from "@/core/saving/filenameAtom";import { store } from "@/core/state/jotai";function createEditor(content: string) {diff --git a/frontend/src/core/codemirror/markdown/commands.ts b/frontend/src/core/codemirror/markdown/commands.tsindex 17dd04f927..35fe0808af 100644--- a/frontend/src/core/codemirror/markdown/commands.ts+++ b/frontend/src/core/codemirror/markdown/commands.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { toast } from "@/components/ui/use-toast";import { sendCreateFileOrFolder } from "@/core/network/requests";-import { filenameAtom } from "@/core/saving/filename";+import { filenameAtom } from "@/core/saving/filenameAtom";import { store } from "@/core/state/jotai";import { Paths, type FilePath } from "@/utils/paths";import {diff --git a/frontend/src/core/saving/filename.ts b/frontend/src/core/saving/filename.tsindex 1f35199bfc..f616d2fea8 100644--- a/frontend/src/core/saving/filename.ts+++ b/frontend/src/core/saving/filename.ts@@ -1,7 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";-import { getFilenameFromDOM } from "../dom/htmlUtils";+import { useAtom, useAtomValue, useSetAtom } from "jotai";import { sendRename } from "../network/requests";import { Paths } from "@/utils/paths";import { updateQueryParams } from "@/utils/urls";@@ -11,8 +10,7 @@ import { WebSocketState } from "../websocket/types";import { useImperativeModal } from "@/components/modal/ImperativeModal";import { connectionAtom } from "../network/connection";import { getAppConfig } from "../config/config";--export const filenameAtom = atom<string | null>(getFilenameFromDOM());+import { filenameAtom } from "./filenameAtom";export function useFilename() {return useAtomValue(filenameAtom);diff --git a/frontend/src/core/saving/filenameAtom.ts b/frontend/src/core/saving/filenameAtom.tsnew file mode 100644index 0000000000..0c26710138--- /dev/null+++ b/frontend/src/core/saving/filenameAtom.ts@@ -0,0 +1,11 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { atom } from "jotai";+import { getFilenameFromDOM } from "../dom/htmlUtils";++// The atom is separated from the filename logic to avoid circular dependencies.+/**+ * Atom for storing the current notebook filename.+ * This is used to scope local storage to the current notebook.+ */+export const filenameAtom = atom<string | null>(getFilenameFromDOM());diff --git a/frontend/src/core/saving/save-component.tsx b/frontend/src/core/saving/save-component.tsxindex 5ec75e5d92..063d74d34b 100644--- a/frontend/src/core/saving/save-component.tsx+++ b/frontend/src/core/saving/save-component.tsx@@ -21,7 +21,8 @@ import { useAutoSave } from "./useAutoSave";import { getSerializedLayout, layoutStateAtom } from "../layout/layout";import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";import { formatAll } from "../codemirror/format";-import { filenameAtom, useFilename, useUpdateFilename } from "./filename";+import { useFilename, useUpdateFilename } from "./filename";+import { filenameAtom } from "./filenameAtom";import { connectionAtom } from "../network/connection";import { autoSaveConfigAtom } from "../config/config";import { lastSavedNotebookAtom, needsSaveAtom } from "./state";diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.cssindex 19b2979ff0..b43ef78aad 100644--- a/frontend/src/css/app/Cell.css+++ b/frontend/src/css/app/Cell.css@@ -220,8 +220,8 @@justify-content: flex-end;height: 100%;position: absolute;- right: -90px;- width: 80px;+ left: calc(100% + 12px);+ width: fit-content;gap: 4px;}diff --git a/frontend/src/hooks/__tests__/useResizeHandle.test.tsx b/frontend/src/hooks/__tests__/useResizeHandle.test.tsxnew file mode 100644index 0000000000..f2eab150f2--- /dev/null+++ b/frontend/src/hooks/__tests__/useResizeHandle.test.tsx@@ -0,0 +1,55 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { renderHook, act } from "@testing-library/react";+import { useResizeHandle } from "../useResizeHandle";+import { describe, it, expect, vi } from "vitest";++describe("useResizeHandle", () => {+ it("should initialize with correct refs and style", () => {+ const { result } = renderHook(() =>+ useResizeHandle({ startingWidth: 500, onResize: vi.fn() }),+ );++ expect(result.current.resizableDivRef.current).toBeNull();+ expect(result.current.handleRef.current).toBeNull();+ expect(result.current.style).toEqual({ width: "500px" });+ });++ it("should handle contentWidth starting width", () => {+ const { result } = renderHook(() =>+ useResizeHandle({ startingWidth: "contentWidth", onResize: vi.fn() }),+ );++ expect(result.current.style).toEqual({ width: "contentWidth" });+ });++ it.skip("should call onResize when resizing ends", () => {+ const onResize = vi.fn();+ const { result } = renderHook(() =>+ useResizeHandle({ startingWidth: 500, onResize }),+ );++ // Mock DOM elements+ const mockDiv = document.createElement("div");+ mockDiv.style.width = "500px";+ // @ts-expect-error - we're testing the ref+ result.current.resizableDivRef.current = mockDiv;++ const mockHandle = document.createElement("div");+ // @ts-expect-error - we're testing the ref+ result.current.handleRef.current = mockHandle;++ // Simulate resize+ act(() => {+ const mousedownEvent = new MouseEvent("mousedown", { clientX: 0 });+ mockHandle.dispatchEvent(mousedownEvent);++ const mousemoveEvent = new MouseEvent("mousemove", { clientX: 100 });+ document.dispatchEvent(mousemoveEvent);++ const mouseupEvent = new MouseEvent("mouseup");+ document.dispatchEvent(mouseupEvent);+ });++ expect(onResize).toHaveBeenCalledWith(600); // 500px + 100px movement+ });+});diff --git a/frontend/src/hooks/useResizeHandle.ts b/frontend/src/hooks/useResizeHandle.tsnew file mode 100644index 0000000000..cf7a35beeb--- /dev/null+++ b/frontend/src/hooks/useResizeHandle.ts@@ -0,0 +1,73 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { useEffect, useRef } from "react";++interface UseResizeHandleProps {+ onResize?: (width: number) => void;+ startingWidth: number | "contentWidth";+}++export const useResizeHandle = ({+ onResize,+ startingWidth,+}: UseResizeHandleProps) => {+ const resizableDivRef = useRef<HTMLDivElement>(null);+ const handleRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const handle = handleRef.current;+ const resizableDiv = resizableDivRef.current;++ if (!handle || !resizableDiv) {+ return;+ }++ let width = Number.parseInt(window.getComputedStyle(resizableDiv).width);+ let lastX = 0;+ let isResizing = false;++ const onMouseMove = (e: MouseEvent) => {+ if (!resizableDiv || !isResizing) {+ return;+ }+ const dx = e.clientX - lastX;+ lastX = e.clientX;+ width += dx;+ resizableDiv.style.width = `${width}px`;+ };++ const onMouseUp = () => {+ if (isResizing) {+ onResize?.(width);+ isResizing = false;+ }+ document.removeEventListener("mousemove", onMouseMove);+ document.removeEventListener("mouseup", onMouseUp);+ };++ const onMouseDown = (e: MouseEvent) => {+ isResizing = true;+ lastX = e.clientX;+ document.addEventListener("mousemove", onMouseMove);+ document.addEventListener("mouseup", onMouseUp);+ };++ handle.addEventListener("mousedown", onMouseDown);++ return () => {+ handle.removeEventListener("mousedown", onMouseDown);+ document.removeEventListener("mousemove", onMouseMove);+ document.removeEventListener("mouseup", onMouseUp);+ };+ }, [onResize]);++ return {+ resizableDivRef,+ handleRef,+ style: {+ width:+ typeof startingWidth === "string"+ ? startingWidth+ : `${startingWidth}px`,+ },+ };+};diff --git a/frontend/src/utils/__tests__/local-storage.test.ts b/frontend/src/utils/__tests__/local-storage.test.tsnew file mode 100644index 0000000000..0b4282f485--- /dev/null+++ b/frontend/src/utils/__tests__/local-storage.test.ts@@ -0,0 +1,75 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, it, expect, afterEach } from "vitest";+import { NotebookScopedLocalStorage } from "../localStorage";+import { z } from "zod";+import { store } from "@/core/state/jotai";+import { filenameAtom } from "@/core/saving/filenameAtom";++describe("NotebookScopedLocalStorage", () => {+ const schema = z.object({+ name: z.string(),+ age: z.number(),+ });++ const getDefaultValue = () => ({+ name: "John Doe",+ age: 30,+ });++ let storage: NotebookScopedLocalStorage<{+ name: string;+ age: number;+ }> | null;++ afterEach(() => {+ // Remove the storage after each test+ if (storage) {+ storage.dispose(); // Make sure to dispose the subscription+ storage.remove();+ storage = null;+ }+ // Reset atoms+ store.set(filenameAtom, null);+ });++ it("should initialize with the default value", () => {+ storage = new NotebookScopedLocalStorage("test", schema, getDefaultValue);+ expect(storage?.get()).toEqual(getDefaultValue());+ });++ it("should return default value after remove is called", () => {+ storage = new NotebookScopedLocalStorage("test", schema, getDefaultValue);+ // Set a custom value first+ storage.set({ name: "Jane Doe", age: 25 });+ expect(storage.get()).toEqual({ name: "Jane Doe", age: 25 });++ // Remove should clear the storage and return default value+ storage.remove();+ expect(storage.get()).toEqual(getDefaultValue());+ });++ it("should scope storage to filename when filename is set", () => {+ // Set initial filename+ store.set(filenameAtom, "notebook.py");++ // Create storage with filename+ storage = new NotebookScopedLocalStorage("test", schema, getDefaultValue);+ expect(storage.getKey()).toEqual("test:notebook.py");++ // Set a value+ storage.set({ name: "Jane Doe", age: 25 });+ expect(storage.get()).toEqual({ name: "Jane Doe", age: 25 });++ // Change filename and verify key updates+ store.set(filenameAtom, "other.py");+ // Force a small delay to allow the subscription to process+ return new Promise((resolve) => {+ setTimeout(() => {+ expect(storage!.getKey()).toEqual("test:other.py");+ expect(storage!.get()).toEqual({ name: "Jane Doe", age: 25 });+ resolve(undefined);+ }, 0);+ });+ });+});diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsxindex 1df6236acb..af3680e248 100644--- a/frontend/src/utils/id-tree.tsx+++ b/frontend/src/utils/id-tree.tsx@@ -3,6 +3,7 @@import { arrayDelete, arrayInsert, arrayInsertMany, arrayMove } from "./arrays";import { Memoize } from "typescript-memoize";import { Logger } from "./Logger";+import { reorderColumnSizes } from "@/components/editor/columns/storage";/*** Branded number to help with type safety@@ -760,17 +761,14 @@ export class MultiColumn<T> {return this;}const fromIdx = this.indexOfOrThrow(fromCol);- if (toCol === "_left_") {- return new MultiColumn(- arrayMove([...this.columns], fromIdx, fromIdx - 1),- );- }- if (toCol === "_right_") {- return new MultiColumn(- arrayMove([...this.columns], fromIdx, fromIdx + 1),- );- }- const toIdx = this.indexOfOrThrow(toCol);+ const toIdx =+ toCol === "_left_"+ ? fromIdx - 1+ : toCol === "_right_"+ ? fromIdx + 1+ : this.indexOfOrThrow(toCol);++ reorderColumnSizes(fromIdx, toIdx);return new MultiColumn(arrayMove([...this.columns], fromIdx, toIdx));}diff --git a/frontend/src/utils/localStorage.ts b/frontend/src/utils/localStorage.tsindex ec6ad3edad..17e48f64a4 100644--- a/frontend/src/utils/localStorage.ts+++ b/frontend/src/utils/localStorage.ts@@ -1,7 +1,15 @@/* Copyright 2024 Marimo. All rights reserved. */+import { filenameAtom } from "@/core/saving/filenameAtom";+import { store } from "@/core/state/jotai";import type { ZodType, ZodTypeDef } from "zod";-export class TypedLocalStorage<T> {+interface Storage<T> {+ get(): T;+ set(value: T): void;+ remove(): void;+}++export class TypedLocalStorage<T> implements Storage<T> {constructor(private key: string,private defaultValue: T,@@ -19,11 +27,15 @@ export class TypedLocalStorage<T> {set(value: T) {window.localStorage.setItem(this.key, JSON.stringify(value));}++ remove() {+ window.localStorage.removeItem(this.key);+ }}-export class ZodLocalStorage<T> {+export class ZodLocalStorage<T> implements Storage<T> {constructor(- private key: string,+ protected key: string,private schema: ZodType<T, ZodTypeDef, unknown>,private getDefaultValue: () => T,) {}@@ -47,3 +59,62 @@ export class ZodLocalStorage<T> {window.localStorage.removeItem(this.key);}}++/**+ * A ZodLocalStorage that is scoped to the current notebook filename.+ * Useful for storing notebook-specific settings, such as column widths.+ */+export class NotebookScopedLocalStorage<T> extends ZodLocalStorage<T> {+ private filename: string | null;+ private baseKey: string;+ private unsubscribeFromFilename: (() => void) | null;++ constructor(+ key: string,+ schema: ZodType<T, ZodTypeDef, unknown>,+ getDefaultValue: () => T,+ ) {+ const filename = store.get(filenameAtom);+ const scopedKey = filename ? `${key}:${filename}` : key;+ super(scopedKey, schema, getDefaultValue);+ this.filename = filename;+ this.baseKey = key;++ try {+ this.unsubscribeFromFilename = store.sub(filenameAtom, () => {+ const newFilename = store.get(filenameAtom);+ this.handleFilenameChange(newFilename);+ });+ } catch {+ this.unsubscribeFromFilename = null;+ }+ }++ private createScopedKey(filename: string | null) {+ return filename ? `${this.baseKey}:${filename}` : this.baseKey;+ }++ private handleFilenameChange(newFilename: string | null) {+ if (newFilename && newFilename !== this.filename) {+ const currentValue = this.get();+ this.remove();++ this.filename = newFilename;+ this.key = this.createScopedKey(newFilename);+ this.set(currentValue);+ }+ }++ // Used in testing+ public getKey() {+ return this.key;+ }++ // Used in testing. Can also call in cleanup functions+ public dispose() {+ if (this.unsubscribeFromFilename) {+ this.unsubscribeFromFilename();+ this.unsubscribeFromFilename = null;+ }+ }+}