Skip to content

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

add slides minimap (#9097)

Shahmir Varqhae50c74c5f182
diff --git a/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx b/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx
index a073edbe97..0d29c2170e 100644
--- a/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx
+++ b/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx
@@ -1,12 +1,13 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import React, { memo } from "react";
-import { outputIsLoading } from "@/core/cells/cell";
+import React, { useState } from "react";
+import { useAtomValue } from "jotai";
+import { numColumnsAtom } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
-import type { CellRuntimeState } from "@/core/cells/types";
-import type { AppMode } from "@/core/mode";
-import { OutputArea } from "../../Output";
import type { ICellRendererProps } from "../types";
import type { SlidesLayout } from "./types";
+import { SlidesMinimap } from "@/components/slides/minimap";
+import { Slide } from "@/components/slides/slide";
+import useEvent from "react-use-event-hook";
type Props = ICellRendererProps<SlidesLayout>;
@@ -22,25 +23,41 @@ export const SlidesLayoutRenderer: React.FC<Props> = ({
mode,
}) => {
const isReading = mode === "read";
+ const numColumns = useAtomValue(numColumnsAtom);
+ const isMultiColumn = numColumns > 1;
+ const [activeCellId, setActiveCellId] = useState<CellId | null>(null);
+
+ const cellsWithOutput = cells.filter(
+ (cell) => cell.output != null && cell.output.data !== "",
+ );
+
+ const activeSlideIndex = activeCellId
+ ? cellsWithOutput.findIndex((c) => c.id === activeCellId)
+ : 0;
+ const resolvedIndex = activeSlideIndex === -1 ? 0 : activeSlideIndex;
+
+ const handleSlideChange = useEvent((index: number) => {
+ const cell = cellsWithOutput[index];
+ if (cell) {
+ setActiveCellId(cell.id);
+ }
+ });
const slides = (
- <LazySlidesComponent forceKeyboardNavigation={true} className="flex-1">
- {cells.map((cell) => {
- const isOutputEmpty = cell.output == null || cell.output.data === "";
- if (isOutputEmpty) {
- return null;
- }
- return (
- <Slide
- key={cell.id}
- cellId={cell.id}
- code={cell.code}
- status={cell.status}
- output={cell.output}
- mode={mode}
- />
- );
- })}
+ <LazySlidesComponent
+ forceKeyboardNavigation={true}
+ className="flex-1 self-center"
+ activeIndex={resolvedIndex}
+ onActiveIndexChange={handleSlideChange}
+ >
+ {cellsWithOutput.map((cell) => (
+ <Slide
+ key={cell.id}
+ cellId={cell.id}
+ status={cell.status}
+ output={cell.output}
+ />
+ ))}
</LazySlidesComponent>
);
@@ -48,27 +65,16 @@ export const SlidesLayoutRenderer: React.FC<Props> = ({
return <div className="p-4 flex flex-col flex-1 max-h-[95%]">{slides}</div>;
}
- return <div className="pr-18 pb-5 flex-1 flex flex-col">{slides}</div>;
-};
-
-interface SlideProps extends Pick<CellRuntimeState, "output" | "status"> {
- className?: string;
- code: string;
- cellId: CellId;
- mode: AppMode;
-}
-
-const Slide = memo(({ output, cellId, status }: SlideProps) => {
- const loading = outputIsLoading(status);
return (
- <OutputArea
- className="contents"
- allowExpand={false}
- output={output}
- cellId={cellId}
- stale={loading}
- loading={loading}
- />
+ // Use 11/12 to ensure all content fits on the page (no overflow, scrolling required)
+ <div className="pr-18 pb-5 flex-1 flex flex-row max-h-11/12 gap-2">
+ <SlidesMinimap
+ cells={cellsWithOutput}
+ canReorder={!isMultiColumn}
+ activeCellId={activeCellId ?? cellsWithOutput[0]?.id ?? null}
+ onSlideClick={handleSlideChange}
+ />
+ {slides}
+ </div>
);
-});
-Slide.displayName = "Slide";
+};
diff --git a/frontend/src/components/slides/__tests__/minimap.test.ts b/frontend/src/components/slides/__tests__/minimap.test.ts
new file mode 100644
index 0000000000..0c96297f3a
--- /dev/null
+++ b/frontend/src/components/slides/__tests__/minimap.test.ts
@@ -0,0 +1,402 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { renderHook, act } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { CellId } from "@/core/cells/ids";
+import type { DragMoveEvent } from "@dnd-kit/core";
+import { MultiColumn } from "@/utils/id-tree";
+import { exportedForTesting } from "../minimap";
+
+const { useVisibleCellIds, projectDropTarget, resolveDropTarget } =
+ exportedForTesting;
+
+let intersectionCallback: IntersectionObserverCallback;
+let mutationCallback: MutationCallback;
+let observeSpy: ReturnType<typeof vi.fn>;
+let intersectionDisconnectSpy: ReturnType<typeof vi.fn>;
+let mutationDisconnectSpy: ReturnType<typeof vi.fn>;
+let mutationObserveSpy: ReturnType<typeof vi.fn>;
+
+function createContainer(...cellIds: string[]): HTMLDivElement {
+ const container = document.createElement("div");
+ for (const id of cellIds) {
+ const child = document.createElement("button");
+ child.dataset.cellId = id;
+ container.appendChild(child);
+ }
+ return container;
+}
+
+function fakeEntry(
+ target: Element,
+ isIntersecting: boolean,
+): IntersectionObserverEntry {
+ return { target, isIntersecting } as unknown as IntersectionObserverEntry;
+}
+
+describe("useVisibleCellIds", () => {
+ beforeEach(() => {
+ observeSpy = vi.fn();
+ intersectionDisconnectSpy = vi.fn();
+ mutationDisconnectSpy = vi.fn();
+ mutationObserveSpy = vi.fn();
+
+ global.IntersectionObserver = class MockIntersectionObserver {
+ constructor(
+ callback: IntersectionObserverCallback,
+ _options?: IntersectionObserverInit,
+ ) {
+ intersectionCallback = callback;
+ }
+ observe = observeSpy;
+ unobserve = vi.fn();
+ disconnect = intersectionDisconnectSpy;
+ root = null;
+ rootMargin = "";
+ thresholds = [0];
+ takeRecords = vi.fn(() => []);
+ } as unknown as typeof IntersectionObserver;
+
+ global.MutationObserver = class MockMutationObserver {
+ constructor(callback: MutationCallback) {
+ mutationCallback = callback;
+ }
+ observe = mutationObserveSpy;
+ disconnect = mutationDisconnectSpy;
+ takeRecords = vi.fn(() => []);
+ } as unknown as typeof MutationObserver;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("returns an empty set initially", () => {
+ const container = createContainer("cell-1");
+ const ref = { current: container };
+
+ const { result } = renderHook(() => useVisibleCellIds(ref));
+
+ expect(result.current.size).toBe(0);
+ });
+
+ it("observes all [data-cell-id] elements on mount", () => {
+ const container = createContainer("a", "b", "c");
+ const ref = { current: container };
+
+ renderHook(() => useVisibleCellIds(ref));
+
+ expect(observeSpy).toHaveBeenCalledTimes(3);
+ });
+
+ it("does not observe when container ref is null", () => {
+ const ref = { current: null };
+
+ const { result } = renderHook(() => useVisibleCellIds(ref));
+
+ expect(observeSpy).not.toHaveBeenCalled();
+ expect(result.current.size).toBe(0);
+ });
+
+ it("adds cell ids when entries become intersecting", () => {
+ const container = createContainer("cell-1", "cell-2");
+ const ref = { current: container };
+ const children = container.querySelectorAll("[data-cell-id]");
+
+ const { result } = renderHook(() => useVisibleCellIds(ref));
+
+ act(() => {
+ intersectionCallback(
+ [fakeEntry(children[0], true)],
+ {} as IntersectionObserver,
+ );
+ });
+
+ expect(result.current.has("cell-1" as CellId)).toBe(true);
+ expect(result.current.has("cell-2" as CellId)).toBe(false);
+ });
+
+ it("removes cell ids when entries stop intersecting", () => {
+ const container = createContainer("cell-1");
+ const ref = { current: container };
+ const children = container.querySelectorAll("[data-cell-id]");
+
+ const { result } = renderHook(() => useVisibleCellIds(ref));
+
+ act(() => {
+ intersectionCallback(
+ [fakeEntry(children[0], true)],
+ {} as IntersectionObserver,
+ );
+ });
+ expect(result.current.has("cell-1" as CellId)).toBe(true);
+
+ act(() => {
+ intersectionCallback(
+ [fakeEntry(children[0], false)],
+ {} as IntersectionObserver,
+ );
+ });
+ expect(result.current.has("cell-1" as CellId)).toBe(false);
+ });
+
+ it("preserves set identity when nothing changed", () => {
+ const container = createContainer("cell-1");
+ const ref = { current: container };
+ const children = container.querySelectorAll("[data-cell-id]");
+
+ const { result } = renderHook(() => useVisibleCellIds(ref));
+
+ act(() => {
+ intersectionCallback(
+ [fakeEntry(children[0], true)],
+ {} as IntersectionObserver,
+ );
+ });
+ const firstSet = result.current;
+
+ act(() => {
+ intersectionCallback(
+ [fakeEntry(children[0], true)],
+ {} as IntersectionObserver,
+ );
+ });
+ expect(result.current).toBe(firstSet);
+ });
+
+ it("handles batch intersection updates", () => {
+ const container = createContainer("a", "b", "c");
+ const ref = { current: container };
+ const children = container.querySelectorAll("[data-cell-id]");
+
+ const { result } = renderHook(() => useVisibleCellIds(ref));
+
+ act(() => {
+ intersectionCallback(
+ [
+ fakeEntry(children[0], true),
+ fakeEntry(children[1], true),
+ fakeEntry(children[2], false),
+ ],
+ {} as IntersectionObserver,
+ );
+ });
+
+ expect(result.current).toEqual(new Set(["a", "b"]));
+ });
+
+ it("ignores entries without data-cell-id", () => {
+ const container = createContainer("cell-1");
+ const orphan = document.createElement("div");
+ container.appendChild(orphan);
+ const ref = { current: container };
+
+ const { result } = renderHook(() => useVisibleCellIds(ref));
+
+ act(() => {
+ intersectionCallback(
+ [fakeEntry(orphan, true)],
+ {} as IntersectionObserver,
+ );
+ });
+
+ expect(result.current.size).toBe(0);
+ });
+
+ it("re-observes elements when MutationObserver fires", () => {
+ const container = createContainer("cell-1");
+ const ref = { current: container };
+
+ renderHook(() => useVisibleCellIds(ref));
+ expect(observeSpy).toHaveBeenCalledTimes(1);
+
+ const newChild = document.createElement("button");
+ newChild.dataset.cellId = "cell-2";
+ container.appendChild(newChild);
+
+ act(() => {
+ mutationCallback([], {} as MutationObserver);
+ });
+
+ // 1 from initial + 2 from re-observe (observe is idempotent on existing)
+ expect(observeSpy).toHaveBeenCalledTimes(3);
+ });
+
+ it("disconnects both observers on unmount", () => {
+ const container = createContainer("cell-1");
+ const ref = { current: container };
+
+ const { unmount } = renderHook(() => useVisibleCellIds(ref));
+
+ // 1 disconnect from the initial observeAll() call
+ expect(intersectionDisconnectSpy).toHaveBeenCalledTimes(1);
+ expect(mutationDisconnectSpy).not.toHaveBeenCalled();
+
+ unmount();
+
+ // +1 disconnect from cleanup
+ expect(intersectionDisconnectSpy).toHaveBeenCalledTimes(2);
+ expect(mutationDisconnectSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
+function rect(top: number, height: number) {
+ return { top, height, left: 0, right: 0, bottom: 0, width: 0 };
+}
+
+type Rect = ReturnType<typeof rect>;
+
+function fakeDragEvent({
+ activeId = "a" as string | number,
+ overId = "b" as string | number | null,
+ translated = rect(0, 40) as Rect | null,
+ initial = undefined as Rect | null | undefined,
+ overRect = rect(0, 40),
+} = {}): DragMoveEvent {
+ return {
+ active: {
+ id: activeId,
+ rect: { current: { translated, initial: initial ?? translated } },
+ },
+ over: overId === null ? null : { id: overId, rect: overRect },
+ } as unknown as DragMoveEvent;
+}
+
+describe("projectDropTarget", () => {
+ it("returns null when over is null", () => {
+ expect(projectDropTarget(fakeDragEvent({ overId: null }))).toBeNull();
+ });
+
+ it("returns null when active id is not a string", () => {
+ expect(projectDropTarget(fakeDragEvent({ activeId: 42 }))).toBeNull();
+ });
+
+ it("returns null when over id is not a string", () => {
+ expect(projectDropTarget(fakeDragEvent({ overId: 42 }))).toBeNull();
+ });
+
+ it("returns null when active and over are the same cell", () => {
+ expect(
+ projectDropTarget(fakeDragEvent({ activeId: "x", overId: "x" })),
+ ).toBeNull();
+ });
+
+ it("returns null when no active rect is available", () => {
+ expect(
+ projectDropTarget(fakeDragEvent({ translated: null, initial: null })),
+ ).toBeNull();
+ });
+
+ it("falls back to initial rect when translated is null", () => {
+ expect(
+ projectDropTarget(
+ fakeDragEvent({
+ translated: null,
+ initial: rect(0, 40),
+ overRect: rect(100, 40),
+ }),
+ ),
+ ).toEqual({ overId: "b", position: "before" });
+ });
+
+ it("prefers translated rect over initial rect", () => {
+ expect(
+ projectDropTarget(
+ fakeDragEvent({
+ translated: rect(200, 40),
+ initial: rect(0, 40),
+ overRect: rect(100, 40),
+ }),
+ ),
+ ).toEqual({ overId: "b", position: "after" });
+ });
+});
+
+describe("resolveDropTarget", () => {
+ const A = "a" as CellId;
+ const B = "b" as CellId;
+ const C = "c" as CellId;
+ const D = "d" as CellId;
+
+ function makeSingleColumnIds(...ids: CellId[]) {
+ return MultiColumn.from([ids]);
+ }
+
+ it("returns null when activeId matches target overId", () => {
+ const cellIds = makeSingleColumnIds(A, B);
+ expect(
+ resolveDropTarget({
+ cellIds,
+ activeId: A,
+ target: { overId: A, position: "after" },
+ }),
+ ).toBeNull();
+ });
+
+ it("returns null for multi-column layouts", () => {
+ const cellIds = MultiColumn.from([[A, B], [C]]);
+ expect(
+ resolveDropTarget({
+ cellIds,
+ activeId: A,
+ target: { overId: B, position: "after" },
+ }),
+ ).toBeNull();
+ });
+
+ it('resolves "before" to the over index', () => {
+ const cellIds = makeSingleColumnIds(A, B, C);
+ const result = resolveDropTarget({
+ cellIds,
+ activeId: A,
+ target: { overId: C, position: "before" },
+ });
+ expect(result).toEqual({
+ cellId: A,
+ columnId: cellIds.atOrThrow(0).id,
+ index: 2,
+ });
+ });
+
+ it('resolves "after" to one past the over index', () => {
+ const cellIds = makeSingleColumnIds(A, B, C);
+ const result = resolveDropTarget({
+ cellIds,
+ activeId: C,
+ target: { overId: A, position: "after" },
+ });
+ expect(result).toEqual({
+ cellId: C,
+ columnId: cellIds.atOrThrow(0).id,
+ index: 1,
+ });
+ });
+
+ it('resolves "before" on first item to index 0', () => {
+ const cellIds = makeSingleColumnIds(A, B, C);
+ const result = resolveDropTarget({
+ cellIds,
+ activeId: C,
+ target: { overId: A, position: "before" },
+ });
+ expect(result).toEqual({
+ cellId: C,
+ columnId: cellIds.atOrThrow(0).id,
+ index: 0,
+ });
+ });
+
+ it('resolves "after" on last item to one past the end', () => {
+ const cellIds = makeSingleColumnIds(A, B, C, D);
+ const result = resolveDropTarget({
+ cellIds,
+ activeId: A,
+ target: { overId: D, position: "after" },
+ });
+ expect(result).toEqual({
+ cellId: A,
+ columnId: cellIds.atOrThrow(0).id,
+ index: 4,
+ });
+ });
+});
diff --git a/frontend/src/components/slides/minimap.tsx b/frontend/src/components/slides/minimap.tsx
new file mode 100644
index 0000000000..1257483754
--- /dev/null
+++ b/frontend/src/components/slides/minimap.tsx
@@ -0,0 +1,534 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useCellActions, useCellIds } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import type { CellColumnId } from "@/utils/id-tree";
+import { useEffect, useRef, useState } from "react";
+import type { ICellRendererProps } from "../editor/renderers/types";
+import type { SlidesLayout } from "../editor/renderers/slides-layout/types";
+import {
+ DndContext,
+ DragOverlay,
+ PointerSensor,
+ useSensor,
+ useSensors,
+ type DragMoveEvent,
+ type DragOverEvent,
+ type DragStartEvent,
+ type DragEndEvent,
+ closestCenter,
+ pointerWithin,
+ type CollisionDetection,
+ type UniqueIdentifier,
+} from "@dnd-kit/core";
+import {
+ SortableContext,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable";
+import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
+import { cn } from "@/utils/cn";
+import { Slide } from "./slide";
+import { InfoIcon } from "lucide-react";
+import { Logger } from "@/utils/Logger";
+
+type Props = ICellRendererProps<SlidesLayout>;
+type SlideCell = Props["cells"][number];
+type CellIdsState = ReturnType<typeof useCellIds>;
+type DropPosition = "before" | "after";
+
+interface ProjectedDropTarget {
+ overId: CellId;
+ position: DropPosition;
+}
+
+interface ResolvedDropTarget {
+ cellId: CellId;
+ columnId: CellColumnId;
+ index: number;
+}
+
+interface SlideThumbnailCardProps extends React.HTMLAttributes<HTMLDivElement> {
+ cell: SlideCell;
+ isActiveSlide?: boolean;
+ isActiveDragSource?: boolean;
+ isOverlay?: boolean;
+ isVisible?: boolean;
+ ref?: React.Ref<HTMLDivElement>;
+}
+
+interface SlideThumbnailRowProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
+ cell: SlideCell;
+ isActiveSlide?: boolean;
+ dropIndicator?: DropPosition | null;
+ isActiveDragSource?: boolean;
+ isVisible?: boolean;
+ ref?: React.Ref<HTMLButtonElement>;
+}
+
+interface SlidesMinimapProps {
+ cells: SlideCell[];
+ canReorder: boolean;
+ activeCellId: CellId | null;
+ onSlideClick: (index: number) => void;
+}
+
+const THUMBNAIL_WIDTH = 256;
+const THUMBNAIL_HEIGHT = 144;
+const THUMBNAIL_SCALE = 0.3;
+const MINIMAP_AUTO_SCROLL = {
+ threshold: { x: 0, y: 0.1 },
+};
+const MINIMAP_GAP = 8;
+const VISIBILITY_ROOT_MARGIN = "200px 0px";
+const minimapCollisionDetection: CollisionDetection = (args) => {
+ const pointerCollisions = pointerWithin(args);
+ return pointerCollisions.length > 0 ? pointerCollisions : closestCenter(args);
+};
+
+/**
+ * Tracks which `[data-cell-id]` elements inside a scrollable container are
+ * within (or near) the viewport using a single shared IntersectionObserver.
+ * A MutationObserver re-observes when children are added or removed.
+ * Off-screen thumbnails can skip rendering expensive <Slide> content.
+ */
+function useVisibleCellIds(
+ containerRef: React.RefObject<HTMLDivElement | null>,
+): ReadonlySet<CellId> {
+ const [visibleIds, setVisibleIds] = useState<ReadonlySet<CellId>>(
+ () => new Set(),
+ );
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) {
+ return;
+ }
+
+ const intersectionObserver = new IntersectionObserver(
+ (entries) => {
+ setVisibleIds((prev) => {
+ const next = new Set(prev);
+ let changed = false;
+ for (const entry of entries) {
+ const id = (entry.target as HTMLElement).dataset.cellId as
+ | CellId
+ | undefined;
+ if (!id) {
+ continue;
+ }
+ if (entry.isIntersecting && !next.has(id)) {
+ next.add(id);
+ changed = true;
+ } else if (!entry.isIntersecting && next.has(id)) {
+ next.delete(id);
+ changed = true;
+ }
+ }
+ return changed ? next : prev;
+ });
+ },
+ { root: container, rootMargin: VISIBILITY_ROOT_MARGIN },
+ );
+
+ const observeAll = () => {
+ intersectionObserver.disconnect();
+ for (const el of container.querySelectorAll<HTMLElement>(
+ "[data-cell-id]",
+ )) {
+ intersectionObserver.observe(el);
+ }
+ };
+
+ observeAll();
+
+ const mutationObserver = new MutationObserver(observeAll);
+ mutationObserver.observe(container, { childList: true });
+
+ return () => {
+ intersectionObserver.disconnect();
+ mutationObserver.disconnect();
+ };
+ }, [containerRef]);
+
+ return visibleIds;
+}
+
+export const SlidesMinimap = ({
+ cells,
+ canReorder,
+ activeCellId,
+ onSlideClick,
+}: SlidesMinimapProps) => {
+ const cellIds = useCellIds();
+ const { moveCellToIndex } = useCellActions();
+ const containerRef = useRef<HTMLDivElement>(null);
+ const visibleIds = useVisibleCellIds(containerRef);
+ const [activeId, setActiveId] = useState<CellId | null>(null);
+ const [dropTarget, setDropTarget] = useState<ProjectedDropTarget | null>(
+ null,
+ );
+
+ useEffect(() => {
+ if (!activeCellId || !containerRef.current) {
+ return;
+ }
+ const el = containerRef.current.querySelector(
+ `[data-cell-id="${activeCellId}"]`,
+ );
+ el?.scrollIntoView({ block: "nearest", behavior: "instant" });
+ }, [activeCellId]);
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, {
+ activationConstraint: {
+ distance: 8,
+ },
+ }),
+ );
+
+ const activeCell = activeId
+ ? (cells.find((cell) => cell.id === activeId) ?? null)
+ : null;
+
+ const resetDragState = () => {
+ setActiveId(null);
+ setDropTarget(null);
+ };
+
+ const updateDropTarget = (event: DragMoveEvent | DragOverEvent) => {
+ const next = projectDropTarget(event);
+
+ setDropTarget((prev) => {
+ if (prev?.overId === next?.overId && prev?.position === next?.position) {
+ return prev;
+ }
+ return next;
+ });
+ };
+
+ const handleDragStart = (event: DragStartEvent) => {
+ setDropTarget(null);
+ const cellId = asCellId(event.active.id);
+ if (cellId) {
+ setActiveId(cellId);
+ }
+ };
+
+ const handleDragEnd = (_event: DragEndEvent) => {
+ try {
+ if (activeId && dropTarget) {
+ const resolvedTarget = resolveDropTarget({
+ cellIds,
+ activeId,
+ target: dropTarget,
+ });
+ if (resolvedTarget) {
+ moveCellToIndex(resolvedTarget);
+ }
+ }
+ } catch (e) {
+ Logger.warn("Drop failed", e);
+ } finally {
+ resetDragState();
+ }
+ };
+
+ if (!canReorder) {
+ return (
+ <SlideThumbnailsContainer ref={containerRef}>
+ <div className="text-xs text-gray-500 flex items-center gap-0.5">
+ <InfoIcon className="h-3 w-3" />
+ Reordering is not supported in multi-column mode
+ </div>
+ {cells.map((cell, index) => (
+ <SlideThumbnailRow
+ key={cell.id}
+ cell={cell}
+ isActiveSlide={cell.id === activeCellId}
+ isVisible={visibleIds.has(cell.id)}
+ onClick={() => onSlideClick(index)}
+ />
+ ))}
+ </SlideThumbnailsContainer>
+ );
+ }
+
+ return (
+ <DndContext
+ autoScroll={MINIMAP_AUTO_SCROLL}
+ collisionDetection={minimapCollisionDetection}
+ modifiers={[restrictToVerticalAxis]}
+ sensors={sensors}
+ onDragStart={handleDragStart}
+ onDragMove={updateDropTarget}
+ onDragOver={updateDropTarget}
+ onDragEnd={handleDragEnd}
+ onDragCancel={resetDragState}
+ >
+ <SlideThumbnailsContainer ref={containerRef}>
+ <SortableContext
+ items={cells.map((cell) => cell.id)}
+ strategy={verticalListSortingStrategy}
+ >
+ {cells.map((cell, index) => (
+ <SortableSlideThumbnail
+ key={cell.id}
+ cell={cell}
+ isActive={activeId === cell.id}
+ isActiveSlide={cell.id === activeCellId}
+ isVisible={visibleIds.has(cell.id)}
+ dropIndicator={
+ dropTarget?.overId === cell.id && activeId !== cell.id
+ ? dropTarget.position
+ : null
+ }
+ onClick={() => onSlideClick(index)}
+ />
+ ))}
+ </SortableContext>
+ </SlideThumbnailsContainer>
+ <DragOverlay>
+ {activeCell && (
+ <SlideThumbnailCard
+ cell={activeCell}
+ isOverlay={true}
+ isActiveDragSource={true}
+ />
+ )}
+ </DragOverlay>
+ </DndContext>
+ );
+};
+
+const SlideThumbnailsContainer = ({
+ children,
+ ref,
+}: {
+ children: React.ReactNode;
+ ref?: React.Ref<HTMLDivElement>;
+}) => {
+ return (
+ <div
+ ref={ref}
+ className="h-full overflow-auto flex flex-col scrollbar-thin"
+ >
+ {children}
+ </div>
+ );
+};
+
+interface SortableSlideThumbnailProps {
+ cell: SlideCell;
+ dropIndicator?: DropPosition | null;
+ isActive: boolean;
+ isActiveSlide?: boolean;
+ isVisible?: boolean;
+ onClick?: () => void;
+}
+
+const SortableSlideThumbnail = ({
+ cell,
+ dropIndicator,
+ isActive,
+ isActiveSlide,
+ isVisible,
+ onClick,
+}: SortableSlideThumbnailProps) => {
+ const { attributes, listeners, setNodeRef } = useSortable({
+ id: cell.id,
+ });
+
+ return (
+ <SlideThumbnailRow
+ ref={setNodeRef}
+ cell={cell}
+ dropIndicator={dropIndicator}
+ isActiveDragSource={isActive}
+ isActiveSlide={isActiveSlide}
+ isVisible={isVisible}
+ onClick={onClick}
+ {...attributes}
+ {...listeners}
+ />
+ );
+};
+
+const SlideThumbnailRow = ({
+ cell,
+ className,
+ style,
+ dropIndicator,
+ isActiveSlide = false,
+ isActiveDragSource = false,
+ isVisible,
+ onClick,
+ ref,
+ ...props
+}: SlideThumbnailRowProps) => {
+ const rowStyle: React.CSSProperties = {
+ paddingTop: MINIMAP_GAP,
+ paddingBottom: MINIMAP_GAP,
+ ...style,
+ };
+
+ return (
+ <button
+ ref={ref}
+ type="button"
+ data-cell-id={cell.id}
+ className={cn(
+ "relative shrink-0 appearance-none text-left p-0 bg-transparent outline-none",
+ className,
+ )}
+ style={rowStyle}
+ onClick={onClick}
+ {...props}
+ >
+ {dropIndicator && (
+ <div
+ className={cn(
+ "absolute left-2 right-2 h-0.5 rounded-full bg-blue-500 z-20 pointer-events-none",
+ dropIndicator === "after"
+ ? "bottom-0 translate-y-1/2"
+ : "top-0 -translate-y-1/2",
+ )}
+ />
+ )}
+ <SlideThumbnailCard
+ cell={cell}
+ isActiveSlide={isActiveSlide}
+ isActiveDragSource={isActiveDragSource}
+ isVisible={isVisible}
+ />
+ </button>
+ );
+};
+
+const SlideThumbnailCard = ({
+ cell,
+ className,
+ style,
+ isActiveSlide = false,
+ isActiveDragSource = false,
+ isOverlay = false,
+ isVisible = false,
+ ref,
+ ...props
+}: SlideThumbnailCardProps) => {
+ const outerStyle: React.CSSProperties = {
+ width: THUMBNAIL_WIDTH,
+ height: THUMBNAIL_HEIGHT,
+ contain: "strict",
+ ...(isOverlay
+ ? null
+ : {
+ contentVisibility: "auto",
+ containIntrinsicSize: `${THUMBNAIL_WIDTH}px ${THUMBNAIL_HEIGHT}px`,
+ }),
+ ...style,
+ };
+
+ const showContent = isVisible || isOverlay;
+
+ return (
+ <div
+ ref={ref}
+ className={cn(
+ "border-2 shrink-0 rounded-md relative select-none bg-background cursor-pointer active:cursor-grabbing",
+ isActiveSlide || isActiveDragSource || isOverlay
+ ? "border-blue-500"
+ : "border-border",
+ isActiveDragSource && !isOverlay && "opacity-35",
+ isOverlay && "opacity-95 shadow-lg",
+ className,
+ )}
+ style={outerStyle}
+ {...props}
+ >
+ {showContent && (
+ <div
+ className="flex p-6 box-border pointer-events-none mo-slide-content overflow-hidden"
+ style={{
+ transform: `scale(${THUMBNAIL_SCALE})`,
+ transformOrigin: "top left",
+ width: THUMBNAIL_WIDTH / THUMBNAIL_SCALE,
+ height: THUMBNAIL_HEIGHT / THUMBNAIL_SCALE,
+ }}
+ >
+ <Slide cellId={cell.id} status={cell.status} output={cell.output} />
+ </div>
+ )}
+ </div>
+ );
+};
+
+function projectDropTarget(
+ event: DragMoveEvent | DragOverEvent,
+): ProjectedDropTarget | null {
+ const { active, over } = event;
+ if (!over) {
+ return null;
+ }
+
+ const activeId = asCellId(active.id);
+ const overId = asCellId(over.id);
+ if (!activeId || !overId || activeId === overId) {
+ return null;
+ }
+
+ const activeRect =
+ active.rect.current.translated ?? active.rect.current.initial;
+ if (!activeRect) {
+ return null;
+ }
+
+ const pointerY = activeRect.top + activeRect.height / 2;
+ const overCenter = over.rect.top + over.rect.height / 2;
+
+ return {
+ overId,
+ position: pointerY < overCenter ? "before" : "after",
+ };
+}
+
+function resolveDropTarget({
+ cellIds,
+ activeId,
+ target,
+}: {
+ cellIds: CellIdsState;
+ activeId: CellId;
+ target: ProjectedDropTarget;
+}): ResolvedDropTarget | null {
+ if (activeId === target.overId) {
+ return null;
+ }
+ if (cellIds.colLength !== 1) {
+ Logger.warn("Multi-column mode is not supported");
+ return null;
+ }
+
+ const column = cellIds.findWithId(target.overId);
+ const overIndex = column.indexOfOrThrow(target.overId);
+
+ return {
+ cellId: activeId,
+ columnId: column.id,
+ index: target.position === "after" ? overIndex + 1 : overIndex,
+ };
+}
+
+/**
+ * Narrows a dnd-kit UniqueIdentifier (string | number) back to CellId.
+ * Safe because we only pass CellId values as sortable item IDs.
+ */
+function asCellId(id: UniqueIdentifier): CellId | null {
+ return typeof id === "string" ? (id as CellId) : null;
+}
+
+export const exportedForTesting = {
+ useVisibleCellIds,
+ projectDropTarget,
+ resolveDropTarget,
+};
diff --git a/frontend/src/components/slides/slide.tsx b/frontend/src/components/slides/slide.tsx
new file mode 100644
index 0000000000..5670e77f56
--- /dev/null
+++ b/frontend/src/components/slides/slide.tsx
@@ -0,0 +1,29 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { outputIsLoading } from "@/core/cells/cell";
+import { OutputArea } from "../editor/Output";
+import { memo } from "react";
+import type { CellId } from "@/core/cells/ids";
+import type { CellRuntimeState } from "@/core/cells/types";
+
+interface SlideContentProps extends Pick<
+ CellRuntimeState,
+ "output" | "status"
+> {
+ cellId: CellId;
+}
+
+export const Slide = memo(({ output, cellId, status }: SlideContentProps) => {
+ const loading = outputIsLoading(status);
+ return (
+ <OutputArea
+ className="contents"
+ allowExpand={false}
+ output={output}
+ cellId={cellId}
+ stale={loading}
+ loading={loading}
+ />
+ );
+});
+Slide.displayName = "Slide";
diff --git a/frontend/src/components/slides/slides-component.tsx b/frontend/src/components/slides/slides-component.tsx
index 233e317a5a..a2652e7dc9 100644
--- a/frontend/src/components/slides/slides-component.tsx
+++ b/frontend/src/components/slides/slides-component.tsx
@@ -22,6 +22,8 @@ interface SlidesComponentProps {
index?: string | null;
height?: string | number | null;
wrapAround?: boolean;
+ activeIndex?: number | null;
+ onActiveIndexChange?: (index: number) => void;
}
const SlidesComponent = ({
@@ -30,11 +32,23 @@ const SlidesComponent = ({
height,
forceKeyboardNavigation = false,
wrapAround = false,
+ activeIndex,
+ onActiveIndexChange,
}: PropsWithChildren<SlidesComponentProps>): JSX.Element => {
const el = React.useRef<SwiperRef>(null);
const [isFullscreen, setIsFullscreen] = React.useState(false);
const { hasFullscreen } = useIframeCapabilities();
+ useEffect(() => {
+ if (activeIndex != null && el.current?.swiper.realIndex !== activeIndex) {
+ if (wrapAround) {
+ el.current?.swiper.slideToLoop(activeIndex);
+ } else {
+ el.current?.swiper.slideTo(activeIndex);
+ }
+ }
+ }, [activeIndex, wrapAround]);
+
useEventListener(document, "fullscreenchange", () => {
if (document.fullscreenElement) {
el.current?.swiper.keyboard.enable();
@@ -63,7 +77,7 @@ const SlidesComponent = ({
)}
spaceBetween={50}
style={{
- height: isFullscreen ? "100%" : height || "550px",
+ height: isFullscreen ? "100%" : height || "650px",
}}
slidesPerView={1}
modules={modules}
@@ -85,6 +99,7 @@ const SlidesComponent = ({
// that overlay content more legible
speed={1}
loop={wrapAround}
+ onSlideChange={(swiper) => onActiveIndexChange?.(swiper.realIndex)}
>
{React.Children.map(children, (child, index) => {
if (child == null) {
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 2fde4e8c82..6546b87b0d 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -22,7 +22,11 @@ import { foldAllBulk, unfoldAllBulk } from "@/core/codemirror/editing/commands";
import { adaptiveLanguageConfiguration } from "@/core/codemirror/language/extension";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import type { OutputMessage } from "@/core/kernel/messages";
-import { type CollapsibleTree, MultiColumn } from "@/utils/id-tree";
+import {
+ type CollapsibleTree,
+ MultiColumn,
+ type CellColumnId,
+} from "@/utils/id-tree";
import type { Seconds } from "@/utils/time";
import {
exportedForTesting,
@@ -495,6 +499,106 @@ describe("cell reducer", () => {
`);
});
+ it("can move a cell to an exact index within a column", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ });
+ actions.createNewCell({
+ cellId: cellId("1"),
+ before: false,
+ });
+
+ const columnId = state.cellIds.atOrThrow(0).id;
+ actions.moveCellToIndex({
+ cellId: firstCellId,
+ columnId,
+ index: 3,
+ });
+
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [1] ''
+
+ [2] ''
+
+ [0] ''
+ "
+ `);
+ });
+
+ it("can move a cell to an exact index across columns", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ });
+ actions.createNewCell({
+ cellId: cellId("1"),
+ before: false,
+ });
+ actions.addColumnBreakpoint({ cellId: cellId("1") });
+
+ const secondColumnId = state.cellIds.atOrThrow(1).id;
+ actions.moveCellToIndex({
+ cellId: firstCellId,
+ columnId: secondColumnId,
+ index: 1,
+ });
+
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ > col 0
+
+
+ > col 1
+ [1] ''
+
+ [0] ''
+
+ [2] ''
+ "
+ `);
+ });
+
+ it("moveCellToIndex is a no-op when moving to the same position", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ });
+ actions.createNewCell({
+ cellId: cellId("1"),
+ before: false,
+ });
+
+ const columnId = state.cellIds.atOrThrow(0).id;
+ const before = formatCells(state);
+
+ actions.moveCellToIndex({
+ cellId: firstCellId,
+ columnId,
+ index: 0,
+ });
+
+ expect(formatCells(state)).toBe(before);
+ });
+
+ it("moveCellToIndex is a no-op for an invalid columnId", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ });
+
+ const before = formatCells(state);
+
+ actions.moveCellToIndex({
+ cellId: firstCellId,
+ columnId: "nonexistent-column" as CellColumnId,
+ index: 0,
+ });
+
+ expect(formatCells(state)).toBe(before);
+ });
+
it("can run cell and receive cell messages", () => {
// HAPPY PATH
/////////////////
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index f7ec8483af..6ee94fce81 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -338,6 +338,49 @@ const {
scrollKey: cellId,
};
},
+ moveCellToIndex: (
+ state,
+ action: {
+ cellId: CellId;
+ columnId: CellColumnId;
+ index: number;
+ },
+ ) => {
+ const { cellId, columnId, index } = action;
+ const fromColumn = state.cellIds.findWithId(cellId);
+ const fromIndex = fromColumn.indexOfOrThrow(cellId);
+
+ const destinationColumn = state.cellIds.get(columnId);
+ if (!destinationColumn) {
+ return state;
+ }
+
+ const clampedIndex = Math.max(0, Math.min(index, destinationColumn.length));
+ const adjustedIndex =
+ fromColumn.id === columnId && fromIndex < clampedIndex
+ ? clampedIndex - 1
+ : clampedIndex;
+
+ if (fromColumn.id === columnId && fromIndex === adjustedIndex) {
+ return state;
+ }
+
+ const withoutCell = state.cellIds.deleteById(cellId);
+ const updatedColumn = withoutCell.get(columnId);
+ if (!updatedColumn) {
+ return state;
+ }
+
+ return {
+ ...state,
+ cellIds: withoutCell.insertId(
+ cellId,
+ columnId,
+ Math.max(0, Math.min(adjustedIndex, updatedColumn.length)),
+ ),
+ scrollKey: null,
+ };
+ },
dropCellOverCell: (state, action: { cellId: CellId; overCellId: CellId }) => {
const { cellId, overCellId } = action;
diff --git a/frontend/src/core/cells/document-changes.ts b/frontend/src/core/cells/document-changes.ts
index 0351a6fd62..5fcec39ba6 100644
--- a/frontend/src/core/cells/document-changes.ts
+++ b/frontend/src/core/cells/document-changes.ts
@@ -215,12 +215,13 @@ export function toDocumentChanges(
];
}
- // dropCellOverCell/dropCellOverColumn → set-config + reorder-cells
+ // dropCellOverCell/dropCellOverColumn/moveCellToIndex → set-config + reorder-cells
// Drag-and-drop reorders can move cells within or across columns.
// We emit config changes for cells whose column changed, then
// the full ordering.
case "dropCellOverCell":
case "dropCellOverColumn":
+ case "moveCellToIndex":
return columnChanges(prevState, newState);
// updateCellCode → set-code