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.

fix(frontend): preserve output DOM across present/edit mode toggles (#10160)

Myles Scolnick6e16b6d5c6ff
diff --git a/frontend/e2e-tests/layout-grid.spec.ts b/frontend/e2e-tests/layout-grid.spec.ts
index 881de9b3fb..af2e85a77c 100644
--- a/frontend/e2e-tests/layout-grid.spec.ts
+++ b/frontend/e2e-tests/layout-grid.spec.ts
@@ -109,7 +109,11 @@ function expectValidBoundingBox(
}
async function bbForText(page: Page, text: string) {
- const el = page.getByText(text).first();
+ // Scope to the visible match: while presenting, the vertical layout renders
+ // the editable cell tree with its CodeMirror editors mounted but
+ // `display:none`, so an unscoped `getByText` also resolves the hidden editor
+ // line, whose text precedes the rendered output in the DOM.
+ const el = page.getByText(text).filter({ visible: true }).first();
await expect(el).toBeVisible();
const bb = await el.boundingBox();
expectValidBoundingBox(bb);
diff --git a/frontend/src/components/editor/SortableCell.tsx b/frontend/src/components/editor/SortableCell.tsx
index ec16e6b195..5acc778ec1 100644
--- a/frontend/src/components/editor/SortableCell.tsx
+++ b/frontend/src/components/editor/SortableCell.tsx
@@ -15,6 +15,10 @@ interface Props extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
cellId: CellId;
canMoveX?: boolean;
+ /**
+ * If true, dragging is disabled (e.g. while presenting).
+ */
+ disabled?: boolean;
}
/**
@@ -42,7 +46,7 @@ function isTransformNoop(transform: Transform | null) {
export const SortableCell = React.forwardRef(
(
- { cellId, canMoveX, ...props }: Props,
+ { cellId, canMoveX, disabled, ...props }: Props,
ref: React.ForwardedRef<HTMLDivElement>,
) => {
// This hook re-renders every time _any_ cell is dragged,
@@ -54,7 +58,7 @@ export const SortableCell = React.forwardRef(
transform,
transition,
isDragging,
- } = useSortable({ id: cellId.toString() });
+ } = useSortable({ id: cellId.toString(), disabled });
// Perf:
// If the transform is a noop, keep it as null
diff --git a/frontend/src/components/editor/__tests__/output-persistence.test.tsx b/frontend/src/components/editor/__tests__/output-persistence.test.tsx
new file mode 100644
index 0000000000..9b379126d0
--- /dev/null
+++ b/frontend/src/components/editor/__tests__/output-persistence.test.tsx
@@ -0,0 +1,241 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { render } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { beforeAll, describe, expect, it } from "vitest";
+import { SetupMocks } from "@/__mocks__/common";
+import { MockNotebook } from "@/__mocks__/notebook";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { cellId } from "@/__tests__/branded";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { notebookAtom } from "@/core/cells/cells";
+import type { CellRuntimeState } from "@/core/cells/types";
+import { createCellRuntimeState } from "@/core/cells/types";
+import { defaultUserConfig } from "@/core/config/config-schema";
+import type { AppMode } from "@/core/mode";
+import { requestClientAtom } from "@/core/network/requests";
+import { Cell } from "../notebook-cell";
+
+const cid = cellId("test");
+
+function createTestWrapper() {
+ const store = createStore();
+ store.set(requestClientAtom, MockRequestClient.create());
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider store={store}>{children}</Provider>
+ );
+ return { wrapper, store };
+}
+
+function seedNotebook(
+ store: ReturnType<typeof createStore>,
+ runtimeOverrides: Partial<CellRuntimeState> = {},
+) {
+ const notebook = MockNotebook.notebookState({
+ cellData: {
+ [cid]: {
+ code: "1 + 1",
+ name: "test_cell",
+ edited: false,
+ serializedEditorState: null,
+ config: {
+ disabled: false,
+ hide_code: false,
+ column: null,
+ },
+ },
+ },
+ });
+ notebook.cellRuntime[cid] = createCellRuntimeState({
+ status: "idle",
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<span>persist me</span>",
+ timestamp: 0,
+ },
+ ...runtimeOverrides,
+ });
+ store.set(notebookAtom, notebook);
+}
+
+function renderCell(mode: AppMode) {
+ return (
+ <TooltipProvider>
+ <Cell
+ cellId={cid}
+ mode={mode}
+ canDelete={true}
+ userConfig={defaultUserConfig()}
+ isCollapsed={false}
+ collapseCount={0}
+ canMoveX={false}
+ theme="light"
+ showPlaceholder={false}
+ />
+ </TooltipProvider>
+ );
+}
+
+beforeAll(() => {
+ SetupMocks.resizeObserver();
+ global.HTMLDivElement.prototype.scrollIntoView = () => {
+ // do nothing
+ };
+});
+
+describe("output persistence across mode changes", () => {
+ it("preserves the output DOM node when toggling edit <-> present", () => {
+ const { store, wrapper } = createTestWrapper();
+ seedNotebook(store);
+
+ const { container, rerender } = render(renderCell("edit"), { wrapper });
+
+ const outputNode = container.querySelector<HTMLElement>(
+ '[data-cell-role="output"]',
+ );
+ expect(outputNode).toBeTruthy();
+ // A property survives only if the exact DOM node instance survives.
+ (outputNode as HTMLElement & { __sentinel?: string }).__sentinel = "alive";
+
+ rerender(renderCell("present"));
+ const presentNode = container.querySelector<HTMLElement>(
+ '[data-cell-role="output"]',
+ );
+ expect(presentNode).toBe(outputNode);
+ expect(presentNode?.isConnected).toBe(true);
+ expect(
+ (presentNode as HTMLElement & { __sentinel?: string }).__sentinel,
+ ).toBe("alive");
+
+ // Edit chrome is hidden but stays mounted while presenting
+ const tray = container.querySelector<HTMLElement>(
+ "[data-testid='cell-tray']",
+ );
+ expect(tray).toBeTruthy();
+ expect(tray?.hidden).toBe(true);
+ // Present styling is applied
+ expect(
+ container
+ .querySelector(`[data-cell-id="${cid}"]`)
+ ?.classList.contains("published"),
+ ).toBe(true);
+
+ rerender(renderCell("edit"));
+ expect(container.querySelector('[data-cell-role="output"]')).toBe(
+ outputNode,
+ );
+ expect(
+ container.querySelector<HTMLElement>("[data-testid='cell-tray']")?.hidden,
+ ).toBe(false);
+ expect(
+ container
+ .querySelector(`[data-cell-id="${cid}"]`)
+ ?.classList.contains("published"),
+ ).toBe(false);
+ });
+
+ it("hides all edit chrome while presenting", () => {
+ const { store, wrapper } = createTestWrapper();
+ seedNotebook(store);
+
+ const { container, rerender } = render(renderCell("edit"), { wrapper });
+
+ // Returns true when the element is not visible: either gone from the DOM or
+ // inside a `hidden` ancestor. Edit chrome may unmount while presenting (only
+ // the cell *output* is contractually kept mounted — see the DOM-node test
+ // above); either way it must not be visible.
+ const isHidden = (testId: string) => {
+ const el = container.querySelector(`[data-testid='${testId}']`);
+ return el === null || el.closest("[hidden]") !== null;
+ };
+
+ // Everything visible in edit mode
+ const editChrome = [
+ "cell-tray",
+ "drag-button",
+ "cell-actions-button",
+ "delete-button",
+ "create-cell-button",
+ "console-output-area",
+ ];
+ for (const testId of editChrome) {
+ expect({ testId, hidden: isHidden(testId) }).toEqual({
+ testId,
+ hidden: false,
+ });
+ }
+
+ rerender(renderCell("present"));
+ for (const testId of editChrome) {
+ expect({ testId, hidden: isHidden(testId) }).toEqual({
+ testId,
+ hidden: true,
+ });
+ }
+
+ rerender(renderCell("edit"));
+ for (const testId of editChrome) {
+ expect({ testId, hidden: isHidden(testId) }).toEqual({
+ testId,
+ hidden: false,
+ });
+ }
+ });
+
+ it("does not dim edited-but-not-run outputs as stale while presenting", () => {
+ const { store, wrapper } = createTestWrapper();
+ seedNotebook(store);
+ // Mark the cell as edited without re-running it
+ const notebook = store.get(notebookAtom);
+ notebook.cellData[cid] = { ...notebook.cellData[cid], edited: true };
+ store.set(notebookAtom, { ...notebook });
+
+ const { container, rerender } = render(renderCell("edit"), { wrapper });
+ expect(container.querySelector(".marimo-output-stale")).toBeTruthy();
+
+ // The read view never dims pending edits; present mode matches it
+ rerender(renderCell("present"));
+ expect(container.querySelector(".marimo-output-stale")).toBeFalsy();
+
+ rerender(renderCell("edit"));
+ expect(container.querySelector(".marimo-output-stale")).toBeTruthy();
+ });
+
+ it("hides errored cells while presenting without unmounting them", () => {
+ const { store, wrapper } = createTestWrapper();
+ seedNotebook(store, {
+ errored: true,
+ output: {
+ channel: "marimo-error",
+ mimetype: "application/vnd.marimo+error",
+ data: [{ type: "exception", exception_type: "ValueError", msg: "!" }],
+ timestamp: 0,
+ },
+ });
+
+ const { container, rerender } = render(renderCell("edit"), { wrapper });
+
+ const outputNode = container.querySelector<HTMLElement>(
+ '[data-cell-role="output"]',
+ );
+ expect(outputNode).toBeTruthy();
+
+ const getSortableWrapper = () =>
+ container.querySelector<HTMLElement>(`[data-cell-id="${cid}"]`)
+ ?.parentElement;
+ expect(getSortableWrapper()?.hidden).toBe(false);
+
+ rerender(renderCell("present"));
+ // Still mounted, but hidden
+ expect(container.querySelector('[data-cell-role="output"]')).toBe(
+ outputNode,
+ );
+ expect(getSortableWrapper()?.hidden).toBe(true);
+
+ rerender(renderCell("edit"));
+ expect(container.querySelector('[data-cell-role="output"]')).toBe(
+ outputNode,
+ );
+ expect(getSortableWrapper()?.hidden).toBe(false);
+ });
+});
diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsx
index 8bd44fd6b1..cd632d8b61 100644
--- a/frontend/src/components/editor/cell/cell-context-menu.tsx
+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx
@@ -39,12 +39,18 @@ interface Props extends Pick<
"cellId" | "getEditorView"
> {
children: React.ReactNode;
+ /**
+ * If true, the custom context menu is disabled and the native one is used
+ * (e.g. while presenting).
+ */
+ disabled?: boolean;
}
export const CellActionsContextMenu = ({
children,
cellId,
getEditorView,
+ disabled,
}: Props) => {
const cellData = useCellData(cellId);
const cellRuntime = useCellRuntime(cellId);
@@ -187,6 +193,7 @@ export const CellActionsContextMenu = ({
return (
<ContextMenu>
<ContextMenuTrigger
+ disabled={disabled}
onContextMenu={(evt) => {
if (evt.target instanceof HTMLImageElement) {
setImageRightClicked(evt.target);
diff --git a/frontend/src/components/editor/columns/__tests__/cell-column.test.tsx b/frontend/src/components/editor/columns/__tests__/cell-column.test.tsx
new file mode 100644
index 0000000000..e34a436df7
--- /dev/null
+++ b/frontend/src/components/editor/columns/__tests__/cell-column.test.tsx
@@ -0,0 +1,105 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { render } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { describe, expect, it } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import type { CellColumnId } from "@/utils/id-tree";
+import { Column } from "../cell-column";
+
+const columnId = "col-1" as CellColumnId;
+
+function renderColumn({
+ width,
+ presenting,
+}: {
+ width: "compact" | "columns";
+ presenting: boolean;
+}) {
+ const store = createStore();
+ return render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <Column
+ columnId={columnId}
+ index={0}
+ width={width}
+ canDelete={false}
+ canMoveLeft={false}
+ canMoveRight={false}
+ presenting={presenting}
+ >
+ <div data-testid="column-children" />
+ </Column>
+ </TooltipProvider>
+ </Provider>,
+ );
+}
+
+describe("Column (single-column notebook)", () => {
+ it("spaces cells with the --notebook-cell-gap variable", () => {
+ const { getByTestId } = renderColumn({
+ width: "compact",
+ presenting: false,
+ });
+ const column = getByTestId("cell-column");
+ expect(column.classList.contains("gap-(--notebook-cell-gap)")).toBe(true);
+ expect(column.classList.contains("[--notebook-cell-gap:0px]")).toBe(false);
+ });
+
+ it("zeroes the cell gap while presenting", () => {
+ const { getByTestId } = renderColumn({
+ width: "compact",
+ presenting: true,
+ });
+ const column = getByTestId("cell-column");
+ expect(column.classList.contains("gap-(--notebook-cell-gap)")).toBe(true);
+ expect(column.classList.contains("[--notebook-cell-gap:0px]")).toBe(true);
+ });
+});
+
+describe("Column (multi-column notebook)", () => {
+ it("shows column chrome when not presenting", () => {
+ const { getByTestId, getAllByTestId } = renderColumn({
+ width: "columns",
+ presenting: false,
+ });
+
+ expect(getByTestId("column-header").hidden).toBe(false);
+ expect(getByTestId("column-frame").classList.contains("border")).toBe(true);
+ for (const handle of getAllByTestId("column-resize-handle")) {
+ expect(handle.hidden).toBe(false);
+ }
+ });
+
+ it("hides column chrome while presenting, without unmounting it", () => {
+ const { getByTestId, getAllByTestId } = renderColumn({
+ width: "columns",
+ presenting: true,
+ });
+
+ // Header (drag handle, move/delete/add buttons) is hidden but mounted
+ expect(getByTestId("column-header").hidden).toBe(true);
+ // No border around the column
+ expect(getByTestId("column-frame").classList.contains("border")).toBe(
+ false,
+ );
+ // Resize handles are hidden
+ const handles = getAllByTestId("column-resize-handle");
+ expect(handles.length).toBeGreaterThan(0);
+ for (const handle of handles) {
+ expect(handle.hidden).toBe(true);
+ }
+ // Cell gap is zeroed on the column root (cascades to descendants)
+ const columnRoot = getByTestId("column-frame").parentElement;
+ expect(columnRoot?.classList.contains("[--notebook-cell-gap:0px]")).toBe(
+ true,
+ );
+ // Editor geometry (saved widths, min-width, gutters) is replaced by the
+ // published content width
+ const inner = getByTestId("column-children").parentElement;
+ expect(inner?.classList.contains("min-w-[500px]")).toBe(false);
+ expect(inner?.classList.contains("w-(--content-width)")).toBe(true);
+ // Children stay mounted
+ expect(getByTestId("column-children")).toBeTruthy();
+ });
+});
diff --git a/frontend/src/components/editor/columns/cell-column.tsx b/frontend/src/components/editor/columns/cell-column.tsx
index 5eb7ee2894..0eb5d8da0c 100644
--- a/frontend/src/components/editor/columns/cell-column.tsx
+++ b/frontend/src/components/editor/columns/cell-column.tsx
@@ -3,6 +3,7 @@
import React, { memo, useRef } from "react";
import type { AppConfig } from "@/core/config/config-schema";
import { useResizeHandle } from "@/hooks/useResizeHandle";
+import { cn } from "@/utils/cn";
import type { CellColumnId } from "@/utils/id-tree";
import { SortableColumn } from "./sortable-column";
import { storageFn } from "./storage";
@@ -17,6 +18,11 @@ interface Props {
canDelete: boolean;
canMoveLeft: boolean;
canMoveRight: boolean;
+ /**
+ * If true, column chrome (drag handles, resize handles, borders) is hidden
+ * while keeping the same component tree mounted.
+ */
+ presenting?: boolean;
}
const { getColumnWidth, saveColumnWidth } = storageFn;
@@ -24,6 +30,10 @@ const { getColumnWidth, saveColumnWidth } = storageFn;
export const Column = memo((props: Props) => {
const columnRef = useRef<HTMLDivElement>(null);
+ // Published cells are not spaced apart. Set once on the column root; the
+ // CSS variable cascades to the gap-using descendants.
+ const zeroGapWhenPresenting = props.presenting && "[--notebook-cell-gap:0px]";
+
if (props.width === "columns") {
return (
<SortableColumn
@@ -33,14 +43,16 @@ export const Column = memo((props: Props) => {
columnId={props.columnId}
canMoveLeft={props.canMoveLeft}
canMoveRight={props.canMoveRight}
- className="group/column"
+ className={cn("group/column", zeroGapWhenPresenting)}
footer={props.footer}
+ presenting={props.presenting}
>
<ResizableComponent
startingWidth={getColumnWidth(props.index)}
onResize={(width: number) => {
saveColumnWidth(props.index, width);
}}
+ presenting={props.presenting}
>
{props.children}
</ResizableComponent>
@@ -50,7 +62,13 @@ export const Column = memo((props: Props) => {
return (
<>
- <div data-testid="cell-column" className="flex flex-col gap-5">
+ <div
+ data-testid="cell-column"
+ className={cn(
+ "flex flex-col gap-(--notebook-cell-gap)",
+ zeroGapWhenPresenting,
+ )}
+ >
{props.children}
</div>
{props.footer}
@@ -64,12 +82,14 @@ interface ResizableComponentProps {
startingWidth: number | "contentWidth";
onResize?: (width: number) => void;
children: React.ReactNode;
+ presenting?: boolean;
}
const ResizableComponent = ({
startingWidth,
onResize,
children,
+ presenting,
}: ResizableComponentProps) => {
const { resizableDivRef, handleRefs, style } = useResizeHandle({
startingWidth,
@@ -80,11 +100,13 @@ const ResizableComponent = ({
return (
<div
ref={ref}
+ data-testid="column-resize-handle"
className={`w-[3px] cursor-col-resize transition-colors duration-200 z-100
relative before:content-[''] before:absolute before:inset-y-0 before:left-[-3px]
before:right-[-3px] before:w-[9px] before:z-[-1]
hover/column:bg-[var(--slate-3)] dark:hover/column:bg-[var(--slate-5)]
hover/column:hover:bg-primary/60 dark:hover/column:hover:bg-primary/60`}
+ hidden={presenting}
/>
);
};
@@ -94,8 +116,16 @@ const ResizableComponent = ({
{renderResizeHandler(handleRefs.left)}
<div
ref={resizableDivRef}
- className="flex flex-col gap-5 box-content min-h-[100px] px-11 pt-3 pb-6 min-w-[500px] z-1"
- style={style}
+ className={cn(
+ "flex flex-col gap-(--notebook-cell-gap) box-content z-1",
+ // While presenting, use the published content width instead of the
+ // editor geometry (saved pixel width, 500px minimum, gutters),
+ // which overflows narrow screens.
+ presenting
+ ? "w-(--content-width)"
+ : "min-h-[100px] px-11 pt-3 pb-6 min-w-[500px]",
+ )}
+ style={presenting ? undefined : style}
>
{children}
</div>
diff --git a/frontend/src/components/editor/columns/sortable-column.tsx b/frontend/src/components/editor/columns/sortable-column.tsx
index 2fc1271f74..2969f7034c 100644
--- a/frontend/src/components/editor/columns/sortable-column.tsx
+++ b/frontend/src/components/editor/columns/sortable-column.tsx
@@ -30,11 +30,24 @@ interface Props extends React.HTMLAttributes<HTMLDivElement> {
canMoveLeft: boolean;
canMoveRight: boolean;
footer?: React.ReactNode;
+ /**
+ * If true, dragging is disabled and the column chrome is hidden
+ * (e.g. while presenting).
+ */
+ presenting?: boolean;
}
const SortableColumnInternal = React.forwardRef(
(
- { columnId, canDelete, canMoveLeft, canMoveRight, footer, ...props }: Props,
+ {
+ columnId,
+ canDelete,
+ canMoveLeft,
+ canMoveRight,
+ footer,
+ presenting,
+ ...props
+ }: Props,
ref: React.Ref<HTMLDivElement>,
) => {
const {
@@ -45,7 +58,7 @@ const SortableColumnInternal = React.forwardRef(
transition,
isDragging,
isOver,
- } = useSortable({ id: columnId });
+ } = useSortable({ id: columnId, disabled: presenting });
const style: React.CSSProperties = {
transform: transform
@@ -78,7 +91,11 @@ const SortableColumnInternal = React.forwardRef(
};
const dragHandle = (
- <div className="px-2 pb-0 group flex items-center overflow-hidden border-b border-(--slate-7)">
+ <div
+ data-testid="column-header"
+ className="px-2 pb-0 group flex items-center overflow-hidden border-b border-(--slate-7)"
+ hidden={presenting}
+ >
<Tooltip content="Move column left" side="top" delayDuration={300}>
<Button
variant="text"
@@ -161,7 +178,10 @@ const SortableColumnInternal = React.forwardRef(
isOver && "bg-accent/20", // Add a background color when dragging over
)}
>
- <div className="border border-(--slate-7)">
+ <div
+ data-testid="column-frame"
+ className={cn(!presenting && "border border-(--slate-7)")}
+ >
{dragHandle}
{props.children}
</div>
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsx
index 4412abb2e9..df00ff0f95 100644
--- a/frontend/src/components/editor/notebook-cell.tsx
+++ b/frontend/src/components/editor/notebook-cell.tsx
@@ -14,6 +14,7 @@ import {
type KeyboardEvent,
memo,
useCallback,
+ useEffect,
useImperativeHandle,
useMemo,
useRef,
@@ -54,6 +55,8 @@ import {
cellNeedsRun,
cellStatusClasses,
isUninstantiated,
+ publishedCellClasses,
+ shouldHidePublishedCell,
} from "../../core/cells/utils";
import type { UserConfig } from "../../core/config/config-schema";
import { isAppInteractionDisabled } from "../../core/websocket/connection-utils";
@@ -303,7 +306,9 @@ const CellComponent = (props: CellProps) => {
);
}
- if (mode === "edit") {
+ // Present mode is handled by EditableCellComponent with the edit chrome
+ // hidden, so that the output DOM is not remounted when toggling modes.
+ if (mode === "edit" || mode === "present") {
return (
<EditableCellComponent
{...props}
@@ -329,14 +334,14 @@ const ReadonlyCellComponent = forwardRef(
published: true,
});
- const outputIsError = isErrorMime(cellRuntime.output?.mimetype);
-
// Hide the output if it's an error or stopped.
- const hidden =
- cellRuntime.errored ||
- cellRuntime.interrupted ||
- cellRuntime.stopped ||
- outputIsError;
+ const hidden = shouldHidePublishedCell({
+ errored: cellRuntime.errored,
+ interrupted: cellRuntime.interrupted,
+ stopped: cellRuntime.stopped,
+ output: cellRuntime.output,
+ showErrorTracebacks: false,
+ });
if (hidden) {
return null;
@@ -368,6 +373,7 @@ const EditableCellComponent = ({
theme,
showPlaceholder,
cellId,
+ mode,
canDelete,
userConfig,
isCollapsed,
@@ -415,6 +421,28 @@ const EditableCellComponent = ({
const loading = outputIsLoading(cellRuntime.status);
+ const isPresenting = mode === "present";
+
+ // While presenting, the cell may be hidden (matching the read view), but it
+ // stays mounted (CSS-hidden) so its DOM survives mode toggles.
+ const presentHidden =
+ isPresenting &&
+ shouldHidePublishedCell({
+ errored: cellRuntime.errored,
+ interrupted: cellRuntime.interrupted,
+ stopped: cellRuntime.stopped,
+ output: cellRuntime.output,
+ showErrorTracebacks: userConfig.runtime.show_tracebacks ?? false,
+ });
+
+ // CodeMirror cannot measure itself while the tray is display:none, so
+ // re-measure when returning to edit mode.
+ useEffect(() => {
+ if (!isPresenting) {
+ editorView.current?.requestMeasure();
+ }
+ }, [isPresenting, editorView]);
+
// console output is cleared immediately on run, so check for queued instead
// of loading to determine staleness
const consoleOutputStale =
@@ -454,7 +482,12 @@ const EditableCellComponent = ({
});
const canCollapse = canCollapseOutline(cellRuntime.outline);
const hasOutput = !isOutputEmpty(cellRuntime.output);
- const isStaleCell = outputIsStale(cellRuntime, cellData.edited);
+ // While presenting, pending edits do not dim the output as stale,
+ // matching the read view.
+ const isStaleCell = outputIsStale(
+ cellRuntime,
+ cellData.edited && !isPresenting,
+ );
const hasConsoleOutput = cellRuntime.consoleOutputs.length > 0;
const cellOutput = userConfig.display.cell_output;
@@ -487,7 +520,8 @@ const EditableCellComponent = ({
},
});
- const emptyMarkdownPlaceholder = isMarkdownCodeHidden &&
+ const emptyMarkdownPlaceholder = !isPresenting &&
+ isMarkdownCodeHidden &&
isEmptyMarkdownContent &&
!needsRun && (
<div
@@ -509,25 +543,31 @@ const EditableCellComponent = ({
);
const outputArea = hasOutput && !isEmptyMarkdownContent && (
- <div className="relative" onDoubleClick={showHiddenCodeIfMarkdown}>
- <div className="absolute top-5 -left-7 z-20 print:hidden">
- <CollapseToggle
- isCollapsed={isCollapsed}
- onClick={() => {
- if (isCollapsed) {
- actions.expandCell({ cellId });
- } else {
- actions.collapseCell({ cellId });
- }
- }}
- canCollapse={canCollapse}
- />
- </div>
+ <div
+ className="relative"
+ onDoubleClick={isPresenting ? undefined : showHiddenCodeIfMarkdown}
+ >
+ {!isPresenting && (
+ <div className="absolute top-5 -left-7 z-20 print:hidden">
+ <CollapseToggle
+ isCollapsed={isCollapsed}
+ onClick={() => {
+ if (isCollapsed) {
+ actions.expandCell({ cellId });
+ } else {
+ actions.collapseCell({ cellId });
+ }
+ }}
+ canCollapse={canCollapse}
+ />
+ </div>
+ )}
<OutputArea
- // Only allow expanding in edit mode
+ // `allowExpand` must stay constant across modes: flipping it swaps the
+ // output's container component and would remount the output DOM.
allowExpand={true}
- // Force expand when markdown is hidden
- forceExpand={isMarkdownCodeHidden}
+ // Force expand when markdown is hidden or when presenting
+ forceExpand={isMarkdownCodeHidden || isPresenting}
className={CSSClasses.outputArea}
cellId={cellId}
output={cellRuntime.output}
@@ -537,19 +577,32 @@ const EditableCellComponent = ({
</div>
);
- const className = clsx("marimo-cell", "hover-actions-parent z-10", {
- interactive: true,
- ...cellStatusClasses({
- needsRun,
- errored: cellRuntime.errored,
- stopped: cellRuntime.stopped,
- disabled: cellData.config.disabled,
- status: cellRuntime.status,
- }),
- borderless:
- isMarkdownCodeHidden && hasOutput && !navigationProps["data-selected"],
- "pending-cut": isPendingCut,
- });
+ const className = clsx(
+ "marimo-cell",
+ "hover-actions-parent",
+ isPresenting
+ ? // Match the published styling of the read view
+ publishedCellClasses({
+ errored: cellRuntime.errored,
+ stopped: cellRuntime.stopped,
+ })
+ : {
+ "z-10": true,
+ interactive: true,
+ ...cellStatusClasses({
+ needsRun,
+ errored: cellRuntime.errored,
+ stopped: cellRuntime.stopped,
+ disabled: cellData.config.disabled,
+ status: cellRuntime.status,
+ }),
+ borderless:
+ isMarkdownCodeHidden &&
+ hasOutput &&
+ !navigationProps["data-selected"],
+ "pending-cut": isPendingCut,
+ },
+ );
const handleRefactorWithAI: OnRefactorWithAI = useEvent(
(opts: { prompt: string; triggerImmediately: boolean }) => {
@@ -578,7 +631,11 @@ const EditableCellComponent = ({
return (
<TooltipProvider>
- <CellActionsContextMenu cellId={cellId} getEditorView={getEditorView}>
+ <CellActionsContextMenu
+ cellId={cellId}
+ getEditorView={getEditorView}
+ disabled={isPresenting}
+ >
<SortableCell
tabIndex={-1}
ref={cellRef}
@@ -587,23 +644,34 @@ const EditableCellComponent = ({
onKeyDown={resumeCompletionHandler}
cellId={cellId}
canMoveX={canMoveX}
+ disabled={isPresenting}
+ hidden={presentHidden}
title={renderCellTitle()}
>
<div
tabIndex={-1}
- {...navigationProps}
+ {...(isPresenting ? undefined : navigationProps)}
className={cn(
className,
- navigationProps.className,
- "focus:ring-1 focus:ring-(--slate-8) focus:ring-offset-2",
+ !isPresenting && navigationProps.className,
+ !isPresenting &&
+ "focus:ring-1 focus:ring-(--slate-8) focus:ring-offset-2",
)}
ref={cellContainerRef}
{...cellDomProps(cellId, cellData.name)}
>
- <CellLeftSideActions cellId={cellId} actions={actions} />
+ {!isPresenting && (
+ <CellLeftSideActions cellId={cellId} actions={actions} />
+ )}
{cellOutput === "above" && (outputArea || emptyMarkdownPlaceholder)}
+ {/* The tray is hidden-but-mounted while presenting so CodeMirror
+ state survives mode toggles. Hide via the `hidden` attribute:
+ preflight's `[hidden] { display: none !important }` beats
+ `.tray { display: flex }`, which a display class would not. */}
<div
- className={cn("tray")}
+ data-testid="cell-tray"
+ className="tray"
+ hidden={isPresenting}
data-has-output-above={hasOutputAbove}
data-hidden={isMarkdownCodeHidden}
>
@@ -643,21 +711,25 @@ const EditableCellComponent = ({
setLanguageAdapter={setLanguageAdapter}
outputArea={cellOutput}
/>
- <CellRightSideActions
- className={cn(
- isMarkdownCodeHidden && cellOutput === "below" && "top-14",
- )}
- edited={cellData.edited}
- status={cellRuntime.status}
- isCellStatusInline={isCellStatusInline}
- uninstantiated={uninstantiated}
- disabled={cellData.config.disabled}
- runElapsedTimeMs={cellRuntime.runElapsedTimeMs}
- runStartTimestamp={cellRuntime.runStartTimestamp}
- lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}
- staleInputs={cellRuntime.staleInputs}
- interrupted={cellRuntime.interrupted}
- />
+ {/* Unmounted while presenting: the status timer re-renders every
+ frame for running cells. */}
+ {!isPresenting && (
+ <CellRightSideActions
+ className={cn(
+ isMarkdownCodeHidden && cellOutput === "below" && "top-14",
+ )}
+ edited={cellData.edited}
+ status={cellRuntime.status}
+ isCellStatusInline={isCellStatusInline}
+ uninstantiated={uninstantiated}
+ disabled={cellData.config.disabled}
+ runElapsedTimeMs={cellRuntime.runElapsedTimeMs}
+ runStartTimestamp={cellRuntime.runStartTimestamp}
+ lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}
+ staleInputs={cellRuntime.staleInputs}
+ interrupted={cellRuntime.interrupted}
+ />
+ )}
<div className="shoulder-bottom hover-action">
{canDelete && isCellCodeShown && (
<DeleteButton
@@ -675,12 +747,14 @@ const EditableCellComponent = ({
)}
</div>
</div>
- <SqlValidationErrorBanner
- cellId={cellId}
- hide={cellRuntime.errored && !isStaleCell}
- />
+ {!isPresenting && (
+ <SqlValidationErrorBanner
+ cellId={cellId}
+ hide={cellRuntime.errored && !isStaleCell}
+ />
+ )}
{cellOutput === "below" && (outputArea || emptyMarkdownPlaceholder)}
- {cellRuntime.serialization && (
+ {!isPresenting && cellRuntime.serialization && (
<div className="py-1 px-2 flex items-center justify-end gap-2 last:rounded-b">
{isToplevel && (
<a
@@ -738,34 +812,36 @@ const EditableCellComponent = ({
</Tooltip>
</div>
)}
- <ConsoleOutput
- consoleOutputs={cellRuntime.consoleOutputs}
- stale={consoleOutputStale}
- interrupted={cellRuntime.interrupted}
- // Empty name if serialization triggered
- cellName={cellRuntime.serialization ? "_" : cellData.name}
- onRefactorWithAI={handleRefactorWithAI}
- onClear={() => {
- actions.clearCellConsoleOutput({ cellId });
- // The debugger "Clear" (trashcan) also drops this cell's
- // breakpoints; no-op when none are set.
- clearCellBreakpoints(cellId);
- }}
- onSubmitDebugger={(text, index) => {
- actions.setStdinResponse({
- cellId,
- response: text,
- outputIndex: index,
- });
- sendStdin({ text });
- }}
- cellId={cellId}
- debuggerActive={cellRuntime.debuggerActive}
- />
+ {!isPresenting && (
+ <ConsoleOutput
+ consoleOutputs={cellRuntime.consoleOutputs}
+ stale={consoleOutputStale}
+ interrupted={cellRuntime.interrupted}
+ // Empty name if serialization triggered
+ cellName={cellRuntime.serialization ? "_" : cellData.name}
+ onRefactorWithAI={handleRefactorWithAI}
+ onClear={() => {
+ actions.clearCellConsoleOutput({ cellId });
+ // The debugger "Clear" (trashcan) also drops this cell's
+ // breakpoints; no-op when none are set.
+ clearCellBreakpoints(cellId);
+ }}
+ onSubmitDebugger={(text, index) => {
+ actions.setStdinResponse({
+ cellId,
+ response: text,
+ outputIndex: index,
+ });
+ sendStdin({ text });
+ }}
+ cellId={cellId}
+ debuggerActive={cellRuntime.debuggerActive}
+ />
+ )}
<PendingDeleteConfirmation cellId={cellId} />
</div>
- <StagedAICellFooter cellId={cellId} />
- {isCollapsed && (
+ {!isPresenting && <StagedAICellFooter cellId={cellId} />}
+ {isCollapsed && !isPresenting && (
<CollapsedCellBanner
onClick={() => actions.expandCell({ cellId })}
count={collapseCount}
@@ -970,6 +1046,7 @@ const SetupCellComponent = ({
theme,
showPlaceholder,
cellId,
+ mode,
canDelete,
userConfig,
canMoveX,
@@ -1080,10 +1157,26 @@ const SetupCellComponent = ({
return undefined;
};
+ const isPresenting = mode === "present";
+
+ // CodeMirror cannot measure itself while its hidden ancestor is display:none,
+ // so re-measure when returning to edit mode. (Mirrors EditableCellComponent.)
+ useEffect(() => {
+ if (!isPresenting) {
+ editorView.current?.requestMeasure();
+ }
+ }, [isPresenting, editorView]);
+
return (
<TooltipProvider>
- <CellActionsContextMenu cellId={cellId} getEditorView={getEditorView}>
- <div>
+ <CellActionsContextMenu
+ cellId={cellId}
+ getEditorView={getEditorView}
+ disabled={isPresenting}
+ >
+ {/* The setup cell has no visible output, so it is hidden (but stays
+ mounted) while presenting. */}
+ <div hidden={isPresenting}>
<div
data-status={cellRuntime.status}
ref={cellRef}
@@ -1145,18 +1238,22 @@ const SetupCellComponent = ({
setLanguageAdapter={Functions.NOOP}
showLanguageToggles={false}
/>
- <CellRightSideActions
- edited={cellData.edited}
- status={cellRuntime.status}
- isCellStatusInline={false}
- uninstantiated={uninstantiated}
- disabled={cellData.config.disabled}
- runElapsedTimeMs={cellRuntime.runElapsedTimeMs}
- runStartTimestamp={cellRuntime.runStartTimestamp}
- lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}
- staleInputs={cellRuntime.staleInputs}
- interrupted={cellRuntime.interrupted}
- />
+ {/* Unmounted while presenting: the status timer re-renders every
+ frame for running cells. */}
+ {!isPresenting && (
+ <CellRightSideActions
+ edited={cellData.edited}
+ status={cellRuntime.status}
+ isCellStatusInline={false}
+ uninstantiated={uninstantiated}
+ disabled={cellData.config.disabled}
+ runElapsedTimeMs={cellRuntime.runElapsedTimeMs}
+ runStartTimestamp={cellRuntime.runStartTimestamp}
+ lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}
+ staleInputs={cellRuntime.staleInputs}
+ interrupted={cellRuntime.interrupted}
+ />
+ )}
<div className="shoulder-bottom hover-action">
{canDelete && (
<DeleteButton
diff --git a/frontend/src/components/editor/renderers/__tests__/cells-renderer.test.tsx b/frontend/src/components/editor/renderers/__tests__/cells-renderer.test.tsx
new file mode 100644
index 0000000000..0edc812348
--- /dev/null
+++ b/frontend/src/components/editor/renderers/__tests__/cells-renderer.test.tsx
@@ -0,0 +1,66 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { render } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { describe, expect, it } from "vitest";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { parseAppConfig } from "@/core/config/config-schema";
+import { initialLayoutState, layoutStateAtom } from "@/core/layout/layout";
+import { type AppMode, kioskModeAtom } from "@/core/mode";
+import { requestClientAtom } from "@/core/network/requests";
+import { CellsRenderer } from "../cells-renderer";
+import type { LayoutType } from "../types";
+
+function renderWithStore(
+ mode: AppMode,
+ {
+ kiosk = false,
+ layout = "vertical",
+ }: { kiosk?: boolean; layout?: LayoutType } = {},
+) {
+ const store = createStore();
+ store.set(requestClientAtom, MockRequestClient.create());
+ store.set(kioskModeAtom, kiosk);
+ store.set(layoutStateAtom, {
+ ...initialLayoutState(),
+ selectedLayout: layout,
+ });
+
+ return render(
+ <Provider store={store}>
+ <CellsRenderer appConfig={parseAppConfig({})} mode={mode}>
+ <div data-testid="notebook-children" />
+ </CellsRenderer>
+ </Provider>,
+ );
+}
+
+describe("CellsRenderer", () => {
+ it("renders children in edit mode", () => {
+ const { queryByTestId } = renderWithStore("edit");
+ expect(queryByTestId("notebook-children")).toBeTruthy();
+ });
+
+ it("keeps children mounted in present mode with the vertical layout", () => {
+ // This preserves cell output DOM across the edit <-> present toggle;
+ // swapping to the layout renderer would remount every output.
+ const { queryByTestId } = renderWithStore("present");
+ expect(queryByTestId("notebook-children")).toBeTruthy();
+ });
+
+ it("uses the layout renderer in present mode with a non-vertical layout", () => {
+ // Only present+vertical keeps the editable tree mounted; grid/slides swap
+ // to their layout renderer (which remounts outputs) per the toggle logic.
+ const { queryByTestId } = renderWithStore("present", { layout: "grid" });
+ expect(queryByTestId("notebook-children")).toBeFalsy();
+ });
+
+ it("uses the layout renderer in read mode", () => {
+ const { queryByTestId } = renderWithStore("read");
+ expect(queryByTestId("notebook-children")).toBeFalsy();
+ });
+
+ it("uses the layout renderer in kiosk mode", () => {
+ const { queryByTestId } = renderWithStore("edit", { kiosk: true });
+ expect(queryByTestId("notebook-children")).toBeFalsy();
+ });
+});
diff --git a/frontend/src/components/editor/renderers/cell-array.tsx b/frontend/src/components/editor/renderers/cell-array.tsx
index 04faac42de..843deda29d 100644
--- a/frontend/src/components/editor/renderers/cell-array.tsx
+++ b/frontend/src/components/editor/renderers/cell-array.tsx
@@ -89,22 +89,32 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
const { theme } = useTheme();
const { toggleSidebarPanel } = useChromeActions();
+ const isPresenting = mode === "present";
+
// Side-effects
useFocusFirstEditor();
// HOTKEYS
- useHotkey("global.focusTop", actions.focusTopCell);
- useHotkey("global.focusBottom", actions.focusBottomCell);
+ // Cell-editing hotkeys are disabled while presenting
+ const whilePresenting = { disabled: isPresenting };
+ useHotkey("global.focusTop", actions.focusTopCell, whilePresenting);
+ useHotkey("global.focusBottom", actions.focusBottomCell, whilePresenting);
useHotkey("global.toggleSidebar", toggleSidebarPanel);
- useHotkey("global.foldCode", actions.foldAll);
- useHotkey("global.unfoldCode", actions.unfoldAll);
- useHotkey("global.formatAll", () => {
- formatAll();
- });
+ useHotkey("global.foldCode", actions.foldAll, whilePresenting);
+ useHotkey("global.unfoldCode", actions.unfoldAll, whilePresenting);
+ useHotkey(
+ "global.formatAll",
+ () => {
+ formatAll();
+ },
+ whilePresenting,
+ );
// Catch all to avoid native OS behavior
- // Otherwise a user might try to hide a cell and accidentally hide the OS window
- useHotkey("cell.hideCode", Functions.NOOP);
- useHotkey("cell.format", Functions.NOOP);
+ // Otherwise a user might try to hide a cell and accidentally hide the OS
+ // window. While presenting, no cell editing is possible, so let the
+ // keystrokes reach the browser/OS.
+ useHotkey("cell.hideCode", Functions.NOOP, whilePresenting);
+ useHotkey("cell.format", Functions.NOOP, whilePresenting);
const cellIds = useCellIds();
const scrollKey = useScrollKey();
@@ -121,10 +131,11 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
return (
<VerticalLayoutWrapper
// 'pb' allows the user to put the cell in the middle of the screen
- className="pb-[40vh]"
+ className={cn(!isPresenting && "pb-[40vh]")}
invisible={false}
appConfig={appConfig}
- innerClassName="pr-4" // For the floating actions
+ // 'pr' makes room for the floating actions
+ innerClassName={cn(!isPresenting && "pr-4")}
>
<PackageAlert />
<StartupLogsAlert />
@@ -186,6 +197,7 @@ const CellColumn: React.FC<{
const hasOnlyOneCell = cellIds.hasOnlyOneId();
const hasSetupCell = cellIds.inOrderIds.includes(SETUP_CELL_ID);
+ const isPresenting = mode === "present";
return (
<Column
@@ -195,8 +207,9 @@ const CellColumn: React.FC<{
canMoveRight={index < columnsLength - 1}
width={appConfig.width}
canDelete={columnsLength > 1}
+ presenting={isPresenting}
footer={
- hideControls ? null : (
+ hideControls || isPresenting ? null : (
<AddCellButtons
columnId={columnId}
className={cn(
diff --git a/frontend/src/components/editor/renderers/cells-renderer.tsx b/frontend/src/components/editor/renderers/cells-renderer.tsx
index 713f3a68e2..afa03cf071 100644
--- a/frontend/src/components/editor/renderers/cells-renderer.tsx
+++ b/frontend/src/components/editor/renderers/cells-renderer.tsx
@@ -29,8 +29,14 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
const { selectedLayout, layoutData } = useLayoutState();
const kioskMode = useAtomValue(kioskModeAtom);
- // Just render children if we are in edit mode
- if (mode === "edit" && !kioskMode) {
+ // Render children (the editable notebook) in edit mode, and in present
+ // mode with the vertical layout: keeping the same tree across the
+ // edit<->present toggle preserves cell output DOM (iframes, widgets).
+ // Grid/slides layouts and kiosk mode swap to their layout renderer.
+ if (
+ !kioskMode &&
+ (mode === "edit" || (mode === "present" && selectedLayout === "vertical"))
+ ) {
return children;
}
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
index 656874c078..c1ce8d2fa0 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -33,11 +33,14 @@ import { getReadonlyCodeDisplay } from "@/core/cells/readonly-code-display";
import { MarkdownLanguageAdapter } from "@/core/codemirror/language/languages/markdown";
import { useResolvedMarimoConfig } from "@/core/config/config";
import { CSSClasses, KnownQueryParams } from "@/core/constants";
-import type { MarimoError, OutputMessage } from "@/core/kernel/messages";
+import type { OutputMessage } from "@/core/kernel/messages";
import { kernelStateAtom } from "@/core/kernel/state";
import { useNotebookCodeAvailable } from "@/core/meta/code-visibility";
import { showCodeInRunModeAtom } from "@/core/meta/state";
-import { isErrorMime } from "@/core/mime";
+import {
+ publishedCellClasses,
+ shouldHidePublishedCell,
+} from "@/core/cells/utils";
import { type AppMode, kioskModeAtom } from "@/core/mode";
import { useRequestClient } from "@/core/network/requests";
import type { CellConfig } from "@/core/network/types";
@@ -362,12 +365,13 @@ const VerticalCell = memo(
const className = cn(
"marimo-cell",
"hover-actions-parent empty:invisible",
- {
- published: published,
- "has-error": errored,
- stopped: stopped,
- borderless: isPureMarkdown && !published,
- },
+ published
+ ? publishedCellClasses({ errored, stopped })
+ : {
+ "has-error": errored,
+ stopped: stopped,
+ borderless: isPureMarkdown,
+ },
);
// Read mode and show code
@@ -419,19 +423,15 @@ const VerticalCell = memo(
);
}
- const outputIsError = isErrorMime(output?.mimetype);
// When show_tracebacks is enabled, show error outputs inline
// instead of hiding them
- const hasTraceback =
- showErrorTracebacks &&
- outputIsError &&
- Array.isArray(output?.data) &&
- output.data.some(
- (e: MarimoError) =>
- e.type === "exception" && "traceback" in e && e.traceback,
- );
- const hidden =
- (errored || interrupted || stopped || outputIsError) && !hasTraceback;
+ const hidden = shouldHidePublishedCell({
+ errored,
+ interrupted,
+ stopped,
+ output,
+ showErrorTracebacks,
+ });
if (hidden) {
return null;
}
diff --git a/frontend/src/core/cells/__tests__/utils.test.ts b/frontend/src/core/cells/__tests__/utils.test.ts
index 678ac3870d..79217a34e7 100644
--- a/frontend/src/core/cells/__tests__/utils.test.ts
+++ b/frontend/src/core/cells/__tests__/utils.test.ts
@@ -8,11 +8,13 @@ import {
} from "@/core/cells/cells";
import { CellId } from "@/core/cells/ids";
import type { CellData, CellRuntimeState } from "@/core/cells/types";
+import type { OutputMessage } from "@/core/kernel/messages";
import { MultiColumn } from "@/utils/id-tree";
import {
disabledCellIds,
enabledCellIds,
isUninstantiated,
+ shouldHidePublishedCell,
staleCellIds,
} from "../utils";
@@ -426,3 +428,60 @@ describe("enabledCellIds", () => {
expect(result).toEqual([cellId2, cellId3]);
});
});
+
+describe("shouldHidePublishedCell", () => {
+ const base = {
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ output: null,
+ showErrorTracebacks: false,
+ };
+ const errorOutput = (traceback?: string): OutputMessage => ({
+ channel: "marimo-error",
+ mimetype: "application/vnd.marimo+error",
+ data: [
+ { type: "exception", exception_type: "ValueError", msg: "!", traceback },
+ ],
+ timestamp: 0,
+ });
+
+ it("does not hide a healthy cell", () => {
+ expect(shouldHidePublishedCell(base)).toBe(false);
+ });
+
+ it.each(["errored", "interrupted", "stopped"] as const)(
+ "hides a %s cell",
+ (key) => {
+ expect(shouldHidePublishedCell({ ...base, [key]: true })).toBe(true);
+ },
+ );
+
+ it("hides error outputs", () => {
+ expect(shouldHidePublishedCell({ ...base, output: errorOutput() })).toBe(
+ true,
+ );
+ });
+
+ it("shows error outputs with a traceback when show_tracebacks is enabled", () => {
+ expect(
+ shouldHidePublishedCell({
+ ...base,
+ errored: true,
+ output: errorOutput("Traceback (most recent call last) ..."),
+ showErrorTracebacks: true,
+ }),
+ ).toBe(false);
+ });
+
+ it("hides error outputs without a traceback even when show_tracebacks is enabled", () => {
+ expect(
+ shouldHidePublishedCell({
+ ...base,
+ errored: true,
+ output: errorOutput(),
+ showErrorTracebacks: true,
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.ts
index cc6e860280..ca2780de7c 100644
--- a/frontend/src/core/cells/utils.ts
+++ b/frontend/src/core/cells/utils.ts
@@ -2,6 +2,8 @@
import type { EditorView } from "@codemirror/view";
import { Objects } from "@/utils/objects";
+import type { MarimoError, OutputMessage } from "../kernel/messages";
+import { isErrorMime } from "../mime";
import type { RuntimeState } from "../network/types";
import type { NotebookState } from "./cells";
import type { CellId } from "./ids";
@@ -196,3 +198,52 @@ export function cellStatusClasses({
stale: status === "disabled-transitively",
};
}
+
+/**
+ * Status classes for a published cell (read or present mode, output only).
+ */
+export function publishedCellClasses({
+ errored,
+ stopped,
+}: {
+ errored: boolean;
+ stopped: boolean;
+}) {
+ return {
+ published: true,
+ "has-error": errored,
+ stopped: stopped,
+ };
+}
+
+/**
+ * Whether a published cell (read or present mode) should be hidden.
+ *
+ * Errored, interrupted, and stopped cells (and error outputs) are hidden in
+ * published views, unless `show_tracebacks` is enabled and the output carries
+ * an exception traceback to display inline.
+ */
+export function shouldHidePublishedCell({
+ errored,
+ interrupted,
+ stopped,
+ output,
+ showErrorTracebacks,
+}: {
+ errored: boolean;
+ interrupted: boolean;
+ stopped: boolean;
+ output: OutputMessage | null;
+ showErrorTracebacks: boolean;
+}): boolean {
+ const outputIsError = isErrorMime(output?.mimetype);
+ const hasTraceback =
+ showErrorTracebacks &&
+ outputIsError &&
+ Array.isArray(output?.data) &&
+ output.data.some(
+ (e: MarimoError) =>
+ e.type === "exception" && "traceback" in e && e.traceback,
+ );
+ return (errored || interrupted || stopped || outputIsError) && !hasTraceback;
+}
diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.css
index 4fc253380d..b7d168e6b3 100644
--- a/frontend/src/css/app/Cell.css
+++ b/frontend/src/css/app/Cell.css
@@ -255,6 +255,12 @@
border: none;
box-shadow: none;
+ /* No dividers between sections. Tailwind v4's divide-y is structural
+ * (`> :not(:last-child)`), so hidden-but-mounted children (e.g. the tray
+ * while presenting) still count as siblings and would otherwise draw a
+ * stray rule under the output. */
+ @apply divide-y-0;
+
.output-area {
/* flow-root interferes with margin collapsing, but appears to be unneeded
* when cell outlines are hidden; clear:both is sufficient.
@@ -443,6 +449,10 @@
/* 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: 100px;
+
+ /* Vertical gap between notebook cells (gap-5). Overridable via custom css;
+ * zeroed while presenting, when published cells flow together. */
+ --notebook-cell-gap: 1.25rem;
}
/* ------------------------ CodeMirror Editor ----------------------------- */
diff --git a/frontend/src/hooks/__tests__/useHotkey.test.tsx b/frontend/src/hooks/__tests__/useHotkey.test.tsx
new file mode 100644
index 0000000000..c38c67fed0
--- /dev/null
+++ b/frontend/src/hooks/__tests__/useHotkey.test.tsx
@@ -0,0 +1,88 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { renderHook } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { describe, expect, it, vi } from "vitest";
+import { Functions } from "@/utils/functions";
+import { useHotkey } from "../useHotkey";
+
+// global.hideCode is bound to "Mod-." by default; "mod" accepts ctrl or meta.
+const SHORTCUT = "global.hideCode";
+
+function createWrapper() {
+ const store = createStore();
+ return ({ children }: { children: React.ReactNode }) => (
+ <Provider store={store}>{children}</Provider>
+ );
+}
+
+function press() {
+ const event = new KeyboardEvent("keydown", {
+ key: ".",
+ ctrlKey: true,
+ cancelable: true,
+ bubbles: true,
+ });
+ document.dispatchEvent(event);
+ return event;
+}
+
+describe("useHotkey", () => {
+ it("invokes the callback and prevents default", () => {
+ const callback = vi.fn();
+ renderHook(() => useHotkey(SHORTCUT, callback), {
+ wrapper: createWrapper(),
+ });
+
+ const event = press();
+ expect(callback).toHaveBeenCalledOnce();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it("does not prevent default when the callback returns false", () => {
+ const callback = vi.fn(() => false);
+ renderHook(() => useHotkey(SHORTCUT, callback), {
+ wrapper: createWrapper(),
+ });
+
+ const event = press();
+ expect(callback).toHaveBeenCalledOnce();
+ expect(event.defaultPrevented).toBe(false);
+ });
+
+ it("still swallows the keystroke for NOOP catch-all handlers", () => {
+ renderHook(() => useHotkey(SHORTCUT, Functions.NOOP), {
+ wrapper: createWrapper(),
+ });
+
+ const event = press();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it("neither runs the callback nor prevents default when disabled", () => {
+ const callback = vi.fn();
+ renderHook(() => useHotkey(SHORTCUT, callback, { disabled: true }), {
+ wrapper: createWrapper(),
+ });
+
+ const event = press();
+ expect(callback).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+ });
+
+ it("re-enables when disabled flips back to false", () => {
+ const callback = vi.fn();
+ const { rerender } = renderHook(
+ ({ disabled }: { disabled: boolean }) =>
+ useHotkey(SHORTCUT, callback, { disabled }),
+ { wrapper: createWrapper(), initialProps: { disabled: true } },
+ );
+
+ press();
+ expect(callback).not.toHaveBeenCalled();
+
+ rerender({ disabled: false });
+ const event = press();
+ expect(callback).toHaveBeenCalledOnce();
+ expect(event.defaultPrevented).toBe(true);
+ });
+});
diff --git a/frontend/src/hooks/useHotkey.ts b/frontend/src/hooks/useHotkey.ts
index 56055b2ead..60e29b755c 100644
--- a/frontend/src/hooks/useHotkey.ts
+++ b/frontend/src/hooks/useHotkey.ts
@@ -17,13 +17,31 @@ type HotkeyHandler = (
// oxlint-disable-next-line typescript/no-invalid-void-type
) => boolean | void | undefined | Promise<void>;
+interface HotkeyOptions {
+ /**
+ * If true, the hotkey is not handled at all: the callback does not run, the
+ * event's default is not prevented, and the action is not registered in the
+ * shortcut registry.
+ *
+ * This differs from passing `Functions.NOOP` as the callback, which still
+ * swallows the keystroke (preventDefault) to suppress native browser/OS
+ * behavior.
+ */
+ disabled?: boolean;
+}
+
/**
* Registers a hotkey listener for the given shortcut.
*
* @param callback The callback to run when the shortcut is pressed. It does not need to be memoized as this hook will always use the latest callback.
* If the callback returns false, preventDefault will not be called on the event.
*/
-export function useHotkey(shortcut: HotkeyAction, callback: HotkeyHandler) {
+export function useHotkey(
+ shortcut: HotkeyAction,
+ callback: HotkeyHandler,
+ options: HotkeyOptions = {},
+) {
+ const { disabled = false } = options;
const { registerAction, unregisterAction } = useSetRegisteredAction();
const hotkeys = useAtomValue(hotkeysAtom);
@@ -31,7 +49,7 @@ export function useHotkey(shortcut: HotkeyAction, callback: HotkeyHandler) {
const memoizeCallback = useEvent((evt?: KeyboardEvent) => callback(evt));
const listener = useEvent((e: KeyboardEvent) => {
- if (e.defaultPrevented) {
+ if (disabled || e.defaultPrevented) {
return;
}
@@ -51,11 +69,18 @@ export function useHotkey(shortcut: HotkeyAction, callback: HotkeyHandler) {
// Register with the shortcut registry
useEffect(() => {
- if (!isNOOP) {
+ if (!isNOOP && !disabled) {
registerAction(shortcut, memoizeCallback);
return () => unregisterAction(shortcut);
}
- }, [memoizeCallback, shortcut, isNOOP, registerAction, unregisterAction]);
+ }, [
+ memoizeCallback,
+ shortcut,
+ isNOOP,
+ disabled,
+ registerAction,
+ unregisterAction,
+ ]);
}
/**