Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: collapsible sections (#1826)

Myles Scolnickaeeb9fd36e9b
diff --git a/frontend/package.json b/frontend/package.json
index 39abf8003c..6621c6ffdc 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -126,6 +126,7 @@
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
"timestring": "^7.0.0",
+ "typescript-memoize": "^1.1.1",
"use-resize-observer": "^9.1.0",
"vega-lite": "^5.19.0",
"vega-loader": "^4.5.2",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 93c65ac11f..bb734f6932 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -344,6 +344,9 @@ dependencies:
timestring:
specifier: ^7.0.0
version: 7.0.0
+ typescript-memoize:
+ specifier: ^1.1.1
+ version: 1.1.1
use-resize-observer:
specifier: ^9.1.0
@@ -18783,6 +18786,10 @@ packages:
yargs: 6.6.0
dev: false
+ resolution: {integrity: sha512-GQ90TcKpIH4XxYTI2F98yEQYZgjNMOGPpOgdjIBhaLaWji5HPWlRnZ4AeA1hfBxtY7bCGDJsqDDHk/KaHOl5bA==}
+ dev: false
+
resolution: {integrity: sha512-K3UOLVZbmb0mXh2dNfvY20u5PSqiyyhDHcCboXVRsmLavjbuZocp9D3fPdtAWZmdQ1UERwxqLeGmXDSQsWcL8g==}
engines: {node: '>=4.2.0'}
diff --git a/frontend/src/components/dependency-graph/custom-node.tsx b/frontend/src/components/dependency-graph/custom-node.tsx
index a5231e6248..31f82848b8 100644
--- a/frontend/src/components/dependency-graph/custom-node.tsx
+++ b/frontend/src/components/dependency-graph/custom-node.tsx
@@ -4,10 +4,10 @@ import { cn } from "@/utils/cn";
import { useAtomValue } from "jotai";
import React, { memo, useContext } from "react";
import { Handle, Position, useStore } from "reactflow";
-import { CustomNodeProps, getNodeHeight } from "./elements";
+import { type CustomNodeProps, getNodeHeight } from "./elements";
import { displayCellName } from "@/core/cells/names";
import { useCellIds } from "@/core/cells/cells";
-import { LayoutDirection } from "./types";
+import type { LayoutDirection } from "./types";
function getWidth(canvasWidth: number) {
const minWidth = 100;
@@ -29,7 +29,7 @@ const EQUALITY_CHECK = (
export const CustomNode = memo((props: CustomNodeProps) => {
const { data, selected } = props; // must match the equality check
const cell = useAtomValue(data.atom);
- const cellIndex = useCellIds().indexOf(cell.id);
+ const cellIndex = useCellIds().inOrderIds.indexOf(cell.id);
const nonSelectedColor = "var(--gray-3)";
const selectedColor = "var(--gray-9)";
const color = selected ? selectedColor : nonSelectedColor;
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 5043aa6e7e..60fcb85bf0 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -1,10 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { closeCompletion, completionStatus } from "@codemirror/autocomplete";
-import { EditorView } from "@codemirror/view";
+import type { EditorView } from "@codemirror/view";
import {
memo,
- FocusEvent,
- KeyboardEvent,
+ type FocusEvent,
+ type KeyboardEvent,
forwardRef,
useCallback,
useImperativeHandle,
@@ -13,9 +13,9 @@ import {
import { saveCellConfig, sendRun, sendStdin } from "@/core/network/requests";
import { autocompletionKeymap } from "@/core/codemirror/cm";
-import { UserConfig } from "../../core/config/config-schema";
-import { CellData, CellRuntimeState } from "../../core/cells/types";
-import { CellActions, isUninstantiated } from "../../core/cells/cells";
+import type { UserConfig } from "../../core/config/config-schema";
+import type { CellData, CellRuntimeState } from "../../core/cells/types";
+import { type CellActions, isUninstantiated } from "../../core/cells/cells";
import { derefNotNull } from "../../utils/dereference";
import { OutputArea } from "./Output";
import { ConsoleOutput } from "./output/ConsoleOutput";
@@ -30,13 +30,13 @@ import { Functions } from "../../utils/functions";
import { Logger } from "../../utils/Logger";
import { CellDragHandle, SortableCell } from "./SortableCell";
import { HTMLCellId } from "../../core/cells/ids";
-import { Theme } from "../../theme/useTheme";
+import type { Theme } from "../../theme/useTheme";
import {
CellActionsDropdown,
- CellActionsDropdownHandle,
+ type CellActionsDropdownHandle,
} from "./cell/cell-actions";
import { CellActionsContextMenu } from "./cell/cell-context-menu";
-import { AppMode } from "@/core/mode";
+import type { AppMode } from "@/core/mode";
import useEvent from "react-use-event-hook";
import { CellEditor } from "./cell/code/cell-editor";
import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
@@ -45,6 +45,8 @@ import { isOutputEmpty } from "@/core/cells/outputs";
import { useHotkeysOnElement, useKeydownOnElement } from "@/hooks/useHotkey";
import { useSetAtom } from "jotai";
import { aiCompletionCellAtom } from "@/core/ai/state";
+import { CollapsedCellBanner, CollapseToggle } from "./cell/collapse";
+import { canCollapseOutline } from "@/core/dom/outline";
/**
* Imperative interface of the cell.
@@ -65,6 +67,7 @@ export interface CellProps
CellRuntimeState,
| "consoleOutputs"
| "status"
+ | "outline"
| "output"
| "errored"
| "interrupted"
@@ -86,6 +89,8 @@ export interface CellProps
| "deleteCell"
| "focusCell"
| "moveCell"
+ | "collapseCell"
+ | "expandCell"
| "moveToNextCell"
| "updateCellConfig"
| "clearSerializedEditorState"
@@ -104,6 +109,9 @@ export interface CellProps
*/
allowFocus: boolean;
userConfig: UserConfig;
+
+ isCollapsed: boolean;
+ collapseCount: number;
}
// TODO(akshayka): a component for displaying/editing the cell's name.
@@ -141,7 +149,12 @@ const CellComponent = (
clearSerializedEditorState,
sendToBottom,
sendToTop,
+ collapseCell,
+ expandCell,
userConfig,
+ outline,
+ isCollapsed,
+ collapseCount,
config: cellConfig,
name,
}: CellProps,
@@ -278,17 +291,34 @@ const CellComponent = (
[cellRef, editorView],
);
- const outputArea = (
- <OutputArea
- allowExpand={editing}
- output={output}
- className="output-area"
- cellId={cellId}
- stale={outputStale}
- />
+ const hasOutput = !isOutputEmpty(output);
+
+ const outputArea = hasOutput && (
+ <div className="relative">
+ <div className="absolute top-5 -left-8 z-10">
+ <CollapseToggle
+ isCollapsed={isCollapsed}
+ onClick={() => {
+ if (isCollapsed) {
+ expandCell({ cellId });
+ } else {
+ collapseCell({ cellId });
+ }
+ }}
+ canCollapse={canCollapseOutline(outline)}
+ />
+ </div>
+ <OutputArea
+ allowExpand={editing}
+ output={output}
+ className="output-area"
+ cellId={cellId}
+ stale={outputStale}
+ />
+ </div>
);
- const className = clsx("Cell", "hover-actions-parent", {
+ const className = clsx("Cell", "hover-actions-parent z-10", {
published: !editing,
interactive: editing,
"needs-run": needsRun,
@@ -401,8 +431,6 @@ const CellComponent = (
}
};
- const hasOutput = !isOutputEmpty(output);
-
return (
<CellActionsContextMenu
cellId={cellId}
@@ -414,111 +442,118 @@ const CellComponent = (
>
<SortableCell
tabIndex={-1}
- id={HTMLId}
ref={cellRef}
- className={className}
data-status={status}
onBlur={closeCompletionHandler}
onKeyDown={resumeCompletionHandler}
cellId={cellId}
title={cellTitle()}
>
- {userConfig.display.cell_output === "above" && outputArea}
- <div className="tray">
- <div className="absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-2">
- <CreateCellButton
- tooltipContent={renderShortcut("cell.createAbove")}
- appClosed={appClosed}
- onClick={appClosed ? undefined : createAbove}
- />
- <div className="flex-1" />
- <CreateCellButton
- tooltipContent={renderShortcut("cell.createBelow")}
- appClosed={appClosed}
- onClick={appClosed ? undefined : createBelow}
- />
- </div>
- <CellEditor
- theme={theme}
- showPlaceholder={showPlaceholder}
- allowFocus={allowFocus}
- id={cellId}
- code={code}
- status={status}
- serializedEditorState={serializedEditorState}
- runCell={handleRun}
- updateCellCode={updateCellCode}
- createNewCell={createNewCell}
- deleteCell={deleteCell}
- focusCell={focusCell}
- moveCell={moveCell}
- moveToNextCell={moveToNextCell}
- updateCellConfig={updateCellConfig}
- clearSerializedEditorState={clearSerializedEditorState}
- userConfig={userConfig}
- editorViewRef={editorView}
- hidden={cellConfig.hide_code}
- />
- <div className="shoulder-right">
- <CellStatusComponent
- status={status}
- staleInputs={staleInputs}
- interrupted={interrupted}
- editing={editing}
- edited={edited}
- disabled={cellConfig.disabled ?? false}
- elapsedTime={runElapsedTimeMs}
- runStartTimestamp={runStartTimestamp}
- uninstantiated={uninstantiated}
- />
- <div className="flex align-bottom">
- <RunButton
- edited={edited}
- onClick={appClosed ? Functions.NOOP : handleRun}
+ <div className={className} id={HTMLId}>
+ {userConfig.display.cell_output === "above" && outputArea}
+ <div className="tray">
+ <div className="absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-2">
+ <CreateCellButton
+ tooltipContent={renderShortcut("cell.createAbove")}
appClosed={appClosed}
- status={status}
- config={cellConfig}
- needsRun={needsRun}
+ onClick={appClosed ? undefined : createAbove}
/>
- <CellActionsDropdown
- ref={cellActionDropdownRef}
- cellId={cellId}
- status={status}
- getEditorView={getEditorView}
- name={name}
- config={cellConfig}
- hasOutput={hasOutput}
- >
- <CellDragHandle />
- </CellActionsDropdown>
- </div>
- </div>
- <div className="shoulder-bottom hover-action">
- {showDeleteButton ? (
- <DeleteButton
+ <div className="flex-1" />
+ <CreateCellButton
+ tooltipContent={renderShortcut("cell.createBelow")}
appClosed={appClosed}
+ onClick={appClosed ? undefined : createBelow}
+ />
+ </div>
+ <CellEditor
+ theme={theme}
+ showPlaceholder={showPlaceholder}
+ allowFocus={allowFocus}
+ id={cellId}
+ code={code}
+ status={status}
+ serializedEditorState={serializedEditorState}
+ runCell={handleRun}
+ updateCellCode={updateCellCode}
+ createNewCell={createNewCell}
+ deleteCell={deleteCell}
+ focusCell={focusCell}
+ moveCell={moveCell}
+ moveToNextCell={moveToNextCell}
+ updateCellConfig={updateCellConfig}
+ clearSerializedEditorState={clearSerializedEditorState}
+ userConfig={userConfig}
+ editorViewRef={editorView}
+ hidden={cellConfig.hide_code}
+ />
+ <div className="shoulder-right">
+ <CellStatusComponent
status={status}
- onClick={() => {
- if (!loading && !appClosed) {
- deleteCell({ cellId });
- }
- }}
+ staleInputs={staleInputs}
+ interrupted={interrupted}
+ editing={editing}
+ edited={edited}
+ disabled={cellConfig.disabled ?? false}
+ elapsedTime={runElapsedTimeMs}
+ runStartTimestamp={runStartTimestamp}
+ uninstantiated={uninstantiated}
/>
- ) : null}
+ <div className="flex align-bottom">
+ <RunButton
+ edited={edited}
+ onClick={appClosed ? Functions.NOOP : handleRun}
+ appClosed={appClosed}
+ status={status}
+ config={cellConfig}
+ needsRun={needsRun}
+ />
+ <CellActionsDropdown
+ ref={cellActionDropdownRef}
+ cellId={cellId}
+ status={status}
+ getEditorView={getEditorView}
+ name={name}
+ config={cellConfig}
+ hasOutput={hasOutput}
+ >
+ <CellDragHandle />
+ </CellActionsDropdown>
+ </div>
+ </div>
+ <div className="shoulder-bottom hover-action">
+ {showDeleteButton ? (
+ <DeleteButton
+ appClosed={appClosed}
+ status={status}
+ onClick={() => {
+ if (!loading && !appClosed) {
+ deleteCell({ cellId });
+ }
+ }}
+ />
+ ) : null}
+ </div>
</div>
+ {userConfig.display.cell_output === "below" && outputArea}
+ <ConsoleOutput
+ consoleOutputs={consoleOutputs}
+ stale={consoleOutputStale}
+ cellName={name}
+ onSubmitDebugger={(text, index) => {
+ setStdinResponse({ cellId, response: text, outputIndex: index });
+ sendStdin({ text });
+ }}
+ cellId={cellId}
+ debuggerActive={debuggerActive}
+ />
</div>
- {userConfig.display.cell_output === "below" && outputArea}
- <ConsoleOutput
- consoleOutputs={consoleOutputs}
- stale={consoleOutputStale}
- cellName={name}
- onSubmitDebugger={(text, index) => {
- setStdinResponse({ cellId, response: text, outputIndex: index });
- sendStdin({ text });
- }}
- cellId={cellId}
- debuggerActive={debuggerActive}
- />
+ {isCollapsed && (
+ <CollapsedCellBanner
+ onClick={() => expandCell({ cellId })}
+ count={collapseCount}
+ cellId={cellId}
+ />
+ )}
</SortableCell>
</CellActionsContextMenu>
);
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index 86ad8b8e61..1fe33521cd 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -51,7 +51,7 @@ import { MarkdownIcon, PythonIcon } from "../cell/code/icons";
import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";
import { useDeleteCellCallback } from "../cell/useDeleteCell";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { CellConfig, CellStatus } from "@/core/network/types";
+import type { CellConfig, CellStatus } from "@/core/network/types";
import { kioskModeAtom } from "@/core/mode";
export interface CellActionButtonProps
@@ -92,7 +92,7 @@ export function useCellActionButtons({ cell }: Props) {
}
const { cellId, config, getEditorView, name, hasOutput, status } = cell;
- const cellIdx = cellIds.indexOf(cellId);
+ const cellIdx = cellIds.inOrderIds.indexOf(cellId);
const editorView = getEditorView();
const toggleDisabled = async () => {
diff --git a/frontend/src/components/editor/cell/collapse.tsx b/frontend/src/components/editor/cell/collapse.tsx
new file mode 100644
index 0000000000..58f0c0bbda
--- /dev/null
+++ b/frontend/src/components/editor/cell/collapse.tsx
@@ -0,0 +1,97 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { Toolbar } from "@/components/layout/toolbar";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import { useNotebook } from "@/core/cells/cells";
+import { CellId } from "@/core/cells/ids";
+import { getDescendantsStatus } from "@/core/cells/utils";
+import { cn } from "@/utils/cn";
+import {
+ AlertOctagonIcon,
+ ChevronDownIcon,
+ ChevronRightIcon,
+ ChevronsUpDownIcon,
+ Loader2Icon,
+ RefreshCcw,
+} from "lucide-react";
+import type React from "react";
+import { memo } from "react";
+
+interface Props {
+ isCollapsed: boolean;
+ canCollapse: boolean;
+ onClick: () => void;
+}
+
+export const CollapseToggle: React.FC<Props> = (props) => {
+ // It could be collapsed, but the markdown headers were removed.
+ // So we still want to be able to expand it, if it is collapsed.
+ if (!props.canCollapse && !props.isCollapsed) {
+ return null;
+ }
+
+ return (
+ <Button variant="text" size="icon" onClick={props.onClick}>
+ <Tooltip content={props.isCollapsed ? "Expand" : "Collapse"}>
+ <Arrow isCollapsed={props.isCollapsed} />
+ </Tooltip>
+ </Button>
+ );
+};
+
+const Arrow = ({ isCollapsed }: { isCollapsed: boolean }) => {
+ return isCollapsed ? (
+ <ChevronRightIcon className="w-5 h-5 flex-shrink-0" />
+ ) : (
+ <ChevronDownIcon className="w-5 h-5 flex-shrink-0" />
+ );
+};
+
+export const CollapsedCellBanner: React.FC<{
+ onClick: () => void;
+ cellId: CellId;
+ count: number;
+}> = memo(({ onClick, count, cellId }) => {
+ const notebook = useNotebook();
+ const states = getDescendantsStatus(notebook, cellId);
+
+ return (
+ <div
+ onClick={onClick}
+ className={cn(
+ "flex items-center justify-between w-[calc(100%-2rem)] h-9 bg-muted rounded-b mx-4 opacity-80 hover:opacity-100 cursor-pointer",
+ )}
+ >
+ <Toolbar
+ center={
+ <>
+ <ChevronsUpDownIcon className="w-4 h-4 flex-shrink-0" />
+ <span className="text-sm text-gray-500">
+ {count} {count === 1 ? "cell" : "cells"} collapsed
+ </span>
+ </>
+ }
+ right={
+ <>
+ {states.errored && (
+ <Tooltip content="Has errors" delayDuration={100}>
+ <AlertOctagonIcon className="w-4 h-4 flex-shrink-0 text-destructive" />
+ </Tooltip>
+ )}
+ {states.stale && (
+ <Tooltip content="Has stale cells" delayDuration={100}>
+ <RefreshCcw className="w-4 h-4 flex-shrink-0 text-[var(--yellow-11)]" />
+ </Tooltip>
+ )}
+ {states.runningOrQueued && (
+ <Tooltip content="Running" delayDuration={100}>
+ <Loader2Icon className="w-4 h-4 flex-shrink-0 animate-spin" />
+ </Tooltip>
+ )}
+ </>
+ }
+ />
+ </div>
+ );
+});
+CollapsedCellBanner.displayName = "CollapsedCellBanner";
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
index 92cd7ea82f..cf234af306 100644
--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
@@ -63,7 +63,7 @@ const sortedTablesAtom = atom((get) => {
return 0;
}
- const index = cellIds.indexOf(variable.declaredBy[0]);
+ const index = cellIds.inOrderIds.indexOf(variable.declaredBy[0]);
if (index === -1) {
return 0;
}
diff --git a/frontend/src/components/editor/chrome/panels/dependency-graph-panel.tsx b/frontend/src/components/editor/chrome/panels/dependency-graph-panel.tsx
index 619af74874..e1358973ec 100644
--- a/frontend/src/components/editor/chrome/panels/dependency-graph-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/dependency-graph-panel.tsx
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useCellDataAtoms, useCellIds } from "@/core/cells/cells";
import { useVariables } from "@/core/variables/state";
-import React from "react";
+import type React from "react";
import { DependencyGraph } from "../../../dependency-graph/dependency-graph";
import { cn } from "@/utils/cn";
@@ -15,7 +15,7 @@ export const DependencyGraphPanel: React.FC = () => {
<DependencyGraph
cellAtoms={cells}
variables={variables}
- cellIds={cellIds}
+ cellIds={cellIds.inOrderIds}
/>
</div>
);
diff --git a/frontend/src/components/editor/chrome/panels/variable-panel.tsx b/frontend/src/components/editor/chrome/panels/variable-panel.tsx
index 15ca77e1bd..c62ac0cf59 100644
--- a/frontend/src/components/editor/chrome/panels/variable-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/variable-panel.tsx
@@ -2,7 +2,7 @@
import { VariableTable } from "@/components/variables/variables-table";
import { useCellIds } from "@/core/cells/cells";
import { useVariables } from "@/core/variables/state";
-import React from "react";
+import type React from "react";
import { PanelEmptyState } from "./empty-state";
import { FunctionSquareIcon } from "lucide-react";
@@ -21,6 +21,10 @@ export const VariablePanel: React.FC = () => {
}
return (
- <VariableTable className="flex-1" cellIds={cellIds} variables={variables} />
+ <VariableTable
+ className="flex-1"
+ cellIds={cellIds.inOrderIds}
+ variables={variables}
+ />
);
};
diff --git a/frontend/src/components/editor/links/cell-link-list.tsx b/frontend/src/components/editor/links/cell-link-list.tsx
index 183caefe07..29a01e49d4 100644
--- a/frontend/src/components/editor/links/cell-link-list.tsx
+++ b/frontend/src/components/editor/links/cell-link-list.tsx
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { CellId } from "@/core/cells/ids";
-import React from "react";
+import type { CellId } from "@/core/cells/ids";
+import type React from "react";
import { CellLink } from "./cell-link";
import {
Popover,
@@ -24,7 +24,7 @@ export const CellLinkList: React.FC<Props> = ({
}) => {
const cellIndex = useCellIds();
const sortedCellIds = [...cellIds].sort((a, b) => {
- return cellIndex.indexOf(a) - cellIndex.indexOf(b);
+ return cellIndex.inOrderIds.indexOf(a) - cellIndex.inOrderIds.indexOf(b);
});
if (cellIds.length === 0) {
diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsx
index c93202c507..78036f2595 100644
--- a/frontend/src/components/editor/links/cell-link.tsx
+++ b/frontend/src/components/editor/links/cell-link.tsx
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { CellId, HTMLCellId } from "@/core/cells/ids";
+import { type CellId, HTMLCellId } from "@/core/cells/ids";
import { Logger } from "../../../utils/Logger";
import { cn } from "@/utils/cn";
import { displayCellName } from "@/core/cells/names";
-import { useCellIds, useCellNames } from "@/core/cells/cells";
+import { useCellActions, useCellIds, useCellNames } from "@/core/cells/cells";
interface Props {
cellId: CellId;
@@ -18,7 +18,8 @@ interface Props {
export const CellLink = (props: Props): JSX.Element => {
const { className, cellId, variant, onClick, skipScroll } = props;
const cellName = useCellNames()[cellId] ?? "";
- const cellIndex = useCellIds().indexOf(cellId);
+ const cellIndex = useCellIds().inOrderIds.indexOf(cellId);
+ const { showCellIfHidden } = useCellActions();
return (
<div
@@ -27,12 +28,15 @@ export const CellLink = (props: Props): JSX.Element => {
className,
)}
onClick={(e) => {
+ showCellIfHidden({ cellId });
e.stopPropagation();
e.preventDefault();
- const succeeded = scrollAndHighlightCell(cellId, variant, skipScroll);
- if (succeeded) {
- onClick?.();
- }
+ requestAnimationFrame(() => {
+ const succeeded = scrollAndHighlightCell(cellId, variant, skipScroll);
+ if (succeeded) {
+ onClick?.();
+ }
+ });
}}
>
{displayCellName(cellName, cellIndex)}
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index 2bd424be54..5958a2bcf7 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -7,7 +7,7 @@ import {
} from "../../../core/websocket/types";
import {
type NotebookState,
- flattenNotebookCells,
+ flattenTopLevelNotebookCells,
useCellActions,
} from "../../../core/cells/cells";
import type { AppConfig, UserConfig } from "../../../core/config/config-schema";
@@ -58,37 +58,20 @@ export const CellArray: React.FC<CellArrayProps> = ({
appConfig,
connStatus,
}) => {
- const {
- updateCellCode,
- prepareForRun,
- moveCell,
- moveToNextCell,
- updateCellConfig,
- clearSerializedEditorState,
- focusCell,
- createNewCell,
- focusBottomCell,
- focusTopCell,
- scrollToTarget,
- foldAll,
- unfoldAll,
- sendToBottom,
- sendToTop,
- setStdinResponse,
- } = useCellActions();
+ const actions = useCellActions();
const { theme } = useTheme();
const { togglePanel } = useChromeActions();
const { invisible } = useDelayVisibility(notebook.cellIds.length, mode);
// HOTKEYS
- useHotkey("global.focusTop", focusTopCell);
- useHotkey("global.focusBottom", focusBottomCell);
+ useHotkey("global.focusTop", actions.focusTopCell);
+ useHotkey("global.focusBottom", actions.focusBottomCell);
useHotkey("global.toggleSidebar", togglePanel);
- useHotkey("global.foldCode", foldAll);
- useHotkey("global.unfoldCode", unfoldAll);
+ useHotkey("global.foldCode", actions.foldAll);
+ useHotkey("global.unfoldCode", actions.unfoldAll);
useHotkey("global.formatAll", () => {
- formatAll(updateCellCode);
+ formatAll(actions.updateCellCode);
});
// Catch all to avoid native OS behavior
// Otherwise a user might try to hide a cell and accidentally hide the OS window
@@ -98,13 +81,14 @@ export const CellArray: React.FC<CellArrayProps> = ({
const onDeleteCell = useDeleteCellCallback();
// Scroll to a cell targeted by a previous action
+ const scrollToTarget = actions.scrollToTarget;
useEffect(() => {
if (notebook.scrollKey !== null) {
scrollToTarget();
}
}, [notebook.cellIds, notebook.scrollKey, scrollToTarget]);
- const cells = flattenNotebookCells(notebook);
+ const cells = flattenTopLevelNotebookCells(notebook);
return (
<VerticalLayoutWrapper
@@ -115,49 +99,44 @@ export const CellArray: React.FC<CellArrayProps> = ({
>
<PackageAlert />
<NotebookBanner />
- {cells.map((cell) => (
- <Cell
- key={cell.id.toString()}
- theme={theme}
- showPlaceholder={cells.length === 1}
- allowFocus={!invisible}
- id={cell.id}
- code={cell.code}
- 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}
- staleInputs={cell.staleInputs}
- runStartTimestamp={cell.runStartTimestamp}
- runElapsedTimeMs={
- cell.runElapsedTimeMs ?? (cell.lastExecutionTime as Milliseconds)
- }
- serializedEditorState={cell.serializedEditorState}
- showDeleteButton={cells.length > 1 && !cell.config.hide_code}
- createNewCell={createNewCell}
- deleteCell={onDeleteCell}
- focusCell={focusCell}
- moveToNextCell={moveToNextCell}
- setStdinResponse={setStdinResponse}
- updateCellConfig={updateCellConfig}
- clearSerializedEditorState={clearSerializedEditorState}
- moveCell={moveCell}
- mode={mode}
- appClosed={connStatus.state !== WebSocketState.OPEN}
- ref={notebook.cellHandles[cell.id]}
- sendToBottom={sendToBottom}
- sendToTop={sendToTop}
- userConfig={userConfig}
- debuggerActive={cell.debuggerActive}
- config={cell.config}
- name={cell.name}
- />
- ))}
+ <div className="flex flex-col gap-5">
+ {cells.map((cell) => (
+ <Cell
+ key={cell.id.toString()}
+ theme={theme}
+ showPlaceholder={cells.length === 1}
+ allowFocus={!invisible && !notebook.scrollKey}
+ id={cell.id}
+ code={cell.code}
+ outline={cell.outline}
+ output={cell.output}
+ consoleOutputs={cell.consoleOutputs}
+ status={cell.status}
+ edited={cell.edited}
+ interrupted={cell.interrupted}
+ errored={cell.errored}
+ stopped={cell.stopped}
+ staleInputs={cell.staleInputs}
+ runStartTimestamp={cell.runStartTimestamp}
+ runElapsedTimeMs={
+ cell.runElapsedTimeMs ?? (cell.lastExecutionTime as Milliseconds)
+ }
+ serializedEditorState={cell.serializedEditorState}
+ showDeleteButton={cells.length > 1 && !cell.config.hide_code}
+ mode={mode}
+ appClosed={connStatus.state !== WebSocketState.OPEN}
+ ref={notebook.cellHandles[cell.id]}
+ userConfig={userConfig}
+ debuggerActive={cell.debuggerActive}
+ config={cell.config}
+ name={cell.name}
+ isCollapsed={notebook.cellIds.isCollapsed(cell.id)}
+ collapseCount={notebook.cellIds.getCount(cell.id)}
+ {...actions}
+ deleteCell={onDeleteCell}
+ />
+ ))}
+ </div>
<AddCellButtons />
</VerticalLayoutWrapper>
);
diff --git a/frontend/src/components/editor/renderers/cells-renderer.tsx b/frontend/src/components/editor/renderers/cells-renderer.tsx
index 504c99c74b..9657325708 100644
--- a/frontend/src/components/editor/renderers/cells-renderer.tsx
+++ b/frontend/src/components/editor/renderers/cells-renderer.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { flattenNotebookCells, useNotebook } from "@/core/cells/cells";
+import { flattenTopLevelNotebookCells, useNotebook } from "@/core/cells/cells";
import React, { PropsWithChildren, memo } from "react";
import { cellRendererPlugins } from "./plugins";
import { AppConfig } from "@/core/config/config-schema";
@@ -31,7 +31,7 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
return children;
}
- const cells = flattenNotebookCells(notebook);
+ const cells = flattenTopLevelNotebookCells(notebook);
const Renderer = plugin.Component;
const body = (
diff --git a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
index 67734b8769..38718c4532 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
+++ b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { AppMode } from "@/core/mode";
+import type { AppMode } from "@/core/mode";
import { getNotebook } from "@/core/cells/cells";
import { useState, useEffect } from "react";
@@ -30,7 +30,7 @@ export function useDelayVisibility(numCells: number, mode: AppMode) {
function focusFirstEditor() {
const { cellIds, cellData, cellHandles } = getNotebook();
// Focus on the first cell if it's been mounted and is not hidden
- for (const cellId of cellIds) {
+ for (const cellId of cellIds.topLevelIds) {
const handle = cellHandles[cellId];
const hidden = cellData[cellId].config.hide_code;
if (!hidden && handle?.current?.editorView) {
diff --git a/frontend/src/components/layout/toolbar.tsx b/frontend/src/components/layout/toolbar.tsx
new file mode 100644
index 0000000000..f7ed4383cc
--- /dev/null
+++ b/frontend/src/components/layout/toolbar.tsx
@@ -0,0 +1,26 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+
+interface Props {
+ left?: React.ReactNode;
+ center?: React.ReactNode;
+ right?: React.ReactNode;
+}
+
+/**
+ * Layout elements for toolbar.
+ * This is better than justify-between since it handles adding/removing items.
+ */
+export const Toolbar: React.FC<Props> = (props) => {
+ return (
+ <div className="flex items-center gap-2 w-full px-3">
+ <div className="flex-1 flex item-center gap-2">{props.left}</div>
+ <div className="flex-1 flex item-center gap-2 justify-center">
+ {props.center}
+ </div>
+ <div className="flex-1 flex item-center gap-2 justify-end">
+ {props.right}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsx
index 560cfc7cf7..57d7b2daf6 100644
--- a/frontend/src/components/sort/SortableCellsProvider.tsx
+++ b/frontend/src/components/sort/SortableCellsProvider.tsx
@@ -6,7 +6,7 @@ import {
KeyboardSensor,
PointerSensor,
useSensor,
- DragEndEvent,
+ type DragEndEvent,
useSensors,
} from "@dnd-kit/core";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
@@ -17,7 +17,7 @@ import {
} from "@dnd-kit/sortable";
import { useCellActions, useNotebook } from "../../core/cells/cells";
import { useEvent } from "../../hooks/useEvent";
-import { CellId } from "@/core/cells/ids";
+import type { CellId } from "@/core/cells/ids";
interface SortableCellsProviderProps {
children: React.ReactNode;
@@ -43,7 +43,7 @@ const SortableCellsProviderInternal = ({
}),
);
- const ids = notebook.cellIds;
+ const ids = notebook.cellIds.topLevelIds;
const handleDragEnd = useEvent((event: DragEndEvent) => {
const { active, over } = event;
diff --git a/frontend/src/core/cells/__tests__/add-missing-import.test.ts b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
index 9adfa35d80..ea00b6b56b 100644
--- a/frontend/src/core/cells/__tests__/add-missing-import.test.ts
+++ b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
@@ -7,8 +7,9 @@ import type { Variables } from "@/core/variables/types";
import { type NotebookState, notebookAtom } from "../cells";
import type { CellId } from "../ids";
import type { CellData } from "../types";
+import { CollapsibleTree } from "@/utils/id-tree";
-const CELL_IDS = ["1" as CellId];
+const CELL_IDS = CollapsibleTree.from(["1" as CellId]);
describe("maybeAddMissingImport", () => {
it("should not add an import if the variable is already in the variables state", () => {
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 5c79cbd477..4ebb2c16fa 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -1,14 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
- NotebookState,
+ type NotebookState,
exportedForTesting,
- flattenNotebookCells,
+ flattenTopLevelNotebookCells,
} from "../cells";
import { notebookCells } from "../utils";
import { CellId } from "@/core/cells/ids";
-import { OutputMessage } from "@/core/kernel/messages";
-import { Seconds } from "@/utils/time";
+import type { OutputMessage } from "@/core/kernel/messages";
+import type { Seconds } from "@/utils/time";
const { initialNotebookState, reducer, createActions } = exportedForTesting;
@@ -21,12 +21,12 @@ function formatCells(notebook: NotebookState) {
describe("cell reducer", () => {
let state: NotebookState;
- let cells: ReturnType<typeof flattenNotebookCells>;
+ let cells: ReturnType<typeof flattenTopLevelNotebookCells>;
let firstCellId: CellId;
const actions = createActions((action) => {
state = reducer(state, action);
- cells = flattenNotebookCells(state);
+ cells = flattenTopLevelNotebookCells(state);
});
let i = 0;
@@ -43,7 +43,7 @@ describe("cell reducer", () => {
state = initialNotebookState();
actions.createNewCell({ cellId: undefined!, before: false });
- firstCellId = state.cellIds[0];
+ firstCellId = state.cellIds.atOrThrow(0);
});
afterAll(() => {
diff --git a/frontend/src/core/cells/add-missing-import.ts b/frontend/src/core/cells/add-missing-import.ts
index 57d1f9c7df..1d9595eaaa 100644
--- a/frontend/src/core/cells/add-missing-import.ts
+++ b/frontend/src/core/cells/add-missing-import.ts
@@ -29,7 +29,7 @@ export function maybeAddMissingImport(
`import[ \t]+${moduleName}[ \t]+as[ \t]+${variableName}`,
"g",
);
- for (const cell of cellIds) {
+ for (const cell of cellIds.inOrderIds) {
if (regex.test(cellData[cell].code)) {
return false;
}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 0ee687184d..e541e35c63 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -13,14 +13,12 @@ import {
scrollToTop,
focusAndScrollCellIntoView,
} from "./scrollCellIntoView";
-import { arrayMove } from "@dnd-kit/sortable";
import { CellId } from "./ids";
import { prepareCellForExecution, transitionCell } from "./cell";
import { store } from "../state/jotai";
import { createReducerAndAtoms } from "../../utils/createReducer";
-import { arrayInsert, arrayDelete } from "@/utils/arrays";
import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";
-import { mergeOutlines } from "../dom/outline";
+import { findCollapseRange, mergeOutlines } from "../dom/outline";
import type { CellHandle } from "@/components/editor/Cell";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
@@ -45,6 +43,8 @@ import type {
import { getUserConfig } from "@/core/config/config";
import { syncCellIds } from "../network/requests";
import { kioskModeAtom } from "../mode";
+import { CollapsibleTree } from "@/utils/id-tree";
+import { isEqual } from "lodash-es";
export const SCRATCH_CELL_ID = "__scratch__" as CellId;
@@ -55,7 +55,7 @@ export interface NotebookState {
/**
* Order of cells on the page.
*/
- cellIds: CellId[];
+ cellIds: CollapsibleTree<CellId>;
/**
* Map of cells to their view state
*/
@@ -153,7 +153,7 @@ function initialNotebookState(): NotebookState {
}
return {
- cellIds: cellIds,
+ cellIds: CollapsibleTree.from(cellIds),
cellData: cellData,
cellRuntime: cellRuntime,
cellHandles: {},
@@ -164,7 +164,7 @@ function initialNotebookState(): NotebookState {
}
return withScratchCell({
- cellIds: [],
+ cellIds: CollapsibleTree.from([]),
cellData: {},
cellRuntime: {},
cellHandles: {},
@@ -207,12 +207,12 @@ const {
const index =
cellId === "__end__"
? state.cellIds.length - 1
- : state.cellIds.indexOf(cellId);
+ : state.cellIds.topLevelIds.indexOf(cellId);
const insertionIndex = before ? index : index + 1;
return {
...state,
- cellIds: arrayInsert(state.cellIds, insertionIndex, newCellId),
+ cellIds: state.cellIds.insert(newCellId, insertionIndex),
cellData: {
...state.cellData,
[newCellId]: createCell({
@@ -236,19 +236,19 @@ const {
},
moveCell: (state, action: { cellId: CellId; before: boolean }) => {
const { cellId, before } = action;
- const index = state.cellIds.indexOf(cellId);
- const cell = state.cellIds[index];
+ const index = state.cellIds.indexOfOrThrow(cellId);
+
if (before && index === 0) {
return {
...state,
- cellIds: [cell, ...state.cellIds.slice(1)],
+ cellIds: state.cellIds.moveToFront(cellId),
scrollKey: cellId,
};
}
if (!before && index === state.cellIds.length - 1) {
return {
...state,
- cellIds: [...state.cellIds.slice(0, -1), cell],
+ cellIds: state.cellIds.moveToBack(cellId),
scrollKey: cellId,
};
}
@@ -256,22 +256,22 @@ const {
return before
? {
...state,
- cellIds: arrayMove(state.cellIds, index, index - 1),
+ cellIds: state.cellIds.move(index, index - 1),
scrollKey: cellId,
}
: {
...state,
- cellIds: arrayMove(state.cellIds, index, index + 1),
+ cellIds: state.cellIds.move(index, index + 1),
scrollKey: cellId,
};
},
dropCellOver: (state, action: { cellId: CellId; overCellId: CellId }) => {
const { cellId, overCellId } = action;
- const fromIndex = state.cellIds.indexOf(cellId);
- const toIndex = state.cellIds.indexOf(overCellId);
+ const fromIndex = state.cellIds.indexOfOrThrow(cellId);
+ const toIndex = state.cellIds.indexOfOrThrow(overCellId);
return {
...state,
- cellIds: arrayMove(state.cellIds, fromIndex, toIndex),
+ cellIds: state.cellIds.move(fromIndex, toIndex),
scrollKey: null,
};
},
@@ -281,11 +281,11 @@ const {
}
const { cellId, before } = action;
- const index = state.cellIds.indexOf(cellId);
+ const index = state.cellIds.indexOfOrThrow(cellId);
let focusIndex = before ? index - 1 : index + 1;
// clamp
focusIndex = clamp(focusIndex, 0, state.cellIds.length - 1);
- const focusCellId = state.cellIds[focusIndex];
+ const focusCellId = state.cellIds.atOrThrow(focusIndex);
// can scroll immediately, without setting scrollKey in state, because
// CellArray won't need to re-render
focusAndScrollCellIntoView({
@@ -302,9 +302,9 @@ const {
return state;
}
- const cellKey = state.cellIds[0];
- const cellData = state.cellData[cellKey];
- const cellHandle = state.cellHandles[cellKey];
+ const cellId = state.cellIds.first();
+ const cellData = state.cellData[cellId];
+ const cellHandle = state.cellHandles[cellId];
if (!cellData.config.hide_code) {
cellHandle.current?.editorView.focus();
}
@@ -316,9 +316,9 @@ const {
return state;
}
- const cellKey = state.cellIds[state.cellIds.length - 1];
- const cellData = state.cellData[cellKey];
- const cellHandle = state.cellHandles[cellKey];
+ const cellId = state.cellIds.last();
+ const cellData = state.cellData[cellId];
+ const cellHandle = state.cellHandles[cellId];
if (!cellData.config.hide_code) {
cellHandle.current?.editorView.focus();
}
@@ -331,10 +331,10 @@ const {
}
const { cellId } = action;
- const index = state.cellIds.indexOf(cellId);
+ const index = state.cellIds.indexOfOrThrow(cellId);
return {
...state,
- cellIds: arrayMove(state.cellIds, index, 0),
+ cellIds: state.cellIds.move(index, 0),
scrollKey: cellId,
};
},
@@ -344,10 +344,10 @@ const {
}
const { cellId } = action;
- const index = state.cellIds.indexOf(cellId);
+ const index = state.cellIds.indexOfOrThrow(cellId);
return {
...state,
- cellIds: arrayMove(state.cellIds, index, state.cellIds.length - 1),
+ cellIds: state.cellIds.move(index, state.cellIds.length - 1),
scrollKey: cellId,
};
},
@@ -357,21 +357,20 @@ const {
return state;
}
- const index = state.cellIds.indexOf(cellId);
- const cellKey = state.cellIds[index];
+ const index = state.cellIds.indexOfOrThrow(cellId);
const focusIndex = index === 0 ? 1 : index - 1;
- const scrollKey = state.cellIds[focusIndex];
+ const scrollKey = state.cellIds.atOrThrow(focusIndex);
const serializedEditorState = state.cellHandles[
- cellKey
+ cellId
].current?.editorView.state.toJSON({ history: historyField });
return {
...state,
- cellIds: arrayDelete(state.cellIds, index),
+ cellIds: state.cellIds.delete(index),
history: [
...state.history,
{
- name: state.cellData[cellKey].name,
+ name: state.cellData[cellId].name,
serializedEditorState: serializedEditorState,
index: index,
},
@@ -401,7 +400,7 @@ const {
});
return {
...state,
- cellIds: arrayInsert(state.cellIds, index, cellId),
+ cellIds: state.cellIds.insert(cellId, index),
cellData: {
...state.cellData,
[cellId]: undoCell,
@@ -523,7 +522,7 @@ const {
return {
...state,
- cellIds: action.cellIds,
+ cellIds: CollapsibleTree.from(action.cellIds),
cellData: nextCellData,
cellRuntime: nextCellRuntime,
cellHandles: nextCellHandles,
@@ -588,7 +587,7 @@ const {
return withScratchCell({
...state,
- cellIds: cells.map((cell) => cell.id),
+ cellIds: CollapsibleTree.from(cells.map((cell) => cell.id)),
cellData: cellData,
cellRuntime: cellRuntime,
cellHandles: Object.fromEntries(
@@ -610,7 +609,7 @@ const {
action: { cellId: CellId; before: boolean; noCreate?: boolean },
) => {
const { cellId, before, noCreate = false } = action;
- const index = state.cellIds.indexOf(cellId);
+ const index = state.cellIds.indexOfOrThrow(cellId);
const nextCellIndex = before ? index - 1 : index + 1;
// Create a new cell at the end; no need to update scrollKey,
// because cell will be created with autoScrollIntoView
@@ -618,7 +617,7 @@ const {
const newCellId = CellId.create();
return {
...state,
- cellIds: [...state.cellIds, newCellId],
+ cellIds: state.cellIds.insertAtEnd(newCellId),
cellData: {
...state.cellData,
[newCellId]: createCell({ id: newCellId }),
@@ -640,7 +639,7 @@ const {
const newCellId = CellId.create();
return {
...state,
- cellIds: [newCellId, ...state.cellIds],
+ cellIds: state.cellIds.insertAtStart(newCellId),
cellData: {
...state.cellData,
[newCellId]: createCell({ id: newCellId }),
@@ -656,7 +655,7 @@ const {
};
}
- const nextCellId = state.cellIds[nextCellIndex];
+ const nextCellId = state.cellIds.atOrThrow(nextCellIndex);
// Just focus, no state change
focusAndScrollCellIntoView({
cellId: nextCellId,
@@ -674,15 +673,15 @@ const {
return state;
}
- const index = state.cellIds.indexOf(scrollKey);
+ const index = state.cellIds.indexOfOrThrow(scrollKey);
// Special-case scrolling to the end of the page: bug in Chrome where
// browser fails to scrollIntoView an element at the end of a long page
if (index === state.cellIds.length - 1) {
- const cellId = state.cellIds[state.cellIds.length - 1];
+ const cellId = state.cellIds.last();
state.cellHandles[cellId].current?.editorView.focus();
} else {
- const nextCellId = state.cellIds[index];
+ const nextCellId = state.cellIds.atOrThrow(index);
focusAndScrollCellIntoView({
cellId: nextCellId,
cell: state.cellHandles[nextCellId],
@@ -717,9 +716,49 @@ const {
cellLogs: [],
};
},
+ collapseCell: (state, action: { cellId: CellId }) => {
+ const { cellId } = action;
+ // Get all the top-level outlines
+ const outlines = state.cellIds.topLevelIds.map((id) => {
+ const cell = state.cellRuntime[id];
+ return cell.outline;
+ });
+ // Find the start/end of the collapsed range
+ const startIndex = state.cellIds.indexOfOrThrow(cellId);
+ const range = findCollapseRange(startIndex, outlines);
+
+ if (!range) {
+ return state;
+ }
+ // Get the end of the range
+ const endCellId = state.cellIds.atOrThrow(range[1]);
+
+ return {
+ ...state,
+ // Collapse the range
+ cellIds: state.cellIds.collapse(cellId, endCellId),
+ scrollKey: cellId,
+ };
+ },
+ expandCell: (state, action: { cellId: CellId }) => {
+ const { cellId } = action;
+ return {
+ ...state,
+ cellIds: state.cellIds.expand(cellId),
+ scrollKey: cellId,
+ };
+ },
+ showCellIfHidden: (state, action: { cellId: CellId }) => {
+ const { cellId } = action;
+ return {
+ ...state,
+ cellIds: state.cellIds.findAndExpandDeep(cellId),
+ scrollKey: cellId,
+ };
+ },
splitCell: (state, action: { cellId: CellId }) => {
const { cellId } = action;
- const index = state.cellIds.indexOf(cellId);
+ const index = state.cellIds.indexOfOrThrow(cellId);
const cell = state.cellData[cellId];
const cellHandle = state.cellHandles[cellId].current;
@@ -737,7 +776,7 @@ const {
return {
...state,
- cellIds: arrayInsert(state.cellIds, index + 1, newCellId),
+ cellIds: state.cellIds.insert(newCellId, index + 1),
cellData: {
...state.cellData,
[cellId]: {
@@ -823,7 +862,7 @@ export const hasOnlyOneCellAtom = atom((get) => get(cellIdsAtom).length === 1);
const cellErrorsAtom = atom((get) => {
const { cellIds, cellRuntime, cellData } = get(notebookAtom);
- const errors = cellIds
+ const errors = cellIds.inOrderIds
.map((cellId) => {
const cell = cellRuntime[cellId];
const { name } = cellData[cellId];
@@ -855,7 +894,9 @@ export const notebookHasCellsAtom = atom((get) => get(cellIdsAtom).length > 0);
export const notebookOutline = atom((get) => {
const { cellIds, cellRuntime } = get(notebookAtom);
- const outlines = cellIds.map((cellId) => cellRuntime[cellId].outline);
+ const outlines = cellIds.inOrderIds.map(
+ (cellId) => cellRuntime[cellId].outline,
+ );
return mergeOutlines(outlines);
});
@@ -864,7 +905,7 @@ export const cellErrorCount = atom((get) => get(cellErrorsAtom).length);
export const cellIdToNamesMap = atom((get) => {
const { cellIds, cellData } = get(notebookAtom);
const names: Record<CellId, string | undefined> = Objects.fromEntries(
- cellIds.map((cellId) => [cellId, cellData[cellId]?.name]),
+ cellIds.inOrderIds.map((cellId) => [cellId, cellData[cellId]?.name]),
);
return names;
});
@@ -913,12 +954,12 @@ export const getCells = () => store.get(notebookAtom).cellIds;
*/
export const getCellNames = () => {
const { cellIds, cellData } = store.get(notebookAtom);
- return cellIds.map((id) => cellData[id]?.name).filter(Boolean);
+ return cellIds.inOrderIds.map((id) => cellData[id]?.name).filter(Boolean);
};
const cellDataAtoms = splitAtom(
selectAtom(notebookAtom, (cells) =>
- cells.cellIds.map((id) => cells.cellData[id]),
+ cells.cellIds.inOrderIds.map((id) => cells.cellData[id]),
),
);
export const useCellDataAtoms = () => useAtom(cellDataAtoms);
@@ -932,7 +973,7 @@ export const notebookIsRunningAtom = atom((get) =>
*/
export const getAllEditorViews = () => {
const { cellIds, cellHandles } = store.get(notebookAtom);
- return cellIds
+ return cellIds.inOrderIds
.map((cellId) => cellHandles[cellId].current?.editorView)
.filter(Boolean);
};
@@ -970,7 +1011,7 @@ export function staleCellIds(state: NotebookState) {
const autoInstantiate = getUserConfig().runtime.auto_instantiate;
const { cellIds, cellData, cellRuntime } = state;
- return cellIds.filter(
+ return cellIds.inOrderIds.filter(
(cellId) =>
isUninstantiated(
autoInstantiate,
@@ -994,9 +1035,11 @@ export function staleCellIds(state: NotebookState) {
);
}
-export function flattenNotebookCells(state: NotebookState) {
+export function flattenTopLevelNotebookCells(
+ state: NotebookState,
+): Array<CellData & CellRuntimeState> {
const { cellIds, cellData, cellRuntime } = state;
- return cellIds.map((cellId) => ({
+ return cellIds.topLevelIds.map((cellId) => ({
...cellData[cellId],
...cellRuntime[cellId],
}));
@@ -1016,7 +1059,10 @@ export function useCellActions() {
export type CellActions = ReturnType<typeof createActions>;
export const CellEffects = {
- onCellIdsChange: (cellIds: CellId[], prevCellIds: CellId[]) => {
+ onCellIdsChange: (
+ cellIds: CollapsibleTree<CellId>,
+ prevCellIds: CollapsibleTree<CellId>,
+ ) => {
const kioskMode = store.get(kioskModeAtom);
if (kioskMode) {
return;
@@ -1032,10 +1078,10 @@ export const CellEffects = {
}
// If they are different references, send an update to the server
- if (cellIds !== prevCellIds) {
+ if (!isEqual(cellIds.inOrderIds, prevCellIds.inOrderIds)) {
// "name" property is not actually required
void syncCellIds({
- cell_ids: cellIds,
+ cell_ids: cellIds.inOrderIds,
} as unknown as UpdateCellIdsRequest);
}
},
diff --git a/frontend/src/core/cells/outline.ts b/frontend/src/core/cells/outline.ts
index 7b86a66fb3..f7cbe08adb 100644
--- a/frontend/src/core/cells/outline.ts
+++ b/frontend/src/core/cells/outline.ts
@@ -4,14 +4,24 @@
* Table of contents outline.
*/
export interface OutlineItem {
+ /**
+ * The human-readable heading name.
+ */
name: string;
- by:
- | {
- id: string;
- }
- | {
- path: string;
- };
+ /**
+ * Locator of the item.
+ *
+ * If `id` is provided, the item is located by #id.
+ *
+ * If `path` is provided, the item is located by xpath.
+ */
+ by: { id: string } | { path: string };
+ /**
+ * The level of the item.
+ * h1 -> 1
+ * h2 -> 2
+ * etc.
+ */
level: number;
}
diff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.ts
index e5926ad918..a085faf07c 100644
--- a/frontend/src/core/cells/scrollCellIntoView.ts
+++ b/frontend/src/core/cells/scrollCellIntoView.ts
@@ -37,6 +37,11 @@ export function focusAndScrollCellIntoView({
if (!editor) {
return;
}
+ // If already focused, do nothing.
+ if (editor.hasFocus) {
+ return;
+ }
+
editor.focus();
if (codeFocus === "top") {
// If codeFocus is top, move the cursor to the top of the editor.
diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.ts
index 12459d9dee..b1d4c5acc3 100644
--- a/frontend/src/core/cells/utils.ts
+++ b/frontend/src/core/cells/utils.ts
@@ -1,11 +1,15 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { CellId } from "./ids";
+import type { CellId } from "./ids";
import { arrayShallowEquals } from "@/utils/arrays";
import { Objects } from "@/utils/objects";
-import { EditorView } from "@codemirror/view";
-import { LayoutState } from "../layout/layout";
+import type { EditorView } from "@codemirror/view";
+import type { LayoutState } from "../layout/layout";
import { isEqual } from "lodash-es";
-import { NotebookState, LastSavedNotebook, staleCellIds } from "./cells";
+import {
+ type NotebookState,
+ type LastSavedNotebook,
+ staleCellIds,
+} from "./cells";
export function notebookIsRunning(state: NotebookState) {
return Object.values(state.cellRuntime).some(
@@ -22,7 +26,7 @@ export function notebookNeedsSave(
return false;
}
const { cellIds, cellData } = state;
- const data = cellIds.map((cellId) => cellData[cellId]);
+ const data = cellIds.inOrderIds.map((cellId) => cellData[cellId]);
const codes = data.map((d) => d.code);
const configs = data.map((d) => d.config);
const names = data.map((d) => d.name);
@@ -40,7 +44,7 @@ export function notebookNeedsRun(state: NotebookState) {
}
export function notebookCells(state: NotebookState) {
- return state.cellIds.map((cellId) => state.cellData[cellId]);
+ return state.cellIds.inOrderIds.map((cellId) => state.cellData[cellId]);
}
export function notebookCellEditorViews({ cellHandles }: NotebookState) {
@@ -56,14 +60,14 @@ export function notebookCellEditorViews({ cellHandles }: NotebookState) {
export function disabledCellIds(state: NotebookState) {
const { cellIds, cellData } = state;
- return cellIds
+ return cellIds.inOrderIds
.map((cellId) => cellData[cellId])
.filter((cell) => cell.config.disabled);
}
export function enabledCellIds(state: NotebookState) {
const { cellIds, cellData } = state;
- return cellIds
+ return cellIds.inOrderIds
.map((cellId) => cellData[cellId])
.filter((cell) => !cell.config.disabled);
}
@@ -71,3 +75,25 @@ export function enabledCellIds(state: NotebookState) {
export function canUndoDeletes(state: NotebookState) {
return state.history.length > 0;
}
+
+/**
+ * Get the status of the descendants of the given cell.
+ */
+export function getDescendantsStatus(state: NotebookState, cellId: CellId) {
+ const descendants = state.cellIds.getDescendants(cellId);
+ const stale = descendants.some(
+ (id) => state.cellRuntime[id]?.staleInputs || state.cellData[id]?.edited,
+ );
+ const errored = descendants.some((id) => state.cellRuntime[id]?.errored);
+ const runningOrQueued = descendants.some(
+ (id) =>
+ state.cellRuntime[id]?.status === "running" ||
+ state.cellRuntime[id]?.status === "queued",
+ );
+
+ return {
+ stale,
+ errored,
+ runningOrQueued,
+ };
+}
diff --git a/frontend/src/core/dom/__tests__/outline.test.ts b/frontend/src/core/dom/__tests__/outline.test.ts
index 4cdd26e9ba..7d254cf960 100644
--- a/frontend/src/core/dom/__tests__/outline.test.ts
+++ b/frontend/src/core/dom/__tests__/outline.test.ts
@@ -1,6 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { parseOutline } from "../outline";
+import {
+ canCollapseOutline,
+ findCollapseRange,
+ mergeOutlines,
+ parseOutline,
+} from "../outline";
+import type { Outline } from "@/core/cells/outline";
describe("parseOutline", () => {
it("can parse html outline", () => {
@@ -194,3 +200,128 @@ describe("parseOutline", () => {
`);
});
});
+
+const OUTLINE_1: Outline = {
+ items: [
+ {
+ name: "h1",
+ level: 1,
+ by: { id: "h1" },
+ },
+ {
+ name: "h2",
+ level: 2,
+ by: { id: "h2" },
+ },
+ {
+ name: "h3",
+ level: 3,
+ by: { id: "h3" },
+ },
+ ],
+};
+
+const OUTLINE_2: Outline = {
+ items: [
+ {
+ name: "other-h1",
+ level: 1,
+ by: { path: "other-h1" },
+ },
+ {
+ name: "other-h2",
+ level: 2,
+ by: { path: "other-h2" },
+ },
+ ],
+};
+
+it("mergeOutlines", () => {
+ expect(
+ mergeOutlines([OUTLINE_1, null, OUTLINE_2, null]),
+ ).toMatchInlineSnapshot(`
+ {
+ "items": [
+ {
+ "by": {
+ "id": "h1",
+ },
+ "level": 1,
+ "name": "h1",
+ },
+ {
+ "by": {
+ "id": "h2",
+ },
+ "level": 2,
+ "name": "h2",
+ },
+ {
+ "by": {
+ "id": "h3",
+ },
+ "level": 3,
+ "name": "h3",
+ },
+ {
+ "by": {
+ "path": "other-h1",
+ },
+ "level": 1,
+ "name": "other-h1",
+ },
+ {
+ "by": {
+ "path": "other-h2",
+ },
+ "level": 2,
+ "name": "other-h2",
+ },
+ ],
+ }
+ `);
+});
+
+const makeOutline = (levels: number[]) => {
+ return {
+ items: levels.map((level) => ({
+ name: `h${level}`,
+ level,
+ by: { id: `h${level}` },
+ })),
+ };
+};
+
+it("canCollapseOutline", () => {
+ expect(canCollapseOutline(null)).toBe(false);
+ expect(canCollapseOutline(makeOutline([1]))).toBe(true);
+ expect(canCollapseOutline(makeOutline([1, 2]))).toBe(true);
+ expect(canCollapseOutline(makeOutline([2]))).toBe(true);
+ expect(canCollapseOutline(makeOutline([3]))).toBe(true);
+ expect(canCollapseOutline(makeOutline([1, 4]))).toBe(true);
+ expect(canCollapseOutline(makeOutline([4]))).toBe(false);
+});
+
+describe("findCollapseRange", () => {
+ it("can collapse range", () => {
+ expect(findCollapseRange(0, [makeOutline([1, 2, 3, 4])])).toEqual([0, 0]);
+ });
+
+ it("can collapse range with gaps", () => {
+ const outlines = [
+ makeOutline([1, 2, 3, 4]),
+ makeOutline([2, 3, 4]),
+ null,
+ makeOutline([2]),
+ makeOutline([1]),
+ makeOutline([2]),
+ ];
+ expect(findCollapseRange(0, outlines)).toEqual([0, 3]);
+ expect(findCollapseRange(1, outlines)).toEqual([1, 2]);
+ expect(findCollapseRange(4, outlines)).toEqual([4, 5]);
+ expect(findCollapseRange(5, outlines)).toEqual([5, 5]);
+ // bad ranges
+ expect(findCollapseRange(10, outlines)).toEqual(null);
+ expect(findCollapseRange(2, outlines)).toEqual(null);
+ });
+});
diff --git a/frontend/src/core/dom/outline.ts b/frontend/src/core/dom/outline.ts
index 9f26b54ed2..e4ac630821 100644
--- a/frontend/src/core/dom/outline.ts
+++ b/frontend/src/core/dom/outline.ts
@@ -1,8 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { Logger } from "@/utils/Logger";
-import { OutputMessage } from "../kernel/messages";
-import { Outline } from "../cells/outline";
+import type { OutputMessage } from "../kernel/messages";
+import type { Outline } from "../cells/outline";
import { invariant } from "@/utils/invariant";
function getOutline(html: string): Outline {
@@ -62,3 +62,54 @@ export function parseOutline(output: OutputMessage | null): Outline | null {
return null;
}
}
+
+/**
+ * We can only collapse if it has an H1 or H2
+ */
+export function canCollapseOutline(outline: Outline | null): boolean {
+ if (outline == null) {
+ return false;
+ }
+ // Only can collapse if has items with a level 1 or 2 or 3
+ return outline.items.some((item) => item.level <= 3);
+}
+
+/**
+ * Find the range of cells to collapse in the outline
+ * given the start index.
+ *
+ * End index is inclusive
+ */
+export function findCollapseRange(
+ startIndex: number,
+ outlines: Array<Outline | null>,
+): [number, number] | null {
+ // Higher header is the lowest value
+ const getHighestHeader = (outline: Outline) => {
+ if (outline.items.length === 0) {
+ return 7; // default to imaginary H7
+ }
+ return Math.min(...outline.items.map((item) => item.level));
+ };
+
+ // Get the start max heading
+ const startOutline = outlines[startIndex];
+ if (startOutline == null || startOutline.items.length === 0) {
+ Logger.warn("Failed to find a starting outline");
+ return null;
+ }
+ // Higher header has the lowest value
+ const highestHeader = getHighestHeader(startOutline);
+
+ // Find the next index where an equal or higher header (lower number) is found
+ let endIndex = startIndex + 1;
+ while (endIndex < outlines.length) {
+ const outline = outlines[endIndex];
+ if (outline && getHighestHeader(outline) <= highestHeader) {
+ return [startIndex, endIndex - 1];
+ }
+ endIndex++;
+ }
+
+ return [startIndex, outlines.length - 1];
+}
diff --git a/frontend/src/core/islands/components/web-components.tsx b/frontend/src/core/islands/components/web-components.tsx
index cc10473368..9f7511be20 100644
--- a/frontend/src/core/islands/components/web-components.tsx
+++ b/frontend/src/core/islands/components/web-components.tsx
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { invariant } from "@/utils/invariant";
-import { CellId } from "../../cells/ids";
+import type { CellId } from "../../cells/ids";
import { store } from "../../state/jotai";
import { notebookAtom } from "../../cells/cells";
-import ReactDOM, { Root } from "react-dom/client";
+import ReactDOM, { type Root } from "react-dom/client";
import { isValidElement } from "react";
import { extractIslandCodeFromEmbed } from "../parse";
import { MarimoOutputWrapper } from "./output-wrapper";
@@ -40,8 +40,7 @@ export class MarimoIslandElement extends HTMLElement {
invariant(this.dataset.cellIdx, "Missing data-cell-idx attribute");
const { cellIds } = store.get(notebookAtom);
const idx = Number.parseInt(this.dataset.cellIdx, 10);
- invariant(cellIds[idx], `Cell ID not found for index ${idx}`);
- return cellIds[idx];
+ return cellIds.atOrThrow(idx);
}
get code(): string {
diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.css
index 41553986c2..b08c4b7aef 100644
--- a/frontend/src/css/app/Cell.css
+++ b/frontend/src/css/app/Cell.css
@@ -7,7 +7,6 @@
* */
.Cell {
position: relative;
- margin-bottom: 21px;
border-radius: 10px;
max-width: inherit;
width: 100%;
@@ -24,7 +23,7 @@
}
&:focus-within {
- z-index: 10;
+ z-index: 20;
}
/* Hover z-index is higher than focus-within z-index
@@ -32,7 +31,7 @@
* not focused in another cell.
*/
&:hover {
- z-index: 20;
+ z-index: 30;
}
/* Interactive */
@@ -174,7 +173,6 @@
/* Published - when its just the output */
&.published {
- margin-bottom: 0;
border: none;
box-shadow: none;
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index c2eb72ef46..3c73ba4e07 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -40,6 +40,11 @@ const props: CellProps = {
showDeleteButton: true,
allowFocus: false,
debuggerActive: false,
+ isCollapsed: false,
+ collapseCount: 0,
+ outline: null,
+ collapseCell: Logger.log,
+ expandCell: Logger.log,
createNewCell: Logger.log,
deleteCell: Logger.log,
focusCell: Logger.log,
diff --git a/frontend/src/utils/__tests__/id-tree.test.ts b/frontend/src/utils/__tests__/id-tree.test.ts
new file mode 100644
index 0000000000..c53e801d02
--- /dev/null
+++ b/frontend/src/utils/__tests__/id-tree.test.ts
@@ -0,0 +1,396 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { TreeNode, CollapsibleTree } from "../id-tree";
+import { beforeEach } from "vitest";
+
+let tree: CollapsibleTree<string>;
+
+describe("CollapsibleTree", () => {
+ beforeEach(() => {
+ const nodes = [
+ new TreeNode("one", false, []),
+ new TreeNode("two", false, []),
+ new TreeNode("three", false, []),
+ new TreeNode("four", false, []),
+ ];
+ tree = new CollapsibleTree(nodes);
+ });
+
+ it("initializes correctly", () => {
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three
+ four
+ "
+ `);
+ });
+
+ it("collapses nodes correctly with no end", () => {
+ const collapsedTree = tree.collapse("two", undefined);
+ expect(collapsedTree.nodes[1].isCollapsed).toBe(true);
+ expect(collapsedTree.isCollapsed("two")).toBe(true);
+ expect(collapsedTree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three
+ four
+ "
+ `);
+ });
+
+ it("collapses nodes correctly with an 'until' in the middle", () => {
+ const collapsedTree = tree.collapse("two", "three");
+ expect(collapsedTree.nodes[1].isCollapsed).toBe(true);
+ expect(collapsedTree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three
+ four
+ "
+ `);
+ });
+
+ it("collapses nodes correctly with an 'until' at the end", () => {
+ const collapsedTree = tree.collapse("two", "four");
+ expect(collapsedTree.nodes[1].isCollapsed).toBe(true);
+ expect(collapsedTree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three
+ four
+ "
+ `);
+ });
+
+ it("collapses nodes correctly if just the last node", () => {
+ const collapsedTree = tree.collapse("four", undefined);
+ expect(collapsedTree.nodes[3].isCollapsed).toBe(true);
+ expect(collapsedTree.toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three
+ four (collapsed)
+ "
+ `);
+ });
+
+ it("collapses nodes correctly if just the first node", () => {
+ const collapsedTree = tree.collapse("one", undefined);
+ expect(collapsedTree.nodes[0].isCollapsed).toBe(true);
+ expect(collapsedTree.toString()).toMatchInlineSnapshot(`
+ "one (collapsed)
+ two
+ three
+ four
+ "
+ `);
+ });
+
+ it("can double collapse", () => {
+ const collapsedTree = tree
+ .collapse("three", undefined)
+ .collapse("two", undefined);
+ expect(collapsedTree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three (collapsed)
+ four
+ "
+ `);
+ });
+
+ it("failures to collapse", () => {
+ expect(() =>
+ tree.collapse("five", undefined),
+ ).toThrowErrorMatchingInlineSnapshot(
+ `[Error: Node five not found in tree. Valid ids: one,two,three,four]`,
+ );
+ expect(() =>
+ tree.collapse("one", "five"),
+ ).toThrowErrorMatchingInlineSnapshot(
+ "[Error: Node five not found in tree]",
+ );
+ expect(() =>
+ tree.collapse("two", "one"),
+ ).toThrowErrorMatchingInlineSnapshot(
+ "[Error: Node one is before node two]",
+ );
+ expect(() => {
+ tree.collapse("two", undefined);
+ tree.collapse("two", undefined);
+ }).toThrowErrorMatchingInlineSnapshot(
+ "[Error: Node two is already collapsed]",
+ );
+ });
+
+ it("expands nodes correctly", () => {
+ const collapsed = tree.collapse("two", undefined);
+ expect(collapsed.nodes[1].isCollapsed).toBe(true);
+ const expandedTree = collapsed.expand("two");
+ expect(expandedTree.nodes[1].isCollapsed).toBe(false);
+ expect(expandedTree.toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three
+ four
+ "
+ `);
+ });
+
+ it("fails to expand", () => {
+ expect(() => tree.expand("five")).toThrowErrorMatchingInlineSnapshot(
+ `[Error: Node five not found in tree. Valid ids: one,two,three,four]`,
+ );
+ expect(() => {
+ tree.expand("one");
+ tree.expand("one");
+ }).toThrowErrorMatchingInlineSnapshot(
+ "[Error: Node one is already expanded]",
+ );
+ });
+
+ it("moves nodes correctly", () => {
+ const movedTree = tree.move(0, 1);
+ expect(movedTree.toString()).toMatchInlineSnapshot(`
+ "two
+ one
+ three
+ four
+ "
+ `);
+ });
+
+ it("moves a collapsed node correctly", () => {
+ const collapsed = tree.collapse("two", "three");
+ expect(collapsed.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three
+ four
+ "
+ `);
+ const movedTree = collapsed.move(1, 2);
+ expect(movedTree.toString()).toMatchInlineSnapshot(`
+ "one
+ four
+ two (collapsed)
+ three
+ "
+ `);
+ });
+
+ it("inserts nodes correctly", () => {
+ tree = tree.insert("newNode", 1);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ newNode
+ two
+ three
+ four
+ "
+ `);
+
+ tree = tree.insert("newNode2", tree.length - 1);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ newNode
+ two
+ three
+ newNode2
+ four
+ "
+ `);
+
+ tree = tree.insert("newNode3", 10_000);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ newNode
+ two
+ three
+ newNode2
+ four
+ newNode3
+ "
+ `);
+ });
+
+ it("counts children correctly", () => {
+ expect(tree.getCount("who")).toBe(0);
+ expect(tree.getCount("one")).toBe(0);
+ // Collapse three and get count
+ tree = tree.collapse("three", undefined);
+ expect(tree.getCount("three")).toBe(1);
+ // Collapse two and get count
+ tree = tree.collapse("two", undefined);
+ expect(tree.getCount("two")).toBe(2);
+ });
+
+ it("finds deep correctly", () => {
+ expect(tree.find("three")).toEqual(["three"]);
+ tree = tree.collapse("three", undefined).collapse("two", undefined);
+ expect(tree.find("three")).toEqual(["two", "three"]);
+ expect(tree.find("four")).toEqual(["two", "three", "four"]);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three (collapsed)
+ four
+ "
+ `);
+ });
+
+ it("finds and expands correctly at a leaf", () => {
+ tree = tree.collapse("three", undefined).collapse("two", undefined);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three (collapsed)
+ four
+ "
+ `);
+ expect(tree.findAndExpandDeep("four").toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three
+ four
+ "
+ `);
+ });
+
+ it("finds and expands correctly at a non-leaf", () => {
+ tree = tree.collapse("three", undefined).collapse("two", undefined);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three (collapsed)
+ four
+ "
+ `);
+ expect(tree.findAndExpandDeep("three").toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three
+ four
+ "
+ `);
+ });
+
+ it("can delete nodes", () => {
+ tree = tree.collapse("three", undefined).collapse("two", undefined);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ two (collapsed)
+ three (collapsed)
+ four
+ "
+ `);
+ tree = tree.delete(1);
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ three (collapsed)
+ four
+ "
+ `);
+ });
+
+ it("fails to delete nodes", () => {
+ expect(() => tree.delete(5)).toThrowErrorMatchingInlineSnapshot(
+ `[Error: Node at index 5 not found in tree]`,
+ );
+ });
+
+ it("top-level ids are correct", () => {
+ expect(tree.topLevelIds).toMatchInlineSnapshot(`
+ [
+ "one",
+ "two",
+ "three",
+ "four",
+ ]
+ `);
+
+ const collapsed = tree.collapse("two", undefined);
+ expect(collapsed.topLevelIds).toMatchInlineSnapshot(`
+ [
+ "one",
+ "two",
+ ]
+ `);
+ });
+
+ it("in order ids are correct", () => {
+ expect(tree.inOrderIds).toMatchInlineSnapshot(`
+ [
+ "one",
+ "two",
+ "three",
+ "four",
+ ]
+ `);
+
+ const collapsed = tree.collapse("two", undefined);
+ expect(collapsed.inOrderIds).toMatchInlineSnapshot(`
+ [
+ "one",
+ "two",
+ "three",
+ "four",
+ ]
+ `);
+ });
+
+ it("atOrThrow throws if not found", () => {
+ expect(() => tree.atOrThrow(5)).toThrowErrorMatchingInlineSnapshot(
+ `[Error: Node at index 5 not found in tree]`,
+ );
+ });
+
+ it("first and last are correct", () => {
+ expect(tree.first()).toBe("one");
+ expect(tree.last()).toBe("four");
+ });
+
+ it("length is correct", () => {
+ expect(tree.length).toBe(4);
+
+ const collapsed = tree.collapse("two", undefined);
+ expect(collapsed.length).toBe(2);
+ });
+
+ it("moves to front and back correctly", () => {
+ tree = tree.collapse("three", undefined).moveToBack("three");
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three (collapsed)
+ four
+ "
+ `);
+
+ tree = tree.moveToFront("two");
+ expect(tree.toString()).toMatchInlineSnapshot(`
+ "two
+ one
+ three (collapsed)
+ four
+ "
+ `);
+ });
+
+ it("getDescendants correctly", () => {
+ expect(tree.getDescendants("two")).toEqual([]);
+ expect(tree.getDescendants("who")).toEqual([]);
+
+ tree = tree.collapse("three", undefined).collapse("two", undefined);
+ expect(tree.getDescendants("two")).toMatchInlineSnapshot(`
+ [
+ "three",
+ "four",
+ ]
+ `);
+
+ // We only get descendants of the top level
+ expect(tree.getDescendants("three")).toMatchInlineSnapshot(`[]`);
+ });
+});
diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.ts
index bc91b262aa..2464506edb 100644
--- a/frontend/src/utils/arrays.ts
+++ b/frontend/src/utils/arrays.ts
@@ -6,11 +6,18 @@ export function arrayDelete<T>(array: T[], index: number): T[] {
}
export function arrayInsert<T>(array: T[], index: number, value: T): T[] {
+ return arrayInsertMany(array, index, [value]);
+}
+
+export function arrayInsertMany<T>(
+ array: T[],
+ index: number,
+ values: T[],
+): T[] {
if (array.length === 0) {
- return [value];
+ return values;
}
-
- return [...array.slice(0, index), value, ...array.slice(index)];
+ return [...array.slice(0, index), ...values, ...array.slice(index)];
}
export function arrayShallowEquals<T>(a: T[], b: T[]): boolean {
diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx
new file mode 100644
index 0000000000..362401262c
--- /dev/null
+++ b/frontend/src/utils/id-tree.tsx
@@ -0,0 +1,320 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { arrayMove } from "@dnd-kit/sortable";
+import { arrayDelete, arrayInsert, arrayInsertMany } from "./arrays";
+import { Memoize } from "typescript-memoize";
+import { Logger } from "./Logger";
+
+/**
+ * Tree data structure for handling ids with nested children
+ */
+export class TreeNode<T> {
+ constructor(
+ public value: T,
+ public isCollapsed: boolean,
+ public children: Array<TreeNode<T>>,
+ ) {}
+
+ /**
+ * Recursively count the number of nodes in the tree
+ */
+ geDescendantCount(): number {
+ return this.children.reduce(
+ (acc, child) => acc + 1 + child.geDescendantCount(),
+ 0,
+ );
+ }
+
+ getDescendants(): T[] {
+ return this.children.flatMap((c) => [c.value, ...c.getDescendants()]);
+ }
+
+ get inOrderIds(): T[] {
+ return this.children.flatMap((c) => [c.value, ...c.inOrderIds]);
+ }
+
+ toString(): string {
+ if (this.isCollapsed) {
+ return `${this.value} (collapsed)`;
+ }
+ return String(this.value);
+ }
+}
+
+export class CollapsibleTree<T> {
+ constructor(public nodes: Array<TreeNode<T>>) {}
+
+ static from<T>(ids: T[]): CollapsibleTree<T> {
+ return new CollapsibleTree(ids.map((id) => new TreeNode(id, false, [])));
+ }
+
+ get topLevelIds(): T[] {
+ return this.nodes.map((n) => n.value);
+ }
+
+ @Memoize()
+ get inOrderIds(): T[] {
+ return this.nodes.flatMap((n) => [n.value, ...n.inOrderIds]);
+ }
+
+ get length(): number {
+ return this.nodes.length;
+ }
+
+ /**
+ * Get the descendants of the given node
+ *
+ * Only works for the top-level nodes
+ */
+ getDescendants(id: T): T[] {
+ const node = this.nodes.find((n) => n.value === id);
+ if (!node) {
+ Logger.warn(
+ `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,
+ );
+ return [];
+ }
+ return node.getDescendants();
+ }
+
+ /**
+ * Check if the given node is collapsed
+ *
+ * Only works for the top-level nodes
+ */
+ isCollapsed(id: T): boolean {
+ const node = this.nodes.find((n) => n.value === id);
+ if (!node) {
+ Logger.warn(
+ `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,
+ );
+ return false;
+ }
+ return node.isCollapsed;
+ }
+
+ /**
+ * Get the index of the given node, or throw
+ */
+ indexOfOrThrow(id: T): number {
+ const index = this.nodes.findIndex((n) => n.value === id);
+ if (index === -1) {
+ throw new Error(
+ `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,
+ );
+ }
+ return index;
+ }
+
+ /**
+ * Move the given node to the front
+ */
+ moveToFront(id: T): CollapsibleTree<T> {
+ const index = this.indexOfOrThrow(id);
+ return new CollapsibleTree(arrayMove(this.nodes, index, 0));
+ }
+
+ /**
+ * Move the given node to the back
+ */
+ moveToBack(id: T): CollapsibleTree<T> {
+ const index = this.indexOfOrThrow(id);
+ return new CollapsibleTree(
+ arrayMove(this.nodes, index, this.nodes.length - 1),
+ );
+ }
+
+ /**
+ * Collapse everything past the given node @param id
+ * until @param until or the end of the tree
+ */
+ collapse(id: T, until: T | undefined): CollapsibleTree<T> {
+ const nodeIndex = this.nodes.findIndex((n) => n.value === id);
+ if (nodeIndex === -1) {
+ throw new Error(
+ `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,
+ );
+ }
+
+ const untilIndex =
+ until === undefined
+ ? this.nodes.length
+ : this.nodes.findIndex((n) => n.value === until);
+
+ if (untilIndex === -1) {
+ throw new Error(`Node ${until} not found in tree`);
+ }
+ if (untilIndex < nodeIndex) {
+ throw new Error(`Node ${until} is before node ${id}`);
+ }
+
+ const node = this.nodes[nodeIndex];
+ if (node.isCollapsed) {
+ throw new Error(`Node ${id} is already collapsed`);
+ }
+
+ // Fold the next nodes into the current node
+ node.children = this.nodes.splice(nodeIndex + 1, untilIndex - nodeIndex);
+ node.isCollapsed = true;
+
+ return new CollapsibleTree(this.nodes);
+ }
+
+ /**
+ * Expand a node and all of its children
+ */
+ expand(id: T): CollapsibleTree<T> {
+ const nodeIndex = this.nodes.findIndex((n) => n.value === id);
+ if (nodeIndex === -1) {
+ throw new Error(
+ `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,
+ );
+ }
+
+ const node = this.nodes[nodeIndex];
+ if (!node.isCollapsed) {
+ throw new Error(`Node ${id} is already expanded`);
+ }
+
+ node.isCollapsed = false;
+ this.nodes = arrayInsertMany(this.nodes, nodeIndex + 1, node.children);
+ node.children = [];
+
+ return new CollapsibleTree(this.nodes);
+ }
+
+ /**
+ * Move a node from one index to another
+ */
+ move(fromIdx: number, toIdx: number): CollapsibleTree<T> {
+ this.nodes = arrayMove(this.nodes, fromIdx, toIdx);
+ return new CollapsibleTree(this.nodes);
+ }
+
+ /**
+ * Get the node at the given index
+ */
+ at(index: number): T | undefined {
+ return this.nodes.at(index)?.value;
+ }
+
+ /**
+ * Get the node at the given index
+ */
+ atOrThrow(index: number): T {
+ const node = this.nodes.at(index);
+ if (node === undefined) {
+ throw new Error(`Node at index ${index} not found in tree`);
+ }
+ return node.value;
+ }
+
+ /**
+ * Get the first node, or throw
+ */
+ first(): T {
+ return this.atOrThrow(0);
+ }
+
+ /**
+ * Get the last node, or throw
+ */
+ last(): T {
+ return this.atOrThrow(this.nodes.length - 1);
+ }
+
+ /**
+ * Insert a node at the given index
+ */
+ insert(id: T, index: number): CollapsibleTree<T> {
+ this.nodes = arrayInsert(this.nodes, index, new TreeNode(id, false, []));
+ return new CollapsibleTree(this.nodes);
+ }
+
+ /**
+ * Insert a node at the end
+ */
+ insertAtEnd(id: T): CollapsibleTree<T> {
+ return this.insert(id, this.nodes.length);
+ }
+
+ /**
+ * Insert a node at the start
+ */
+ insertAtStart(id: T): CollapsibleTree<T> {
+ return this.insert(id, 0);
+ }
+
+ /**
+ * Delete a node, expand if it was collapsed
+ */
+ delete(idx: number): CollapsibleTree<T> {
+ const id = this.atOrThrow(idx);
+ try {
+ this.expand(id);
+ } catch {
+ // Don't care if its not expanded
+ }
+ return new CollapsibleTree(arrayDelete(this.nodes, idx));
+ }
+
+ /**
+ * Get the number of nodes in the tree, not-including the given node
+ */
+ getCount(id: T): number {
+ return this.nodes.find((n) => n.value === id)?.geDescendantCount() ?? 0;
+ }
+
+ /**
+ * Find and expand the node and all of its children
+ */
+ findAndExpandDeep(id: T): CollapsibleTree<T> {
+ const found = this.find(id);
+ for (const node of found) {
+ try {
+ this.expand(node);
+ } catch {
+ // Don't care if its the last node and its not expanded
+ }
+ }
+
+ return new CollapsibleTree(this.nodes);
+ }
+
+ /**
+ * Find a node, returning the path to it
+ * With the last element being the node itself
+ */
+ find(id: T): T[] {
+ // We need to recursively find the node
+ function findNode(nodes: Array<TreeNode<T>>, path: T[]): T[] {
+ for (const node of nodes) {
+ if (node.value === id) {
+ return [...path, id];
+ }
+ const result = findNode(node.children, [...path, node.value]);
+ if (result.length > 0) {
+ return result;
+ }
+ }
+ return [];
+ }
+
+ return findNode(this.nodes, []);
+ }
+
+ toString(): string {
+ let depth = 0;
+ let result = "";
+ const asString = (nodes: Array<TreeNode<T>>) => {
+ for (const node of nodes) {
+ result += `${" ".repeat(depth * 2)}${node.toString()}\n`;
+ depth += 1;
+ asString(node.children);
+ depth -= 1;
+ }
+ };
+ asString(this.nodes);
+ return result;
+ }
+}