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.

Add reactive notebook minimap for navigating and visualizing dataflow (#5707)

Trevor Manz958c19de0f59
diff --git a/frontend/src/components/data-table/hooks/use-panel-ownership.ts b/frontend/src/components/data-table/hooks/use-panel-ownership.ts
index b655a5e524..8dc1d241ea 100644
--- a/frontend/src/components/data-table/hooks/use-panel-ownership.ts
+++ b/frontend/src/components/data-table/hooks/use-panel-ownership.ts
@@ -7,7 +7,7 @@ import {
isCellAwareAtom,
} from "@/components/editor/chrome/panels/context-aware-panel/atoms";
import type { PanelType } from "@/components/editor/chrome/panels/context-aware-panel/context-aware-panel";
-import { lastFocusedCellIdAtom } from "@/core/cells/focus";
+import { useCellFocusActions, useLastFocusedCellId } from "@/core/cells/focus";
import type { CellId } from "@/core/cells/ids";
import { Logger } from "@/utils/Logger";
@@ -21,9 +21,8 @@ export function usePanelOwnership(
cellId?: CellId | null,
): PanelOwnershipResult {
let isPanelCellAware = useAtomValue(isCellAwareAtom);
- const [lastFocusedCellId, setLastFocusedCellId] = useAtom(
- lastFocusedCellIdAtom,
- );
+ const { focusCell } = useCellFocusActions();
+ const lastFocusedCellId = useLastFocusedCellId();
const [panelType, setPanelType] = useAtom(contextAwarePanelType);
const [panelOwner, setPanelOwner] = useAtom(contextAwarePanelOwner);
const [isContextAwarePanelOpen, setContextAwarePanelOpen] = useAtom(
@@ -64,7 +63,7 @@ export function usePanelOwnership(
setPanelOwner(panelId);
// if cell-aware, we want to focus on this cell when toggled open
if (isPanelCellAware && cellId) {
- setLastFocusedCellId(cellId);
+ focusCell({ cellId });
}
setContextAwarePanelOpen(true);
setPanelType(panelType);
diff --git a/frontend/src/components/editor/chrome/state.ts b/frontend/src/components/editor/chrome/state.ts
index e95f46c1df..e8568bed0a 100644
--- a/frontend/src/components/editor/chrome/state.ts
+++ b/frontend/src/components/editor/chrome/state.ts
@@ -10,6 +10,7 @@ export interface ChromeState {
selectedPanel: PanelType | undefined;
isSidebarOpen: boolean;
isTerminalOpen: boolean;
+ isMinimapOpen: boolean;
}
const KEY = "marimo:sidebar";
@@ -21,6 +22,7 @@ const storage = new ZodLocalStorage<ChromeState>(
.transform((v) => v as PanelType),
isSidebarOpen: z.boolean(),
isTerminalOpen: z.boolean(),
+ isMinimapOpen: z.boolean(),
}),
initialState,
);
@@ -30,6 +32,7 @@ function initialState(): ChromeState {
selectedPanel: "variables", // initial panel
isSidebarOpen: false,
isTerminalOpen: false,
+ isMinimapOpen: false,
};
}
@@ -71,6 +74,14 @@ const {
...state,
isTerminalOpen: isOpen,
}),
+ toggleMinimap: (state) => ({
+ ...state,
+ isMinimapOpen: !state.isMinimapOpen,
+ }),
+ setIsMinimapOpen: (state, isOpen: boolean) => ({
+ ...state,
+ isMinimapOpen: isOpen,
+ }),
},
[(_prevState, newState) => storage.set(KEY, newState)],
);
diff --git a/frontend/src/components/editor/chrome/wrapper/__tests__/minimap-state.test.ts b/frontend/src/components/editor/chrome/wrapper/__tests__/minimap-state.test.ts
new file mode 100644
index 0000000000..9f9d24afbc
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/__tests__/minimap-state.test.ts
@@ -0,0 +1,209 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import type { CellId } from "@/core/cells/ids";
+import type { VariableName, Variables } from "@/core/variables/types";
+import { buildCellGraph } from "../minimap-state";
+
+const cellId = (id: string) => id as CellId;
+const varName = (name: string) => name as VariableName;
+
+describe("buildCellGraph", () => {
+ it("builds graph for simple linear dependency", () => {
+ // cell1 declares x, cell2 uses x
+ const cellIds = [cellId("cell1"), cellId("cell2")];
+ const variables: Variables = {
+ [varName("x")]: {
+ name: varName("x"),
+ declaredBy: [cellId("cell1")],
+ usedBy: [cellId("cell2")],
+ },
+ };
+
+ const graph = buildCellGraph(cellIds, variables);
+
+ expect(graph).toMatchInlineSnapshot(`
+ {
+ "cell1": {
+ "ancestors": Set {},
+ "children": Set {
+ "cell2",
+ },
+ "descendants": Set {
+ "cell2",
+ },
+ "parents": Set {},
+ "variables": [
+ "x",
+ ],
+ },
+ "cell2": {
+ "ancestors": Set {
+ "cell1",
+ },
+ "children": Set {},
+ "descendants": Set {},
+ "parents": Set {
+ "cell1",
+ },
+ "variables": [],
+ },
+ }
+ `);
+ });
+
+ it("builds graph for diamond pattern", () => {
+ // cell1 declares x
+ // cell2 and cell3 both use x and declare y and z
+ // cell4 uses y and z
+ const cellIds = [
+ cellId("cell1"),
+ cellId("cell2"),
+ cellId("cell3"),
+ cellId("cell4"),
+ ];
+ const variables: Variables = {
+ [varName("x")]: {
+ name: varName("x"),
+ declaredBy: [cellId("cell1")],
+ usedBy: [cellId("cell2"), cellId("cell3")],
+ },
+ [varName("y")]: {
+ name: varName("y"),
+ declaredBy: [cellId("cell2")],
+ usedBy: [cellId("cell4")],
+ },
+ [varName("z")]: {
+ name: varName("z"),
+ declaredBy: [cellId("cell3")],
+ usedBy: [cellId("cell4")],
+ },
+ };
+
+ const graph = buildCellGraph(cellIds, variables);
+
+ expect(graph).toMatchInlineSnapshot(`
+ {
+ "cell1": {
+ "ancestors": Set {},
+ "children": Set {
+ "cell2",
+ "cell3",
+ },
+ "descendants": Set {
+ "cell2",
+ "cell4",
+ "cell3",
+ },
+ "parents": Set {},
+ "variables": [
+ "x",
+ ],
+ },
+ "cell2": {
+ "ancestors": Set {
+ "cell1",
+ },
+ "children": Set {
+ "cell4",
+ },
+ "descendants": Set {
+ "cell4",
+ },
+ "parents": Set {
+ "cell1",
+ },
+ "variables": [
+ "y",
+ ],
+ },
+ "cell3": {
+ "ancestors": Set {
+ "cell1",
+ },
+ "children": Set {
+ "cell4",
+ },
+ "descendants": Set {
+ "cell4",
+ },
+ "parents": Set {
+ "cell1",
+ },
+ "variables": [
+ "z",
+ ],
+ },
+ "cell4": {
+ "ancestors": Set {
+ "cell2",
+ "cell1",
+ "cell3",
+ },
+ "children": Set {},
+ "descendants": Set {},
+ "parents": Set {
+ "cell2",
+ "cell3",
+ },
+ "variables": [],
+ },
+ }
+ `);
+ });
+
+ it("handles self-referencing and isolated cells", () => {
+ const cellIds = [cellId("cell1"), cellId("cell2"), cellId("cell3")];
+ const variables: Variables = {
+ [varName("x")]: {
+ name: varName("x"),
+ declaredBy: [cellId("cell1")],
+ usedBy: [cellId("cell1"), cellId("cell2")], // self-reference + downstream
+ },
+ [varName("y")]: {
+ name: varName("y"),
+ declaredBy: [cellId("cell3")],
+ usedBy: [], // isolated variable
+ },
+ };
+
+ const graph = buildCellGraph(cellIds, variables);
+
+ expect(graph).toMatchInlineSnapshot(`
+ {
+ "cell1": {
+ "ancestors": Set {},
+ "children": Set {
+ "cell2",
+ },
+ "descendants": Set {
+ "cell2",
+ },
+ "parents": Set {},
+ "variables": [
+ "x",
+ ],
+ },
+ "cell2": {
+ "ancestors": Set {
+ "cell1",
+ },
+ "children": Set {},
+ "descendants": Set {},
+ "parents": Set {
+ "cell1",
+ },
+ "variables": [],
+ },
+ "cell3": {
+ "ancestors": Set {},
+ "children": Set {},
+ "descendants": Set {},
+ "parents": Set {},
+ "variables": [
+ "y",
+ ],
+ },
+ }
+ `);
+ });
+});
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index 4d96af9dae..295f597030 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -32,6 +32,7 @@ import { SnippetsPanel } from "../panels/snippets-panel";
import { TracingPanel } from "../panels/tracing-panel";
import { VariablePanel } from "../panels/variable-panel";
import { useChromeActions, useChromeState } from "../state";
+import { Minimap } from "./minimap";
import { PanelsWrapper } from "./panels";
import { createStorage } from "./storage";
import { handleDragging } from "./utils";
@@ -244,6 +245,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
</Panel>
<ContextAwarePanel />
</PanelGroup>
+ <Minimap />
<ErrorBoundary>
<TooltipProvider>
<Footer />
diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/minimap-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/minimap-status.tsx
new file mode 100644
index 0000000000..f1880702b3
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/minimap-status.tsx
@@ -0,0 +1,21 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { MapIcon } from "lucide-react";
+import { useChromeActions, useChromeState } from "../../state";
+import { FooterItem } from "../footer-item";
+
+export const MinimapStatusIcon: React.FC = () => {
+ const { isMinimapOpen } = useChromeState();
+ const { toggleMinimap } = useChromeActions();
+
+ return (
+ <FooterItem
+ tooltip="Toggle Minimap"
+ selected={isMinimapOpen}
+ onClick={() => toggleMinimap()}
+ data-testid="footer-minimap"
+ >
+ <MapIcon className="h-4 w-4" />
+ </FooterItem>
+ );
+};
diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsx
index deb19bd725..9a54346683 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx
@@ -17,6 +17,7 @@ import { AIStatusIcon } from "./footer-items/ai-status";
import { BackendConnection } from "./footer-items/backend-status";
import { CopilotStatusIcon } from "./footer-items/copilot-status";
import { MachineStats } from "./footer-items/machine-stats";
+import { MinimapStatusIcon } from "./footer-items/minimap-status";
import { RTCStatus } from "./footer-items/rtc-status";
import { RuntimeSettings } from "./footer-items/runtime-settings";
@@ -78,6 +79,7 @@ export const Footer: React.FC = () => {
<div className="flex items-center flex-shrink-0 min-w-0">
<MachineStats />
+ <MinimapStatusIcon />
<AIStatusIcon />
<CopilotStatusIcon />
<RTCStatus />
diff --git a/frontend/src/components/editor/chrome/wrapper/minimap-state.ts b/frontend/src/components/editor/chrome/wrapper/minimap-state.ts
new file mode 100644
index 0000000000..fdc15b8d73
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/minimap-state.ts
@@ -0,0 +1,160 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { atom } from "jotai";
+import { notebookAtom } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import { variablesAtom } from "@/core/variables/state";
+import type { Variable, VariableName, Variables } from "@/core/variables/types";
+
+export interface CellGraph {
+ variables: readonly VariableName[];
+
+ // Direct connections for traversal
+ parents: ReadonlySet<CellId>; // Cells I depend on (direct upstream)
+ children: ReadonlySet<CellId>; // Cells that depend on me (direct downstream)
+
+ // Pre-computed transitive closure
+ ancestors: ReadonlySet<CellId>; // All cells upstream (includes parents)
+ descendants: ReadonlySet<CellId>; // All cells downstream (includes children)
+}
+
+function computeTransitiveClosure(
+ cellId: CellId,
+ getDirectConnections: (id: CellId) => Set<CellId>,
+ visited = new Set<CellId>(),
+): Set<CellId> {
+ if (visited.has(cellId)) {
+ return new Set();
+ }
+ visited.add(cellId);
+
+ const result = new Set<CellId>();
+ for (const connectedId of getDirectConnections(cellId)) {
+ result.add(connectedId);
+ for (const id of computeTransitiveClosure(
+ connectedId,
+ getDirectConnections,
+ visited,
+ )) {
+ result.add(id);
+ }
+ }
+
+ return result;
+}
+
+export function buildCellGraph(
+ cellIds: CellId[],
+ variables: Variables,
+): Record<CellId, CellGraph> {
+ // First pass: build direct connections
+ const dependencyMap = new Map<
+ CellId,
+ {
+ variables: Set<VariableName>;
+ parents: Set<CellId>;
+ children: Set<CellId>;
+ }
+ >();
+ for (const cellId of cellIds) {
+ dependencyMap.set(cellId, {
+ variables: new Set(),
+ parents: new Set(),
+ children: new Set(),
+ });
+ }
+ // get parent-child relationships from variables
+ for (const variable of Object.values(variables)) {
+ if (variable.dataType === "module") {
+ // skip modules
+ continue;
+ }
+ for (const declarer of variable.declaredBy) {
+ dependencyMap.get(declarer)?.variables.add(variable.name);
+ for (const user of variable.usedBy) {
+ if (declarer !== user) {
+ dependencyMap.get(user)?.parents.add(declarer);
+ dependencyMap.get(declarer)?.children.add(user);
+ }
+ }
+ }
+ }
+
+ // Second pass: build final graph with transitive closures
+ const graphs: Record<CellId, CellGraph> = {};
+ for (const [cellId, cellDeps] of dependencyMap.entries()) {
+ graphs[cellId] = {
+ parents: cellDeps.parents,
+ children: cellDeps.children,
+ variables: [...cellDeps.variables],
+ ancestors: computeTransitiveClosure(
+ cellId,
+ (id) => dependencyMap.get(id)?.parents ?? new Set(),
+ ),
+ descendants: computeTransitiveClosure(
+ cellId,
+ (id) => dependencyMap.get(id)?.children ?? new Set(),
+ ),
+ };
+ }
+
+ return graphs;
+}
+
+export const cellGraphsAtom = atom((get) => {
+ const notebook = get(notebookAtom);
+ const variables = get(variablesAtom);
+ return buildCellGraph(notebook.cellIds.inOrderIds, variables);
+});
+
+/**
+ * Determines if a variable should be highlighted when a cell is selected.
+ *
+ * For upstream dataflow: We can precisely track which variables flow INTO the selected cell
+ * by checking what the selected cell actually uses.
+ *
+ * For downstream dataflow: We only have cell-level dependency information, not variable-level,
+ * so we highlight ALL variables in descendant cells since they will all be re-executed
+ * when the selected cell changes.
+ *
+ * @param variable - The variable to check for highlighting
+ * @param options - The currently selected cell and its dependency graph
+ */
+export function isVariableAffectedBySelectedCell(
+ variable: Variable,
+ options: { selectedCellId: CellId; selectedGraph: CellGraph },
+): boolean {
+ // Case 1: Variable is used by the selected cell (incoming dataflow)
+ if (variable.usedBy.includes(options.selectedCellId)) {
+ return true;
+ }
+
+ // Case 2: Variable is declared by the selected cell (outgoing dataflow)
+ if (variable.declaredBy.includes(options.selectedCellId)) {
+ return true;
+ }
+
+ // Case 3: Variable is declared by an ancestor AND used by selected cell or descendants
+ // This captures the flow-through case
+ const isDeclaredByAncestor = variable.declaredBy.some((declarer) =>
+ options.selectedGraph.parents.has(declarer),
+ );
+
+ if (isDeclaredByAncestor) {
+ return variable.usedBy.some((user) =>
+ options.selectedGraph.parents.has(user),
+ );
+ }
+
+ // Case 4: Variable is declared by a descendant
+ // These will be re-executed when the selected cell changes
+ const isDeclaredByDescendant = variable.declaredBy.some((declarer) =>
+ options.selectedGraph.children.has(declarer),
+ );
+
+ if (isDeclaredByDescendant) {
+ return true;
+ }
+
+ return false;
+}
diff --git a/frontend/src/components/editor/chrome/wrapper/minimap.tsx b/frontend/src/components/editor/chrome/wrapper/minimap.tsx
new file mode 100644
index 0000000000..eade978628
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/minimap.tsx
@@ -0,0 +1,417 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useAtomValue } from "jotai";
+import { XIcon } from "lucide-react";
+import * as React from "react";
+import { Button } from "@/components/ui/button";
+import { useCellActions, useNotebook } from "@/core/cells/cells";
+import { cellFocusAtom, useCellFocusActions } from "@/core/cells/focus";
+import type { CellId } from "@/core/cells/ids";
+import { useVariables } from "@/core/variables/state";
+import type { VariableName } from "@/core/variables/types";
+import { cn } from "@/utils/cn";
+import { useChromeActions, useChromeState } from "../state";
+import {
+ type CellGraph,
+ cellGraphsAtom,
+ isVariableAffectedBySelectedCell,
+} from "./minimap-state";
+
+interface MinimapCellProps {
+ cellId: CellId;
+ cellPositions: Readonly<Record<CellId, number>>;
+}
+
+const MinimapCell: React.FC<MinimapCellProps> = (props) => {
+ const { cellId, cellPositions } = props;
+ const notebook = useNotebook();
+ const focusState = useAtomValue(cellFocusAtom);
+ const selectedCellId = focusState.focusedCellId;
+ const graphs = useAtomValue(cellGraphsAtom);
+ const actions = useCellActions();
+ const focusActions = useCellFocusActions();
+
+ const cell = notebook.cellData[cellId];
+ const runtime = notebook.cellRuntime[cellId];
+
+ const graph = graphs[cellId];
+ const selectedGraph = selectedCellId ? graphs[selectedCellId] : undefined;
+
+ const isSelected = selectedCellId === cellId;
+
+ const handleClick = () => {
+ if (isSelected) {
+ // If clicking the already focused cell, blur it
+ focusActions.blurCell();
+ } else {
+ // Otherwise focus the cell
+ actions.focusCell({ cellId, where: "exact" });
+ focusActions.focusCell({ cellId });
+ }
+ };
+
+ return (
+ <button
+ data-node-id={cellId}
+ className={cn(
+ "group bg-transparent text-left w-full flex relative justify-between items-center",
+ "border-none rounded cursor-pointer",
+ "h-[21px] pl-[51px] font-inherit",
+ isSelected
+ ? "text-primary-foreground"
+ : "text-[var(--gray-8)] hover:text-[var(--gray-9)]",
+ )}
+ onClick={handleClick}
+ // Prevent the default mousedown behavior to avoid blur events on the currently
+ // focused cell. Without this, clicking the minimap causes a flicker as the focus
+ // transitions from current cell -> null -> new cell.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ <div
+ className={cn(
+ "group-hover:bg-[var(--gray-2)] flex h-full w-full px-0.5 items-center rounded",
+ isSelected && "bg-primary group-hover:bg-primary",
+ )}
+ >
+ <div
+ className="truncate px-1 font-mono text-sm flex gap-1"
+ title={cell.code}
+ >
+ {graph.variables.length > 0 ? (
+ <VariablesList
+ cellId={cellId}
+ variableNames={graph.variables}
+ selectedCellId={selectedCellId}
+ selectedGraph={selectedGraph}
+ />
+ ) : (
+ <span className="overflow-hidden text-ellipsis whitespace-nowrap max-w-full">
+ {codePreview(cell.code) ?? <span className="italic">empty</span>}
+ </span>
+ )}
+ </div>
+ </div>
+ <svg
+ className={cn(
+ "absolute z-20 overflow-visible top-[10.5px] left-[calc(var(--spacing-extra-small,8px)_+_17px)] pointer-events-none",
+ runtime.errored
+ ? "text-destructive"
+ : selectedCellId === null
+ ? "text-foreground"
+ : isSelected ||
+ selectedGraph?.parents.has(cellId) ||
+ selectedGraph?.children.has(cellId)
+ ? "text-primary"
+ : "text-[var(--gray-8)]",
+ )}
+ width="1"
+ height="1"
+ >
+ {isSelected ? (
+ <SelectedCell
+ cellId={cellId}
+ cellPositions={cellPositions}
+ graph={graph}
+ />
+ ) : (
+ <UnselectedCell
+ cellId={cellId}
+ graph={graph}
+ selectedGraph={selectedGraph}
+ />
+ )}
+ </svg>
+ </button>
+ );
+};
+
+const MinimapInternal: React.FC<{
+ open: boolean;
+ setOpen: (update: boolean) => void;
+}> = ({ open, setOpen }) => {
+ const notebook = useNotebook();
+ const cellPositions: Record<CellId, number> = Object.fromEntries(
+ notebook.cellIds.inOrderIds.map((id, idx) => [id, idx]),
+ );
+ const columnBoundaries: number[] = [];
+ let cellCount = 0;
+ for (const [idx, column] of notebook.cellIds.getColumns().entries()) {
+ if (idx > 0) {
+ columnBoundaries.push(cellCount);
+ }
+ cellCount += column.inOrderIds.length;
+ }
+ return (
+ <div
+ className={cn(
+ "fixed top-14 right-5 z-50 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 rounded-lg border shadow-lg w-64 flex flex-col max-h-[58vh]",
+ "motion-safe:transition-transform motion-safe:duration-200 motion-safe:ease-in-out",
+ open ? "translate-x-0" : "translate-x-[calc(100%+20px)]",
+ )}
+ >
+ <div className="flex items-center justify-between p-4 border-b">
+ <span className="text-sm font-semibold">Minimap</span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6"
+ onClick={() => setOpen(false)}
+ >
+ <XIcon className="h-4 w-4" />
+ </Button>
+ </div>
+ <div className="overflow-y-auto overflow-x-hidden flex-1 scrollbar-none">
+ <div className="py-3 pl-3 pr-4 relative min-h-full">
+ {notebook.cellIds.inOrderIds.map((cellId, idx) => {
+ const isColumnBoundary = columnBoundaries.includes(idx);
+ return (
+ <React.Fragment key={cellId}>
+ {/* Subtle visual divider between nodes */}
+ {isColumnBoundary && (
+ <div
+ className="absolute left-5 w-[36px] h-px bg-[var(--gray-4)] pointer-events-none"
+ aria-hidden="true"
+ />
+ )}
+ <MinimapCell cellId={cellId} cellPositions={cellPositions} />
+ </React.Fragment>
+ );
+ })}
+ </div>
+ {/* Invisible element to prevent SVG overflow from affecting scroll */}
+ <div className="h-0 overflow-hidden" aria-hidden="true" />
+ </div>
+ </div>
+ );
+};
+
+export const Minimap: React.FC = () => {
+ const { setIsMinimapOpen } = useChromeActions();
+ const { isMinimapOpen } = useChromeState();
+ return <MinimapInternal open={isMinimapOpen} setOpen={setIsMinimapOpen} />;
+};
+
+function codePreview(code: string): string | undefined {
+ return code.split("\n")[0].trim() || undefined;
+}
+
+const VariablesList: React.FC<{
+ cellId: CellId;
+ variableNames: readonly VariableName[];
+ selectedCellId: CellId | null;
+ selectedGraph?: CellGraph;
+}> = ({ variableNames, selectedGraph, cellId, selectedCellId }) => {
+ const variables = useVariables();
+ const isSelected = cellId === selectedCellId;
+ return (
+ <>
+ {variableNames.map((varName, idx) => {
+ const variable = variables[varName];
+ return (
+ <React.Fragment key={varName}>
+ {idx > 0 && ", "}
+ <span
+ className={cn({
+ "text-foreground": selectedGraph === undefined,
+ "font-bold": isSelected,
+ "text-primary font-medium":
+ !isSelected &&
+ selectedGraph &&
+ selectedCellId &&
+ isVariableAffectedBySelectedCell(variable, {
+ selectedCellId,
+ selectedGraph,
+ }),
+ })}
+ >
+ {varName}
+ </span>
+ </React.Fragment>
+ );
+ })}
+ </>
+ );
+};
+
+// Connection paths (for selected)
+const SelectedCell = (options: {
+ cellId: CellId;
+ cellPositions: Record<CellId, number>;
+ graph: CellGraph;
+}) => {
+ const { cellId, cellPositions, graph } = options;
+ const dy = 21;
+ const paths: React.ReactElement[] = [];
+ const currentY = cellPositions[cellId] ?? 0;
+
+ // First, identify all cycles (nodes that are both parent and child)
+ const cycles = new Set<CellId>();
+ for (const parentCellId of graph.parents) {
+ if (graph.children.has(parentCellId)) {
+ cycles.add(parentCellId);
+ }
+ }
+
+ // Add cycle paths first
+ for (const cycleCellId of cycles) {
+ const targetY = cellPositions[cycleCellId];
+ if (targetY !== undefined) {
+ const yDiff = (targetY - currentY) * dy;
+ // Draw a rectangular path around both nodes to show the cycle
+ paths.push(
+ <path
+ key={`${cellId}-cycle-${cycleCellId}`}
+ d={`M -3 0 H -7 v ${yDiff} h 14 v ${-yDiff} H 3`}
+ fill="none"
+ strokeWidth="2"
+ stroke="currentColor"
+ />,
+ );
+ }
+ }
+
+ // Add regular upstream connections (excluding cycles)
+ for (const parentCellId of graph.parents) {
+ if (cycles.has(parentCellId)) {
+ continue; // Skip - already handled as cycle
+ }
+ const targetY = cellPositions[parentCellId];
+ if (targetY !== undefined) {
+ const yDiff = (targetY - currentY) * dy;
+ paths.push(
+ <path
+ key={`${cellId}-up-${parentCellId}`}
+ d={`M -3 0 H -7 v ${yDiff} h -4`}
+ fill="none"
+ strokeWidth="2"
+ stroke="currentColor"
+ />,
+ );
+ }
+ }
+
+ // Add regular downstream connections (excluding cycles)
+ for (const childCellId of graph.children) {
+ if (cycles.has(childCellId)) {
+ continue; // Skip - already handled as cycle
+ }
+ const targetY = cellPositions[childCellId];
+ if (targetY !== undefined) {
+ const yDiff = (targetY - currentY) * dy;
+ paths.push(
+ <path
+ key={`${cellId}-down-${childCellId}`}
+ d={`M 3 0 H 7 v ${yDiff} h 4`}
+ fill="none"
+ strokeWidth="2"
+ stroke="currentColor"
+ />,
+ );
+ }
+ }
+
+ return (
+ <g transform="translate(0, 0)">
+ <circle
+ r={getCircleRadius(graph)}
+ fill="currentColor"
+ className="pointer-events-auto"
+ />
+ <g className="pen pointer-events-auto">{paths}</g>
+ </g>
+ );
+};
+
+function isOrphan(graph: CellGraph): boolean {
+ return graph.ancestors.size === 0 && graph.descendants.size === 0;
+}
+
+function getCircleRadius(graph: CellGraph): number {
+ return isOrphan(graph) ? 1.5 : 3;
+}
+
+// Connection indicators for non-selected cells
+function UnselectedCell(options: {
+ cellId: CellId;
+ graph: CellGraph;
+ selectedGraph?: CellGraph;
+}) {
+ const { cellId, graph, selectedGraph } = options;
+ const circleRadius = getCircleRadius(graph);
+
+ const hasAncestors = graph.ancestors.size > 0;
+ const hasDescendants = graph.descendants.size > 0;
+
+ if (!selectedGraph) {
+ // There is no selection, so show all upstream/downstream indicators
+ return drawConnectionGlyph({
+ circleRadius,
+ leftWisker: hasAncestors,
+ rightWisker: hasDescendants,
+ });
+ }
+
+ const isAncestorOfSelected = selectedGraph.ancestors.has(cellId);
+ const isDescendantOfSelected = selectedGraph.descendants.has(cellId);
+ if (isAncestorOfSelected || isDescendantOfSelected) {
+ return drawConnectionGlyph({
+ circleRadius,
+ leftWisker: hasAncestors,
+ rightWisker: hasDescendants,
+ // Node is a part of the current selection, need to jitter
+ // If it's both ancestor and descendant (cycle), keep it centered
+ shift:
+ isAncestorOfSelected && isDescendantOfSelected
+ ? undefined
+ : isAncestorOfSelected
+ ? "left"
+ : "right",
+ });
+ }
+
+ // Node is outside of the current selection (keep center & hide upstream/downstream indicators)
+ return drawConnectionGlyph({
+ circleRadius,
+ leftWisker: false,
+ rightWisker: false,
+ });
+}
+
+function drawConnectionGlyph(options: {
+ circleRadius: number;
+ leftWisker: boolean;
+ rightWisker: boolean;
+ shift?: "left" | "right";
+}) {
+ const { circleRadius, leftWisker, rightWisker, shift } = options;
+ const dx = shift === undefined ? 0 : shift === "left" ? -14 : 14;
+ return (
+ <g transform={`translate(${dx}, 0)`}>
+ <g>
+ {/* Whisker pointing left (has upstream connections) */}
+ {leftWisker && (
+ <path
+ d="M 0 0 h -8"
+ fill="none"
+ strokeWidth="2"
+ stroke="currentColor"
+ />
+ )}
+ {/* Whisker pointing right (has downstream connections) */}
+ {rightWisker && (
+ <path
+ d="M 0 0 h 8"
+ fill="none"
+ strokeWidth="2"
+ stroke="currentColor"
+ />
+ )}
+ </g>
+ <circle
+ r={circleRadius}
+ fill="currentColor"
+ className="pointer-events-auto"
+ />
+ </g>
+ );
+}
diff --git a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
index b59a7fc886..b77d709a38 100644
--- a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
@@ -25,8 +25,9 @@ vi.mock("@/core/cells/cells", async (importOriginal) => ({
useCellActions: vi.fn(),
}));
-vi.mock("@/core/cells/focus", () => ({
- useSetLastFocusedCellId: vi.fn(),
+vi.mock("@/core/cells/focus", async (importOriginal) => ({
+ ...(await importOriginal()),
+ useCellFocusActions: vi.fn(),
}));
vi.mock("@/core/saving/save-component", () => ({
@@ -237,7 +238,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: false,
+ where: "after",
});
});
@@ -254,7 +255,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: true,
+ where: "before",
});
});
@@ -423,7 +424,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: true,
+ where: "before",
});
});
@@ -443,7 +444,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: false,
+ where: "after",
});
});
@@ -507,7 +508,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: false,
+ where: "after",
});
});
@@ -524,7 +525,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: true,
+ where: "before",
});
});
@@ -541,7 +542,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: false,
+ where: "after",
});
});
@@ -558,7 +559,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: mockCellId,
- before: true,
+ where: "before",
});
});
@@ -1355,7 +1356,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: cellId1,
- before: false,
+ where: "after",
});
expect(mockEvent.preventDefault).toHaveBeenCalled();
});
@@ -1377,7 +1378,7 @@ describe("useCellNavigationProps", () => {
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
cellId: cellId1,
- before: true,
+ where: "before",
});
expect(mockEvent.preventDefault).toHaveBeenCalled();
});
diff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.ts
index dd769db6d5..fde97f72b9 100644
--- a/frontend/src/components/editor/navigation/navigation.ts
+++ b/frontend/src/components/editor/navigation/navigation.ts
@@ -5,7 +5,7 @@ import { useAtomValue, useSetAtom, useStore } from "jotai";
import { mergeProps, useFocusWithin, useKeyboard } from "react-aria";
import { aiCompletionCellAtom } from "@/core/ai/state";
import { cellIdsAtom, notebookAtom, useCellActions } from "@/core/cells/cells";
-import { useSetLastFocusedCellId } from "@/core/cells/focus";
+import { useCellFocusActions } from "@/core/cells/focus";
import type { CellId } from "@/core/cells/ids";
import { usePendingDeleteService } from "@/core/cells/pending-delete-service";
import {
@@ -78,7 +78,7 @@ function addSingleHandler(handler: HotkeyHandler["bulkHandle"]): HotkeyHandler {
}
function useCellFocusProps(cellId: CellId) {
- const setLastFocusedCellId = useSetLastFocusedCellId();
+ const focusActions = useCellFocusActions();
const actions = useCellActions();
const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);
const pendingDeleteService = usePendingDeleteService();
@@ -87,13 +87,14 @@ function useCellFocusProps(cellId: CellId) {
const { focusWithinProps } = useFocusWithin({
onFocusWithin: () => {
// On focus, set the last focused cell id.
- setLastFocusedCellId(cellId);
+ focusActions.focusCell({ cellId });
},
onBlurWithin: () => {
// On blur, hide the code if it was temporarily shown.
setTemporarilyShownCode(false);
actions.markTouched({ cellId });
pendingDeleteService.clear();
+ focusActions.blurCell();
},
});
@@ -186,13 +187,13 @@ export function useCellNavigationProps(
},
// Move up
ArrowUp: () => {
- actions.focusCell({ cellId, before: true });
+ actions.focusCell({ cellId, where: "before" });
selectionActions.clear();
return true;
},
// Move down
ArrowDown: () => {
- actions.focusCell({ cellId, before: false });
+ actions.focusCell({ cellId, where: "after" });
selectionActions.clear();
return true;
},
@@ -207,7 +208,7 @@ export function useCellNavigationProps(
selectionActions.extend({ cellId: beforeCellId, allCellIds });
}
// Focus the cell
- actions.focusCell({ cellId, before: true });
+ actions.focusCell({ cellId, where: "before" });
return true;
},
// Select down
@@ -221,7 +222,7 @@ export function useCellNavigationProps(
selectionActions.extend({ cellId: afterCellId, allCellIds });
}
// Focus the cell
- actions.focusCell({ cellId, before: false });
+ actions.focusCell({ cellId, where: "after" });
return true;
},
// Clear selection
@@ -361,7 +362,7 @@ export function useCellNavigationProps(
// Only focus if it is a single cell
if (cellIds.length === 1) {
const cellId = cellIds[0];
- actions.focusCell({ cellId, before: false });
+ actions.focusCell({ cellId, where: "after" });
if (nextHideCode) {
// Move focus from the editor to the cell
editorView.current?.contentDOM.blur();
@@ -374,11 +375,11 @@ export function useCellNavigationProps(
return true;
}),
"cell.focusDown": (cellId) => {
- actions.focusCell({ cellId, before: false });
+ actions.focusCell({ cellId, where: "after" });
return true;
},
"cell.focusUp": (cellId) => {
- actions.focusCell({ cellId, before: true });
+ actions.focusCell({ cellId, where: "before" });
return true;
},
"cell.sendToBottom": addSingleHandler((cellIds) => {
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index b63745e329..6f1dda6a2e 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -1282,7 +1282,7 @@ describe("cell reducer", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
actions.createNewCell({ cellId: "1" as CellId, before: false });
- actions.focusCell({ cellId: "1" as CellId, before: true });
+ actions.focusCell({ cellId: "1" as CellId, where: "before" });
expect(focusAndScrollCellIntoView).toHaveBeenCalledWith(
expect.objectContaining({
cellId: "0" as CellId,
diff --git a/frontend/src/core/cells/__tests__/focus.test.ts b/frontend/src/core/cells/__tests__/focus.test.ts
new file mode 100644
index 0000000000..49d4a5d486
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/focus.test.ts
@@ -0,0 +1,271 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { beforeEach, describe, expect, it } from "vitest";
+import type { CellId } from "@/core/cells/ids";
+import type { CellFocusState } from "../focus";
+import { exportedForTesting } from "../focus";
+
+const { initialState, reducer, createActions } = exportedForTesting;
+
+const CellIds = {
+ a: "a" as CellId,
+ b: "b" as CellId,
+ c: "c" as CellId,
+};
+
+describe("cell focus reducer", () => {
+ let state: CellFocusState;
+
+ const actions = createActions((action) => {
+ state = reducer(state, action);
+ });
+
+ beforeEach(() => {
+ state = initialState();
+ });
+
+ it("should have initial state", () => {
+ expect(state).toEqual({
+ focusedCellId: null,
+ lastFocusedCellId: null,
+ });
+ });
+
+ describe("focusCell", () => {
+ it("should focus a cell from initial state", () => {
+ actions.focusCell({ cellId: CellIds.a });
+
+ expect(state).toEqual({
+ focusedCellId: CellIds.a,
+ lastFocusedCellId: CellIds.a,
+ });
+ });
+
+ it("should change focus to a different cell", () => {
+ // First focus cell a
+ actions.focusCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+
+ // Then focus cell b
+ actions.focusCell({ cellId: CellIds.b });
+
+ expect(state).toEqual({
+ focusedCellId: CellIds.b,
+ lastFocusedCellId: CellIds.b,
+ });
+ });
+
+ it("should maintain both focus and last focus when focusing same cell", () => {
+ // Focus cell a
+ actions.focusCell({ cellId: CellIds.a });
+
+ // Focus same cell again
+ actions.focusCell({ cellId: CellIds.a });
+
+ expect(state).toEqual({
+ focusedCellId: CellIds.a,
+ lastFocusedCellId: CellIds.a,
+ });
+ });
+
+ it("should preserve last focused cell when focusing different cells", () => {
+ // Focus cell a
+ actions.focusCell({ cellId: CellIds.a });
+
+ // Focus cell b
+ actions.focusCell({ cellId: CellIds.b });
+
+ // Focus cell c
+ actions.focusCell({ cellId: CellIds.c });
+
+ expect(state).toEqual({
+ focusedCellId: CellIds.c,
+ lastFocusedCellId: CellIds.c,
+ });
+ });
+ });
+
+ describe("toggleCell", () => {
+ it("should focus a cell when none is focused", () => {
+ actions.toggleCell({ cellId: CellIds.a });
+
+ expect(state).toEqual({
+ focusedCellId: CellIds.a,
+ lastFocusedCellId: CellIds.a,
+ });
+ });
+
+ it("should blur a cell when it is already focused", () => {
+ // First focus a cell
+ actions.focusCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+
+ // Toggle the same cell should blur it
+ actions.toggleCell({ cellId: CellIds.a });
+
+ expect(state).toEqual({
+ focusedCellId: null,
+ lastFocusedCellId: CellIds.a, // last focused should remain
+ });
+ });
+
+ it("should switch focus when toggling a different cell", () => {
+ // First focus cell a
+ actions.focusCell({ cellId: CellIds.a });
+
+ // Toggle cell b should switch focus
+ actions.toggleCell({ cellId: CellIds.b });
+
+ expect(state).toEqual({
+ focusedCellId: CellIds.b,
+ lastFocusedCellId: CellIds.b,
+ });
+ });
+
+ it("should handle multiple toggles correctly", () => {
+ // Toggle cell a (focus it)
+ actions.toggleCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+
+ // Toggle cell a again (blur it)
+ actions.toggleCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(null);
+ expect(state.lastFocusedCellId).toBe(CellIds.a);
+
+ // Toggle cell a again (focus it)
+ actions.toggleCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+ expect(state.lastFocusedCellId).toBe(CellIds.a);
+ });
+
+ it("should toggle between different cells", () => {
+ // Toggle cell a
+ actions.toggleCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+
+ // Toggle cell b
+ actions.toggleCell({ cellId: CellIds.b });
+ expect(state.focusedCellId).toBe(CellIds.b);
+ expect(state.lastFocusedCellId).toBe(CellIds.b);
+
+ // Toggle cell c
+ actions.toggleCell({ cellId: CellIds.c });
+ expect(state.focusedCellId).toBe(CellIds.c);
+ expect(state.lastFocusedCellId).toBe(CellIds.c);
+
+ // Toggle cell c again (blur it)
+ actions.toggleCell({ cellId: CellIds.c });
+ expect(state.focusedCellId).toBe(null);
+ expect(state.lastFocusedCellId).toBe(CellIds.c);
+ });
+ });
+
+ describe("blurCell", () => {
+ it("should blur focused cell", () => {
+ // First focus a cell
+ actions.focusCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+
+ // Blur it
+ actions.blurCell();
+
+ expect(state).toEqual({
+ focusedCellId: null,
+ lastFocusedCellId: CellIds.a, // last focused should remain
+ });
+ });
+
+ it("should handle blurring when no cell is focused", () => {
+ // Blur when nothing is focused
+ actions.blurCell();
+
+ expect(state).toEqual({
+ focusedCellId: null,
+ lastFocusedCellId: null,
+ });
+ });
+
+ it("should preserve last focused cell when blurring", () => {
+ // Focus cell a, then cell b
+ actions.focusCell({ cellId: CellIds.a });
+ actions.focusCell({ cellId: CellIds.b });
+
+ // Blur
+ actions.blurCell();
+
+ expect(state).toEqual({
+ focusedCellId: null,
+ lastFocusedCellId: CellIds.b,
+ });
+ });
+
+ it("should handle multiple blur calls", () => {
+ // Focus and blur
+ actions.focusCell({ cellId: CellIds.a });
+ actions.blurCell();
+
+ const firstBlurState = { ...state };
+
+ // Blur again
+ actions.blurCell();
+
+ // Should remain the same
+ expect(state).toEqual(firstBlurState);
+ });
+ });
+
+ describe("complex scenarios", () => {
+ it("should handle focus -> blur -> toggle sequence", () => {
+ // Focus cell a
+ actions.focusCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+
+ // Blur it
+ actions.blurCell();
+ expect(state.focusedCellId).toBe(null);
+ expect(state.lastFocusedCellId).toBe(CellIds.a);
+
+ // Toggle cell a (should focus it)
+ actions.toggleCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+ expect(state.lastFocusedCellId).toBe(CellIds.a);
+ });
+
+ it("should handle toggle -> focus -> blur sequence", () => {
+ // Toggle cell a (focus it)
+ actions.toggleCell({ cellId: CellIds.a });
+ expect(state.focusedCellId).toBe(CellIds.a);
+
+ // Focus cell b
+ actions.focusCell({ cellId: CellIds.b });
+ expect(state.focusedCellId).toBe(CellIds.b);
+
+ // Blur
+ actions.blurCell();
+ expect(state.focusedCellId).toBe(null);
+ expect(state.lastFocusedCellId).toBe(CellIds.b);
+ });
+
+ it("should handle mixed operations maintaining last focused", () => {
+ // Focus a
+ actions.focusCell({ cellId: CellIds.a });
+
+ // Toggle b (switch focus)
+ actions.toggleCell({ cellId: CellIds.b });
+ expect(state.lastFocusedCellId).toBe(CellIds.b);
+
+ // Toggle b again (blur)
+ actions.toggleCell({ cellId: CellIds.b });
+ expect(state.focusedCellId).toBe(null);
+ expect(state.lastFocusedCellId).toBe(CellIds.b);
+
+ // Focus c
+ actions.focusCell({ cellId: CellIds.c });
+ expect(state.lastFocusedCellId).toBe(CellIds.c);
+
+ // Blur
+ actions.blurCell();
+ expect(state.focusedCellId).toBe(null);
+ expect(state.lastFocusedCellId).toBe(CellIds.c);
+ });
+ });
+});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 751f868796..b287a53e89 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -410,17 +410,26 @@ const {
cellIds: state.cellIds.moveColumn(action.column, action.overColumn),
};
},
- focusCell: (state, action: { cellId: CellId; before: boolean }) => {
+ focusCell: (
+ state,
+ action: { cellId: CellId; where: "before" | "after" | "exact" },
+ ) => {
const column = state.cellIds.findWithId(action.cellId);
if (column.length === 0) {
return state;
}
- const { cellId, before } = action;
+ const { cellId, where } = action;
const index = column.indexOfOrThrow(cellId);
- let focusIndex = before ? index - 1 : index + 1;
- // clamp
- focusIndex = clamp(focusIndex, 0, column.length - 1);
+
+ let focusIndex: number;
+ if (where === "before") {
+ focusIndex = clamp(index - 1, 0, column.length - 1);
+ } else if (where === "after") {
+ focusIndex = clamp(index + 1, 0, column.length - 1);
+ } else {
+ focusIndex = index;
+ }
const focusCellId = column.atOrThrow(focusIndex);
// can scroll immediately, without setting scrollKey in state, because
// CellArray won't need to re-render
@@ -428,7 +437,7 @@ const {
cellId: focusCellId,
cell: state.cellHandles[focusCellId],
isCodeHidden: isCellCodeHidden(state, focusCellId),
- codeFocus: before ? "bottom" : "top",
+ codeFocus: where === "after" ? "top" : "bottom",
variableName: undefined,
});
return state;
diff --git a/frontend/src/core/cells/focus.ts b/frontend/src/core/cells/focus.ts
index eec77998c5..d7d4b14123 100644
--- a/frontend/src/core/cells/focus.ts
+++ b/frontend/src/core/cells/focus.ts
@@ -1,28 +1,74 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { EditorView } from "@codemirror/view";
-import { atom, useAtomValue, useSetAtom } from "jotai";
+import { atom, useAtomValue } from "jotai";
+import { createReducerAndAtoms } from "@/utils/createReducer";
import type { CellConfig, RuntimeState } from "../network/types";
import { type NotebookState, notebookAtom, SCRATCH_CELL_ID } from "./cells";
import type { CellId } from "./ids";
+export interface CellFocusState {
+ focusedCellId: CellId | null;
+ lastFocusedCellId: CellId | null;
+}
+
+function initialState(): CellFocusState {
+ return {
+ focusedCellId: null,
+ lastFocusedCellId: null,
+ };
+}
+
+const {
+ reducer,
+ createActions,
+ valueAtom: cellFocusAtom,
+ useActions: useCellFocusActions,
+} = createReducerAndAtoms(initialState, {
+ // Focus a cell
+ focusCell: (
+ state: CellFocusState,
+ payload: { cellId: CellId },
+ ): CellFocusState => ({
+ ...state,
+ focusedCellId: payload.cellId,
+ lastFocusedCellId: payload.cellId,
+ }),
+ // Toggle focus on a cell
+ // If the cell is already focused, blur it
+ // If the cell is not focused, focus it
+ toggleCell: (
+ state: CellFocusState,
+ payload: { cellId: CellId },
+ ): CellFocusState => {
+ if (state.focusedCellId === payload.cellId) {
+ return {
+ ...state,
+ focusedCellId: null,
+ };
+ }
+ return {
+ ...state,
+ focusedCellId: payload.cellId,
+ lastFocusedCellId: payload.cellId,
+ };
+ },
+ // Blur the focused cell
+ blurCell: (state: CellFocusState): CellFocusState => ({
+ ...state,
+ focusedCellId: null,
+ }),
+});
/**
* Holds state for the last focused cell.
*/
-export const lastFocusedCellIdAtom = atom<CellId | null>(null);
+export const lastFocusedCellIdAtom = atom(
+ (get) => get(cellFocusAtom).lastFocusedCellId,
+);
export function useLastFocusedCellId() {
return useAtomValue(lastFocusedCellIdAtom);
}
-export function useSetLastFocusedCellId() {
- const setter = useSetAtom(lastFocusedCellIdAtom);
- return (cellId: CellId | null) => {
- if (SCRATCH_CELL_ID === cellId) {
- return;
- }
- setter(cellId);
- };
-}
export const lastFocusedCellAtom = atom<{
name: string;
@@ -71,3 +117,12 @@ function cellFocusDetails(cellId: CellId, notebookState: NotebookState) {
hasConsoleOutput: runtime?.consoleOutputs != null,
};
}
+
+export { useCellFocusActions, cellFocusAtom };
+
+export const exportedForTesting = {
+ reducer,
+ createActions,
+ initialState,
+ cellFocusAtom,
+};