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.

Simplify editor operations after document migration (#11623)

Trevor Manzac0079aa39c6
diff --git a/frontend/src/core/cells/__tests__/arrange.test.ts b/frontend/src/core/cells/__tests__/arrange.test.ts
index 484e11fa4e..553e1778a4 100644
--- a/frontend/src/core/cells/__tests__/arrange.test.ts
+++ b/frontend/src/core/cells/__tests__/arrange.test.ts
@@ -138,12 +138,13 @@ describe("sendToTopAtom and sendToBottomAtom", () => {
it("move a cell to the ends of its column", () => {
const { store, order, notebook } = setup({ c3: cell("c3", "z = 3") });
- store.set(sendToBottomAtom, { cellId: c1 });
+ store.set(sendToBottomAtom, { cellId: c1, scroll: false });
expect(order()).toEqual([c2, c3, c1]);
- expect(notebook().scrollKey).toBe(c1);
+ expect(notebook().scrollKey).toBeNull();
- store.set(sendToTopAtom, { cellId: c1, scroll: false });
+ store.set(sendToTopAtom, { cellId: c1 });
expect(order()).toEqual([c1, c2, c3]);
+ expect(notebook().scrollKey).toBe(c1);
});
it("send a folded header with its section and leave an edge cell alone", () => {
@@ -171,6 +172,22 @@ describe("drag and drop", () => {
expect(order()).toEqual([c1, c2, c3]);
});
+ it("ignores a drop from or onto a cell hidden in a fold", () => {
+ const { store, model, heading, notebook } = setup({
+ c3: cell("c3", "z = 3"),
+ });
+ heading(c2, 1);
+ store.set(collapseCellAtom, { cellId: c2 });
+ const before = store.get(model.documentAtom);
+ const focused = notebook().scrollKey;
+
+ store.set(dropCellOverCellAtom, { cellId: c1, overCellId: c3 });
+ store.set(dropCellOverCellAtom, { cellId: c3, overCellId: c1 });
+
+ expect(store.get(model.documentAtom)).toBe(before);
+ expect(notebook().scrollKey).toBe(focused);
+ });
+
it("drops a cell before another cell in another column", () => {
const { store, columns, cellIn } = twoColumns();
store.set(dropCellOverCellAtom, { cellId: c1, overCellId: c4 });
diff --git a/frontend/src/core/cells/actions.ts b/frontend/src/core/cells/actions.ts
index 2d62b45b6b..d8b80a8ac6 100644
--- a/frontend/src/core/cells/actions.ts
+++ b/frontend/src/core/cells/actions.ts
@@ -148,15 +148,7 @@ export const createCellAtom = atom(
// The new cell has no heading, so every section that runs past the
// cell before it holds it too. Those open, so the cell is on the page.
const hiding = follows === undefined ? [] : foldsAfter(layout, follows);
- if (hiding.length > 0) {
- set(collapsedAtom, (collapsed) => {
- const next = new Set(collapsed);
- for (const header of hiding) {
- next.delete(header);
- }
- return next;
- });
- }
+ unfoldSections(set, hiding);
focusWhenMounted(set, id);
// Hidden code stays showing until the cell is blurred for the first time.
if (config.hide_code) {
@@ -326,6 +318,19 @@ export const focusBottomCellAtom = atom(null, (get): void => {
// A folded header hides the cells of its section. Which headers are folded is
// editor state; the section each one hides derives from the outlines.
+function unfoldSections(set: Setter, headers: readonly CellId[]): void {
+ if (headers.length === 0) {
+ return;
+ }
+ set(collapsedAtom, (collapsed) => {
+ const next = new Set(collapsed);
+ for (const header of headers) {
+ next.delete(header);
+ }
+ return next;
+ });
+}
+
/** Fold the section under `cellId`, if its output has a heading. */
export const collapseCellAtom = atom(
null,
@@ -342,11 +347,7 @@ export const collapseCellAtom = atom(
export const expandCellAtom = atom(
null,
(_get, set, { cellId }: { cellId: CellId }): void => {
- set(collapsedAtom, (collapsed) => {
- const next = new Set(collapsed);
- next.delete(cellId);
- return next;
- });
+ unfoldSections(set, [cellId]);
focusWhenMounted(set, cellId);
},
);
@@ -371,17 +372,7 @@ export const expandAllCellsAtom = atom(null, (_get, set): void => {
export const showCellIfHiddenAtom = atom(
null,
(get, set, { cellId }: { cellId: CellId }): void => {
- const hiding = foldsHiding(get(layoutAtom), cellId);
- if (hiding.length === 0) {
- return;
- }
- set(collapsedAtom, (collapsed) => {
- const next = new Set(collapsed);
- for (const header of hiding) {
- next.delete(header);
- }
- return next;
- });
+ unfoldSections(set, foldsHiding(get(layoutAtom), cellId));
},
);
diff --git a/frontend/src/core/cells/arrange.ts b/frontend/src/core/cells/arrange.ts
index 03534c3f37..b0450036ef 100644
--- a/frontend/src/core/cells/arrange.ts
+++ b/frontend/src/core/cells/arrange.ts
@@ -41,13 +41,23 @@ function blocksOf(column: LayoutColumn): CellId[][] {
return column.visible.map((id) => blockOf(column, id));
}
-/** The cells of every column, as arrays to rearrange. */
-function columnsOf(layout: Layout): CellId[][] {
- return layout.columns.map((column) => [...column.ids]);
+interface ArrangedColumn {
+ id: CellColumnId;
+ ids: CellId[];
}
-function without(columns: CellId[][], ids: ReadonlySet<CellId>): CellId[][] {
- return columns.map((column) => column.filter((id) => !ids.has(id)));
+function columnsOf(layout: Layout): ArrangedColumn[] {
+ return layout.columns.map(({ id, ids }) => ({ id, ids: [...ids] }));
+}
+
+function without(
+ columns: ArrangedColumn[],
+ ids: ReadonlySet<CellId>,
+): ArrangedColumn[] {
+ return columns.map((column) => ({
+ ...column,
+ ids: column.ids.filter((id) => !ids.has(id)),
+ }));
}
/**
@@ -58,13 +68,13 @@ function without(columns: CellId[][], ids: ReadonlySet<CellId>): CellId[][] {
* cell still names its index, until a drop compacts it.
*/
function columnConfigs(
- columns: readonly (readonly CellId[])[],
+ columns: readonly ArrangedColumn[],
configured: (id: CellId) => number | null,
): Array<[CellId, number | null]> {
const fixes: Array<[CellId, number | null]> = [];
const single = columns.length === 1;
columns.forEach((column, index) => {
- column.forEach((id, position) => {
+ column.ids.forEach((id, position) => {
const target = !single && position === 0 ? index : null;
if (configured(id) !== target) {
fixes.push([id, target]);
@@ -77,9 +87,9 @@ function columnConfigs(
/** The steps that make the document's cells fall into `columns`, or null when they do. */
function arrangement(
document: EditableDocument,
- columns: readonly (readonly CellId[])[],
+ columns: readonly ArrangedColumn[],
): ((tx: DocumentEditor) => void) | null {
- const order = columns.flat();
+ const order = columns.flatMap((column) => column.ids);
const fixes = columnConfigs(
columns,
(id) => document.cells.get(id)?.config.column ?? null,
@@ -102,47 +112,70 @@ function arrangement(
* How many of `columns` the document holds: all but the trailing empty
* ones, which the page alone keeps.
*/
-function heldByDocument(columns: readonly (readonly CellId[])[]): number {
+function heldByDocument(columns: readonly ArrangedColumn[]): number {
let count = columns.length;
- while (count > 1 && columns[count - 1].length === 0) {
+ while (count > 1 && columns[count - 1].ids.length === 0) {
count -= 1;
}
return count;
}
-/** Name the page's columns: `count` of `ids` for the document's, the rest kept empty. */
+/** Name the document's columns and the trailing empty columns kept on the page. */
function nameColumns(
set: Setter,
- ids: readonly CellColumnId[],
+ columns: readonly ArrangedColumn[],
count: number,
): void {
+ const ids = columns.map((column) => column.id);
set(columnIdsAtom, ids.slice(0, count));
set(emptyColumnIdsAtom, ids.slice(count));
}
/**
* Make the document's cells fall into `columns`, in that order, as one
- * edit, and name the columns `ids`, by default as they stand. Nothing is
- * written when the cells already fall that way. Trailing columns left
- * empty stay on the page, as the document cannot hold them, until a drop
- * compacts them.
+ * edit, keeping each column's identity. Nothing is written when the cells
+ * already fall that way. Trailing empty columns stay on the page, as the
+ * document cannot hold them, until a drop compacts them.
*/
export function arrange(
get: Getter,
set: Setter,
- columns: CellId[][],
- ids: readonly CellColumnId[] = get(layoutAtom).columns.map(
- (column) => column.id,
- ),
+ columns: ArrangedColumn[],
): void {
const count = heldByDocument(columns);
- nameColumns(set, ids, count);
+ nameColumns(set, columns, count);
const edit = arrangement(documentOf(get), columns.slice(0, count));
if (edit !== null) {
set(modelOf(get).editAtom, edit);
}
}
+function reorderBlock(
+ get: Getter,
+ set: Setter,
+ cellId: CellId,
+ targetIndex: (index: number, visible: readonly CellId[]) => number,
+): boolean {
+ const layout = get(layoutAtom);
+ const column = columnOf(layout, cellId);
+ const index = column.visible.indexOf(cellId);
+ if (index === -1) {
+ return false;
+ }
+ const target = targetIndex(index, column.visible);
+ if (target < 0 || target >= column.visible.length || target === index) {
+ return false;
+ }
+ const columns = columnsOf(layout);
+ columns[layout.columns.indexOf(column)].ids = arrayMove(
+ blocksOf(column),
+ index,
+ target,
+ ).flat();
+ arrange(get, set, columns);
+ return true;
+}
+
/**
* Move a cell one block up or down its column, or to the start of the
* neighbouring column. A folded header moves with its section.
@@ -158,29 +191,23 @@ export const moveCellAtom = atom(
direction,
}: { cellId: CellId; before?: boolean; direction?: "left" | "right" },
): void => {
- const layout = get(layoutAtom);
- const column = columnOf(layout, cellId);
- const at = layout.columns.indexOf(column);
- const columns = columnsOf(layout);
if (direction) {
+ const layout = get(layoutAtom);
+ const column = columnOf(layout, cellId);
+ const at = layout.columns.indexOf(column);
+ const columns = columnsOf(layout);
const to = direction === "left" ? at - 1 : at + 1;
if (to < 0 || to >= columns.length) {
return;
}
const block = blockOf(column, cellId);
const cleaned = without(columns, new Set(block));
- cleaned[to] = [...block, ...cleaned[to]];
+ cleaned[to].ids.unshift(...block);
arrange(get, set, cleaned);
focusWhenMounted(set, cellId);
return;
}
- const blocks = blocksOf(column);
- const index = blocks.findIndex((block) => block[0] === cellId);
- const target = before ? index - 1 : index + 1;
- if (index !== -1 && target >= 0 && target < blocks.length) {
- columns[at] = arrayMove(blocks, index, target).flat();
- arrange(get, set, columns);
- }
+ reorderBlock(get, set, cellId, (index) => (before ? index - 1 : index + 1));
focusWhenMounted(set, cellId);
},
);
@@ -191,22 +218,10 @@ function sendTo(
{ cellId, scroll = true }: { cellId: CellId; scroll?: boolean },
edge: "top" | "bottom",
): void {
- const layout = get(layoutAtom);
- const column = columnOf(layout, cellId);
- const blocks = blocksOf(column);
- const index = blocks.findIndex((block) => block[0] === cellId);
- const target = edge === "top" ? 0 : blocks.length - 1;
- if (index === -1 || index === target) {
- return;
- }
- const columns = columnsOf(layout);
- columns[layout.columns.indexOf(column)] = arrayMove(
- blocks,
- index,
- target,
- ).flat();
- arrange(get, set, columns);
- if (scroll) {
+ const moved = reorderBlock(get, set, cellId, (_index, visible) =>
+ edge === "top" ? 0 : visible.length - 1,
+ );
+ if (moved && scroll) {
focusWhenMounted(set, cellId);
}
}
@@ -236,25 +251,15 @@ export const dropCellOverCellAtom = atom(
const layout = get(layoutAtom);
const from = columnOf(layout, cellId);
const to = columnOf(layout, overCellId);
- const columns = columnsOf(layout);
if (from === to) {
- const blocks = blocksOf(from);
- const index = blocks.findIndex((block) => block[0] === cellId);
- const target = blocks.findIndex((block) => block[0] === overCellId);
- if (index === -1 || target === -1 || index === target) {
- return;
- }
- columns[layout.columns.indexOf(from)] = arrayMove(
- blocks,
- index,
- target,
- ).flat();
- arrange(get, set, columns);
+ reorderBlock(get, set, cellId, (_index, visible) =>
+ visible.indexOf(overCellId),
+ );
return;
}
const block = blockOf(from, cellId);
- const cleaned = without(columns, new Set(block));
- const target = cleaned[layout.columns.indexOf(to)];
+ const cleaned = without(columnsOf(layout), new Set(block));
+ const target = cleaned[layout.columns.indexOf(to)].ids;
const at = target.indexOf(overCellId);
target.splice(at, 0, ...block);
arrange(get, set, cleaned);
@@ -276,7 +281,7 @@ export const dropCellOverColumnAtom = atom(
}
const block = blockOf(columnOf(layout, cellId), cellId);
const cleaned = without(columnsOf(layout), new Set(block));
- cleaned[layout.columns.indexOf(to)].unshift(...block);
+ cleaned[layout.columns.indexOf(to)].ids.unshift(...block);
arrange(get, set, cleaned);
},
);
@@ -303,7 +308,7 @@ export const moveCellToIndexAtom = atom(
const columns = columnsOf(layout);
const fromIndex = from.ids.indexOf(cellId);
const cleaned = without(columns, new Set(block));
- const target = cleaned[layout.columns.indexOf(to)];
+ const target = cleaned[layout.columns.indexOf(to)].ids;
let at = Math.max(0, Math.min(index, to.ids.length));
if (from === to && fromIndex < at) {
at -= block.length;
@@ -341,7 +346,7 @@ export const moveCellsRelativeToAtom = atom(
const moving = new Set(cellIds);
const cleaned = without(columnsOf(layout), moving);
const target =
- cleaned[layout.columns.indexOf(columnOf(layout, targetCellId))];
+ cleaned[layout.columns.indexOf(columnOf(layout, targetCellId))].ids;
let at = target.indexOf(targetCellId);
if (at === -1) {
// The target moves too, so the cells go to the end of its column.
@@ -386,7 +391,7 @@ export function placeCells(
}))
.toSorted((a, b) => a.column - b.column || a.index - b.index);
for (const { id, column, index } of sorted) {
- const target = cleaned[column];
+ const target = cleaned[column].ids;
target.splice(Math.max(0, Math.min(index, target.length)), 0, id);
}
arrange(get, set, cleaned);
@@ -405,13 +410,11 @@ export const addColumnAtom = atom(
}
const id = CellId.create();
const columns = columnsOf(layout);
- columns.splice(at + 1, 0, [id]);
- const ids = layout.columns.map((column) => column.id);
- ids.splice(at + 1, 0, newColumnId());
+ columns.splice(at + 1, 0, { id: newColumnId(), ids: [id] });
const document = documentOf(get);
const previous = layout.columns[at].ids.at(-1);
const count = heldByDocument(columns);
- nameColumns(set, ids, count);
+ nameColumns(set, columns, count);
set(modelOf(get).editAtom, (tx) => {
tx.createCell(
{ id, code: "", config: { column: at + 1 } },
@@ -435,11 +438,15 @@ export const addColumnBreakpointAtom = atom(
return;
}
const columns = columnsOf(layout);
- columns.splice(at, 1, column.ids.slice(0, index), column.ids.slice(index));
- const ids = layout.columns.map((column) => column.id);
// The id stays with the cells, so the half without any is the new one.
- ids.splice(index === 0 ? at : at + 1, 0, newColumnId());
- arrange(get, set, columns, ids);
+ const added = newColumnId();
+ columns.splice(
+ at,
+ 1,
+ { id: index === 0 ? added : column.id, ids: column.ids.slice(0, index) },
+ { id: index === 0 ? column.id : added, ids: column.ids.slice(index) },
+ );
+ arrange(get, set, columns);
},
);
@@ -454,14 +461,12 @@ export const deleteColumnAtom = atom(
}
const columns = columnsOf(layout);
const target = at === 0 ? 1 : at - 1;
- columns[target] =
+ columns[target].ids =
at === 0
- ? [...columns[at], ...columns[target]]
- : [...columns[target], ...columns[at]];
+ ? [...columns[at].ids, ...columns[target].ids]
+ : [...columns[target].ids, ...columns[at].ids];
columns.splice(at, 1);
- const ids = layout.columns.map((column) => column.id);
- ids.splice(at, 1);
- arrange(get, set, columns, ids);
+ arrange(get, set, columns);
},
);
@@ -471,27 +476,22 @@ export const mergeAllColumnsAtom = atom(null, (get, set): void => {
if (layout.columns.length <= 1) {
return;
}
- arrange(
- get,
- set,
- [layout.columns.flatMap((column) => [...column.ids])],
- [layout.columns[0].id],
- );
+ arrange(get, set, [
+ {
+ id: layout.columns[0].id,
+ ids: layout.columns.flatMap((column) => [...column.ids]),
+ },
+ ]);
});
/** Drop the columns a drag left empty. */
export const compactColumnsAtom = atom(null, (get, set): void => {
const layout = get(layoutAtom);
- const kept = layout.columns.filter((column) => column.ids.length > 0);
+ const kept = columnsOf(layout).filter((column) => column.ids.length > 0);
if (kept.length === layout.columns.length || layout.columns.length <= 1) {
return;
}
- arrange(
- get,
- set,
- kept.map((column) => [...column.ids]),
- kept.map((column) => column.id),
- );
+ arrange(get, set, kept);
});
/** Move a column where another is, or one step left or right, with its saved width. */
@@ -512,23 +512,18 @@ export const moveColumnAtom = atom(
return;
}
const layout = get(layoutAtom);
- const ids = layout.columns.map((column) => column.id);
- const from = ids.indexOf(column);
+ const columns = columnsOf(layout);
+ const from = columns.findIndex(({ id }) => id === column);
const to =
overColumn === "_left_"
? from - 1
: overColumn === "_right_"
? from + 1
- : ids.indexOf(overColumn);
- if (from === -1 || to < 0 || to >= ids.length) {
+ : columns.findIndex(({ id }) => id === overColumn);
+ if (from === -1 || to < 0 || to >= columns.length) {
return;
}
- arrange(
- get,
- set,
- arrayMove(columnsOf(layout), from, to),
- arrayMove(ids, from, to),
- );
+ arrange(get, set, arrayMove(columns, from, to));
reorderColumnSizes(from, to);
},
);
diff --git a/frontend/src/core/saving/__tests__/useAutoSave.test.tsx b/frontend/src/core/saving/__tests__/useAutoSave.test.tsx
new file mode 100644
index 0000000000..4a30efd97f
--- /dev/null
+++ b/frontend/src/core/saving/__tests__/useAutoSave.test.tsx
@@ -0,0 +1,67 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ConnectionState } from "../../session/types";
+import { useAutoSave } from "../useAutoSave";
+
+function options(): Parameters<typeof useAutoSave>[0] {
+ return {
+ version: 1,
+ config: {
+ autosave: "after_delay",
+ autosave_delay: 1000,
+ format_on_save: false,
+ },
+ connStatus: { state: ConnectionState.OPEN },
+ needsSave: true,
+ canEdit: true,
+ onSave: vi.fn(),
+ };
+}
+
+describe("useAutoSave", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("waits for the full delay after the latest confirmed change", () => {
+ const initial = options();
+ const { rerender } = renderHook(useAutoSave, { initialProps: initial });
+
+ act(() => vi.advanceTimersByTime(600));
+ rerender({ ...initial, version: 2 });
+ act(() => vi.advanceTimersByTime(999));
+ expect(initial.onSave).not.toHaveBeenCalled();
+
+ act(() => vi.advanceTimersByTime(1));
+ expect(initial.onSave).toHaveBeenCalledExactlyOnceWith();
+ });
+
+ it("cancels pending saves when editing is disabled or the component unmounts", () => {
+ const initial = options();
+ const { rerender, unmount } = renderHook(useAutoSave, {
+ initialProps: initial,
+ });
+
+ act(() => vi.advanceTimersByTime(600));
+ rerender({ ...initial, canEdit: false });
+ act(() => vi.advanceTimersByTime(1000));
+ expect(initial.onSave).not.toHaveBeenCalled();
+
+ rerender(initial);
+ act(() => vi.advanceTimersByTime(999));
+ expect(initial.onSave).not.toHaveBeenCalled();
+ act(() => vi.advanceTimersByTime(1));
+ expect(initial.onSave).toHaveBeenCalledExactlyOnceWith();
+
+ rerender({ ...initial, version: 2 });
+ unmount();
+ act(() => vi.advanceTimersByTime(1000));
+ expect(initial.onSave).toHaveBeenCalledExactlyOnceWith();
+ });
+});
diff --git a/frontend/src/core/saving/useAutoSave.ts b/frontend/src/core/saving/useAutoSave.ts
index ed5f874940..a7116bd866 100644
--- a/frontend/src/core/saving/useAutoSave.ts
+++ b/frontend/src/core/saving/useAutoSave.ts
@@ -1,5 +1,5 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { useEffect, useRef } from "react";
+import { useEffect } from "react";
import type { UserConfig } from "../config/config-schema";
import { type ConnectionStatus, ConnectionState } from "../session/types";
@@ -14,28 +14,19 @@ export function useAutoSave(opts: {
onSave: () => void;
}) {
const { version, config, connStatus, needsSave, canEdit, onSave } = opts;
- const autosaveTimeoutId = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
- if (!canEdit) {
+ if (
+ !canEdit ||
+ config.autosave !== "after_delay" ||
+ !needsSave ||
+ connStatus.state !== ConnectionState.OPEN
+ ) {
return;
}
- if (config.autosave === "after_delay") {
- if (autosaveTimeoutId.current !== null) {
- clearTimeout(autosaveTimeoutId.current);
- }
-
- if (needsSave && connStatus.state === ConnectionState.OPEN) {
- autosaveTimeoutId.current = setTimeout(onSave, config.autosave_delay);
- }
- }
-
- return () => {
- if (autosaveTimeoutId.current !== null) {
- clearTimeout(autosaveTimeoutId.current);
- }
- };
+ const timeout = setTimeout(onSave, config.autosave_delay);
+ return () => clearTimeout(timeout);
// `version` restarts the delay on every confirmed change.
}, [version, config, connStatus.state, onSave, canEdit, needsSave]);
}