Skip to content

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

experimental: multi-column notebooks (#2531)

Wasim Sandhu6a33a26752a9
diff --git a/frontend/src/components/app-config/app-config-form.tsx b/frontend/src/components/app-config/app-config-form.tsx
index 69734fbaeb..46a2ffca6c 100644
--- a/frontend/src/components/app-config/app-config-form.tsx
+++ b/frontend/src/components/app-config/app-config-form.tsx
@@ -13,9 +13,9 @@ import {
import {
type AppConfig,
AppConfigSchema,
- APP_WIDTHS,
AppTitleSchema,
} from "../../core/config/config-schema";
+import { getAppWidths } from "@/core/config/widths";
import { Input } from "../ui/input";
import { NativeSelect } from "../ui/native-select";
import { useAppConfig } from "@/core/config/config";
@@ -78,7 +78,7 @@ export const AppConfigForm: React.FC = () => {
disabled={field.disabled}
className="inline-flex mr-2"
>
- {APP_WIDTHS.map((option) => (
+ {getAppWidths().map((option) => (
<option value={option} key={option}>
{option}
</option>
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 936656761b..81b60c75f6 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -25,10 +25,10 @@ import { KEYMAP_PRESETS } from "@/core/codemirror/keymaps/keymaps";
import { useUserConfig } from "@/core/config/config";
import {
UserConfigSchema,
- APP_WIDTHS,
PackageManagerNames,
type UserConfig,
} from "@/core/config/config-schema";
+import { getAppWidths } from "@/core/config/widths";
import { saveUserConfig } from "@/core/network/requests";
import { isWasm } from "@/core/wasm/utils";
import { THEMES } from "@/theme/useTheme";
@@ -373,7 +373,7 @@ export const UserConfigForm: React.FC = () => {
disabled={field.disabled}
className="inline-flex mr-2"
>
- {APP_WIDTHS.map((option) => (
+ {getAppWidths().map((option) => (
<option value={option} key={option}>
{option}
</option>
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index cc2b9d49d9..1d6c08cd6f 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -114,7 +114,7 @@ export interface CellProps
*/
allowFocus: boolean;
userConfig: UserConfig;
-
+ canMoveX: boolean;
isCollapsed: boolean;
collapseCount: number;
}
@@ -161,6 +161,7 @@ const CellComponent = (
isCollapsed,
collapseCount,
config: cellConfig,
+ canMoveX,
name,
}: CellProps,
ref: React.ForwardedRef<CellHandle>,
@@ -457,6 +458,7 @@ const CellComponent = (
onBlur={closeCompletionHandler}
onKeyDown={resumeCompletionHandler}
cellId={cellId}
+ canMoveX={canMoveX}
title={cellTitle()}
>
<div className={className} id={HTMLId}>
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsx
index 651ae9c7f2..eb39c95c38 100644
--- a/frontend/src/components/editor/Output.tsx
+++ b/frontend/src/components/editor/Output.tsx
@@ -330,7 +330,7 @@ const ExpandableOutput = React.memo(
<>
<div>
<div className="relative print:hidden">
- <div className="absolute -right-10 top-1 z-[1] flex flex-col gap-1">
+ <div className="absolute -right-9 top-1 z-[1] flex flex-col gap-1">
<Tooltip content="Fullscreen" side="left">
<Button
data-testid="fullscreen-output-button"
diff --git a/frontend/src/components/editor/SortableCell.tsx b/frontend/src/components/editor/SortableCell.tsx
index eb0051f6ab..726c9df9b1 100644
--- a/frontend/src/components/editor/SortableCell.tsx
+++ b/frontend/src/components/editor/SortableCell.tsx
@@ -9,6 +9,7 @@ import { cn } from "@/utils/cn";
interface Props extends React.HTMLAttributes<HTMLDivElement> {
cellId: CellId;
+ canMoveX?: boolean;
}
/**
@@ -23,7 +24,7 @@ export const CellDragHandle: React.FC = memo(() => {
CellDragHandle.displayName = "DragHandle";
const SortableCellInternal = React.forwardRef(
- ({ cellId, ...props }: Props, ref: React.Ref<HTMLDivElement>) => {
+ ({ cellId, canMoveX, ...props }: Props, ref: React.Ref<HTMLDivElement>) => {
// Sort
const {
attributes,
@@ -37,8 +38,7 @@ const SortableCellInternal = React.forwardRef(
const style: React.CSSProperties = {
transform: transform
? CSS.Transform.toString({
- // No x-transform since only sorting in the y-axis
- x: 0,
+ x: canMoveX ? transform.x : 0,
y: transform.y,
scaleX: 1,
scaleY: 1,
@@ -69,6 +69,7 @@ const SortableCellInternal = React.forwardRef(
tabIndex={-1}
ref={mergedRef}
{...props}
+ data-is-dragging={isDragging}
className={cn(props.className, isMoving && "is-moving")}
style={style}
>
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index 37d4013dae..c574d55d22 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -29,6 +29,7 @@ import {
EyeOffIcon,
SparklesIcon,
DatabaseIcon,
+ Columns2Icon,
} from "lucide-react";
import type { ActionButton } from "./types";
import { MultiIcon } from "@/components/icons/multi-icon";
@@ -48,7 +49,11 @@ import {
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { MarkdownIcon, PythonIcon } from "../cell/code/icons";
-import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";
+import {
+ aiEnabledAtom,
+ appWidthAtom,
+ autoInstantiateAtom,
+} from "@/core/config/config";
import { useDeleteCellCallback } from "../cell/useDeleteCell";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
import type { CellConfig, RuntimeState } from "@/core/network/types";
@@ -75,6 +80,7 @@ export function useCellActionButtons({ cell }: Props) {
moveCell,
sendToTop,
sendToBottom,
+ addColumnBreakpoint,
} = useCellActions();
const runCell = useRunCell(cell?.cellId);
const hasOnlyOneCell = useAtomValue(hasOnlyOneCellAtom);
@@ -86,6 +92,7 @@ export function useCellActionButtons({ cell }: Props) {
const autoInstantiate = useAtomValue(autoInstantiateAtom);
const cellIds = useCellIds();
const kioskMode = useAtomValue(kioskModeAtom);
+ const appWidth = useAtomValue(appWidthAtom);
if (!cell || kioskMode) {
return [];
@@ -322,6 +329,13 @@ export function useCellActionButtons({ cell }: Props) {
hotkey: "cell.sendToBottom",
handle: () => sendToBottom({ cellId }),
},
+ {
+ icon: <Columns2Icon size={13} strokeWidth={1.5} />,
+ label: "Break into new column",
+ hotkey: "cell.addColumnBreakpoint",
+ hidden: appWidth !== "columns",
+ handle: () => addColumnBreakpoint({ cellId }),
+ },
],
// Delete
diff --git a/frontend/src/components/editor/actions/useConfigActions.tsx b/frontend/src/components/editor/actions/useConfigActions.tsx
index 37342028e4..6f59a8aa32 100644
--- a/frontend/src/components/editor/actions/useConfigActions.tsx
+++ b/frontend/src/components/editor/actions/useConfigActions.tsx
@@ -1,11 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { saveAppConfig, saveUserConfig } from "@/core/network/requests";
import type { ActionButton } from "./types";
-import {
- APP_WIDTHS,
- type AppConfig,
- type UserConfig,
-} from "@/core/config/config-schema";
+import type { AppConfig, UserConfig } from "@/core/config/config-schema";
+import { getAppWidths } from "@/core/config/widths";
import { useAppConfig, useUserConfig } from "@/core/config/config";
import { useTheme } from "@/theme/useTheme";
@@ -27,15 +24,17 @@ export function useConfigActions() {
};
const actions: ActionButton[] = [
- ...APP_WIDTHS.filter((width) => width !== appConfig.width).map((width) => ({
- label: `App config > Set width=${width}`,
- handle: () => {
- handleAppConfig({
- ...appConfig,
- width: width,
- });
- },
- })),
+ ...getAppWidths()
+ .filter((width) => width !== appConfig.width)
+ .map((width) => ({
+ label: `App config > Set width=${width}`,
+ handle: () => {
+ handleAppConfig({
+ ...appConfig,
+ width: width,
+ });
+ },
+ })),
{
label: "Config > Toggle dark mode",
handle: () => {
diff --git a/frontend/src/components/editor/app-container.tsx b/frontend/src/components/editor/app-container.tsx
index fcacd37757..073cd1b690 100644
--- a/frontend/src/components/editor/app-container.tsx
+++ b/frontend/src/components/editor/app-container.tsx
@@ -34,7 +34,7 @@ export const AppContainer: React.FC<PropsWithChildren<Props>> = ({
className={cn(
connectionState === WebSocketState.CLOSED && "disconnected",
"bg-background w-full h-full text-textColor",
- "flex flex-col overflow-y-auto overflow-x-hidden",
+ "flex flex-col overflow-y-auto overflow-x-auto",
width === "full" && "config-width-full",
"print:height-fit",
)}
diff --git a/frontend/src/components/editor/cell/toolbar.tsx b/frontend/src/components/editor/cell/toolbar.tsx
index ad302f620f..60b70a9e11 100644
--- a/frontend/src/components/editor/cell/toolbar.tsx
+++ b/frontend/src/components/editor/cell/toolbar.tsx
@@ -6,7 +6,7 @@ import { Toolbar as ReactAriaToolbar } from "react-aria-components";
import { cva, type VariantProps } from "class-variance-authority";
const toolbarItemVariants = cva(
- "rounded-full shadow-xsSolid border p-[5px] transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 [&>svg]:size-3 active:shadow-none",
+ "rounded-full shadow-xsSolid border p-[5px] transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 [&>svg]:size-3 active:shadow-none bg-background",
{
variants: {
variant: {
@@ -14,7 +14,7 @@ const toolbarItemVariants = cva(
stale:
"bg-[var(--yellow-3)] hover:bg-[var(--yellow-4)] text-[var(--yellow-11)]",
green:
- "hover:bg-[var(--grass-2)] hover:text-[var(--grass-11)] hover:border-[var(--grass-7)]",
+ "hover:bg-[var(--grass-2)] hover:text-[var(--grass-11)] hover:border-[var(--grass-7)],",
disabled: "opacity-50 cursor-not-allowed",
danger: "hover:bg-[var(--red-3)] hover:text-[var(--red-11)]",
},
@@ -53,11 +53,7 @@ export const ToolbarItem: React.FC<ToolbarItemProps> = ({
// Prevent focus on the toolbar after clicking
evt.preventDefault();
}}
- className={cn(
- toolbarItemVariants({ variant }),
- disabled && "opacity-50 cursor-not-allowed",
- rest.className,
- )}
+ className={cn(toolbarItemVariants({ variant }), rest.className)}
>
{children}
</button>
@@ -86,7 +82,7 @@ interface ToolbarProps {
export const Toolbar: React.FC<ToolbarProps> = ({ children, className }) => (
<ReactAriaToolbar
className={cn(
- "flex items-center gap-1 bg-background p-[2px] rounded-md",
+ "flex items-center gap-1 bg-background m-[2px] rounded-full",
className,
)}
>
diff --git a/frontend/src/components/editor/cell/useDeleteCell.tsx b/frontend/src/components/editor/cell/useDeleteCell.tsx
index 844863d8b1..53728417af 100644
--- a/frontend/src/components/editor/cell/useDeleteCell.tsx
+++ b/frontend/src/components/editor/cell/useDeleteCell.tsx
@@ -1,18 +1,18 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { UndoButton } from "@/components/buttons/undo-button";
import { toast } from "@/components/ui/use-toast";
-import { getCells, useCellActions } from "@/core/cells/cells";
+import { hasOnlyOneCellAtom, useCellActions } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { sendDeleteCell } from "@/core/network/requests";
+import { store } from "@/core/state/jotai";
import useEvent from "react-use-event-hook";
export function useDeleteCellCallback() {
const { deleteCell, undoDeleteCell } = useCellActions();
return useEvent((opts: { cellId: CellId }) => {
- const cells = getCells();
// Can't delete the last cell
- if (cells.length === 1) {
+ if (store.get(hasOnlyOneCellAtom)) {
return;
}
diff --git a/frontend/src/components/editor/columns/cell-column.tsx b/frontend/src/components/editor/columns/cell-column.tsx
new file mode 100644
index 0000000000..cd66ec4210
--- /dev/null
+++ b/frontend/src/components/editor/columns/cell-column.tsx
@@ -0,0 +1,54 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { cn } from "@/utils/cn";
+import { memo, useRef } from "react";
+import { SortableColumn } from "./sortable-column";
+import type { CellColumnId } from "@/utils/id-tree";
+import type { AppConfig } from "@/core/config/config-schema";
+
+interface Props {
+ className?: string;
+ columnId: CellColumnId;
+ children: React.ReactNode;
+ width: AppConfig["width"];
+ footer?: React.ReactNode;
+ canDelete: boolean;
+ canMoveLeft: boolean;
+ canMoveRight: boolean;
+}
+
+export const Column = memo((props: Props) => {
+ const columnRef = useRef<HTMLDivElement>(null);
+
+ const column = (
+ <div
+ className={cn(
+ "flex flex-col gap-5",
+ props.width === "columns" &&
+ "w-contentWidthMedium min-h-[100px] border border-t-0 border-[var(--slate-3)] rounded-b-lg px-11 py-6 bg-[var(--slate-2)]",
+ )}
+ >
+ {props.children}
+ </div>
+ );
+
+ if (props.width === "columns") {
+ return (
+ <SortableColumn
+ tabIndex={-1}
+ ref={columnRef}
+ canDelete={props.canDelete}
+ columnId={props.columnId}
+ canMoveLeft={props.canMoveLeft}
+ canMoveRight={props.canMoveRight}
+ className="group/column"
+ >
+ {column}
+ {props.footer}
+ </SortableColumn>
+ );
+ }
+
+ return column;
+});
+
+Column.displayName = "Column";
diff --git a/frontend/src/components/editor/columns/sortable-column.tsx b/frontend/src/components/editor/columns/sortable-column.tsx
new file mode 100644
index 0000000000..ec7c65aa68
--- /dev/null
+++ b/frontend/src/components/editor/columns/sortable-column.tsx
@@ -0,0 +1,151 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { memo } from "react";
+import { mergeRefs } from "../../../utils/mergeRefs";
+import { useSortable } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { ChevronLeftIcon, ChevronRightIcon, PlusIcon, X } from "lucide-react";
+import type { CellColumnId } from "@/utils/id-tree";
+import { useCellActions } from "@/core/cells/cells";
+import { cn } from "@/utils/cn";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+
+interface Props extends React.HTMLAttributes<HTMLDivElement> {
+ columnId: CellColumnId;
+ canDelete: boolean;
+ canMoveLeft: boolean;
+ canMoveRight: boolean;
+}
+
+const SortableColumnInternal = React.forwardRef(
+ (
+ { columnId, canDelete, canMoveLeft, canMoveRight, ...props }: Props,
+ ref: React.Ref<HTMLDivElement>,
+ ) => {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ isOver,
+ } = useSortable({ id: columnId });
+
+ const style: React.CSSProperties = {
+ transform: transform
+ ? CSS.Transform.toString({
+ x: transform.x,
+ y: 0,
+ scaleX: 1,
+ scaleY: 1,
+ })
+ : undefined,
+ transition,
+ zIndex: isDragging ? 2 : undefined,
+ position: "relative",
+ // @ts-expect-error doesn't allow css variables
+ "--gutter-width": "50px",
+ };
+
+ const mergedRef = mergeRefs<HTMLDivElement>(ref, setNodeRef);
+
+ const { deleteColumn, moveColumn, addColumn } = useCellActions();
+
+ const buttonClasses = cn("h-full hover:bg-muted rounded-none");
+
+ const handleScrollAppRight = () => {
+ const app = document.getElementById("App");
+ if (app) {
+ app.scrollTo({
+ left: app.scrollLeft + 1000,
+ behavior: "smooth",
+ });
+ }
+ };
+
+ const dragHandle = (
+ <div className="h-6 group flex items-center rounded-t-lg border hover:border-border border-[var(--slate-3)] overflow-hidden bg-[var(--slate-1)]">
+ <Tooltip content="Move column left" side="top" delayDuration={300}>
+ <Button
+ variant="text"
+ size="sm"
+ className={buttonClasses}
+ onClick={() =>
+ moveColumn({ column: columnId, overColumn: "_left_" })
+ }
+ disabled={!canMoveLeft}
+ >
+ <ChevronLeftIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip content="Move column right" side="top" delayDuration={300}>
+ <Button
+ variant="text"
+ size="sm"
+ className={buttonClasses}
+ onClick={() =>
+ moveColumn({ column: columnId, overColumn: "_right_" })
+ }
+ disabled={!canMoveRight}
+ >
+ <ChevronRightIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ <div
+ className="flex gap-2 h-full flex-grow active:bg-accent cursor-grab"
+ {...attributes}
+ {...listeners}
+ data-testid="column-drag-button"
+ />
+ {canDelete && (
+ <Tooltip content="Delete column" side="top" delayDuration={300}>
+ <Button
+ variant="text"
+ size="sm"
+ className="opacity-0 group-hover:opacity-70 group-hover:hover:opacity-100 text-destructive h-full hover:bg-destructive/20 rounded-none"
+ onClick={() => deleteColumn({ columnId })}
+ >
+ <X className="size-4" />
+ </Button>
+ </Tooltip>
+ )}
+ <Tooltip content="Add column" side="top" delayDuration={300}>
+ <Button
+ variant="text"
+ size="sm"
+ className={buttonClasses}
+ onClick={() => {
+ addColumn({ columnId });
+ requestAnimationFrame(handleScrollAppRight);
+ }}
+ >
+ <PlusIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ </div>
+ );
+
+ return (
+ <div
+ tabIndex={-1}
+ ref={mergedRef}
+ {...props}
+ style={style}
+ data-is-dragging={isDragging}
+ className={cn(
+ isDragging ? "" : props.className,
+ // Set z-index: dragging should be above everything else
+ isDragging ? "z-20" : "z-1 hover:z-10 focus-within:z-10",
+ isOver && "bg-accent/20", // Add a background color when dragging over
+ )}
+ >
+ {dragHandle}
+ {props.children}
+ </div>
+ );
+ },
+);
+SortableColumnInternal.displayName = "SortableColumn";
+
+export const SortableColumn = memo(SortableColumnInternal);
diff --git a/frontend/src/components/editor/notebook-banner.tsx b/frontend/src/components/editor/notebook-banner.tsx
index f0be8af244..404dab3584 100644
--- a/frontend/src/components/editor/notebook-banner.tsx
+++ b/frontend/src/components/editor/notebook-banner.tsx
@@ -6,8 +6,14 @@ import { AlertCircleIcon, RotateCcwIcon, XIcon } from "lucide-react";
import type React from "react";
import { Button } from "../ui/button";
import { useRestartKernel } from "./actions/useRestartKernel";
+import type { AppConfig } from "@/core/config/config-schema";
+import { cn } from "@/utils/cn";
-export const NotebookBanner: React.FC = (props) => {
+interface Props {
+ width: AppConfig["width"];
+}
+
+export const NotebookBanner: React.FC<Props> = ({ width }) => {
const { banners } = useBanners();
const { removeBanner } = useBannersActions();
@@ -16,7 +22,12 @@ export const NotebookBanner: React.FC = (props) => {
}
return (
- <div className="flex flex-col gap-4 mb-5 print:hidden">
+ <div
+ className={cn(
+ "flex flex-col gap-4 mb-5 print:hidden",
+ width === "columns" && "sticky left-12 w-full max-w-[80vw]",
+ )}
+ >
{banners.map((banner) => (
<Banner
kind={banner.variant || "info"}
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index f3ff1ad9f8..e5377d0e39 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -5,11 +5,7 @@ import {
type ConnectionStatus,
WebSocketState,
} from "../../../core/websocket/types";
-import {
- type NotebookState,
- flattenTopLevelNotebookCells,
- useCellActions,
-} from "../../../core/cells/cells";
+import { type NotebookState, useCellActions } from "../../../core/cells/cells";
import type { AppConfig, UserConfig } from "../../../core/config/config-schema";
import type { AppMode } from "../../../core/mode";
import { useHotkey } from "../../../hooks/useHotkey";
@@ -42,6 +38,14 @@ import { capabilitiesAtom } from "@/core/config/capabilities";
import { Tooltip } from "@/components/ui/tooltip";
import { Kbd } from "@/components/ui/kbd";
import { FloatingOutline } from "../chrome/panels/outline/floating-outline";
+import {
+ horizontalListSortingStrategy,
+ SortableContext,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable";
+import { SortableCellsProvider } from "@/components/sort/SortableCellsProvider";
+import { Column } from "../columns/cell-column";
+import type { CellColumnId } from "@/utils/id-tree";
interface CellArrayProps {
notebook: NotebookState;
@@ -62,7 +66,7 @@ export const CellArray: React.FC<CellArrayProps> = ({
const { theme } = useTheme();
const { toggleSidebarPanel } = useChromeActions();
- const { invisible } = useDelayVisibility(notebook.cellIds.length, mode);
+ const { invisible } = useDelayVisibility(notebook.cellIds.idLength, mode);
// HOTKEYS
useHotkey("global.focusTop", actions.focusTopCell);
@@ -88,7 +92,8 @@ export const CellArray: React.FC<CellArrayProps> = ({
}
}, [notebook.cellIds, notebook.scrollKey, scrollToTarget]);
- const cells = flattenTopLevelNotebookCells(notebook);
+ const columns = notebook.cellIds.getColumns();
+ const hasOnlyOneCell = notebook.cellIds.hasOnlyOneId();
return (
<VerticalLayoutWrapper
@@ -99,52 +104,92 @@ export const CellArray: React.FC<CellArrayProps> = ({
innerClassName="pr-4" // For the floating actions
>
<PackageAlert />
- <NotebookBanner />
- <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 />
+ <NotebookBanner width={appConfig.width} />
+ <SortableCellsProvider multiColumn={appConfig.width === "columns"}>
+ <SortableContext
+ id="column-container"
+ items={columns.map((column) => column.id)}
+ strategy={horizontalListSortingStrategy}
+ >
+ <div
+ className={cn(
+ appConfig.width === "columns" &&
+ "grid grid-flow-col auto-cols-min gap-6",
+ )}
+ >
+ {columns.map((column, index) => {
+ return (
+ <Column
+ key={column.id}
+ columnId={column.id}
+ canMoveLeft={index > 0}
+ canMoveRight={index < columns.length - 1}
+ width={appConfig.width}
+ canDelete={columns.length > 1}
+ footer={<AddCellButtons columnId={column.id} />}
+ >
+ <SortableContext
+ id={`column-${index + 1}`}
+ items={column.topLevelIds}
+ strategy={verticalListSortingStrategy}
+ >
+ {column.topLevelIds.map((cellId) => {
+ const cellData = notebook.cellData[cellId];
+ const cellRuntime = notebook.cellRuntime[cellId];
+ return (
+ <Cell
+ key={cellData.id.toString()}
+ theme={theme}
+ showPlaceholder={hasOnlyOneCell}
+ allowFocus={!invisible && !notebook.scrollKey}
+ id={cellData.id}
+ code={cellData.code}
+ outline={cellRuntime.outline}
+ output={cellRuntime.output}
+ consoleOutputs={cellRuntime.consoleOutputs}
+ status={cellRuntime.status}
+ edited={cellData.edited}
+ interrupted={cellRuntime.interrupted}
+ errored={cellRuntime.errored}
+ stopped={cellRuntime.stopped}
+ staleInputs={cellRuntime.staleInputs}
+ runStartTimestamp={cellRuntime.runStartTimestamp}
+ runElapsedTimeMs={
+ cellRuntime.runElapsedTimeMs ??
+ (cellData.lastExecutionTime as Milliseconds)
+ }
+ serializedEditorState={cellData.serializedEditorState}
+ showDeleteButton={
+ !hasOnlyOneCell && !cellData.config.hide_code
+ }
+ mode={mode}
+ appClosed={connStatus.state !== WebSocketState.OPEN}
+ ref={notebook.cellHandles[cellId]}
+ userConfig={userConfig}
+ debuggerActive={cellRuntime.debuggerActive}
+ config={cellData.config}
+ name={cellData.name}
+ isCollapsed={column.isCollapsed(cellId)}
+ collapseCount={column.getCount(cellId)}
+ canMoveX={appConfig.width === "columns"}
+ {...actions}
+ deleteCell={onDeleteCell}
+ />
+ );
+ })}
+ </SortableContext>
+ </Column>
+ );
+ })}
+ </div>
+ </SortableContext>
+ </SortableCellsProvider>
<FloatingOutline />
</VerticalLayoutWrapper>
);
};
-const AddCellButtons: React.FC = () => {
+const AddCellButtons: React.FC<{ columnId: CellColumnId }> = ({ columnId }) => {
const { createNewCell } = useCellActions();
const autoInstantiate = useAtomValue(autoInstantiateAtom);
const [isAiButtonOpen, isAiButtonOpenActions] = useBoolean(false);
@@ -167,7 +212,12 @@ const AddCellButtons: React.FC = () => {
className={buttonClass}
variant="text"
size="sm"
- onClick={() => createNewCell({ cellId: "__end__", before: false })}
+ onClick={() =>
+ createNewCell({
+ cellId: { type: "__end__", columnId },
+ before: false,
+ })
+ }
>
<SquareCodeIcon className="mr-2 size-4 flex-shrink-0" />
Python
@@ -180,7 +230,7 @@ const AddCellButtons: React.FC = () => {
maybeAddMarimoImport(autoInstantiate, createNewCell);
createNewCell({
- cellId: "__end__",
+ cellId: { type: "__end__", columnId },
before: false,
code: new MarkdownLanguageAdapter().defaultCode,
});
@@ -215,7 +265,7 @@ const AddCellButtons: React.FC = () => {
maybeAddMarimoImport(autoInstantiate, createNewCell);
createNewCell({
- cellId: "__end__",
+ cellId: { type: "__end__", columnId },
before: false,
code: new SQLLanguageAdapter().defaultCode,
});
@@ -251,6 +301,7 @@ const AddCellButtons: React.FC = () => {
<div className="flex justify-center mt-4 pt-6 pb-32 group gap-4 w-full print:hidden">
<div
className={cn(
+ "opacity-0 group-hover/column:opacity-100",
"shadow-sm border border-border rounded transition-all duration-200 overflow-hidden divide-x divide-border flex",
!isAiButtonOpen && "w-fit",
isAiButtonOpen &&
diff --git a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
index 38718c4532..b49f0b5250 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
+++ b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
@@ -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.topLevelIds) {
+ for (const cellId of cellIds.iterateTopLevelIds) {
const handle = cellHandles[cellId];
const hidden = cellData[cellId].config.hide_code;
if (!hidden && handle?.current?.editorView) {
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout-wrapper.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout-wrapper.tsx
index 1218d1eec9..4698061f6e 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout-wrapper.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout-wrapper.tsx
@@ -31,6 +31,7 @@ export const VerticalLayoutWrapper: React.FC<PropsWithChildren<Props>> = ({
appConfig.width === "compact" && "max-w-contentWidth min-w-[400px]",
appConfig.width === "medium" &&
"max-w-contentWidthMedium min-w-[400px]",
+ appConfig.width === "columns" && "w-fit",
appConfig.width === "full" && "max-w-full",
// Hide the cells for a fake loading effect, to avoid flickering
invisible && "invisible",
diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsx
index 5e0291cd94..5ba4d2b9ba 100644
--- a/frontend/src/components/sort/SortableCellsProvider.tsx
+++ b/frontend/src/components/sort/SortableCellsProvider.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import React from "react";
+import React, { useMemo, useState, useCallback } from "react";
import {
DndContext,
closestCenter,
@@ -8,28 +8,56 @@ import {
useSensor,
type DragEndEvent,
useSensors,
+ type AutoScrollOptions,
+ type UniqueIdentifier,
+ type DragStartEvent,
+ pointerWithin,
+ rectIntersection,
+ getFirstCollision,
+ type CollisionDetection,
} from "@dnd-kit/core";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
-import {
- SortableContext,
- sortableKeyboardCoordinates,
- verticalListSortingStrategy,
-} from "@dnd-kit/sortable";
+import { sortableKeyboardCoordinates } from "@dnd-kit/sortable";
import { useCellActions, useNotebook } from "../../core/cells/cells";
import { useEvent } from "../../hooks/useEvent";
import type { CellId } from "@/core/cells/ids";
+import { useAppConfig } from "@/core/config/config";
+import { Arrays } from "@/utils/arrays";
+import type { CellColumnId, MultiColumn } from "@/utils/id-tree";
+import { invariant } from "@/utils/invariant";
interface SortableCellsProviderProps {
+ multiColumn: boolean;
children: React.ReactNode;
- disabled?: boolean;
}
+// autoScroll threshold x: 0 is required to disable horizontal scroll
+// threshold y: 0.1 means scroll y when near bottom/top 10% of
+// scrollable container
+const autoScroll: AutoScrollOptions = {
+ threshold: { x: 0, y: 0.1 },
+};
+
const SortableCellsProviderInternal = ({
children,
- disabled,
+ multiColumn,
}: SortableCellsProviderProps) => {
- const notebook = useNotebook();
- const { dropCellOver } = useCellActions();
+ const { cellIds } = useNotebook();
+ const { dropCellOverCell, dropCellOverColumn, moveColumn, compactColumns } =
+ useCellActions();
+
+ const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
+ const [clonedItems, setClonedItems] = useState<MultiColumn<CellId> | null>(
+ null,
+ );
+
+ const [config] = useAppConfig();
+ const modifiers = useMemo(() => {
+ if (config.width === "columns") {
+ return Arrays.EMPTY;
+ }
+ return [restrictToVerticalAxis];
+ }, [config.width]);
const sensors = useSensors(
useSensor(PointerSensor, {
@@ -43,42 +71,170 @@ const SortableCellsProviderInternal = ({
}),
);
- const ids = notebook.cellIds.topLevelIds;
+ const handleDragStart = useEvent((event: DragStartEvent) => {
+ setActiveId(event.active.id);
+ setClonedItems(cellIds);
+ });
- const handleDragEnd = useEvent((event: DragEndEvent) => {
- const { active, over } = event;
- if (over === null) {
+ const handleDragCancel = useEvent(() => {
+ // TODO: restore cloned items
+ if (clonedItems) {
+ // Reset items to their original state in case items have been
+ // Dragged across containers
+ // setItems(clonedItems);
+ }
+
+ setActiveId(null);
+ setClonedItems(null);
+ });
+
+ /**
+ * Custom collision detection:
+ * 1. If dragging a column, we can only drop on other columns
+ * - We just use closestCenter
+ * - We filter the droppableContainers to only consider other columns
+ * 2. If dragging a cell, we want to find the best column to drop on
+ * - We get the first intersection
+ * - Find the closest column to the cell
+ * - If the column is empty, we consider it a valid drop target
+ * - Otherwise, we only consider the cells in the same column
+ */
+ const collisionDetectionStrategy = useCallback(
+ (args: Parameters<CollisionDetection>[0]) => {
+ const columnContainers = args.droppableContainers.filter((container) =>
+ isColumnId(container.id),
+ );
+
+ // 1. Handle column dragging
+ if (activeId && isColumnId(activeId)) {
+ return closestCenter({
+ ...args,
+ droppableContainers: columnContainers,
+ });
+ }
+
+ // 2. Handle cell dragging
+
+ // Get the first column intersection
+ const pointerIntersections = pointerWithin({
+ ...args,
+ droppableContainers: columnContainers,
+ });
+ const intersections =
+ pointerIntersections.length > 0
+ ? pointerIntersections
+ : rectIntersection({
+ ...args,
+ droppableContainers: columnContainers,
+ });
+ const overId = getFirstCollision(intersections, "id");
+ if (!overId) {
+ return [];
+ }
+ invariant(isColumnId(overId), `Expected column id. Got: ${overId}`);
+
+ // If column is empty, we can drop on it
+ const column = cellIds.get(overId);
+ invariant(column, `Expected column. Got: ${overId}`);
+ if (column && column.topLevelIds.length === 0) {
+ // Return the column
+ return [{ id: overId }];
+ }
+
+ // If the column is not empty, we only consider the cells in the same column
+ const cellIdSet = new Set(column.topLevelIds);
+ const collisions = closestCenter({
+ ...args,
+ droppableContainers: args.droppableContainers.filter(
+ (container) =>
+ container.id !== overId && cellIdSet.has(container.id as CellId),
+ ),
+ });
+
+ if (collisions.length > 0) {
+ const overId = collisions[0].id;
+ invariant(isCellId(overId), `Expected cell id. Got: ${overId}`);
+ // Return the cell
+ return [{ id: overId }];
+ }
+
+ return [];
+ },
+ [activeId, cellIds],
+ );
+
+ const handleDragOver = useEvent(({ active, over }) => {
+ const overId = over?.id;
+
+ if (overId == null || active.id === overId) {
return;
}
- if (active.id === over.id) {
+
+ // Handle moving cells
+ if (isCellId(active.id)) {
+ // Moving a cell to a column
+ if (isColumnId(overId)) {
+ dropCellOverColumn({
+ cellId: active.id,
+ columnId: overId,
+ });
+ return;
+ }
+
+ // Moving a cell above another cell
+ if (isCellId(overId)) {
+ dropCellOverCell({
+ cellId: active.id,
+ overCellId: overId,
+ });
+ return;
+ }
+ }
+
+ // Moving a column to another column
+ if (isColumnId(active.id) && isColumnId(overId)) {
+ moveColumn({
+ column: active.id,
+ overColumn: overId,
+ });
+ }
+ });
+
+ const handleDragEnd = useEvent((event: DragEndEvent) => {
+ const { active, over } = event;
+
+ if (over === null || active.id === over.id) {
return;
}
- dropCellOver({
- cellId: active.id as CellId,
- overCellId: over.id as CellId,
- });
+
+ compactColumns();
});
- // autoScroll threshold x: 0 is required to disable horizontal scroll
- // threshold y: 0.1 means scroll y when near bottom/top 10% of
- // scrollable container
return (
<DndContext
- autoScroll={{ threshold: { x: 0, y: 0.1 } }}
+ autoScroll={autoScroll}
sensors={sensors}
- collisionDetection={closestCenter}
- modifiers={[restrictToVerticalAxis]}
+ // For single-column, we just do closestCenter
+ collisionDetection={
+ multiColumn ? collisionDetectionStrategy : closestCenter
+ }
+ modifiers={modifiers}
onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
+ onDragCancel={handleDragCancel}
+ onDragOver={handleDragOver}
>
- <SortableContext
- items={ids}
- disabled={disabled}
- strategy={verticalListSortingStrategy}
- >
- {children}
- </SortableContext>
+ {children}
</DndContext>
);
};
export const SortableCellsProvider = React.memo(SortableCellsProviderInternal);
+
+function isCellId(id: UniqueIdentifier): id is CellId {
+ return typeof id === "string" && !id.startsWith("tree_");
+}
+
+function isColumnId(id: UniqueIdentifier): id is CellColumnId {
+ return typeof id === "string" && id.startsWith("tree_");
+}
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 ea00b6b56b..ff82909424 100644
--- a/frontend/src/core/cells/__tests__/add-missing-import.test.ts
+++ b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
@@ -7,9 +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";
+import { CollapsibleTree, MultiColumn } from "@/utils/id-tree";
-const CELL_IDS = CollapsibleTree.from(["1" as CellId]);
+const CELL_IDS = new MultiColumn([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 57fb1cc1d6..3d03a660f7 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -13,7 +13,6 @@ import {
exportedForTesting,
flattenTopLevelNotebookCells,
} from "../cells";
-import { notebookCells } from "../utils";
import { CellId } from "@/core/cells/ids";
import type { OutputMessage } from "@/core/kernel/messages";
import type { Seconds } from "@/utils/time";
@@ -30,6 +29,8 @@ import {
scrollToTop,
scrollToBottom,
} from "../scrollCellIntoView";
+import { type CollapsibleTree, MultiColumn } from "@/utils/id-tree";
+import type { CellData } from "../types";
vi.mock("@/core/codemirror/editing/commands", () => ({
foldAllBulk: vi.fn(),
@@ -46,11 +47,31 @@ vi.mock("../scrollCellIntoView", async (importOriginal) => {
};
});
+const FIRST_COLUMN = 0;
+
const { initialNotebookState, reducer, createActions } = exportedForTesting;
function formatCells(notebook: NotebookState) {
- const cells = notebookCells(notebook);
- return `\n${cells.map((cell) => [`key: ${cell.id}`, `code: '${cell.code}'`].join("\n")).join("\n\n")}`;
+ const { cellIds, cellData } = notebook;
+ const wrap = (text: string) => {
+ return `\n${text}\n`;
+ };
+
+ const printCell = (cell: CellData) => {
+ return `[${cell.id}] '${cell.code}'`;
+ };
+ const printCells = (cellsId: CellId[]) => {
+ const cells = cellsId.map((cellId) => cellData[cellId]);
+ return cells.map((cell) => printCell(cell)).join("\n\n");
+ };
+ const printColumn = (column: CollapsibleTree<CellId>, columnIdx: number) => {
+ return `> col ${columnIdx}\n${printCells(column.inOrderIds)}`;
+ };
+ const columns = cellIds.getColumns();
+ if (columns.length > 1) {
+ return wrap(columns.map(printColumn).join("\n\n"));
+ }
+ return wrap(printCells(cellIds.inOrderIds));
}
function createEditor(content: string) {
@@ -112,8 +133,9 @@ describe("cell reducer", () => {
i = 0;
state = initialNotebookState();
- actions.createNewCell({ cellId: undefined!, before: false });
- firstCellId = state.cellIds.atOrThrow(0);
+ state.cellIds = MultiColumn.from([]);
+ actions.createNewCell({ cellId: "__end__", before: false });
+ firstCellId = state.cellIds.inOrderIds[0];
});
afterAll(() => {
@@ -127,11 +149,10 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''
+ [0] ''
- key: 1
- code: ''"
+ [1] ''
+ "
`);
});
@@ -143,11 +164,10 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''
+ [0] ''
- key: 1
- code: 'import numpy as np'"
+ [1] 'import numpy as np'
+ "
`);
// Cell should be added to the end and edited
@@ -163,11 +183,10 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 1
- code: ''
+ [1] ''
- key: 0
- code: ''"
+ [0] ''
+ "
`);
});
@@ -181,19 +200,18 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 1
- code: ''"
+ [1] ''
+ "
`);
// undo
actions.undoDeleteCell();
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 2
- code: ''
+ [2] ''
- key: 1
- code: ''"
+ [1] ''
+ "
`);
});
@@ -203,25 +221,24 @@ describe("cell reducer", () => {
before: false,
code: `df = mo.sql("""SELECT * FROM table""")`,
});
- const newCellId = state.cellIds.atOrThrow(1);
+ const newCellId = state.cellIds.getColumns()[0].atOrThrow(1);
actions.deleteCell({
cellId: newCellId,
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''"
+ [0] ''
+ "
`);
// undo
actions.undoDeleteCell();
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''
+ [0] ''
- key: 2
- code: 'df = mo.sql("""SELECT * FROM table""")'"
+ [2] 'df = mo.sql("""SELECT * FROM table""")'
+ "
`);
});
@@ -232,25 +249,24 @@ describe("cell reducer", () => {
before: false,
code: `mo.md(r"""${text}""")`,
});
- const newCellId = state.cellIds.atOrThrow(1);
+ const newCellId = state.cellIds.getColumns()[0].atOrThrow(1);
actions.deleteCell({
cellId: newCellId,
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''"
+ [0] ''
+ "
`);
// undo
actions.undoDeleteCell();
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''
+ [0] ''
- key: 2
- code: 'mo.md(r"""${text}""")'"
+ [2] 'mo.md(r"""The quick brown fox jumps over the lazy dog.""")'
+ "
`);
});
@@ -262,8 +278,8 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: 'import numpy as np'"
+ [0] 'import numpy as np'
+ "
`);
});
@@ -274,11 +290,10 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''
+ [0] ''
- key: 1
- code: ''"
+ [1] ''
+ "
`);
// move first cell to the end
@@ -288,11 +303,10 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 1
- code: ''
+ [1] ''
- key: 0
- code: ''"
+ [0] ''
+ "
`);
// move it back
@@ -302,11 +316,10 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''
+ [0] ''
- key: 1
- code: ''"
+ [1] ''
+ "
`);
});
@@ -321,48 +334,42 @@ describe("cell reducer", () => {
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 0
- code: ''
+ [0] ''
- key: 1
- code: ''
+ [1] ''
- key: 2
- code: ''"
+ [2] ''
+ "
`);
// drag first cell to the end
- actions.dropCellOver({
+ actions.dropCellOverCell({
cellId: firstCellId,
overCellId: "2" as CellId,
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 1
- code: ''
+ [1] ''
- key: 2
- code: ''
+ [2] ''
- key: 0
- code: ''"
+ [0] ''
+ "
`);
// drag it back to the middle
- actions.dropCellOver({
+ actions.dropCellOverCell({
cellId: firstCellId,
overCellId: "2" as CellId,
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 1
- code: ''
+ [1] ''
- key: 0
- code: ''
+ [0] ''
- key: 2
- code: ''"
+ [2] ''
+ "
`);
});
@@ -1165,14 +1172,12 @@ describe("cell reducer", () => {
actions.sendToTop({ cellId: "2" as CellId });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 2
- code: ''
+ [2] ''
- key: 0
- code: ''
+ [0] ''
- key: 1
- code: ''"
+ [1] ''
+ "
`);
});
@@ -1182,14 +1187,12 @@ describe("cell reducer", () => {
actions.sendToBottom({ cellId: firstCellId });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
- key: 1
- code: ''
+ [1] ''
- key: 2
- code: ''
+ [2] ''
- key: 0
- code: ''"
+ [0] ''
+ "
`);
});
@@ -1221,7 +1224,7 @@ describe("cell reducer", () => {
const newCodes = ["code1", "code2", "code3"];
actions.setCellIds({ cellIds: newIds });
- expect(state.cellIds.topLevelIds).toEqual(newIds);
+ expect(state.cellIds.atOrThrow(FIRST_COLUMN).topLevelIds).toEqual(newIds);
actions.setCellCodes({ codes: newCodes, ids: newIds });
newIds.forEach((id, index) => {
@@ -1259,18 +1262,19 @@ describe("cell reducer", () => {
code: "## Subheader",
});
- const id = state.cellIds.atOrThrow(1);
+ const id = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(1);
state.cellRuntime[id] = {
...state.cellRuntime[id],
outline: {
items: [{ name: "Header", level: 1, by: { id: "header" } }],
},
};
+
actions.collapseCell({ cellId: id });
- expect(state.cellIds.isCollapsed(id)).toBe(true);
+ expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(id)).toBe(true);
actions.expandCell({ cellId: id });
- expect(state.cellIds.isCollapsed(id)).toBe(false);
+ expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(id)).toBe(false);
});
it("can show hidden cells", () => {
@@ -1279,7 +1283,9 @@ describe("cell reducer", () => {
actions.collapseCell({ cellId: firstCellId });
actions.showCellIfHidden({ cellId: "1" as CellId });
- expect(state.cellIds.isCollapsed(firstCellId)).toBe(false);
+ expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(firstCellId)).toBe(
+ false,
+ );
});
it("can split and undo split cells", () => {
@@ -1288,9 +1294,9 @@ describe("cell reducer", () => {
before: false,
code: "line1\nline2",
});
- const nextCellId = state.cellIds.atOrThrow(1);
+ const nextCellId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(1);
- const originalCellCount = state.cellIds.length;
+ const originalCellCount = state.cellIds.atOrThrow(FIRST_COLUMN).length;
// Move cursor to the second line
const editor = state.cellHandles[nextCellId].current?.editorView;
if (!editor) {
@@ -1298,12 +1304,18 @@ describe("cell reducer", () => {
}
editor.dispatch({ selection: { anchor: 5, head: 5 } });
actions.splitCell({ cellId: nextCellId });
- expect(state.cellIds.length).toBe(originalCellCount + 1);
+ expect(state.cellIds.atOrThrow(FIRST_COLUMN).length).toBe(
+ originalCellCount + 1,
+ );
expect(state.cellData[nextCellId].code).toBe("line1");
- expect(state.cellData[state.cellIds.atOrThrow(2)].code).toBe("line2");
+ expect(
+ state.cellData[state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(2)].code,
+ ).toBe("line2");
actions.undoSplitCell({ cellId: nextCellId, snapshot: "line1\nline2" });
- expect(state.cellIds.length).toBe(originalCellCount);
+ expect(state.cellIds.atOrThrow(FIRST_COLUMN).length).toBe(
+ originalCellCount,
+ );
expect(state.cellData[nextCellId].code).toBe("line1\nline2");
});
@@ -1333,4 +1345,280 @@ describe("cell reducer", () => {
const cell = cells[0];
expect(cell.consoleOutputs).toEqual([STDOUT1, STDOUT2]);
});
+
+ it("can add a column breakpoint", () => {
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: "2" as CellId, before: false });
+
+ expect(state.cellIds.getColumns().length).toBe(1);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+
+ [2] ''
+
+ [3] ''
+ "
+ `);
+
+ actions.addColumnBreakpoint({ cellId: "2" as CellId });
+
+ expect(state.cellIds.getColumns().length).toBe(2);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+ [0] ''
+
+ [1] ''
+
+ > col 1
+ [2] ''
+
+ [3] ''
+ "
+ `);
+
+ // Check that the cells are in the correct columns
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0", "1"]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["2", "3"]);
+ });
+
+ it("cannot add a column breakpoint before the first cell", () => {
+ expect(state.cellIds.getColumns().length).toBe(1);
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.addColumnBreakpoint({ cellId: firstCellId });
+ expect(state.cellIds.getColumns().length).toBe(1);
+ });
+
+ it("can delete a column", () => {
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: "2" as CellId, before: false });
+ actions.addColumnBreakpoint({ cellId: "2" as CellId });
+
+ expect(state.cellIds.getColumns().length).toBe(2);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+ [0] ''
+
+ [1] ''
+
+ > col 1
+ [2] ''
+
+ [3] ''
+ "
+ `);
+
+ const columnId = state.cellIds.atOrThrow(0).id;
+ actions.deleteColumn({ columnId: columnId });
+
+ expect(state.cellIds.getColumns().length).toBe(1);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [2] ''
+
+ [3] ''
+
+ [0] ''
+
+ [1] ''
+ "
+ `);
+
+ // Check that all cells are now in the remaining column
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual([
+ "2",
+ "3",
+ "0",
+ "1",
+ ]);
+ });
+
+ it("deleting the last column does nothing", () => {
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+
+ const initialState = { ...state };
+
+ actions.deleteColumn({ columnId: initialState.cellIds.atOrThrow(0).id });
+
+ // State should not change
+ expect(state).toEqual(initialState);
+ });
+
+ it("can drop a cell over another cell", () => {
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: "2" as CellId, before: false });
+
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+
+ [2] ''
+
+ [3] ''
+ "
+ `);
+
+ actions.dropCellOverCell({
+ cellId: "0" as CellId,
+ overCellId: "3" as CellId,
+ });
+
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [1] ''
+
+ [2] ''
+
+ [3] ''
+
+ [0] ''
+ "
+ `);
+ });
+
+ it("can drop a cell over a new column", () => {
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+
+ expect(state.cellIds.getColumns().length).toBe(1);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+
+ [2] ''
+ "
+ `);
+
+ actions.dropOverNewColumn({ cellId: "1" as CellId });
+
+ expect(state.cellIds.getColumns().length).toBe(2);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+ [0] ''
+
+ [2] ''
+
+ > col 1
+ [1] ''
+ "
+ `);
+
+ // Check that the cells are in the correct columns
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0", "2"]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["1"]);
+ });
+
+ it("can drop a column over another column", () => {
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: "2" as CellId, before: false });
+ actions.addColumnBreakpoint({ cellId: "2" as CellId });
+
+ expect(state.cellIds.getColumns().length).toBe(2);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+ [0] ''
+
+ [1] ''
+
+ > col 1
+ [2] ''
+
+ [3] ''
+ "
+ `);
+
+ const columnId0 = state.cellIds.atOrThrow(0).id;
+ const columnId1 = state.cellIds.atOrThrow(1).id;
+ expect(columnId0).not.toBe(columnId1);
+ actions.moveColumn({ column: columnId1, overColumn: columnId0 });
+
+ expect(state.cellIds.getColumns().length).toBe(2);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+ [2] ''
+
+ [3] ''
+
+ > col 1
+ [0] ''
+
+ [1] ''
+ "
+ `);
+
+ // Check that the columns have swapped positions
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["2", "3"]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["0", "1"]);
+ });
+
+ it("can compact columns", () => {
+ // Create initial state with 3 columns, including an empty one
+ actions.createNewCell({ cellId: firstCellId, before: false });
+ actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.addColumnBreakpoint({ cellId: "1" as CellId });
+ actions.addColumnBreakpoint({ cellId: "2" as CellId });
+ actions.dropOverNewColumn({ cellId: "2" as CellId });
+
+ expect(state.cellIds.getColumns().length).toBe(4);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+ [0] ''
+
+ > col 1
+ [1] ''
+
+ > col 2
+
+
+ > col 3
+ [2] ''
+ "
+ `);
+
+ // Check initial column structure
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0"]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["1"]);
+ expect(state.cellIds.getColumns()[2].topLevelIds).toEqual([]);
+ expect(state.cellIds.getColumns()[3].topLevelIds).toEqual(["2"]);
+
+ // Compact columns
+ actions.compactColumns();
+
+ expect(state.cellIds.getColumns().length).toBe(3);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+ [0] ''
+
+ > col 1
+ [1] ''
+
+ > col 2
+ [2] ''
+ "
+ `);
+
+ // Check compacted column structure
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0"]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["1"]);
+ expect(state.cellIds.getColumns()[2].topLevelIds).toEqual(["2"]);
+ });
});
diff --git a/frontend/src/core/cells/__tests__/utils.test.ts b/frontend/src/core/cells/__tests__/utils.test.ts
new file mode 100644
index 0000000000..ee5ec45054
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/utils.test.ts
@@ -0,0 +1,115 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { getCellConfigs, type NotebookState } from "@/core/cells/cells";
+import { CellId } from "@/core/cells/ids";
+import { MultiColumn } from "@/utils/id-tree";
+import type { CellData, CellRuntimeState } from "@/core/cells/types";
+
+describe("getCellConfigs", () => {
+ it("should return correct cell configs with column indices", () => {
+ // Create mock cell IDs
+ const cellId1 = CellId.create();
+ const cellId2 = CellId.create();
+ const cellId3 = CellId.create();
+ const cellId4 = CellId.create();
+
+ // Create a mock NotebookState
+ const mockState: NotebookState = {
+ cellIds: MultiColumn.from([
+ [cellId1, cellId2],
+ [cellId3, cellId4],
+ ]),
+ cellData: {
+ [cellId1]: {
+ id: cellId1,
+ config: { hide_code: false, disabled: false },
+ } as CellData,
+ [cellId2]: {
+ id: cellId2,
+ config: { hide_code: true, disabled: false },
+ } as CellData,
+ [cellId3]: {
+ id: cellId3,
+ config: { hide_code: false, disabled: true },
+ } as CellData,
+ [cellId4]: {
+ id: cellId4,
+ config: { hide_code: true, disabled: true },
+ } as CellData,
+ },
+ cellRuntime: {} as Record<CellId, CellRuntimeState>,
+ cellHandles: {},
+ history: [],
+ scrollKey: null,
+ cellLogs: [],
+ };
+
+ // Call the function
+ const result = getCellConfigs(mockState);
+
+ // Assert the results
+ expect(result).toEqual([
+ { hide_code: false, disabled: false, column: 0 },
+ { hide_code: true, disabled: false },
+ { hide_code: false, disabled: true, column: 1 },
+ { hide_code: true, disabled: true },
+ ]);
+
+ // Check that the original state was not modified
+ expect(mockState.cellData[cellId1].config).toEqual({
+ hide_code: false,
+ disabled: false,
+ column: 0,
+ });
+ expect(mockState.cellData[cellId2].config).toEqual({
+ hide_code: true,
+ disabled: false,
+ });
+ expect(mockState.cellData[cellId3].config).toEqual({
+ hide_code: false,
+ disabled: true,
+ column: 1,
+ });
+ expect(mockState.cellData[cellId4].config).toEqual({
+ hide_code: true,
+ disabled: true,
+ });
+ });
+
+ it("should handle single column", () => {
+ const cellId1 = CellId.create();
+ const mockState: NotebookState = {
+ cellIds: MultiColumn.from([[cellId1]]),
+ cellData: {
+ [cellId1]: {
+ id: cellId1,
+ config: { hide_code: false, disabled: false },
+ } as CellData,
+ },
+ cellRuntime: {},
+ cellHandles: {},
+ history: [],
+ scrollKey: null,
+ cellLogs: [],
+ };
+
+ const result = getCellConfigs(mockState);
+ expect(result).toEqual([{ hide_code: false, disabled: false }]);
+ });
+
+ it("should handle empty notebook state", () => {
+ const mockState: NotebookState = {
+ cellIds: MultiColumn.from([]),
+ cellData: {},
+ cellRuntime: {},
+ cellHandles: {},
+ history: [],
+ scrollKey: null,
+ cellLogs: [],
+ };
+
+ const result = getCellConfigs(mockState);
+
+ expect(result).toEqual([]);
+ });
+});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index c6e9da8a90..cbfce6e831 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -43,7 +43,11 @@ import type {
import { getUserConfig } from "@/core/config/config";
import { syncCellIds } from "../network/requests";
import { kioskModeAtom } from "../mode";
-import { CollapsibleTree } from "@/utils/id-tree";
+import {
+ type CellColumnId,
+ type CellIndex,
+ MultiColumn,
+} from "@/utils/id-tree";
import { isEqual } from "lodash-es";
export const SCRATCH_CELL_ID = "__scratch__" as CellId;
@@ -55,7 +59,7 @@ export interface NotebookState {
/**
* Order of cells on the page.
*/
- cellIds: CollapsibleTree<CellId>;
+ cellIds: MultiColumn<CellId>;
/**
* Map of cells to their view state
*/
@@ -73,8 +77,13 @@ export interface NotebookState {
*
* (CodeMirror types the serialized config as any.)
*/
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- history: Array<{ name: string; serializedEditorState: any; index: number }>;
+ history: Array<{
+ name: string;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ serializedEditorState: any;
+ column: CellColumnId;
+ index: CellIndex;
+ }>;
/**
* Key of cell to scroll to; typically set by actions that re-order the cell
* array. Call the SCROLL_TO_TARGET action to scroll to the specified cell
@@ -95,10 +104,11 @@ export interface LastSavedNotebook {
}
function withScratchCell(notebookState: NotebookState): NotebookState {
+ const config = { column: 0, hide_code: false, disabled: false };
return {
...notebookState,
cellData: {
- [SCRATCH_CELL_ID]: createCell({ id: SCRATCH_CELL_ID }),
+ [SCRATCH_CELL_ID]: createCell({ id: SCRATCH_CELL_ID, config: config }),
...notebookState.cellData,
},
cellRuntime: {
@@ -157,7 +167,7 @@ function initialNotebookState(): NotebookState {
}
return {
- cellIds: CollapsibleTree.from(cellIds),
+ cellIds: MultiColumn.from([cellIds]),
cellData: cellData,
cellRuntime: cellRuntime,
cellHandles: {},
@@ -168,7 +178,7 @@ function initialNotebookState(): NotebookState {
}
return withScratchCell({
- cellIds: CollapsibleTree.from([]),
+ cellIds: MultiColumn.from([]),
cellData: {},
cellRuntime: {},
cellHandles: {},
@@ -190,7 +200,7 @@ const {
createNewCell: (
state,
action: {
- cellId: CellId | "__end__";
+ cellId: CellId | "__end__" | { type: "__end__"; columnId: CellColumnId };
before: boolean;
code?: string;
lastCodeRun?: string;
@@ -207,16 +217,33 @@ const {
lastExecutionTime = null,
autoFocus = true,
} = action;
+
+ let columnId: CellColumnId;
+ let cellIndex: number;
+
+ if (cellId === "__end__") {
+ const column = state.cellIds.atOrThrow(0);
+ columnId = column.id;
+ cellIndex = column.length;
+ } else if (typeof cellId === "string") {
+ const column = state.cellIds.findWithId(cellId);
+ columnId = column.id;
+ cellIndex = column.topLevelIds.indexOf(cellId);
+ } else if (cellId.type === "__end__") {
+ const column =
+ state.cellIds.get(cellId.columnId) || state.cellIds.atOrThrow(0);
+ columnId = column.id;
+ cellIndex = column.length;
+ } else {
+ throw new Error("Invalid cellId");
+ }
+
const newCellId = action.newCellId || CellId.create();
- const index =
- cellId === "__end__"
- ? state.cellIds.length - 1
- : state.cellIds.topLevelIds.indexOf(cellId);
- const insertionIndex = before ? index : index + 1;
+ const insertionIndex = before ? cellIndex : cellIndex + 1;
return {
...state,
- cellIds: state.cellIds.insert(newCellId, insertionIndex),
+ cellIds: state.cellIds.insertId(newCellId, columnId, insertionIndex),
cellData: {
...state.cellData,
[newCellId]: createCell({
@@ -240,19 +267,24 @@ const {
},
moveCell: (state, action: { cellId: CellId; before: boolean }) => {
const { cellId, before } = action;
- const index = state.cellIds.indexOfOrThrow(cellId);
+ const column = state.cellIds.findWithId(cellId);
+ const cellIndex = column.indexOfOrThrow(cellId);
- if (before && index === 0) {
+ if (before && cellIndex === 0) {
return {
...state,
- cellIds: state.cellIds.moveToFront(cellId),
+ cellIds: state.cellIds.moveWithinColumn(column.id, cellIndex, 0),
scrollKey: cellId,
};
}
- if (!before && index === state.cellIds.length - 1) {
+ if (!before && cellIndex === column.length - 1) {
return {
...state,
- cellIds: state.cellIds.moveToBack(cellId),
+ cellIds: state.cellIds.moveWithinColumn(
+ column.id,
+ cellIndex,
+ column.length - 1,
+ ),
scrollKey: cellId,
};
}
@@ -260,36 +292,109 @@ const {
return before
? {
...state,
- cellIds: state.cellIds.move(index, index - 1),
+ cellIds: state.cellIds.moveWithinColumn(
+ column.id,
+ cellIndex,
+ cellIndex - 1,
+ ),
scrollKey: cellId,
}
: {
...state,
- cellIds: state.cellIds.move(index, index + 1),
+ cellIds: state.cellIds.moveWithinColumn(
+ column.id,
+ cellIndex,
+ cellIndex + 1,
+ ),
scrollKey: cellId,
};
},
- dropCellOver: (state, action: { cellId: CellId; overCellId: CellId }) => {
+ dropCellOverCell: (state, action: { cellId: CellId; overCellId: CellId }) => {
const { cellId, overCellId } = action;
- const fromIndex = state.cellIds.indexOfOrThrow(cellId);
- const toIndex = state.cellIds.indexOfOrThrow(overCellId);
+
+ const fromColumn = state.cellIds.findWithId(cellId);
+ const toColumn = state.cellIds.findWithId(overCellId);
+
+ const fromIndex = fromColumn.indexOfOrThrow(cellId);
+ const toIndex = toColumn.indexOfOrThrow(overCellId);
+
+ if (fromColumn.id === toColumn.id) {
+ if (fromIndex === toIndex) {
+ return state;
+ }
+ return {
+ ...state,
+ cellIds: state.cellIds.moveWithinColumn(
+ fromColumn.id,
+ fromIndex,
+ toIndex,
+ ),
+ scrollKey: null,
+ };
+ }
+
return {
...state,
- cellIds: state.cellIds.move(fromIndex, toIndex),
+ cellIds: state.cellIds.moveAcrossColumns(
+ fromColumn.id,
+ cellId,
+ toColumn.id,
+ overCellId,
+ ),
scrollKey: null,
};
},
+ dropCellOverColumn: (
+ state,
+ action: { cellId: CellId; columnId: CellColumnId },
+ ) => {
+ const { cellId, columnId } = action;
+ const fromColumn = state.cellIds.findWithId(cellId);
+
+ return {
+ ...state,
+ cellIds: state.cellIds.moveAcrossColumns(
+ fromColumn.id,
+ cellId,
+ columnId,
+ undefined,
+ ),
+ };
+ },
+ dropOverNewColumn: (state, action: { cellId: CellId }) => {
+ const { cellId } = action;
+ return {
+ ...state,
+ cellIds: state.cellIds.moveToNewColumn(cellId),
+ };
+ },
+ moveColumn: (
+ state,
+ action: {
+ column: CellColumnId;
+ overColumn: CellColumnId | "_left_" | "_right_";
+ },
+ ) => {
+ if (action.column === action.overColumn) {
+ return state;
+ }
+ return {
+ ...state,
+ cellIds: state.cellIds.moveColumn(action.column, action.overColumn),
+ };
+ },
focusCell: (state, action: { cellId: CellId; before: boolean }) => {
- if (state.cellIds.length === 0) {
+ const column = state.cellIds.findWithId(action.cellId);
+ if (column.length === 0) {
return state;
}
const { cellId, before } = action;
- const index = state.cellIds.indexOfOrThrow(cellId);
+ const index = column.indexOfOrThrow(cellId);
let focusIndex = before ? index - 1 : index + 1;
// clamp
- focusIndex = clamp(focusIndex, 0, state.cellIds.length - 1);
- const focusCellId = state.cellIds.atOrThrow(focusIndex);
+ focusIndex = clamp(focusIndex, 0, column.length - 1);
+ const focusCellId = column.atOrThrow(focusIndex);
// can scroll immediately, without setting scrollKey in state, because
// CellArray won't need to re-render
focusAndScrollCellIntoView({
@@ -302,11 +407,13 @@ const {
return state;
},
focusTopCell: (state) => {
- if (state.cellIds.length === 0) {
+ // TODO: focus the existing column, not the first column
+ const column = state.cellIds.getColumns().at(0);
+ if (column === undefined || column.length === 0) {
return state;
}
- const cellId = state.cellIds.first();
+ const cellId = column.first();
const cellData = state.cellData[cellId];
const cellHandle = state.cellHandles[cellId];
if (!cellData.config.hide_code) {
@@ -316,11 +423,13 @@ const {
return state;
},
focusBottomCell: (state) => {
- if (state.cellIds.length === 0) {
+ // TODO: focus the existing column, not the last column
+ const column = state.cellIds.getColumns().at(-1);
+ if (column === undefined || column.length === 0) {
return state;
}
- const cellId = state.cellIds.last();
+ const cellId = column.last();
const cellData = state.cellData[cellId];
const cellHandle = state.cellHandles[cellId];
if (!cellData.config.hide_code) {
@@ -330,40 +439,111 @@ const {
return state;
},
sendToTop: (state, action: { cellId: CellId }) => {
- if (state.cellIds.length === 0) {
+ const column = state.cellIds.findWithId(action.cellId);
+ if (column.length === 0) {
return state;
}
const { cellId } = action;
- const index = state.cellIds.indexOfOrThrow(cellId);
+ const cellIndex = column.indexOfOrThrow(cellId);
+ if (cellIndex === 0) {
+ return state;
+ }
+
return {
...state,
- cellIds: state.cellIds.move(index, 0),
+ cellIds: state.cellIds.moveWithinColumn(column.id, cellIndex, 0),
scrollKey: cellId,
};
},
sendToBottom: (state, action: { cellId: CellId }) => {
- if (state.cellIds.length === 0) {
+ const column = state.cellIds.findWithId(action.cellId);
+ if (column.length === 0) {
return state;
}
const { cellId } = action;
- const index = state.cellIds.indexOfOrThrow(cellId);
+ const cellIndex = column.indexOfOrThrow(cellId);
+ const newIndex = column.length - 1;
+
+ if (cellIndex === newIndex) {
+ return state;
+ }
+
return {
...state,
- cellIds: state.cellIds.move(index, state.cellIds.length - 1),
+ cellIds: state.cellIds.moveWithinColumn(column.id, cellIndex, newIndex),
scrollKey: cellId,
};
},
+ addColumn: (state, action: { columnId: CellColumnId }) => {
+ // Add column and new cell
+ const newCellId = CellId.create();
+ return {
+ ...state,
+ cellIds: state.cellIds.addColumn(action.columnId, [newCellId]),
+ cellData: {
+ ...state.cellData,
+ [newCellId]: createCell({
+ id: newCellId,
+ }),
+ },
+ cellRuntime: {
+ ...state.cellRuntime,
+ [newCellId]: createCellRuntimeState(),
+ },
+ cellHandles: {
+ ...state.cellHandles,
+ [newCellId]: createRef(),
+ },
+ scrollKey: newCellId,
+ };
+ },
+ addColumnBreakpoint: (state, action: { cellId: CellId }) => {
+ const { cellId } = action;
+ if (state.cellIds.getColumns()[0].inOrderIds[0] === cellId) {
+ return state;
+ }
+ return {
+ ...state,
+ cellIds: state.cellIds.insertBreakpoint(cellId),
+ };
+ },
+ deleteColumn: (state, action: { columnId: CellColumnId }) => {
+ // Move all cells in the column to the previous column
+ const { columnId } = action;
+ return {
+ ...state,
+ cellIds: state.cellIds.delete(columnId),
+ };
+ },
+ mergeAllColumns: (state) => {
+ return {
+ ...state,
+ cellIds: state.cellIds.mergeAllColumns(),
+ };
+ },
+ compactColumns: (state) => {
+ return {
+ ...state,
+ cellIds: state.cellIds.compact(),
+ };
+ },
deleteCell: (state, action: { cellId: CellId }) => {
const cellId = action.cellId;
- if (state.cellIds.length === 1) {
+
+ // Can't delete the last cell, across all columns
+ if (state.cellIds.hasOnlyOneId()) {
return state;
}
- const index = state.cellIds.indexOfOrThrow(cellId);
- const focusIndex = index === 0 ? 1 : index - 1;
- const scrollKey = state.cellIds.atOrThrow(focusIndex);
+ const column = state.cellIds.findWithId(cellId);
+ const cellIndex = column.indexOfOrThrow(cellId);
+ const focusIndex = cellIndex === 0 ? 1 : cellIndex - 1;
+ let scrollKey: CellId | null = null;
+ if (column.length > 1) {
+ scrollKey = column.atOrThrow(focusIndex);
+ }
const editorView = state.cellHandles[cellId].current?.editorView;
const serializedEditorState = editorView?.state.toJSON({
@@ -373,13 +553,14 @@ const {
return {
...state,
- cellIds: state.cellIds.delete(index),
+ cellIds: state.cellIds.deleteById(cellId),
history: [
...state.history,
{
name: state.cellData[cellId].name,
serializedEditorState: serializedEditorState,
- index: index,
+ column: column.id,
+ index: cellIndex,
},
],
scrollKey: scrollKey,
@@ -395,6 +576,7 @@ const {
const {
name,
serializedEditorState = { doc: "" },
+ column,
index,
} = mostRecentlyDeleted;
@@ -409,7 +591,7 @@ const {
return {
...state,
- cellIds: state.cellIds.insert(cellId, index),
+ cellIds: state.cellIds.insertId(cellId, column, index),
cellData: {
...state.cellData,
[cellId]: undoCell,
@@ -531,7 +713,7 @@ const {
return {
...state,
- cellIds: CollapsibleTree.from(action.cellIds),
+ cellIds: MultiColumn.from([action.cellIds]),
cellData: nextCellData,
cellRuntime: nextCellRuntime,
cellHandles: nextCellHandles,
@@ -596,7 +778,9 @@ const {
return withScratchCell({
...state,
- cellIds: CollapsibleTree.from(cells.map((cell) => cell.id)),
+ cellIds: MultiColumn.fromIdsAndColumns(
+ cells.map((cell) => [cell.id, cell.config.column]),
+ ),
cellData: cellData,
cellRuntime: cellRuntime,
cellHandles: Object.fromEntries(
@@ -618,15 +802,16 @@ const {
action: { cellId: CellId; before: boolean; noCreate?: boolean },
) => {
const { cellId, before, noCreate = false } = action;
- const index = state.cellIds.indexOfOrThrow(cellId);
+ const column = state.cellIds.findWithId(cellId);
+ const index = column.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
- if (nextCellIndex === state.cellIds.length && !noCreate) {
+ if (nextCellIndex === column.length && !noCreate) {
const newCellId = CellId.create();
return {
...state,
- cellIds: state.cellIds.insertAtEnd(newCellId),
+ cellIds: state.cellIds.insertId(newCellId, column.id, nextCellIndex),
cellData: {
...state.cellData,
[newCellId]: createCell({ id: newCellId }),
@@ -648,7 +833,7 @@ const {
const newCellId = CellId.create();
return {
...state,
- cellIds: state.cellIds.insertAtStart(newCellId),
+ cellIds: state.cellIds.insertId(newCellId, column.id, 0),
cellData: {
...state.cellData,
[newCellId]: createCell({ id: newCellId }),
@@ -664,7 +849,7 @@ const {
};
}
- const nextCellId = state.cellIds.atOrThrow(nextCellIndex);
+ const nextCellId = column.atOrThrow(nextCellIndex);
// Just focus, no state change
focusAndScrollCellIntoView({
cellId: nextCellId,
@@ -682,15 +867,16 @@ const {
return state;
}
- const index = state.cellIds.indexOfOrThrow(scrollKey);
+ const column = state.cellIds.findWithId(scrollKey);
+ const index = column.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.last();
+ if (index === column.length - 1) {
+ const cellId = column.last();
state.cellHandles[cellId].current?.editorView.focus();
} else {
- const nextCellId = state.cellIds.atOrThrow(index);
+ const nextCellId = column.atOrThrow(index);
focusAndScrollCellIntoView({
cellId: nextCellId,
cell: state.cellHandles[nextCellId],
@@ -727,25 +913,28 @@ const {
},
collapseCell: (state, action: { cellId: CellId }) => {
const { cellId } = action;
+ const column = state.cellIds.findWithId(cellId);
+
// Get all the top-level outlines
- const outlines = state.cellIds.topLevelIds.map((id) => {
+ const outlines = column.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 startIndex = column.indexOfOrThrow(cellId);
const range = findCollapseRange(startIndex, outlines);
-
if (!range) {
return state;
}
- // Get the end of the range
- const endCellId = state.cellIds.atOrThrow(range[1]);
+ const endCellId = column.atOrThrow(range[1]);
return {
...state,
// Collapse the range
- cellIds: state.cellIds.collapse(cellId, endCellId),
+ cellIds: state.cellIds.transformWithCellId(cellId, (column) =>
+ column.collapse(cellId, endCellId),
+ ),
scrollKey: cellId,
};
},
@@ -753,14 +942,17 @@ const {
const { cellId } = action;
return {
...state,
- cellIds: state.cellIds.expand(cellId),
+ cellIds: state.cellIds.transformWithCellId(cellId, (column) =>
+ column.expand(cellId),
+ ),
scrollKey: cellId,
};
},
showCellIfHidden: (state, action: { cellId: CellId }) => {
const { cellId } = action;
- const prev = state.cellIds;
- const result = state.cellIds.findAndExpandDeep(cellId);
+ const column = state.cellIds.findWithId(cellId);
+ const prev = column;
+ const result = column.findAndExpandDeep(cellId);
if (result.equals(prev)) {
return state;
@@ -768,12 +960,13 @@ const {
return {
...state,
- cellIds: result,
+ cellIds: state.cellIds.transformWithCellId(cellId, () => result),
};
},
splitCell: (state, action: { cellId: CellId }) => {
const { cellId } = action;
- const index = state.cellIds.indexOfOrThrow(cellId);
+ const column = state.cellIds.findWithId(cellId);
+ const index = column.indexOfOrThrow(cellId);
const cell = state.cellData[cellId];
const cellHandle = state.cellHandles[cellId].current;
@@ -791,7 +984,7 @@ const {
return {
...state,
- cellIds: state.cellIds.insert(newCellId, index + 1),
+ cellIds: state.cellIds.insertId(newCellId, column.id, index + 1),
cellData: {
...state.cellData,
[cellId]: {
@@ -827,7 +1020,6 @@ const {
const { cellId, snapshot } = action;
const cell = state.cellData[cellId];
- const newCellIndex = state.cellIds.indexOfOrThrow(cellId) + 1;
const cellHandle = state.cellHandles[cellId].current;
if (cellHandle?.editorView == null) {
@@ -838,7 +1030,10 @@ const {
return {
...state,
- cellIds: state.cellIds.delete(newCellIndex),
+ cellIds: state.cellIds.transformWithCellId(cellId, (column) => {
+ const newCellIndex = column.indexOfOrThrow(cellId) + 1;
+ return column.deleteAtIndex(newCellIndex);
+ }),
cellData: {
...state.cellData,
[cellId]: {
@@ -882,6 +1077,7 @@ function updateCellRuntimeState(
},
};
}
+
function updateCellData(
state: NotebookState,
cellId: CellId,
@@ -901,6 +1097,42 @@ function updateCellData(
};
}
+export function getCellConfigs(state: NotebookState): CellConfig[] {
+ const cells = state.cellData;
+
+ // Handle the case where there's only one column
+ // We don't want to set the column config
+ const hasMultipleColumns = state.cellIds.getColumns().length > 1;
+ if (!hasMultipleColumns) {
+ return state.cellIds.getColumns().flatMap((column) => {
+ return column.inOrderIds.map((cellId) => {
+ return {
+ ...cells[cellId].config,
+ column: undefined,
+ };
+ });
+ });
+ }
+
+ return state.cellIds.getColumns().flatMap((column, columnIndex) => {
+ return column.inOrderIds.map((cellId, cellIndex) => {
+ const config: Partial<CellConfig> = { column: undefined };
+
+ // Only set the column index for the first cell in the column
+ if (cellIndex === 0) {
+ config.column = columnIndex;
+ }
+
+ cells[cellId].config = {
+ ...cells[cellId].config,
+ ...config,
+ };
+
+ return cells[cellId].config;
+ });
+ });
+}
+
export {
createActions as createNotebookActions,
reducer as notebookReducer,
@@ -911,7 +1143,9 @@ export {
export const cellIdsAtom = atom((get) => get(notebookAtom).cellIds);
-export const hasOnlyOneCellAtom = atom((get) => get(cellIdsAtom).length === 1);
+export const hasOnlyOneCellAtom = atom((get) =>
+ get(cellIdsAtom).hasOnlyOneId(),
+);
const cellErrorsAtom = atom((get) => {
const { cellIds, cellRuntime, cellData } = get(notebookAtom);
@@ -943,8 +1177,6 @@ const cellErrorsAtom = atom((get) => {
return errors;
});
-export const notebookHasCellsAtom = atom((get) => get(cellIdsAtom).length > 0);
-
export const notebookOutline = atom((get) => {
const { cellIds, cellRuntime } = get(notebookAtom);
const outlines = cellIds.inOrderIds.map(
@@ -1095,17 +1327,19 @@ export function flattenTopLevelNotebookCells(
state: NotebookState,
): Array<CellData & CellRuntimeState> {
const { cellIds, cellData, cellRuntime } = state;
- return cellIds.topLevelIds.map((cellId) => ({
- ...cellData[cellId],
- ...cellRuntime[cellId],
- }));
+ return cellIds.getColumns().flatMap((column) =>
+ column.topLevelIds.map((cellId) => ({
+ ...cellData[cellId],
+ ...cellRuntime[cellId],
+ })),
+ );
}
/**
* Use this hook to dispatch cell actions. This hook will not cause a re-render
* when cells change.
*/
-export function useCellActions() {
+export function useCellActions(): CellActions {
return useActions();
}
@@ -1116,20 +1350,20 @@ export type CellActions = ReturnType<typeof createActions>;
export const CellEffects = {
onCellIdsChange: (
- cellIds: CollapsibleTree<CellId>,
- prevCellIds: CollapsibleTree<CellId>,
+ cellIds: MultiColumn<CellId>,
+ prevCellIds: MultiColumn<CellId>,
) => {
const kioskMode = store.get(kioskModeAtom);
if (kioskMode) {
return;
}
// If cellIds is empty, return early
- if (cellIds.length === 0) {
+ if (cellIds.isEmpty()) {
return;
}
// If prevCellIds is empty, also return early
// this means that the notebook was just created
- if (prevCellIds.length === 0) {
+ if (prevCellIds.isEmpty()) {
return;
}
diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.ts
index 727c1894e4..e551912a0f 100644
--- a/frontend/src/core/cells/utils.ts
+++ b/frontend/src/core/cells/utils.ts
@@ -85,7 +85,8 @@ export function canUndoDeletes(state: NotebookState) {
* Get the status of the descendants of the given cell.
*/
export function getDescendantsStatus(state: NotebookState, cellId: CellId) {
- const descendants = state.cellIds.getDescendants(cellId);
+ const column = state.cellIds.findWithId(cellId);
+ const descendants = column.getDescendants(cellId);
const stale = descendants.some(
(id) => state.cellRuntime[id]?.staleInputs || state.cellData[id]?.edited,
);
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index 840a706855..65d53191e1 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -14,11 +14,16 @@ export const PackageManagerNames = [
] as const;
export type PackageManagerName = (typeof PackageManagerNames)[number];
-export const APP_WIDTHS = ["compact", "medium", "full"] as const;
/**
* normal == compact, but normal is deprecated
*/
-const VALID_APP_WIDTHS = ["normal", ...APP_WIDTHS] as const;
+const VALID_APP_WIDTHS = [
+ "normal",
+ "compact",
+ "medium",
+ "full",
+ "columns",
+] as const;
export const UserConfigSchema = z
.object({
completion: z
@@ -116,6 +121,7 @@ export const UserConfigSchema = z
experimental: z
.object({
markdown: z.boolean().optional(),
+ multi_column: z.boolean().optional(),
// Add new experimental features here
})
// Pass through so that we don't remove any extra keys that the user has added.
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.ts
index 50e058e946..7043bf9cda 100644
--- a/frontend/src/core/config/config.ts
+++ b/frontend/src/core/config/config.ts
@@ -69,3 +69,5 @@ export function useSetAppConfig() {
export function getAppConfig() {
return store.get(appConfigAtom);
}
+
+export const appWidthAtom = atom((get) => get(appConfigAtom).width);
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index 20e9ba4bf9..c07d73f547 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -10,6 +10,7 @@ export interface ExperimentalFeatures {
markdown: boolean;
wasm_layouts: boolean;
scratchpad: boolean;
+ multi_column: boolean;
// Add new feature flags here
}
@@ -17,6 +18,7 @@ const defaultValues: ExperimentalFeatures = {
markdown: true,
wasm_layouts: false,
scratchpad: true,
+ multi_column: import.meta.env.DEV,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
diff --git a/frontend/src/core/config/widths.ts b/frontend/src/core/config/widths.ts
new file mode 100644
index 0000000000..e775ca9614
--- /dev/null
+++ b/frontend/src/core/config/widths.ts
@@ -0,0 +1,8 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { getFeatureFlag } from "./feature-flag";
+
+export function getAppWidths() {
+ return getFeatureFlag("multi_column")
+ ? (["compact", "medium", "full", "columns"] as const)
+ : (["compact", "medium", "full"] as const);
+}
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 117918bded..42e650ae04 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -20,6 +20,7 @@ import {
useNotebook,
CellEffects,
cellIdsAtom,
+ getCellConfigs,
} from "./cells/cells";
import {
canUndoDeletes,
@@ -43,7 +44,6 @@ import { Logger } from "../utils/Logger";
import { useAutoSave } from "./saving/useAutoSave";
import { useEventListener } from "../hooks/useEventListener";
import { toast } from "../components/ui/use-toast";
-import { SortableCellsProvider } from "../components/sort/SortableCellsProvider";
import { CellArray } from "../components/editor/renderers/CellArray";
import { RuntimeState } from "./kernel/RuntimeState";
import { CellsRenderer } from "../components/editor/renderers/cells-renderer";
@@ -63,6 +63,7 @@ import { Paths } from "@/utils/paths";
import { KnownQueryParams } from "./constants";
import { useTogglePresenting } from "./layout/useTogglePresenting";
import { useAutoExport } from "./export/hooks";
+import { usePrevious } from "@dnd-kit/utilities";
interface AppProps {
userConfig: UserConfig;
@@ -74,7 +75,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
useJotaiEffect(cellIdsAtom, CellEffects.onCellIdsChange);
- const { setCells, updateCellCode } = useCellActions();
+ const { setCells, updateCellCode, mergeAllColumns } = useCellActions();
const viewState = useAtomValue(viewStateAtom);
const [filename, setFilename] = useFilename();
const [lastSavedNotebook, setLastSavedNotebook] =
@@ -148,11 +149,20 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
"Untitled Notebook";
}, [appConfig.app_title, filename]);
+ // Delete column breakpoints if app width changes from "columns"
+ const numColumns = notebook.cellIds.colLength;
+ const previousWidth = usePrevious(appConfig.width);
+ useEffect(() => {
+ if (previousWidth === "columns" && appConfig.width !== "columns") {
+ mergeAllColumns();
+ }
+ }, [appConfig.width, previousWidth, mergeAllColumns, numColumns]);
+
const cells = notebookCells(notebook);
const cellIds = cells.map((cell) => cell.id);
const codes = cells.map((cell) => cell.code);
const cellNames = cells.map((cell) => cell.name);
- const configs = cells.map((cell) => cell.config);
+ const configs = getCellConfigs(notebook);
const needsSave = notebookNeedsSave(notebook, layout, lastSavedNotebook);
// Save the notebook with the given filename
@@ -297,7 +307,11 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
>
<AppHeader
connection={connection}
- className={cn("pt-4 sm:pt-12 pb-2 mb-4 print:hidden")}
+ className={cn(
+ "pt-4 sm:pt-12 pb-2 mb-4 print:hidden",
+ // Keep the header sticky when scrolling horizontally, for column mode
+ "sticky left-0",
+ )}
>
{isEditing && (
<div className="flex items-center justify-center container">
@@ -312,9 +326,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
{/* Don't render until we have a single cell */}
{cells.length > 0 && (
<CellsRenderer appConfig={appConfig} mode={viewState.mode}>
- <SortableCellsProvider disabled={!isEditing}>
- {editableCellsArray}
- </SortableCellsProvider>
+ {editableCellsArray}
</CellsRenderer>
)}
</AppContainer>
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index cd3b679d35..76d3ae6f48 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -81,6 +81,11 @@ const DEFAULT_HOT_KEY = {
group: "Creation and Ordering",
key: "Mod-Shift-2",
},
+ "cell.addColumnBreakpoint": {
+ name: "Add column breakpoint",
+ group: "Creation and Ordering",
+ key: "Mod-Shift-3",
+ },
// Running Cells
"cell.run": {
diff --git a/frontend/src/core/islands/components/web-components.tsx b/frontend/src/core/islands/components/web-components.tsx
index 107dad25a5..626f7179fd 100644
--- a/frontend/src/core/islands/components/web-components.tsx
+++ b/frontend/src/core/islands/components/web-components.tsx
@@ -40,7 +40,9 @@ 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);
- return cellIds.atOrThrow(idx);
+ const cellId = cellIds.inOrderIds.at(idx);
+ invariant(cellId, "Missing cell ID");
+ return cellId;
}
get code(): string {
diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.css
index 2f18c28fcb..a505ea8154 100644
--- a/frontend/src/css/app/Cell.css
+++ b/frontend/src/css/app/Cell.css
@@ -199,7 +199,7 @@
justify-content: flex-end;
height: 100%;
position: absolute;
- right: -94px;
+ right: -90px;
width: 80px;
gap: 4px;
}
@@ -286,7 +286,7 @@
:root {
/* Set a fixed gutter width to ensure the hover area is always wide enough */
/* And make the gutter bigger when the window is super wide */
- --gutter-width: max(calc(50vw - (var(--content-width) / 2)), 50px);
+ --gutter-width: 100px;
}
/* ------------------------ CodeMirror Editor ----------------------------- */
@@ -302,7 +302,7 @@
.Cell .cm-editor {
border: 1px solid transparent;
padding: 3px;
- padding-right:24px;
+ padding-right: 24px;
&.cm-focused {
.cm-activeLineGutter {
diff --git a/frontend/src/css/common.css b/frontend/src/css/common.css
index affa3dd779..7ee48e9a1c 100644
--- a/frontend/src/css/common.css
+++ b/frontend/src/css/common.css
@@ -5,6 +5,12 @@
.hover-action {
display: none !important;
}
+
+ [data-is-dragging='true'] {
+ .hover-actions-parent.hover-actions-parent .hover-action:not(:hover) {
+ display: none !important;
+ }
+ }
}
.hover-action:hover,
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index 3fcc0c70eb..87195b4c8c 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -55,6 +55,7 @@ const props: CellProps = {
updateCellConfig: Logger.log,
setStdinResponse: Logger.log,
clearSerializedEditorState: Logger.log,
+ canMoveX: false,
config: {
hide_code: false,
disabled: false,
diff --git a/frontend/src/theme/namespace.tsx b/frontend/src/theme/namespace.tsx
index f990741588..b9c612d395 100644
--- a/frontend/src/theme/namespace.tsx
+++ b/frontend/src/theme/namespace.tsx
@@ -9,10 +9,15 @@ const style = {
* Adds the 'marimo' className which serves as a namespace to its children,
* so that the styles are scoped to the DOM subtree.
*/
-export const StyleNamespace: React.FC<PropsWithChildren> = ({ children }) => {
+export const StyleNamespace = React.forwardRef<
+ HTMLDivElement,
+ PropsWithChildren<{}>
+>(({ children }, ref) => {
return (
- <div className="marimo" style={style}>
+ <div ref={ref} className="marimo" style={style}>
{children}
</div>
);
-};
+});
+
+StyleNamespace.displayName = "StyleNamespace";
diff --git a/frontend/src/utils/__tests__/id-tree.test.ts b/frontend/src/utils/__tests__/id-tree.test.ts
index 95261b82fb..e6a8a812db 100644
--- a/frontend/src/utils/__tests__/id-tree.test.ts
+++ b/frontend/src/utils/__tests__/id-tree.test.ts
@@ -1,19 +1,18 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, it, expect } from "vitest";
-import { TreeNode, CollapsibleTree } from "../id-tree";
+import {
+ CollapsibleTree,
+ MultiColumn,
+ type CellColumnId,
+ type CellIndex,
+} 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);
+ tree = CollapsibleTree.from(["one", "two", "three", "four"]);
});
it("initializes correctly", () => {
@@ -294,7 +293,7 @@ describe("CollapsibleTree", () => {
four
"
`);
- tree = tree.delete(1);
+ tree = tree.deleteAtIndex(1);
expect(tree.toString()).toMatchInlineSnapshot(`
"one
three (collapsed)
@@ -304,7 +303,7 @@ describe("CollapsibleTree", () => {
});
it("fails to delete nodes", () => {
- expect(() => tree.delete(5)).toThrowErrorMatchingInlineSnapshot(
+ expect(() => tree.deleteAtIndex(5)).toThrowErrorMatchingInlineSnapshot(
"[Error: Node at index 5 not found in tree]",
);
});
@@ -402,4 +401,646 @@ describe("CollapsibleTree", () => {
// We only get descendants of the top level
expect(tree.getDescendants("three")).toMatchInlineSnapshot("[]");
});
+
+ it("handles split correctly", () => {
+ const [left, right] = tree.split("two");
+ expect(left.toString()).toMatchInlineSnapshot(`
+ "one
+ "
+ `);
+ expect(right?.toString()).toMatchInlineSnapshot(`
+ "two
+ three
+ four
+ "
+ `);
+ });
+
+ it("handles split at the beginning", () => {
+ const [left, right] = tree.split("one");
+ expect(left.toString()).toMatchInlineSnapshot(`
+ ""
+ `);
+ expect(right?.toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three
+ four
+ "
+ `);
+ });
+
+ it("handles split at the end", () => {
+ const [left, right] = tree.split("four");
+ expect(left.toString()).toMatchInlineSnapshot(`
+ "one
+ two
+ three
+ "
+ `);
+ expect(right?.toString()).toMatchInlineSnapshot(`
+ "four
+ "
+ `);
+ });
+
+ it("throws when splitting on non-existent node", () => {
+ expect(() => tree.split("five")).toThrow("Node five not found in tree");
+ });
+});
+
+describe("CollapsibleTree edge cases", () => {
+ let tree: CollapsibleTree<string>;
+
+ beforeEach(() => {
+ tree = CollapsibleTree.from(["A", "B", "C", "D"]);
+ });
+
+ it("handles insert at start and end", () => {
+ tree = tree.insertAtStart("Z");
+ expect(tree.topLevelIds).toEqual(["Z", "A", "B", "C", "D"]);
+ tree = tree.insertAtEnd("Y");
+ expect(tree.topLevelIds).toEqual(["Z", "A", "B", "C", "D", "Y"]);
+ });
+
+ it("handles delete with expand", () => {
+ tree = tree.collapse("B", "D");
+ tree = tree.deleteAtIndex(1);
+ expect(tree.topLevelIds).toEqual(["A", "C", "D"]);
+ });
+
+ it("finds nodes correctly", () => {
+ tree = tree.collapse("B", "D");
+ expect(tree.find("C")).toEqual(["B", "C"]);
+ expect(tree.find("E")).toEqual([]);
+ });
+
+ it("handles equality check", () => {
+ const tree2 = CollapsibleTree.from(["A", "B", "C", "D"]);
+ expect(tree.equals(tree2)).toBe(true);
+ tree2.collapse("B", "C");
+ expect(tree.equals(tree2)).toBe(true);
+ });
+
+ it("handles getCount correctly", () => {
+ tree = tree.collapse("B", "D");
+ expect(tree.getCount("A")).toBe(0);
+ expect(tree.getCount("B")).toBe(2);
+ expect(tree.getCount("C")).toBe(0);
+ });
+
+ it("handles findAndExpandDeep", () => {
+ tree = tree.collapse("B", "D");
+ tree = tree.findAndExpandDeep("C");
+ expect(tree.topLevelIds).toEqual(["A", "B", "C", "D"]);
+ });
+
+ it("handles multiple collapses and expands", () => {
+ tree = tree.collapse("B", "C").collapse("A", "D");
+ expect(tree.topLevelIds).toEqual(["A"]);
+ tree = tree.expand("A").expand("B");
+ expect(tree.topLevelIds).toEqual(["A", "B", "C", "D"]);
+ });
+
+ it("handles edge cases for first and last", () => {
+ expect(tree.first()).toBe("A");
+ expect(tree.last()).toBe("D");
+ tree = CollapsibleTree.from([]);
+ expect(() => tree.first()).toThrow();
+ expect(() => tree.last()).toThrow();
+ });
+
+ it("handles inOrderIds with nested structure", () => {
+ tree = tree.collapse("B", "C");
+ expect(tree.inOrderIds).toEqual(["A", "B", "C", "D"]);
+ });
+
+ it("handles moving within bounds", () => {
+ tree = tree.move(0, 2);
+ expect(tree.topLevelIds).toEqual(["B", "C", "A", "D"]);
+ });
+
+ it("handles moving out of bounds", () => {
+ tree = tree.move(0, 10);
+ expect(tree.topLevelIds).toEqual(["B", "C", "D", "A"]);
+ });
+});
+
+describe("MultiColumn", () => {
+ let multiColumn: MultiColumn<string>;
+ let columnIds: CellColumnId[];
+
+ beforeEach(() => {
+ multiColumn = MultiColumn.from([
+ ["A1", "A2", "A3"],
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+
+ columnIds = multiColumn.getColumns().map((c) => c.id);
+ });
+
+ it("initializes correctly", () => {
+ expect(multiColumn.colLength).toBe(3);
+ expect(multiColumn.idLength).toBe(9);
+ expect(multiColumn.topLevelIds).toEqual([
+ ["A1", "A2", "A3"],
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("creates from empty array", () => {
+ const emptyMultiColumn = MultiColumn.from([]);
+ expect(emptyMultiColumn.colLength).toBe(1);
+ expect(emptyMultiColumn.idLength).toBe(0);
+ expect(emptyMultiColumn.isEmpty()).toBe(true);
+ });
+
+ it("creates from ids and columns", () => {
+ const idAndColumns: Array<[string, number | undefined | null]> = [
+ ["A1", 0],
+ ["A2", 0],
+ ["B1", 1],
+ ["C1", 2],
+ ["C2", undefined],
+ ["D1", null],
+ ["E1", -1],
+ ];
+ const fromIdsAndColumns = MultiColumn.fromIdsAndColumns(idAndColumns);
+ expect(fromIdsAndColumns.colLength).toBe(3);
+ expect(fromIdsAndColumns.topLevelIds).toEqual([
+ ["A1", "A2"],
+ ["B1"],
+ ["C1", "C2", "D1", "E1"],
+ ]);
+ });
+
+ it("iterates top-level ids", () => {
+ const ids = [...multiColumn.iterateTopLevelIds];
+ expect(ids).toEqual(["A1", "A2", "A3", "B1", "B2", "C1", "C2", "C3", "C4"]);
+ });
+
+ it("gets in-order ids", () => {
+ expect(multiColumn.inOrderIds).toEqual([
+ "A1",
+ "A2",
+ "A3",
+ "B1",
+ "B2",
+ "C1",
+ "C2",
+ "C3",
+ "C4",
+ ]);
+ });
+
+ it("checks if it has only one column", () => {
+ expect(multiColumn.hasOnlyOneColumn()).toBe(false);
+ const singleColumn = MultiColumn.from([["A1", "A2"]]);
+ expect(singleColumn.hasOnlyOneColumn()).toBe(true);
+ });
+
+ it("checks if it has only one id", () => {
+ expect(multiColumn.hasOnlyOneId()).toBe(false);
+ const singleId = MultiColumn.from([["A1"], ["B1"], ["C1"]]);
+ expect(singleId.hasOnlyOneId()).toBe(false);
+ const singleIdSingleColumn = MultiColumn.from([["A1"]]);
+ expect(singleIdSingleColumn.hasOnlyOneId()).toBe(true);
+ });
+
+ it("adds a column", () => {
+ const columnId = multiColumn.getColumns()[0].id;
+ const newMultiColumn = multiColumn.addColumn(columnId);
+ expect(newMultiColumn.colLength).toBe(4);
+ expect(newMultiColumn.topLevelIds[1]).toEqual([]);
+ });
+
+ it("inserts a breakpoint", () => {
+ const withBreakpoint = multiColumn.insertBreakpoint("C3");
+ expect(withBreakpoint.colLength).toBe(4);
+ expect(withBreakpoint.topLevelIds).toEqual([
+ ["A1", "A2", "A3"],
+ ["B1", "B2"],
+ ["C1", "C2"],
+ ["C3", "C4"],
+ ]);
+ });
+
+ it("deletes a column", () => {
+ const withoutBreakpoint = multiColumn.delete(columnIds[1]);
+ expect(withoutBreakpoint.colLength).toBe(2);
+ expect(withoutBreakpoint.topLevelIds).toEqual([
+ ["A1", "A2", "A3", "B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("deletes a column with only one column", () => {
+ const singleColumn = MultiColumn.from([["A1", "A2"]]);
+ const deleted = singleColumn.delete(columnIds[0]);
+ expect(deleted.colLength).toBe(1);
+ expect(deleted.topLevelIds).toEqual([["A1", "A2"]]);
+ });
+
+ it("deletes the first column", () => {
+ const deleted = multiColumn.delete(columnIds[0]);
+ expect(deleted.colLength).toBe(2);
+ expect(deleted.topLevelIds).toEqual([
+ ["B1", "B2", "A1", "A2", "A3"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("merges all columns", () => {
+ const merged = multiColumn.mergeAllColumns();
+ expect(merged.colLength).toBe(1);
+ expect(merged.topLevelIds).toEqual([
+ ["A1", "A2", "A3", "B1", "B2", "C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("moves within a column", () => {
+ const moved = multiColumn.moveWithinColumn(
+ columnIds[0],
+ 0 as CellIndex,
+ 2 as CellIndex,
+ );
+ expect(moved.topLevelIds[0]).toEqual(["A2", "A3", "A1"]);
+ });
+
+ it("moves across columns", () => {
+ const moved = multiColumn.moveAcrossColumns(
+ columnIds[0],
+ "A1",
+ columnIds[1],
+ "B1",
+ );
+ expect(moved.topLevelIds).toEqual([
+ ["A2", "A3"],
+ ["A1", "B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("moves a column", () => {
+ const moved = multiColumn.moveColumn(columnIds[0], columnIds[2]);
+ expect(moved.topLevelIds).toEqual([
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ["A1", "A2", "A3"],
+ ]);
+ });
+
+ it("moves a column before", () => {
+ const moved = multiColumn.moveColumn(columnIds[1], columnIds[0]);
+ expect(moved.topLevelIds).toEqual([
+ ["B1", "B2"],
+ ["A1", "A2", "A3"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("moves to the left", () => {
+ const moved = multiColumn.moveColumn(columnIds[1], "_left_");
+ expect(moved.topLevelIds).toEqual([
+ ["B1", "B2"],
+ ["A1", "A2", "A3"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("moves to the right", () => {
+ const moved = multiColumn.moveColumn(columnIds[1], "_right_");
+ expect(moved.topLevelIds).toEqual([
+ ["A1", "A2", "A3"],
+ ["C1", "C2", "C3", "C4"],
+ ["B1", "B2"],
+ ]);
+ });
+
+ it("moves to a new column", () => {
+ const newColumn = multiColumn.moveToNewColumn("B1");
+ expect(newColumn.colLength).toBe(4);
+ expect(newColumn.topLevelIds).toEqual([
+ ["A1", "A2", "A3"],
+ ["B2"],
+ ["C1", "C2", "C3", "C4"],
+ ["B1"],
+ ]);
+ });
+
+ it("gets column with id", () => {
+ const column = multiColumn.findWithId("B2");
+ expect(multiColumn.indexOf(column)).toBe(1);
+ expect(column.topLevelIds).toEqual(["B1", "B2"]);
+ });
+
+ it("transforms by id", () => {
+ const transformed = multiColumn.transformWithCellId("B1", (tree) =>
+ tree.moveToFront("B2"),
+ );
+ expect(transformed.topLevelIds[1]).toEqual(["B2", "B1"]);
+ });
+
+ it("inserts an id", () => {
+ const inserted = multiColumn.insertId("D1", columnIds[1], 1 as CellIndex);
+ expect(inserted.topLevelIds[1]).toEqual(["B1", "D1", "B2"]);
+ });
+
+ it("deletes by id", () => {
+ const deleted = multiColumn.deleteById("B1");
+ expect(deleted.topLevelIds[1]).toEqual(["B2"]);
+ });
+
+ it("compacts", () => {
+ const withEmpty = MultiColumn.from([["A1"], [], ["C1"], []]);
+ const compacted = withEmpty.compact();
+ expect(compacted.colLength).toBe(2);
+ expect(compacted.topLevelIds).toEqual([["A1"], ["C1"]]);
+ });
+
+ it("handles errors", () => {
+ expect(() => multiColumn.findWithId("Z1")).toThrow(
+ "Cell Z1 not found in any column",
+ );
+ expect(multiColumn.colLength).toBeGreaterThan(2);
+ expect(() => multiColumn.delete("123" as CellColumnId)).toThrow();
+ });
+
+ it("checks if it's empty", () => {
+ expect(multiColumn.isEmpty()).toBe(false);
+ const emptyMultiColumn = MultiColumn.from([[]]);
+ expect(emptyMultiColumn.isEmpty()).toBe(true);
+ });
+
+ it("gets columns", () => {
+ const columns = multiColumn.getColumns();
+ expect(columns.length).toBe(3);
+ expect(columns[0].topLevelIds).toEqual(["A1", "A2", "A3"]);
+ });
+
+ it("gets index of a column", () => {
+ const column = multiColumn.atOrThrow(1);
+ const index = multiColumn.indexOf(column);
+ expect(index).toBe(1);
+ });
+
+ it("handles at and atOrThrow", () => {
+ expect(multiColumn.at(1)?.topLevelIds).toEqual(["B1", "B2"]);
+ expect(multiColumn.atOrThrow(1).topLevelIds).toEqual(["B1", "B2"]);
+ expect(multiColumn.at(5)).toBeUndefined();
+ expect(() => multiColumn.atOrThrow(5)).toThrow();
+ });
+
+ it("handles moving the last item in a column", () => {
+ const multiColumn = MultiColumn.from([["A1", "A2"], ["B1"]]);
+ const columnIds = multiColumn.getColumns().map((c) => c.id);
+ const moved = multiColumn.moveAcrossColumns(
+ columnIds[1],
+ "B1",
+ columnIds[0],
+ "A2",
+ );
+ expect(moved.topLevelIds).toEqual([["A1", "B1", "A2"], []]);
+ expect(moved.colLength).toBe(2);
+ });
+
+ it("handles moving all items from a column", () => {
+ const multiColumn = MultiColumn.from([
+ ["A1", "A2"],
+ ["B1", "B2"],
+ ]);
+ const columnIds = multiColumn.getColumns().map((c) => c.id);
+ let moved = multiColumn.moveAcrossColumns(
+ columnIds[1],
+ "B1",
+ columnIds[0],
+ "A2",
+ );
+ moved = moved.moveAcrossColumns(columnIds[1], "B2", columnIds[0], "A2");
+ expect(moved.topLevelIds).toEqual([["A1", "B1", "B2", "A2"], []]);
+ expect(moved.colLength).toBe(2);
+ });
+
+ it("handles inserting at out-of-bounds indices", () => {
+ const multiColumn = MultiColumn.from([["A1"], ["B1"]]);
+ const columnId = multiColumn.atOrThrow(1).id;
+ const inserted = multiColumn.insertId("C1", columnId, 10 as CellIndex);
+ expect(inserted.topLevelIds).toEqual([["A1"], ["B1", "C1"]]);
+ });
+
+ it("handles collapsing and expanding in multi-column setup", () => {
+ let multiColumn = MultiColumn.from([
+ ["A1", "A2", "A3"],
+ ["B1", "B2"],
+ ]);
+ multiColumn = multiColumn.transformWithCellId("A1", (tree) =>
+ tree.collapse("A1", "A3"),
+ );
+ expect(multiColumn.topLevelIds).toEqual([["A1"], ["B1", "B2"]]);
+ multiColumn = multiColumn.transformWithCellId("A1", (tree) =>
+ tree.expand("A1"),
+ );
+ expect(multiColumn.topLevelIds).toEqual([
+ ["A1", "A2", "A3"],
+ ["B1", "B2"],
+ ]);
+ });
+
+ it("handles moving a column to its own position", () => {
+ const multiColumn = MultiColumn.from([["A1"], ["B1"], ["C1"]]);
+ const moved = multiColumn.moveColumn(columnIds[1], columnIds[1]);
+ expect(moved.topLevelIds).toEqual([["A1"], ["B1"], ["C1"]]);
+ });
+
+ it("handles compacting when all columns are empty", () => {
+ const multiColumn = MultiColumn.from([[], [], []]);
+ const compacted = multiColumn.compact();
+ expect(compacted.colLength).toBe(1);
+ expect(compacted.isEmpty()).toBe(true);
+ });
+
+ it("handles transformById when id is not found", () => {
+ const multiColumn = MultiColumn.from([["A1"], ["B1"]]);
+ const transformed = multiColumn.transformWithCellId("C1", (tree) =>
+ tree.insertAtEnd("C2"),
+ );
+ expect(transformed).toBe(multiColumn);
+ });
+
+ it("handles nested collapses and expands", () => {
+ let multiColumn = MultiColumn.from([["A1", "A2", "A3", "A4", "A5"]]);
+ multiColumn = multiColumn.transformWithCellId("A1", (tree) =>
+ tree.collapse("A2", "A4"),
+ );
+ multiColumn = multiColumn.transformWithCellId("A1", (tree) =>
+ tree.collapse("A1", undefined),
+ );
+ expect(multiColumn.topLevelIds).toEqual([["A1"]]);
+ multiColumn = multiColumn.transformWithCellId("A1", (tree) =>
+ tree.expand("A1"),
+ );
+ expect(multiColumn.topLevelIds).toEqual([["A1", "A2", "A5"]]);
+ multiColumn = multiColumn.transformWithCellId("A1", (tree) =>
+ tree.expand("A2"),
+ );
+ expect(multiColumn.topLevelIds).toEqual([["A1", "A2", "A3", "A4", "A5"]]);
+ });
+
+ it("handles moving to a new column when it's the last item", () => {
+ let multiColumn = MultiColumn.from([["A1"], ["B1"]]);
+ multiColumn = multiColumn.moveToNewColumn("B1");
+ expect(multiColumn.colLength).toBe(3);
+ expect(multiColumn.topLevelIds).toEqual([["A1"], [], ["B1"]]);
+ });
+
+ it("handles deleting the last item in a column", () => {
+ let multiColumn = MultiColumn.from([["A1"], ["B1"], ["C1"]]);
+ multiColumn = multiColumn.deleteById("B1");
+ expect(multiColumn.colLength).toBe(3);
+ expect(multiColumn.topLevelIds).toEqual([["A1"], [], ["C1"]]);
+ });
+
+ it("handles multiple operations in sequence", () => {
+ let multiColumn = MultiColumn.from([
+ ["A1", "A2"],
+ ["B1", "B2"],
+ ["C1", "C2"],
+ ]);
+ const columnIds = multiColumn.getColumns().map((c) => c.id);
+ multiColumn = multiColumn.moveAcrossColumns(
+ columnIds[0],
+ "A2",
+ columnIds[1],
+ "B1",
+ );
+ expect(multiColumn.topLevelIds).toEqual([
+ ["A1"],
+ ["A2", "B1", "B2"],
+ ["C1", "C2"],
+ ]);
+ multiColumn = multiColumn.insertId("D1", columnIds[2], 1 as CellIndex);
+ expect(multiColumn.topLevelIds).toEqual([
+ ["A1"],
+ ["A2", "B1", "B2"],
+ ["C1", "D1", "C2"],
+ ]);
+ multiColumn = multiColumn.deleteById("B1");
+ expect(multiColumn.topLevelIds).toEqual([
+ ["A1"],
+ ["A2", "B2"],
+ ["C1", "D1", "C2"],
+ ]);
+ multiColumn = multiColumn.moveColumn(columnIds[0], columnIds[2]);
+ expect(multiColumn.topLevelIds).toEqual([
+ ["A2", "B2"],
+ ["C1", "D1", "C2"],
+ ["A1"],
+ ]);
+ multiColumn = multiColumn.compact();
+ expect(multiColumn.topLevelIds).toEqual([
+ ["A2", "B2"],
+ ["C1", "D1", "C2"],
+ ["A1"],
+ ]);
+ });
+
+ it("handles get method", () => {
+ const column = multiColumn.get(columnIds[1]);
+ expect(column?.topLevelIds).toEqual(["B1", "B2"]);
+ });
+
+ it("handles get method with non-existent column id", () => {
+ const column = multiColumn.get("non-existent-id" as CellColumnId);
+ expect(column).toBeUndefined();
+ });
+
+ it("handles indexOfOrThrow method", () => {
+ expect(multiColumn.indexOfOrThrow(columnIds[1])).toBe(1);
+ });
+
+ it("handles indexOfOrThrow method with non-existent column id", () => {
+ expect(() =>
+ multiColumn.indexOfOrThrow("non-existent-id" as CellColumnId),
+ ).toThrow("Column non-existent-id not found. Possible values: ");
+ });
+
+ it("handles transform method", () => {
+ const transformed = multiColumn.transform(columnIds[1], (tree) =>
+ tree.moveToFront("B2"),
+ );
+ expect(transformed.topLevelIds[1]).toEqual(["B2", "B1"]);
+ });
+
+ it("handles transform method with non-existent column id", () => {
+ const transformed = multiColumn.transform(
+ "non-existent-id" as CellColumnId,
+ (tree) => tree.moveToFront("B2"),
+ );
+ const columns1 = multiColumn.getColumns();
+ const columns2 = transformed.getColumns();
+ const allEqual = columns1.every((c, i) => c.equals(columns2[i]));
+ expect(allEqual).toBe(true);
+ });
+
+ it("handles moving across columns with undefined toId", () => {
+ const moved = multiColumn.moveAcrossColumns(
+ columnIds[0],
+ "A1",
+ columnIds[1],
+ undefined,
+ );
+ expect(moved.topLevelIds).toEqual([
+ ["A2", "A3"],
+ ["A1", "B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("handles moving across columns to an empty column", () => {
+ const emptyColumnMultiColumn = multiColumn
+ .deleteById("B1")
+ .deleteById("B2");
+ const moved = emptyColumnMultiColumn.moveAcrossColumns(
+ columnIds[0],
+ "A1",
+ columnIds[1],
+ undefined,
+ );
+ expect(moved.topLevelIds).toEqual([
+ ["A2", "A3"],
+ ["A1"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("handles inserting a breakpoint at the start of a column", () => {
+ const withBreakpoint = multiColumn.insertBreakpoint("A1");
+ expect(withBreakpoint.colLength).toBe(4);
+ expect(withBreakpoint.topLevelIds).toEqual([
+ [],
+ ["A1", "A2", "A3"],
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("handles inserting a breakpoint at the end of a column", () => {
+ const withBreakpoint = multiColumn.insertBreakpoint("A3");
+ expect(withBreakpoint.colLength).toBe(4);
+ expect(withBreakpoint.topLevelIds).toEqual([
+ ["A1", "A2"],
+ ["A3"],
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("handles inserting a breakpoint in a single-item column", () => {
+ const singleItemColumn = MultiColumn.from([["A1"], ["B1"], ["C1"]]);
+ const withBreakpoint = singleItemColumn.insertBreakpoint("B1");
+ expect(withBreakpoint.colLength).toBe(4);
+ expect(withBreakpoint.topLevelIds).toEqual([["A1"], [], ["B1"], ["C1"]]);
+ });
});
diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.ts
index a13042056e..99d00e0c5b 100644
--- a/frontend/src/utils/arrays.ts
+++ b/frontend/src/utils/arrays.ts
@@ -1,14 +1,21 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { invariant } from "./invariant";
+import { clamp } from "./math";
export function arrayDelete<T>(array: T[], index: number): T[] {
return [...array.slice(0, index), ...array.slice(index + 1)];
}
export function arrayInsert<T>(array: T[], index: number, value: T): T[] {
+ index = clamp(index, 0, array.length);
return arrayInsertMany(array, index, [value]);
}
+export function arrayMove<T>(array: T[], from: number, to: number): T[] {
+ const value = array[from];
+ return arrayInsertMany(arrayDelete(array, from), to, [value]);
+}
+
export function arrayInsertMany<T>(
array: T[],
index: number,
@@ -17,6 +24,8 @@ export function arrayInsertMany<T>(
if (array.length === 0) {
return values;
}
+ // Clamp index to the end of the array
+ index = clamp(index, 0, array.length);
return [...array.slice(0, index), ...values, ...array.slice(index)];
}
diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx
index 9eb59a3853..0c7f279488 100644
--- a/frontend/src/utils/id-tree.tsx
+++ b/frontend/src/utils/id-tree.tsx
@@ -1,10 +1,23 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { arrayMove } from "@dnd-kit/sortable";
-import { arrayDelete, arrayInsert, arrayInsertMany } from "./arrays";
+import { arrayDelete, arrayInsert, arrayInsertMany, arrayMove } from "./arrays";
import { Memoize } from "typescript-memoize";
import { Logger } from "./Logger";
+/**
+ * Branded number to help with type safety
+ */
+export type CellColumnIndex = number & { __brand: "CellColumnIndex" };
+
+/**
+ * Branded string to help with type safety
+ */
+export type CellColumnId = string & { __brand: "CellColumnId" };
+/**
+ * Weakly-branded number, since making `__brand` required causes type errors
+ */
+export type CellIndex = number & { __brand?: "CellIndex" };
+
/**
* Tree data structure for handling ids with nested children
*/
@@ -45,11 +58,24 @@ export class TreeNode<T> {
}
}
+let uniqueId = 0;
+
export class CollapsibleTree<T> {
- constructor(public nodes: Array<TreeNode<T>>) {}
+ private constructor(
+ public readonly nodes: Array<TreeNode<T>>,
+ public readonly id: CellColumnId,
+ ) {}
static from<T>(ids: T[]): CollapsibleTree<T> {
- return new CollapsibleTree(ids.map((id) => new TreeNode(id, false, [])));
+ const id = `tree_${uniqueId++}` as CellColumnId;
+ return new CollapsibleTree(
+ ids.map((id) => new TreeNode(id, false, [])),
+ id,
+ );
+ }
+
+ withNodes(nodes: Array<TreeNode<T>>): CollapsibleTree<T> {
+ return new CollapsibleTree(nodes, this.id);
}
get topLevelIds(): T[] {
@@ -100,14 +126,14 @@ export class CollapsibleTree<T> {
/**
* Get the index of the given node, or throw
*/
- indexOfOrThrow(id: T): number {
+ indexOfOrThrow(id: T): CellIndex {
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;
+ return index as CellIndex;
}
/**
@@ -115,7 +141,7 @@ export class CollapsibleTree<T> {
*/
moveToFront(id: T): CollapsibleTree<T> {
const index = this.indexOfOrThrow(id);
- return new CollapsibleTree(arrayMove(this.nodes, index, 0));
+ return this.withNodes(arrayMove(this.nodes, index, 0));
}
/**
@@ -123,9 +149,7 @@ export class CollapsibleTree<T> {
*/
moveToBack(id: T): CollapsibleTree<T> {
const index = this.indexOfOrThrow(id);
- return new CollapsibleTree(
- arrayMove(this.nodes, index, this.nodes.length - 1),
- );
+ return this.withNodes(arrayMove(this.nodes, index, this.nodes.length - 1));
}
/**
@@ -162,7 +186,7 @@ export class CollapsibleTree<T> {
const children = nodes.splice(nodeIndex + 1, untilIndex - nodeIndex);
nodes[nodeIndex] = new TreeNode(node.value, true, children);
- return new CollapsibleTree(nodes);
+ return this.withNodes(nodes);
}
/**
@@ -185,15 +209,14 @@ export class CollapsibleTree<T> {
nodes[nodeIndex] = new TreeNode(node.value, false, []);
nodes = arrayInsertMany(nodes, nodeIndex + 1, node.children);
- return new CollapsibleTree(nodes);
+ return this.withNodes(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);
+ return this.withNodes(arrayMove(this.nodes, fromIdx, toIdx));
}
/**
@@ -232,8 +255,9 @@ export class CollapsibleTree<T> {
* 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);
+ return this.withNodes(
+ arrayInsert(this.nodes, index, new TreeNode(id, false, [])),
+ );
}
/**
@@ -253,15 +277,20 @@ export class CollapsibleTree<T> {
/**
* Delete a node, expand if it was collapsed
*/
- delete(idx: number): CollapsibleTree<T> {
+ deleteAtIndex(idx: number): CollapsibleTree<T> {
const id = this.atOrThrow(idx);
- let tree = new CollapsibleTree(this.nodes);
+ let tree = this.withNodes(this.nodes);
try {
tree = tree.expand(id);
} catch {
// Don't care if its not expanded
}
- return new CollapsibleTree(arrayDelete(tree.nodes, idx));
+ return this.withNodes(arrayDelete(tree.nodes, idx));
+ }
+
+ delete(id: T): CollapsibleTree<T> {
+ const index = this.indexOfOrThrow(id);
+ return this.deleteAtIndex(index);
}
/**
@@ -279,7 +308,7 @@ export class CollapsibleTree<T> {
if (found.length === 0) {
return this;
}
- let result = new CollapsibleTree<T>(this.nodes);
+ let result = this.withNodes(this.nodes);
for (const node of found) {
try {
result = result.expand(node);
@@ -313,6 +342,26 @@ export class CollapsibleTree<T> {
return findNode(this.nodes, []);
}
+ /**
+ * Split the tree into two trees
+ * @param id the id of the node to split at
+ * @returns a tuple of the left and right trees
+ */
+ split(id: T): [CollapsibleTree<T>, CollapsibleTree<T> | undefined] {
+ const index = this.nodes.findIndex((n) => n.value === id);
+ if (index === -1) {
+ throw new Error(`Node ${id} not found in tree`);
+ }
+ const leftNodes = this.nodes.slice(0, index);
+ const rightNodes = this.nodes.slice(index);
+ if (leftNodes.length === 0) {
+ return [CollapsibleTree.from<T>([]), this.withNodes(rightNodes)];
+ }
+ const left = this.withNodes(leftNodes);
+ const right = CollapsibleTree.from<T>([]).withNodes(rightNodes);
+ return [left, right];
+ }
+
equals(other: CollapsibleTree<T>): boolean {
return (
this.nodes.length === other.nodes.length &&
@@ -335,3 +384,344 @@ export class CollapsibleTree<T> {
return result;
}
}
+
+export class MultiColumn<T> {
+ constructor(private readonly columns: ReadonlyArray<CollapsibleTree<T>>) {
+ // Ensure there is always at least one column
+ if (columns.length === 0) {
+ this.columns = [CollapsibleTree.from([])];
+ }
+ }
+
+ static from<T>(idsList: T[][]): MultiColumn<T> {
+ return new MultiColumn(idsList.map((ids) => CollapsibleTree.from(ids)));
+ }
+
+ isEmpty(): boolean {
+ if (this.columns.length === 0) {
+ return true;
+ }
+ return this.columns.every((c) => c.nodes.length === 0);
+ }
+
+ static fromIdsAndColumns<T>(
+ idAndColumns: Array<[T, number | undefined | null]>,
+ ): MultiColumn<T> {
+ // If column is undefined, use the previous column
+ // Ensure there is always at least one column
+ const numColumns = Math.max(
+ 1,
+ ...idAndColumns.map(([_, column]) => (column ?? 0) + 1),
+ );
+ const idsList: T[][] = Array.from({ length: numColumns }, () => []);
+
+ let prevColumn = 0;
+ for (const [id, column] of idAndColumns) {
+ // Avoid negative column indices
+ if (column === undefined || column === null || column < 0) {
+ idsList[prevColumn].push(id);
+ } else {
+ idsList[column].push(id);
+ prevColumn = column;
+ }
+ }
+
+ return MultiColumn.from(idsList);
+ }
+
+ get topLevelIds(): T[][] {
+ return this.columns.map((c) => c.topLevelIds);
+ }
+
+ get iterateTopLevelIds(): Iterable<T> {
+ const columns = this.columns;
+
+ function* iter() {
+ for (const column of columns) {
+ for (const id of column.topLevelIds) {
+ yield id;
+ }
+ }
+ }
+
+ return iter();
+ }
+
+ get inOrderIds(): T[] {
+ return this.columns.flatMap((c) => c.inOrderIds);
+ }
+
+ get colLength(): number {
+ return this.columns.length;
+ }
+
+ get idLength(): number {
+ return this.columns.reduce((acc, c) => acc + c.nodes.length, 0);
+ }
+
+ at(idx: number): CollapsibleTree<T> | undefined {
+ return this.columns[idx];
+ }
+
+ get(columnId: CellColumnId): CollapsibleTree<T> | undefined {
+ return this.columns.find((c) => c.id === columnId);
+ }
+
+ atOrThrow(idx: number): CollapsibleTree<T> {
+ const column = this.columns[idx];
+ if (!column) {
+ throw new Error(`Column ${idx} not found`);
+ }
+ return column;
+ }
+
+ hasOnlyOneColumn(): boolean {
+ return this.columns.length === 1;
+ }
+
+ getColumns(): ReadonlyArray<CollapsibleTree<T>> {
+ return this.columns;
+ }
+
+ hasOnlyOneId(): boolean {
+ return this.idLength === 1;
+ }
+
+ indexOf(column: CollapsibleTree<T>): number {
+ return this.columns.indexOf(column);
+ }
+
+ addColumn(columnId: CellColumnId, initialIds: T[] = []): MultiColumn<T> {
+ return new MultiColumn(
+ this.columns.flatMap((c) => {
+ if (c.id === columnId) {
+ return [c, CollapsibleTree.from(initialIds)];
+ }
+ return [c];
+ }),
+ );
+ }
+
+ insertBreakpoint(cellId: T): MultiColumn<T> {
+ const column = this.findWithId(cellId);
+ const [left, right] = column.split(cellId);
+ const newColumns = this.columns.flatMap((c) => {
+ if (c === column) {
+ return [left, right].filter(Boolean);
+ }
+ return [c];
+ });
+ return new MultiColumn(newColumns);
+ }
+
+ delete(columnId: CellColumnId): MultiColumn<T> {
+ // Move cells to preceding column
+ // If its the first column, move the cells to the next column
+
+ // Noop if there is only one column
+ if (this.columns.length <= 1) {
+ return this;
+ }
+
+ const columnIndex = this.indexOfOrThrow(columnId);
+ const targetColumnIndex = columnIndex === 0 ? 1 : columnIndex - 1;
+
+ const columns = [...this.columns];
+ const column = columns[columnIndex];
+ columns[targetColumnIndex] = column.withNodes([
+ ...columns[targetColumnIndex].nodes,
+ ...column.nodes,
+ ]);
+ columns.splice(columnIndex, 1);
+ return new MultiColumn(columns);
+ }
+
+ mergeAllColumns(): MultiColumn<T> {
+ if (this.columns.length <= 1) {
+ return this;
+ }
+
+ const nodes = this.columns.flatMap((c) => c.nodes);
+ const firstColumn = this.columns[0];
+ return new MultiColumn([firstColumn.withNodes(nodes)]);
+ }
+
+ moveWithinColumn(
+ col: CellColumnId,
+ fromIdx: CellIndex,
+ toIdx: CellIndex,
+ ): MultiColumn<T> {
+ return this.transform(col, (c) => {
+ return c.move(fromIdx, toIdx);
+ });
+ }
+
+ moveAcrossColumns(
+ fromCol: CellColumnId,
+ fromId: T,
+ toCol: CellColumnId,
+ toId: T | undefined,
+ ): MultiColumn<T> {
+ const columns = [...this.columns];
+
+ const fromColumnIndex = this.columns.findIndex((c) => c.id === fromCol);
+ // Full node, not just the top level id
+ const node = columns[fromColumnIndex].nodes.find((n) => n.value === fromId);
+ if (!node) {
+ throw new Error(`Node ${fromId} not found in column ${fromCol}`);
+ }
+
+ return new MultiColumn(
+ columns.map((c, i) => {
+ if (c.id === fromCol) {
+ // We don't use delete since we want to remove the node and it's children
+ return c.withNodes(c.nodes.filter((n) => n.value !== fromId));
+ }
+ if (c.id === toCol) {
+ if (!toId) {
+ return c.withNodes(arrayInsert(c.nodes, 0, node));
+ }
+ return c.withNodes(
+ arrayInsert(c.nodes, c.indexOfOrThrow(toId), node),
+ );
+ }
+ return c;
+ }),
+ );
+ }
+
+ indexOfOrThrow(id: CellColumnId): number {
+ const index = this.columns.findIndex((c) => c.id === id);
+ if (index === -1) {
+ throw new Error(
+ `Column ${id} not found. Possible values: ${this.columns
+ .map((c) => c.id)
+ .join(", ")}`,
+ );
+ }
+ return index;
+ }
+
+ moveColumn(
+ fromCol: CellColumnId,
+ toCol: CellColumnId | "_left_" | "_right_",
+ ): MultiColumn<T> {
+ if (fromCol === toCol) {
+ return this;
+ }
+ const fromIdx = this.indexOfOrThrow(fromCol);
+ if (toCol === "_left_") {
+ return new MultiColumn(
+ arrayMove([...this.columns], fromIdx, fromIdx - 1),
+ );
+ }
+ if (toCol === "_right_") {
+ return new MultiColumn(
+ arrayMove([...this.columns], fromIdx, fromIdx + 1),
+ );
+ }
+ const toIdx = this.indexOfOrThrow(toCol);
+ return new MultiColumn(arrayMove([...this.columns], fromIdx, toIdx));
+ }
+
+ moveToNewColumn(cellId: T): MultiColumn<T> {
+ const fromColumn = this.findWithId(cellId);
+ let columns = [...this.columns];
+ // Delete from existing column
+ columns = columns.map((c) => {
+ if (c.id === fromColumn.id) {
+ return c.delete(cellId);
+ }
+ return c;
+ });
+
+ // Insert into new column
+ const newColumn = CollapsibleTree.from([cellId]);
+ return new MultiColumn([...columns, newColumn]);
+ }
+
+ findWithId(id: T): CollapsibleTree<T> {
+ const found = this.columns.find((c) => {
+ return c.inOrderIds.includes(id);
+ });
+ if (!found) {
+ Logger.log(
+ `Possible values: ${this.columns.map((c) => c.inOrderIds).join(", ")}`,
+ );
+ throw new Error(`Cell ${id} not found in any column`);
+ }
+ return found;
+ }
+
+ /**
+ * Transform the column containing the given cell id
+ * @param id the id of the cell to transform
+ * @param fn the function to transform the column
+ * @returns new MultiColumn with the transformed column
+ * If the column was not updated, we return the object.
+ */
+ transformWithCellId(
+ id: T,
+ fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>,
+ ): MultiColumn<T> {
+ let didChange = false;
+
+ const columns = this.columns.map((c) => {
+ if (c.inOrderIds.includes(id)) {
+ const newColumn = fn(c);
+ if (c !== newColumn) {
+ didChange = true;
+ }
+ return newColumn;
+ }
+ return c;
+ });
+
+ // Avoid unnecessary re-renders
+ if (!didChange) {
+ return this;
+ }
+
+ return new MultiColumn(columns);
+ }
+
+ insertId(id: T, col: CellColumnId, index: CellIndex): MultiColumn<T> {
+ return this.transform(col, (c) => c.insert(id, index));
+ }
+
+ deleteById(cellId: T): MultiColumn<T> {
+ return this.transformWithCellId(cellId, (c) => c.delete(cellId));
+ }
+
+ compact(): MultiColumn<T> {
+ // Don't compact if there's only one column
+ if (this.columns.length === 1) {
+ return this;
+ }
+ // If no need to compact, return the same tree
+ // to avoid unnecessary re-renders
+ const someEmpty = this.columns.some((c) => c.nodes.length === 0);
+ if (!someEmpty) {
+ return this;
+ }
+
+ return new MultiColumn(this.columns.filter((c) => c.nodes.length > 0));
+ }
+
+ /**
+ * Transform the column with the given column id
+ */
+ transform(
+ columnId: CellColumnId,
+ fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>,
+ ): MultiColumn<T> {
+ return new MultiColumn(
+ this.columns.map((c) => {
+ if (c.id === columnId) {
+ return fn(c);
+ }
+ return c;
+ }),
+ );
+ }
+}
diff --git a/frontend/src/utils/vitals.ts b/frontend/src/utils/vitals.ts
index 86a67b5674..22a0fe0db9 100644
--- a/frontend/src/utils/vitals.ts
+++ b/frontend/src/utils/vitals.ts
@@ -1,10 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { onLCP, onFID, onCLS, type Metric } from "web-vitals";
import { Logger } from "./Logger";
-export function reportVitals() {
+export async function reportVitals() {
+ const { onLCP, onINP, onCLS } = await import("web-vitals");
Logger.log("Reporting vitals");
- const logMetric = (metric: Metric) => {
+ const logMetric = (metric: {
+ name: string;
+ value: number;
+ rating: string;
+ }) => {
const color =
metric.rating === "good"
? "green"
@@ -17,6 +21,6 @@ export function reportVitals() {
);
};
onCLS(logMetric);
- onFID(logMetric);
+ onINP(logMetric);
onLCP(logMetric);
}
diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js
index c652a5be1f..65c25d9aaf 100644
--- a/frontend/tailwind.config.js
+++ b/frontend/tailwind.config.js
@@ -41,6 +41,14 @@ module.exports = {
"2xlSolid":
"10px 12px 0px 0px var(--base-shadow-darker), 0 0px 8px 0px hsl(0deg 0% 90% / 50%)",
},
+ width: {
+ contentWidth: "var(--content-width)",
+ contentWidthMedium: "var(--content-width-medium)",
+ },
+ minWidth: {
+ contentWidth: "var(--content-width)",
+ contentWidthMedium: "var(--content-width-medium)",
+ },
maxWidth: {
contentWidth: "var(--content-width)",
contentWidthMedium: "var(--content-width-medium)",
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 6c528fb8b7..27c25024fd 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -191,6 +191,7 @@ class App:
self,
func: Callable[..., Any] | None = None,
*,
+ column: Optional[int] = None,
disabled: bool = False,
hide_code: bool = False,
**kwargs: Any,
@@ -222,7 +223,7 @@ class App:
del kwargs
return self._cell_manager.cell_decorator(
- func, disabled, hide_code, app=InternalApp(self)
+ func, column, disabled, hide_code, app=InternalApp(self)
)
def _unparsable_cell(
@@ -440,11 +441,14 @@ class CellManager:
def cell_decorator(
self,
func: Callable[..., Any] | None,
+ column: Optional[int],
disabled: bool,
hide_code: bool,
app: InternalApp | None = None,
) -> Cell | Callable[..., Cell]:
- cell_config = CellConfig(disabled=disabled, hide_code=hide_code)
+ cell_config = CellConfig(
+ column=column, disabled=disabled, hide_code=hide_code
+ )
def _register(func: Callable[..., Any]) -> Cell:
cell = cell_factory(
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 58fce2ec1f..8b4dfac1b8 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -23,6 +23,8 @@ if TYPE_CHECKING:
@dataclasses.dataclass
class CellConfig:
+ column: Optional[int] = None
+
# If True, the cell and its descendants cannot be executed,
# but they can still be added to the graph.
disabled: bool = False
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index b453f1fde3..6a197f2ab7 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -44,6 +44,8 @@ def _to_decorator(config: Optional[CellConfig]) -> str:
del config.disabled
if not config.hide_code:
del config.hide_code
+ if not isinstance(config.column, int):
+ del config.column
if config == CellConfig():
return "@app.cell"
diff --git a/marimo/_smoke_tests/2d-cells.py b/marimo/_smoke_tests/2d-cells.py
new file mode 100644
index 0000000000..0f3493d542
--- /dev/null
+++ b/marimo/_smoke_tests/2d-cells.py
@@ -0,0 +1,74 @@
+import marimo
+
+__generated_with = "0.9.0"
+app = marimo.App(width="columns")
+
+
+def __():
+ import marimo as mo
+ import altair as alt
+ from vega_datasets import data
+ return alt, data, mo
+
+
+def __(dataset, mo, plot, x, y):
+ mo.vstack([dataset, x, y, plot])
+ return
+
+
+def __(selected_dataset):
+ df = selected_dataset()
+ df
+ return (df,)
+
+
+def __(plot_type, x, y):
+ plot_type().encode(
+ x=x.value,
+ y=y.value,
+ ).interactive()
+ return
+
+
+def __(data, mo):
+ dataset = mo.ui.dropdown(
+ label="Choose dataset", options=data.list_datasets(), value="iris"
+ )
+ return (dataset,)
+
+
+def __(df, mo):
+ x = mo.ui.dropdown(
+ label="Choose X value", options=df.columns.to_list(), value=df.columns[0]
+ )
+ y = mo.ui.dropdown(
+ label="Choose Y value", options=df.columns.to_list(), value=df.columns[1]
+ )
+ plot = mo.ui.dropdown(
+ label="Choose plot type",
+ options=["mark_bar", "mark_circle"],
+ value="mark_bar",
+ )
+ return plot, x, y
+
+
+def __(data, dataset):
+ selected_dataset = getattr(data, dataset.value)
+ return (selected_dataset,)
+
+
+def __(alt, df, plot):
+ plot_type = getattr(alt.Chart(df), plot.value)
+ return (plot_type,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/anywidget/maplibre_example.py b/marimo/_smoke_tests/anywidget_smoke_tests/maplibre_example.py
similarity index 100%
rename from marimo/_smoke_tests/anywidget/maplibre_example.py
rename to marimo/_smoke_tests/anywidget_smoke_tests/maplibre_example.py
diff --git a/marimo/_smoke_tests/anywidget/mosaic_example.py b/marimo/_smoke_tests/anywidget_smoke_tests/mosaic_example.py
similarity index 100%
rename from marimo/_smoke_tests/anywidget/mosaic_example.py
rename to marimo/_smoke_tests/anywidget_smoke_tests/mosaic_example.py
diff --git a/marimo/_smoke_tests/anywidget/weather.yaml b/marimo/_smoke_tests/anywidget_smoke_tests/weather.yaml
similarity index 100%
rename from marimo/_smoke_tests/anywidget/weather.yaml
rename to marimo/_smoke_tests/anywidget_smoke_tests/weather.yaml
diff --git a/openapi/api.yaml b/openapi/api.yaml
index e6b052c32f..d7f9f79eee 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -151,6 +151,9 @@ components:
type: string
CellConfig:
properties:
+ column:
+ nullable: true
+ type: integer
disabled:
type: boolean
hide_code:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index f64657d67c..0375ad0892 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2034,6 +2034,7 @@ export interface components {
| "marimo-error"
| "media";
CellConfig: {
+ column?: number | null;
disabled: boolean;
hide_code: boolean;
};
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index d50ad8af37..0203972b22 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -316,7 +316,7 @@ class TestApp:
def test_cell_config() -> None:
app = App()
- @app.cell(disabled=True)
+ @app.cell(column=0, disabled=True)
def _() -> tuple[int]:
__x__ = 0
return (__x__,)
@@ -329,6 +329,7 @@ class TestApp:
cell_manager = app._cell_manager
configs = tuple(cell_manager.configs())
assert configs[0].disabled
+ assert configs[0].column is not None
assert configs[1].hide_code
@staticmethod
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index bb3d75f0f6..6e7b1a0ff6 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -66,7 +66,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.version = "0.0.0";
- window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};
+ window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA==", "JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA=="], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};
window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};
</script>
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 82428de329..9d8fceac5f 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -66,7 +66,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.version = "0.0.0";
- window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};
+ window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA==", "JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA=="], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};
window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};
</script>