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.

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

import { useCallback } from "react";
import { getNotebook, type NotebookState } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { isOutputEmpty } from "@/core/cells/outputs";
import { useNotebookDocumentEdit } from "@/core/notebook/document";
import type { CellConfig } from "@/core/network/types";
import { Objects } from "@/utils/objects";

/**
 * The `expand_output` config changes needed to expand or clamp every output.
 *
 * Both actions skip cells without output, so their source isn't annotated
 * with a config that has no effect.
 */
export function outputExpansionConfigs(
  notebook: NotebookState,
  expanded: boolean,
): Record<CellId, Partial<CellConfig>> {
  const configs: Record<CellId, Partial<CellConfig>> = {};
  for (const cellId of notebook.cellIds) {
    const cell = notebook.cellData[cellId];
    if (
      cell === undefined ||
      (cell.config.expand_output ?? false) === expanded
    ) {
      continue;
    }
    if (isOutputEmpty(notebook.cellRuntime[cellId]?.output)) {
      continue;
    }
    configs[cellId] = { expand_output: expanded };
  }
  return configs;
}

/**
 * Hook returning a callback that shows every cell's output in full, or clamps
 * every output to a fixed height, by setting each cell's `expand_output` config.
 */
export const useSetOutputsExpanded = () => {
  const edit = useNotebookDocumentEdit();

  return useCallback(
    (expanded: boolean) => {
      const entries = Objects.entries(
        outputExpansionConfigs(getNotebook(), expanded),
      );
      if (entries.length === 0) {
        return;
      }

      edit((tx) => {
        for (const [cellId, config] of entries) {
          tx.updateConfig(cellId, config);
        }
      });
    },
    [edit],
  );
};