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.

21.7 KB
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */

import { useDeleteCellCallback } from "@/components/editor/cell/useDeleteCell";
import { outputIsStale } from "@/core/cells/cell";
import { useCellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import { type CellColumnId, type Layout, useLayout } from "@/core/cells/layout";
import { useEffect, useRef, useState } from "react";
import type { ICellRendererProps } from "../editor/renderers/types";
import type {
  SlideType,
  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 { Events } from "@/utils/events";
import { Slide } from "./slide";
import { InfoIcon, type LucideIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { Tooltip } from "@/components/ui/tooltip";
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuTrigger,
} from "@/components/ui/context-menu";
import { Logger } from "@/utils/Logger";
import { SLIDE_TYPE_OPTIONS_BY_VALUE } from "./slide-form";

type Props = ICellRendererProps<SlidesLayout>;
type SlideCell = Props["cells"][number];
type DropPosition = "before" | "after";

interface ProjectedDropTarget {
  overId: CellId;
  position: DropPosition;
}

interface ResolvedDropTarget {
  cellId: CellId;
  columnId: CellColumnId;
  index: number;
}

interface ThumbnailDimensions {
  width: number;
  height: number;
  scale: number;
}

interface SlideThumbnailCardProps extends React.HTMLAttributes<HTMLDivElement> {
  cell: SlideCell;
  dimensions: ThumbnailDimensions;
  isActiveSlide?: boolean;
  isActiveDragSource?: boolean;
  isOverlay?: boolean;
  isVisible?: boolean;
  isNoOutput?: boolean;
  slideType?: SlideType;
  ref?: React.Ref<HTMLDivElement>;
}

interface SlideThumbnailRowProps extends React.HTMLAttributes<HTMLDivElement> {
  cell: SlideCell;
  dimensions: ThumbnailDimensions;
  isActiveSlide?: boolean;
  dropIndicator?: DropPosition | null;
  isActiveDragSource?: boolean;
  isVisible?: boolean;
  isNoOutput?: boolean;
  slideType?: SlideType;
  onInsertAbove?: () => void;
  onInsertBelow?: () => void;
  onDelete?: () => void;
  ref?: React.Ref<HTMLDivElement>;
}

interface SlidesMinimapProps {
  cells: SlideCell[];
  thumbnailWidth: number;
  canReorder: boolean;
  activeCellId: CellId | null;
  // Set of cell ids that should be visually treated like skipped entries.
  skippedIds?: ReadonlySet<CellId>;
  // Set of cell ids that currently have no rendered output.
  noOutputIds?: ReadonlySet<CellId>;
  slideTypes?: ReadonlyMap<CellId, SlideType>;
  onSlideClick: (index: number) => void;
}

interface ThumbnailVisual {
  label: string;
  description: string;
  Icon?: LucideIcon;
}

function getSlideTypeVisual(
  slideType: SlideType | undefined,
): ThumbnailVisual | null {
  if (!slideType || slideType === "slide") {
    return null;
  }
  const { label, description, Icon } = SLIDE_TYPE_OPTIONS_BY_VALUE[slideType];
  return { label, description, Icon };
}

const NO_OUTPUT_VISUAL: ThumbnailVisual = {
  label: "No output",
  description: "Hidden because this cell has no output.",
};

const SLIDE_ASPECT_RATIO = 16 / 9;
const SLIDE_BASE_WIDTH = 520;

function computeThumbnailDimensions(width: number): ThumbnailDimensions {
  return {
    width,
    height: width / SLIDE_ASPECT_RATIO,
    scale: width / SLIDE_BASE_WIDTH,
  };
}
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,
  thumbnailWidth,
  canReorder,
  activeCellId,
  skippedIds,
  noOutputIds,
  slideTypes,
  onSlideClick,
}: SlidesMinimapProps) => {
  const layout = useLayout();
  const { moveCellToIndex, createCell } = useCellActions();
  const deleteCell = useDeleteCellCallback();
  const containerRef = useRef<HTMLDivElement>(null);
  const visibleIds = useVisibleCellIds(containerRef);
  const [activeId, setActiveId] = useState<CellId | null>(null);
  const [dropTarget, setDropTarget] = useState<ProjectedDropTarget | null>(
    null,
  );
  const dimensions = computeThumbnailDimensions(thumbnailWidth);

  const insertCell = (cellId: CellId, before: boolean) => {
    createCell({
      ...(before ? { before: cellId } : { after: cellId }),
      focus: false,
    });
  };

  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({
          layout,
          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}
            dimensions={dimensions}
            isActiveSlide={cell.id === activeCellId}
            isVisible={visibleIds.has(cell.id)}
            isNoOutput={noOutputIds?.has(cell.id)}
            slideType={resolveSlideType({
              cellId: cell.id,
              slideTypes,
              skippedIds,
            })}
            onInsertAbove={
              index === 0 ? () => insertCell(cell.id, true) : undefined
            }
            onInsertBelow={() => insertCell(cell.id, false)}
            onDelete={() => deleteCell({ cellId: 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}
              dimensions={dimensions}
              isActive={activeId === cell.id}
              isActiveSlide={cell.id === activeCellId}
              isVisible={visibleIds.has(cell.id)}
              isNoOutput={noOutputIds?.has(cell.id)}
              slideType={resolveSlideType({
                cellId: cell.id,
                slideTypes,
                skippedIds,
              })}
              dropIndicator={
                dropTarget?.overId === cell.id && activeId !== cell.id
                  ? dropTarget.position
                  : null
              }
              onInsertAbove={
                index === 0 ? () => insertCell(cell.id, true) : undefined
              }
              onInsertBelow={() => insertCell(cell.id, false)}
              onDelete={() => deleteCell({ cellId: cell.id })}
              onClick={() => onSlideClick(index)}
            />
          ))}
        </SortableContext>
      </SlideThumbnailsContainer>
      <DragOverlay>
        {activeCell && (
          <SlideThumbnailCard
            cell={activeCell}
            dimensions={dimensions}
            isOverlay={true}
            isActiveDragSource={true}
            isNoOutput={noOutputIds?.has(activeCell.id)}
          />
        )}
      </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;
  dimensions: ThumbnailDimensions;
  dropIndicator?: DropPosition | null;
  isActive: boolean;
  isActiveSlide?: boolean;
  isVisible?: boolean;
  isNoOutput?: boolean;
  slideType?: SlideType;
  onInsertAbove?: () => void;
  onInsertBelow?: () => void;
  onDelete?: () => void;
  onClick?: () => void;
}

const SortableSlideThumbnail = ({
  cell,
  dimensions,
  dropIndicator,
  isActive,
  isActiveSlide,
  isVisible,
  isNoOutput,
  slideType,
  onInsertAbove,
  onInsertBelow,
  onDelete,
  onClick,
}: SortableSlideThumbnailProps) => {
  const { attributes, listeners, setNodeRef } = useSortable({
    id: cell.id,
  });

  return (
    <SlideThumbnailRow
      ref={setNodeRef}
      cell={cell}
      dimensions={dimensions}
      dropIndicator={dropIndicator}
      isActiveDragSource={isActive}
      isActiveSlide={isActiveSlide}
      isVisible={isVisible}
      isNoOutput={isNoOutput}
      slideType={slideType}
      onInsertAbove={onInsertAbove}
      onInsertBelow={onInsertBelow}
      onDelete={onDelete}
      onClick={onClick}
      {...attributes}
      {...listeners}
    />
  );
};

const SlideThumbnailRow = ({
  cell,
  dimensions,
  className,
  style,
  dropIndicator,
  isActiveSlide = false,
  isActiveDragSource = false,
  isVisible,
  isNoOutput,
  slideType,
  onInsertAbove,
  onInsertBelow,
  onDelete,
  onClick,
  ref,
  ...props
}: SlideThumbnailRowProps) => {
  const rowStyle: React.CSSProperties = {
    paddingTop: MINIMAP_GAP,
    paddingBottom: MINIMAP_GAP,
    ...style,
  };

  // Space is ignored as Reveal.js listens for Space on `document` to advance
  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    if (event.target === event.currentTarget && event.key === "Enter") {
      event.preventDefault();
      event.stopPropagation();
      event.currentTarget.click();
    }
  };

  const row = (
    <div
      ref={ref}
      // A real <button> can't host the nested insert <button>s (invalid HTML),
      // so we keep button semantics via role + keyboard handling below.
      // eslint-disable-next-line jsx-a11y/prefer-tag-over-role
      role="button"
      tabIndex={0}
      data-cell-id={cell.id}
      className={cn(
        "relative shrink-0 appearance-none text-left p-0 bg-transparent outline-hidden",
        className,
      )}
      style={rowStyle}
      onClick={onClick}
      onKeyDown={handleKeyDown}
      {...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",
          )}
        />
      )}
      {onInsertAbove && (
        <InsertCellLine position="above" onInsert={onInsertAbove} />
      )}
      <SlideThumbnailCard
        cell={cell}
        dimensions={dimensions}
        isActiveSlide={isActiveSlide}
        isActiveDragSource={isActiveDragSource}
        isVisible={isVisible}
        isNoOutput={isNoOutput}
        slideType={slideType}
      />
      {onInsertBelow && (
        <InsertCellLine position="below" onInsert={onInsertBelow} />
      )}
    </div>
  );

  if (!onInsertBelow && !onDelete) {
    return row;
  }

  return (
    <ContextMenu>
      <ContextMenuTrigger asChild={true}>{row}</ContextMenuTrigger>
      <ContextMenuContent>
        {onInsertBelow && (
          <ContextMenuItem onSelect={onInsertBelow}>
            <PlusIcon className="mr-2 h-3.5 w-3.5" />
            Add cell
          </ContextMenuItem>
        )}
        <ContextMenuSeparator />
        {onDelete && (
          <ContextMenuItem variant="danger" onSelect={onDelete}>
            <Trash2Icon className="mr-2 h-3.5 w-3.5" />
            Delete cell
          </ContextMenuItem>
        )}
      </ContextMenuContent>
    </ContextMenu>
  );
};

const InsertCellLine = ({
  position,
  onInsert,
}: {
  position: "above" | "below";
  onInsert: () => void;
}) => {
  return (
    <Tooltip content="Add Python cell">
      <button
        type="button"
        aria-label="Add Python cell"
        data-testid="minimap-insert-cell"
        className={cn(
          "absolute left-0 right-0 z-30 flex h-3 items-center justify-center",
          "opacity-0 transition-opacity hover:opacity-80 focus-visible:opacity-100 focus:outline-hidden",
          position === "below"
            ? "bottom-0 translate-y-1/2"
            : "top-0 -translate-y-1/2",
        )}
        // Stop the pointer event from reaching the row's drag sensor / click.
        onPointerDown={Events.stopPropagation()}
        onClick={Events.stopPropagation(onInsert)}
      >
        <span className="absolute left-2 right-2 h-px rounded-full bg-blue-500" />
        <span className="relative flex h-3 w-3 items-center justify-center rounded-full bg-blue-500 text-background shadow-xs">
          <PlusIcon className="h-2 w-2" strokeWidth={3} />
        </span>
      </button>
    </Tooltip>
  );
};

const SlideThumbnailCard = ({
  cell,
  dimensions,
  className,
  style,
  isActiveSlide = false,
  isActiveDragSource = false,
  isOverlay = false,
  isVisible = false,
  isNoOutput = false,
  slideType,
  ref,
  ...props
}: SlideThumbnailCardProps) => {
  const { width, height, scale } = dimensions;
  const visual = isNoOutput ? NO_OUTPUT_VISUAL : getSlideTypeVisual(slideType);
  const isSkipped = isNoOutput || slideType === "skip";

  const outerStyle: React.CSSProperties = {
    width,
    height,
    contain: "strict",
    ...(isOverlay
      ? null
      : {
          contentVisibility: "auto",
          containIntrinsicSize: `${width}px ${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 overflow-hidden transition-colors",
        isActiveSlide || isActiveDragSource || isOverlay
          ? "border-blue-500"
          : "border-border hover:border-blue-500/50",
        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(${scale})`,
            transformOrigin: "top left",
            width: width / scale,
            height: height / scale,
          }}
        >
          {isNoOutput ? (
            <MiniCodePreview code={cell.code} />
          ) : (
            <Slide
              cellId={cell.id}
              status={cell.status}
              output={cell.output}
              stale={outputIsStale(cell, false)}
            />
          )}
        </div>
      )}
      {isSkipped && (
        <div
          className="absolute inset-0 bg-muted/50 pointer-events-none"
          aria-hidden={true}
        />
      )}
      {visual?.Icon && (
        <Tooltip
          content={
            <span className="text-xs opacity-80">{visual.description}</span>
          }
        >
          <span
            className={cn(
              "absolute top-1 right-1 flex items-center gap-1 rounded-full border p-0.5 font-medium leading-none shadow-xs cursor-help",
              isSkipped
                ? "bg-background/90 border-border text-muted-foreground"
                : "bg-background/95 border-border text-foreground/80",
            )}
            aria-label={visual.label}
          >
            <visual.Icon className="h-3.5 w-3.5" />
          </span>
        </Tooltip>
      )}
    </div>
  );
};

const MiniCodePreview = ({ code }: { code: string }) => {
  return (
    <pre className="my-auto w-full overflow-hidden whitespace-pre-wrap wrap-break-word text-lg">
      {code}
    </pre>
  );
};

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({
  layout,
  activeId,
  target,
}: {
  layout: Layout;
  activeId: CellId;
  target: ProjectedDropTarget;
}): ResolvedDropTarget | null {
  if (activeId === target.overId) {
    return null;
  }
  if (layout.columns.length !== 1) {
    Logger.warn("Multi-column mode is not supported");
    return null;
  }

  const [column] = layout.columns;
  const overIndex = column.ids.indexOf(target.overId);
  if (overIndex === -1) {
    return null;
  }

  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;
}

/**
 * Resolves the effective slide type for a cell. Falls back to `"skip"` if the
 * caller-supplied `skippedIds` set marks the cell as skipped, which keeps this
 * component working when only the legacy `skippedIds` prop is provided.
 * Returns `undefined` for the default `"slide"` type so callers can skip
 * rendering any badge.
 */
function resolveSlideType({
  cellId,
  slideTypes,
  skippedIds,
}: {
  cellId: CellId;
  slideTypes: ReadonlyMap<CellId, SlideType> | undefined;
  skippedIds: ReadonlySet<CellId> | undefined;
}): SlideType | undefined {
  const type = slideTypes?.get(cellId);
  if (type && type !== "slide") {
    return type;
  }
  if (skippedIds?.has(cellId)) {
    return "skip";
  }
  return undefined;
}

export const exportedForTesting = {
  useVisibleCellIds,
  projectDropTarget,
  resolveDropTarget,
};