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.

feat(slides): per-slide show-code config + editor toggles (#9831)

Shahmir Varqha3cc9be1affae
diff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsx
index b496283324..dab65cd665 100644
--- a/frontend/src/components/editor/cell/code/language-toggle.tsx
+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx
@@ -17,6 +17,11 @@ interface LanguageTogglesProps {
code: string;
currentLanguageAdapter: LanguageAdapter["type"] | undefined;
onAfterToggle: () => void;
+ /**
+ * Classes for the wrapper element. Defaults to the absolutely-positioned,
+ * hover-revealed placement used inside the notebook cell editor.
+ */
+ className?: string;
}
export const LanguageToggles: React.FC<LanguageTogglesProps> = ({
@@ -24,6 +29,7 @@ export const LanguageToggles: React.FC<LanguageTogglesProps> = ({
code,
currentLanguageAdapter,
onAfterToggle,
+ className = "absolute right-3 top-2 z-20 flex hover-action gap-1",
}) => {
const canUseMarkdown = useMemo(
() => LanguageAdapters.markdown.isSupported(code) || code.trim() === "",
@@ -35,7 +41,7 @@ export const LanguageToggles: React.FC<LanguageTogglesProps> = ({
);
return (
- <div className="absolute right-3 top-2 z-20 flex hover-action gap-1">
+ <div className={className}>
<LanguageToggle
editorView={editorView}
currentLanguageAdapter={currentLanguageAdapter}
diff --git a/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts b/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts
index dd8a36d4a8..bc0aab9182 100644
--- a/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts
+++ b/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts
@@ -248,6 +248,26 @@ const BACKWARDS_COMPAT_SNAPSHOTS: BackwardsCompatCase[] = [
],
},
},
+ {
+ // `showCode` was added to SlideConfig. The validator must know about it (so
+ // it isn't silently stripped), the deserializer must carry it through, and
+ // serialize → deserialize must round-trip both values.
+ label: "showCode round-trips through validate + (de)serialize",
+ input: {
+ cells: [
+ { type: "slide", showCode: true },
+ { type: "fragment", showCode: false },
+ ],
+ },
+ expected: {
+ deck: {},
+ cellIds: ["a", "b"],
+ cellEntries: [
+ ["a", { type: "slide", showCode: true }],
+ ["b", { type: "fragment", showCode: false }],
+ ],
+ },
+ },
];
describe("SlidesLayoutPlugin backwards compatibility", () => {
diff --git a/frontend/src/components/editor/renderers/slides-layout/types.ts b/frontend/src/components/editor/renderers/slides-layout/types.ts
index eee62542d4..3f395fa9bb 100644
--- a/frontend/src/components/editor/renderers/slides-layout/types.ts
+++ b/frontend/src/components/editor/renderers/slides-layout/types.ts
@@ -9,6 +9,7 @@ export type SlideType = z.infer<typeof SlideTypeSchema>;
const SlideConfigSchema = z.looseObject({
type: SlideTypeSchema.optional(),
speakerNotes: z.string().optional(),
+ showCode: z.boolean().optional(),
});
export type SlideConfig = z.infer<typeof SlideConfigSchema>;
diff --git a/frontend/src/components/slides/__tests__/reveal-component.test.ts b/frontend/src/components/slides/__tests__/reveal-component.test.ts
new file mode 100644
index 0000000000..2118da01ea
--- /dev/null
+++ b/frontend/src/components/slides/__tests__/reveal-component.test.ts
@@ -0,0 +1,425 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import type { CellId } from "@/core/cells/ids";
+import type { RuntimeCell } from "@/core/cells/types";
+import type { SlideConfig } from "../../editor/renderers/slides-layout/types";
+import {
+ deckSlideType,
+ parkedRendersSource,
+ shouldShowCode,
+ useParkedPreview,
+} from "../reveal-component";
+
+const A = cellId("a");
+const B = cellId("b");
+
+const cells = (
+ ...entries: Array<[CellId, SlideConfig]>
+): ReadonlyMap<CellId, SlideConfig> => new Map(entries);
+
+// The hook only reads `cell.id`, so a minimal stub is enough. Cast is confined
+// to this test helper (see `@/__tests__/branded` for the same rationale).
+const cell = (id: CellId): RuntimeCell => ({ id }) as RuntimeCell;
+
+describe("shouldShowCode", () => {
+ it("is off when the code toggle is unavailable, regardless of config/override", () => {
+ expect(
+ shouldShowCode({
+ cells: cells([A, { showCode: true }]),
+ cellId: A,
+ showCodeOverrides: new Set([A]),
+ codeToggleEnabled: false,
+ }),
+ ).toBe(false);
+ });
+
+ it("is off when there is no active cell", () => {
+ expect(
+ shouldShowCode({
+ cells: cells([A, { showCode: true }]),
+ cellId: undefined,
+ showCodeOverrides: new Set(),
+ codeToggleEnabled: true,
+ }),
+ ).toBe(false);
+ });
+
+ it("follows the persisted config when there is no override", () => {
+ expect(
+ shouldShowCode({
+ cells: cells([A, { showCode: true }]),
+ cellId: A,
+ showCodeOverrides: new Set(),
+ codeToggleEnabled: true,
+ }),
+ ).toBe(true);
+ // Missing config entry defaults to off.
+ expect(
+ shouldShowCode({
+ cells: cells(),
+ cellId: A,
+ showCodeOverrides: new Set(),
+ codeToggleEnabled: true,
+ }),
+ ).toBe(false);
+ });
+
+ it("shows code when either the config or the override is set (logical OR)", () => {
+ // Peek: config unset, override present -> shown.
+ expect(
+ shouldShowCode({
+ cells: cells(),
+ cellId: A,
+ showCodeOverrides: new Set([A]),
+ codeToggleEnabled: true,
+ }),
+ ).toBe(true);
+ // Configured + override present -> still shown; the override never hides.
+ expect(
+ shouldShowCode({
+ cells: cells([A, { showCode: true }]),
+ cellId: A,
+ showCodeOverrides: new Set([A]),
+ codeToggleEnabled: true,
+ }),
+ ).toBe(true);
+ });
+});
+
+describe("deckSlideType", () => {
+ const NONE_IDS: ReadonlySet<CellId> = new Set();
+
+ it("uses the configured type for a normal cell", () => {
+ expect(
+ deckSlideType({
+ cell: cell(A),
+ noOutputIds: NONE_IDS,
+ heldEditCellId: null,
+ slideConfigs: cells([A, { type: "fragment" }]),
+ }),
+ ).toBe("fragment");
+ });
+
+ it("defaults to a top-level slide when no type is configured", () => {
+ expect(
+ deckSlideType({
+ cell: cell(A),
+ noOutputIds: NONE_IDS,
+ heldEditCellId: null,
+ slideConfigs: cells(),
+ }),
+ ).toBe("slide");
+ });
+
+ it("drops output-less cells from the deck", () => {
+ expect(
+ deckSlideType({
+ cell: cell(A),
+ noOutputIds: new Set([A]),
+ heldEditCellId: null,
+ // Even an explicit type is overridden by the skip.
+ slideConfigs: cells([A, { type: "sub-slide" }]),
+ }),
+ ).toBe("skip");
+ });
+
+ it("drops the held-edit cell so it isn't mounted twice", () => {
+ expect(
+ deckSlideType({
+ cell: cell(A),
+ noOutputIds: NONE_IDS,
+ heldEditCellId: A,
+ slideConfigs: cells([A, { type: "slide" }]),
+ }),
+ ).toBe("skip");
+ });
+});
+
+describe("parkedRendersSource", () => {
+ it("follows `showCode` for a cell that has output", () => {
+ expect(
+ parkedRendersSource({
+ isNoOutputPreview: false,
+ isEditable: false,
+ showCode: true,
+ }),
+ ).toBe(true);
+ expect(
+ parkedRendersSource({
+ isNoOutputPreview: false,
+ isEditable: true,
+ showCode: false,
+ }),
+ ).toBe(false);
+ });
+
+ it("falls back to source for an editable no-output cell even when showCode is off", () => {
+ expect(
+ parkedRendersSource({
+ isNoOutputPreview: true,
+ isEditable: true,
+ showCode: false,
+ }),
+ ).toBe(true);
+ });
+
+ it("renders output for a read-only no-output cell with showCode off", () => {
+ expect(
+ parkedRendersSource({
+ isNoOutputPreview: true,
+ isEditable: false,
+ showCode: false,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe("useParkedPreview", () => {
+ const NO_CONFIG = cells();
+ const NONE = new Set<CellId>();
+
+ it("is inert for a rendered cell with output", () => {
+ const { result } = renderHook(() =>
+ useParkedPreview({
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ }),
+ );
+ expect(result.current).toEqual({
+ parkedPreviewCell: null,
+ isHeldEdit: false,
+ isNoOutputPreview: false,
+ heldEditCellId: null,
+ heldShowsCode: true,
+ toggleHeldShowsCode: expect.any(Function),
+ });
+ });
+
+ it("is inert when there is no active cell", () => {
+ const { result } = renderHook(() =>
+ useParkedPreview({
+ activeCell: undefined,
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ }),
+ );
+ expect(result.current).toEqual({
+ parkedPreviewCell: null,
+ isHeldEdit: false,
+ isNoOutputPreview: false,
+ heldEditCellId: null,
+ heldShowsCode: true,
+ toggleHeldShowsCode: expect.any(Function),
+ });
+ });
+
+ it("parks a skipped cell without flagging it as a no-output preview", () => {
+ const { result } = renderHook(() =>
+ useParkedPreview({
+ activeCell: cell(A),
+ slideConfigs: cells([A, { type: "skip" }]),
+ noOutputIds: NONE,
+ }),
+ );
+ expect(result.current).toEqual({
+ parkedPreviewCell: cell(A),
+ isHeldEdit: false,
+ isNoOutputPreview: false,
+ heldEditCellId: null,
+ heldShowsCode: true,
+ toggleHeldShowsCode: expect.any(Function),
+ });
+ });
+
+ it("parks an output-less cell as a no-output preview", () => {
+ const { result } = renderHook(() =>
+ useParkedPreview({
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: new Set([A]),
+ }),
+ );
+ expect(result.current).toEqual({
+ parkedPreviewCell: cell(A),
+ isHeldEdit: false,
+ isNoOutputPreview: true,
+ heldEditCellId: null,
+ heldShowsCode: true,
+ toggleHeldShowsCode: expect.any(Function),
+ });
+ });
+
+ it("holds the cell in the overlay once it gains output", () => {
+ const { result, rerender } = renderHook(
+ (props: Parameters<typeof useParkedPreview>[0]) =>
+ useParkedPreview(props),
+ {
+ initialProps: {
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: new Set([A]),
+ },
+ },
+ );
+ expect(result.current.isNoOutputPreview).toBe(true);
+ expect(result.current.isHeldEdit).toBe(false);
+
+ // Same cell, now with output: keep it parked so the editor isn't remounted.
+ rerender({
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ });
+ expect(result.current).toEqual({
+ parkedPreviewCell: cell(A),
+ isHeldEdit: true,
+ isNoOutputPreview: false,
+ heldEditCellId: A,
+ heldShowsCode: true,
+ toggleHeldShowsCode: expect.any(Function),
+ });
+ });
+
+ it("releases the hold when a different cell becomes active", () => {
+ const { result, rerender } = renderHook(
+ (props: Parameters<typeof useParkedPreview>[0]) =>
+ useParkedPreview(props),
+ {
+ initialProps: {
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: new Set([A]),
+ },
+ },
+ );
+ // Arm the hold, then let A gain output (held).
+ rerender({
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ });
+ expect(result.current.isHeldEdit).toBe(true);
+
+ // Navigate to a rendered B: the hold on A is released.
+ rerender({
+ activeCell: cell(B),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ });
+ expect(result.current).toEqual({
+ parkedPreviewCell: null,
+ isHeldEdit: false,
+ isNoOutputPreview: false,
+ heldEditCellId: null,
+ heldShowsCode: true,
+ toggleHeldShowsCode: expect.any(Function),
+ });
+ });
+
+ it("releases a skipped cell into the deck as soon as it is un-skipped", () => {
+ const { result, rerender } = renderHook(
+ (props: Parameters<typeof useParkedPreview>[0]) =>
+ useParkedPreview(props),
+ {
+ initialProps: {
+ activeCell: cell(A),
+ slideConfigs: cells([A, { type: "skip" }]),
+ noOutputIds: NONE,
+ },
+ },
+ );
+ expect(result.current.parkedPreviewCell).toEqual(cell(A));
+
+ // Un-skip the still-active cell: it has output, so it must rejoin the deck
+ // immediately rather than staying held in the overlay until navigation.
+ rerender({
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ });
+ expect(result.current).toEqual({
+ parkedPreviewCell: null,
+ isHeldEdit: false,
+ isNoOutputPreview: false,
+ heldEditCellId: null,
+ heldShowsCode: true,
+ toggleHeldShowsCode: expect.any(Function),
+ });
+ });
+
+ it("shows the held editor by default and toggles it off without navigating", () => {
+ const { result, rerender } = renderHook(
+ (props: Parameters<typeof useParkedPreview>[0]) =>
+ useParkedPreview(props),
+ {
+ initialProps: {
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: new Set([A]),
+ },
+ },
+ );
+ // A gains output: held, with its editor shown by default.
+ rerender({
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ });
+ expect(result.current.isHeldEdit).toBe(true);
+ expect(result.current.heldShowsCode).toBe(true);
+
+ // The `C` toggle hides the editor in place, no navigation required.
+ act(() => {
+ result.current.toggleHeldShowsCode();
+ });
+ expect(result.current.heldShowsCode).toBe(false);
+
+ // Toggling again brings it back.
+ act(() => {
+ result.current.toggleHeldShowsCode();
+ });
+ expect(result.current.heldShowsCode).toBe(true);
+ });
+
+ it("resets held code visibility when a new cell takes the held slot", () => {
+ const { result, rerender } = renderHook(
+ (props: Parameters<typeof useParkedPreview>[0]) =>
+ useParkedPreview(props),
+ {
+ initialProps: {
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: new Set([A]),
+ },
+ },
+ );
+ rerender({
+ activeCell: cell(A),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ });
+ act(() => {
+ result.current.toggleHeldShowsCode();
+ });
+ expect(result.current.heldShowsCode).toBe(false);
+
+ // Move to a fresh output-less cell B, then let it gain output (held).
+ rerender({
+ activeCell: cell(B),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: new Set([B]),
+ });
+ rerender({
+ activeCell: cell(B),
+ slideConfigs: NO_CONFIG,
+ noOutputIds: NONE,
+ });
+ expect(result.current.heldEditCellId).toBe(B);
+ // The new cell starts with its editor visible again.
+ expect(result.current.heldShowsCode).toBe(true);
+ });
+});
diff --git a/frontend/src/components/slides/reveal-component.tsx b/frontend/src/components/slides/reveal-component.tsx
index 57d6cf6d6f..8887297d4a 100644
--- a/frontend/src/components/slides/reveal-component.tsx
+++ b/frontend/src/components/slides/reveal-component.tsx
@@ -27,6 +27,7 @@ import "./reveal-slides.css";
import type {
SlideConfig,
SlidesLayout,
+ SlideType,
} from "../editor/renderers/slides-layout/types";
import {
buildSlideIndices,
@@ -156,14 +157,148 @@ const NotesAside = ({ text }: { text: string }) => {
);
};
+/**
+ * Resolve whether a slide cell shows its source instead of its output.
+ *
+ * Code is shown when either the cell's persisted `showCode` config is set or
+ * the keyboard toggle `C` override is active for it (logical OR).
+ */
+export function shouldShowCode(options: {
+ cells: ReadonlyMap<CellId, SlideConfig>;
+ cellId: CellId | undefined;
+ showCodeOverrides: ReadonlySet<CellId>;
+ codeToggleEnabled: boolean;
+}): boolean {
+ const { cells, cellId, showCodeOverrides, codeToggleEnabled } = options;
+ if (cellId == null || !codeToggleEnabled) {
+ return false;
+ }
+ const configured = cells.get(cellId)?.showCode ?? false;
+ return configured || showCodeOverrides.has(cellId);
+}
+
+/**
+ * The slide type a cell takes *in the composed deck*. Cells without output and
+ * the cell currently held in the parked edit overlay are dropped (`"skip"`) so
+ * they aren't mounted a second time in the deck — the overlay renders them
+ * instead. Everything else uses its configured type, defaulting to a slide.
+ */
+export function deckSlideType(options: {
+ cell: RuntimeCell;
+ noOutputIds: ReadonlySet<CellId>;
+ heldEditCellId: CellId | null;
+ slideConfigs: ReadonlyMap<CellId, SlideConfig>;
+}): SlideType {
+ const { cell, noOutputIds, heldEditCellId, slideConfigs } = options;
+ if (noOutputIds.has(cell.id) || cell.id === heldEditCellId) {
+ return "skip";
+ }
+ return slideConfigs.get(cell.id)?.type ?? DEFAULT_SLIDE_TYPE;
+}
+
+/**
+ * Tracks the cell pinned in the parked overlay (rendered over the deck for
+ * skipped / output-less cells, and during in-progress edits).
+ *
+ * A brand-new (or output-less) cell is edited in the parked overlay, which
+ * lives outside reveal's slide DOM. The moment it first produces output it
+ * would normally jump to its composed slide — a different React subtree that
+ * reveal also re-syncs/transitions — tearing down the editor and dropping
+ * focus mid-edit (e.g. typing in a new markdown cell). To avoid that we *hold*
+ * the cell in the overlay even after it gains output, and only let it settle
+ * into the deck once the user navigates to a different cell.
+ *
+ * The hold is keyed off the active cell rather than DOM focus on purpose: the
+ * slide editor doesn't participate in the global cell-focus state, and the
+ * active cell only changes when the user moves in the minimap — exactly when
+ * we want to release the hold.
+ *
+ * Returns:
+ * - `parkedPreviewCell`: the cell to render in the overlay
+ * - `isHeldEdit`: whether the cell is held in the overlay
+ * - `isNoOutputPreview`: whether the cell is output-less
+ * - `heldEditCellId`: the id of the cell that is held in the overlay
+ */
+export function useParkedPreview(options: {
+ activeCell: RuntimeCell | undefined;
+ slideConfigs: ReadonlyMap<CellId, SlideConfig>;
+ noOutputIds: ReadonlySet<CellId>;
+}): {
+ parkedPreviewCell: RuntimeCell | null;
+ isHeldEdit: boolean;
+ isNoOutputPreview: boolean;
+ heldEditCellId: CellId | null;
+ heldShowsCode: boolean;
+ toggleHeldShowsCode: () => void;
+} {
+ const { activeCell, slideConfigs, noOutputIds } = options;
+ const activeCellId = activeCell?.id ?? null;
+ const isNoOutputPreview =
+ activeCell != null && noOutputIds.has(activeCell.id);
+ const isSkippedPreview =
+ activeCell != null && slideConfigs.get(activeCell.id)?.type === "skip";
+ // Genuinely parked: skipped in the deck, or no output to compose yet.
+ const baseParked = isSkippedPreview || isNoOutputPreview;
+
+ // The cell pinned in the overlay, tracked alongside the active cell it was
+ // armed against so we can release it exactly when the active cell changes.
+ const [held, setHeld] = useState<{
+ activeCellId: CellId | null;
+ cellId: CellId | null;
+ }>({ activeCellId, cellId: null });
+
+ let heldCellId = held.cellId;
+ if (held.activeCellId !== activeCellId) {
+ // Active cell changed: drop any prior hold, arming a fresh one only while
+ // the new cell has no output yet (skipped cells park via `baseParked`).
+ heldCellId = isNoOutputPreview ? activeCellId : null;
+ setHeld({ activeCellId, cellId: heldCellId });
+ } else if (isNoOutputPreview && heldCellId !== activeCellId) {
+ // Same active cell, still output-less: (re)arm the hold.
+ heldCellId = activeCellId;
+ setHeld({ activeCellId, cellId: heldCellId });
+ }
+
+ const isHeldEdit =
+ !baseParked && activeCellId != null && heldCellId === activeCellId;
+ // Keep the held cell out of the composed deck so its editor isn't mounted a
+ // second time (the overlay already renders it); it rejoins once released.
+ const heldEditCellId = isHeldEdit ? heldCellId : null;
+
+ // Code visibility for the held overlay. Defaults to showing the editor so it
+ // survives the no-output -> output transition mid-edit; the `C` toggle can
+ // hide it on demand.
+ const [heldShow, setHeldShow] = useState<{
+ cellId: CellId | null;
+ show: boolean;
+ }>({ cellId: heldEditCellId, show: true });
+ let heldShowsCode = heldShow.show;
+ if (heldShow.cellId !== heldEditCellId) {
+ heldShowsCode = true;
+ setHeldShow({ cellId: heldEditCellId, show: true });
+ }
+ const toggleHeldShowsCode = useEvent(() =>
+ setHeldShow((prev) => ({ ...prev, show: !prev.show })),
+ );
+
+ return {
+ parkedPreviewCell: baseParked || isHeldEdit ? (activeCell ?? null) : null,
+ isHeldEdit,
+ isNoOutputPreview,
+ heldEditCellId,
+ heldShowsCode,
+ toggleHeldShowsCode,
+ };
+}
+
const SubslideView = ({
subslide,
- showCode,
+ resolveShowCode,
isEditable,
slideConfigs,
}: {
subslide: ComposedSubslide<RuntimeCell>;
- showCode: boolean;
+ resolveShowCode: (cellId: CellId) => boolean;
isEditable: boolean;
slideConfigs: ReadonlyMap<CellId, SlideConfig>;
}) => {
@@ -172,12 +307,16 @@ const SubslideView = ({
slideConfigs,
);
+ const anyCodeShown = subslide.blocks.some((block) =>
+ block.cells.some((cell) => resolveShowCode(cell.id)),
+ );
+
return (
<Slide>
<div className="h-full w-full overflow-auto flex">
<div
className={
- showCode
+ anyCodeShown
? "mo-slide-content flex flex-col gap-3"
: "mo-slide-content"
}
@@ -187,7 +326,7 @@ const SubslideView = ({
>
{subslide.blocks.map((block, i) => {
const rendered = block.cells.map((cell) => {
- if (!showCode) {
+ if (!resolveShowCode(cell.id)) {
return (
<CellOutputSlide
key={cell.id}
@@ -222,22 +361,36 @@ const SubslideView = ({
);
};
+/**
+ * Whether the parked overlay renders the cell's *source* instead of its output.
+ */
+export function parkedRendersSource(options: {
+ isNoOutputPreview: boolean;
+ isEditable: boolean;
+ showCode: boolean;
+}): boolean {
+ const { isNoOutputPreview, isEditable, showCode } = options;
+ return isNoOutputPreview ? isEditable || showCode : showCode;
+}
+
const ParkedPreviewContent = ({
cell,
isNoOutputPreview,
isEditable,
- codeShown,
+ showCode,
}: {
cell: RuntimeCell;
isNoOutputPreview: boolean;
isEditable: boolean;
- codeShown: boolean;
+ showCode: boolean;
}) => {
- if (isNoOutputPreview && isEditable) {
- return <SlideCellView cell={cell} />;
- }
- if (isNoOutputPreview && codeShown) {
- return <SlideCellReadOnlyView cell={cell} />;
+ if (parkedRendersSource({ isNoOutputPreview, isEditable, showCode })) {
+ // Editable cells get the live editor; otherwise a read-only source view.
+ return isEditable ? (
+ <SlideCellView cell={cell} />
+ ) : (
+ <SlideCellReadOnlyView cell={cell} />
+ );
}
return (
<CellOutputSlide
@@ -285,39 +438,68 @@ const RevealSlidesComponent = ({
[kioskMode],
);
- const [showCode, setShowCode] = useState(false);
+ // Store the state of the code toggle for each cell
+ // This acts like a 'peek' at the code.
+ const [showCodeOverrides, setShowCodeOverrides] = useState<
+ ReadonlySet<CellId>
+ >(() => new Set());
const codeAvailable = useNotebookCodeAvailable(slideCells);
const codeToggleEnabled = !isIslands() && codeAvailable;
- const codeShown = codeToggleEnabled && showCode;
const activeCell = activeIndex != null ? slideCells[activeIndex] : undefined;
// Fall back to the first cell while the deck settles on an initial slide.
// Still `undefined` when the deck is empty (handled below).
const activeConfigCell = activeCell ?? slideCells.at(0);
+ const {
+ parkedPreviewCell,
+ isHeldEdit,
+ isNoOutputPreview,
+ heldEditCellId,
+ heldShowsCode,
+ toggleHeldShowsCode,
+ } = useParkedPreview({
+ activeCell,
+ slideConfigs: layout.cells,
+ noOutputIds,
+ });
+
+ const resolveShowCode = (cellId: CellId | undefined): boolean =>
+ shouldShowCode({
+ cells: layout.cells,
+ cellId,
+ showCodeOverrides,
+ codeToggleEnabled,
+ });
+
+ // `C` and the toolbar button target the active slide's cell (the revealed
+ // fragment when stepping through a stack, otherwise the lead cell).
+ const cellIdToShowCode = activeCell?.id ?? activeConfigCell?.id;
+ const cellShowsCode = isHeldEdit
+ ? heldShowsCode
+ : resolveShowCode(cellIdToShowCode);
+
+ // A slide persisted with `showCode: true` always renders code
+ const codeAlwaysShown =
+ codeToggleEnabled &&
+ cellIdToShowCode != null &&
+ (layout.cells.get(cellIdToShowCode)?.showCode ?? false);
+
const composition = useMemo(
() =>
composeSlides({
cells: slideCells,
getType: (cell) =>
- noOutputIds.has(cell.id)
- ? "skip"
- : (layout.cells.get(cell.id)?.type ?? DEFAULT_SLIDE_TYPE),
+ deckSlideType({
+ cell,
+ noOutputIds,
+ heldEditCellId,
+ slideConfigs: layout.cells,
+ }),
}),
- [slideCells, noOutputIds, layout.cells],
+ [slideCells, noOutputIds, layout.cells, heldEditCellId],
);
- // Skipped and output-less cells aren't part of the composed deck. When one is
- // selected in the minimap we render a preview over the deck and park reveal on
- // a neighboring real slide; keyboard nav while parked is handled below.
- const activeCellSlideType = activeCell
- ? layout.cells.get(activeCell.id)?.type
- : undefined;
- const isNoOutputPreview =
- activeCell != null && noOutputIds.has(activeCell.id);
- const isParkedPreview = activeCellSlideType === "skip" || isNoOutputPreview;
- const parkedPreviewCell = isParkedPreview ? activeCell : null;
-
const { cellToTarget, targetToCellIndex } = useMemo(
() =>
buildSlideIndices({
@@ -339,6 +521,7 @@ const RevealSlidesComponent = ({
url.searchParams.set("show-chrome", "false");
return url.toString();
}, []);
+
const revealConfig: RevealConfig = useMemo(
() => ({
embedded: true,
@@ -381,14 +564,35 @@ const RevealSlidesComponent = ({
// the state update so the button/keypress paints first and the heavier mount
// can be interrupted by higher-priority work.
const toggleShowCode = useEvent(() => {
- startTransition(() => setShowCode((value) => !value));
+ if (cellIdToShowCode == null || codeAlwaysShown) {
+ return;
+ }
+ if (isHeldEdit) {
+ toggleHeldShowsCode();
+ return;
+ }
+ startTransition(() =>
+ setShowCodeOverrides((prev) => {
+ const next = new Set(prev);
+ if (next.has(cellIdToShowCode)) {
+ next.delete(cellIdToShowCode);
+ } else {
+ next.add(cellIdToShowCode);
+ }
+ return next;
+ }),
+ );
});
const handleDeckReady = useEvent((deck: RevealApi) => {
navigateDeckToActiveCell(deck);
if (codeToggleEnabled) {
deck.addKeyBinding(
- { keyCode: 67, key: "C", description: "Toggle code editor" },
+ {
+ keyCode: 67,
+ key: "C",
+ description: "Toggle code editor",
+ },
toggleShowCode,
);
}
@@ -404,17 +608,6 @@ const RevealSlidesComponent = ({
}
});
- const activeSubslide = useMemo(() => {
- if (!activeCell) {
- return null;
- }
- const target = cellToTarget.get(activeCell.id);
- if (!target) {
- return null;
- }
- return { h: target.h, v: target.v };
- }, [activeCell, cellToTarget]);
-
// Forward the deck's current cell to the parent, except while a parked
// preview is parked: every reveal.js event during that window is an echo
// of the programmatic park (possibly with transient indices), so ignoring
@@ -466,9 +659,22 @@ const RevealSlidesComponent = ({
useEventListener(document, "keydown", handleParkedNavKey, { capture: true });
- const parkedPreviewLabel = isNoOutputPreview
- ? "Hidden as there is no output"
- : "Skipped in presentation";
+ // `isHeldEdit` means the cell already produces output and is only kept in the
+ // overlay so the editor survives the edit, so the parked banners don't apply.
+ const parkedPreviewLabel = isHeldEdit
+ ? null
+ : isNoOutputPreview
+ ? "Hidden as there is no output"
+ : "Skipped in presentation";
+
+ const parkedShowCode = isHeldEdit
+ ? heldShowsCode
+ : resolveShowCode(parkedPreviewCell?.id);
+ const parkedShowsSource = parkedRendersSource({
+ isNoOutputPreview,
+ isEditable,
+ showCode: parkedShowCode,
+ });
const slideArea = (
<div
@@ -488,13 +694,11 @@ const RevealSlidesComponent = ({
>
{composition.stacks.map((stack, h) => {
if (stack.subslides.length === 1) {
- const isActive =
- activeSubslide?.h === h && activeSubslide?.v === 0;
return (
<SubslideView
key={h}
subslide={stack.subslides[0]}
- showCode={codeShown && isActive}
+ resolveShowCode={resolveShowCode}
isEditable={isEditable}
slideConfigs={layout.cells}
/>
@@ -503,13 +707,11 @@ const RevealSlidesComponent = ({
return (
<Stack key={h}>
{stack.subslides.map((sub, v) => {
- const isActive =
- activeSubslide?.h === h && activeSubslide?.v === v;
return (
<SubslideView
key={v}
subslide={sub}
- showCode={codeShown && isActive}
+ resolveShowCode={resolveShowCode}
isEditable={isEditable}
slideConfigs={layout.cells}
/>
@@ -523,16 +725,18 @@ const RevealSlidesComponent = ({
<div
key={parkedPreviewCell.id}
className="absolute inset-0 z-10 border rounded bg-background flex flex-col overflow-hidden"
- aria-label={parkedPreviewLabel}
+ aria-label={parkedPreviewLabel ?? undefined}
>
- <div className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-muted-foreground border-b bg-muted/40">
- <EyeOffIcon className="h-3.5 w-3.5" />
- <span>{parkedPreviewLabel}</span>
- </div>
+ {parkedPreviewLabel && (
+ <div className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-muted-foreground border-b bg-muted/40">
+ <EyeOffIcon className="h-3.5 w-3.5" />
+ <span>{parkedPreviewLabel}</span>
+ </div>
+ )}
<div className="flex-1 overflow-auto flex">
<div
className={
- isNoOutputPreview && (isEditable || codeShown)
+ parkedShowsSource
? "mo-slide-content flex flex-col gap-3"
: "mo-slide-content"
}
@@ -542,7 +746,7 @@ const RevealSlidesComponent = ({
cell={parkedPreviewCell}
isNoOutputPreview={isNoOutputPreview}
isEditable={isEditable}
- codeShown={codeShown}
+ showCode={parkedShowCode}
/>
</div>
</div>
@@ -550,17 +754,35 @@ const RevealSlidesComponent = ({
)}
<div className="absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-70 text-muted-foreground transition-opacity">
{codeToggleEnabled && (
- <Tooltip content={codeShown ? "Hide code (C)" : "Show code (C)"}>
+ <Tooltip
+ content={
+ codeAlwaysShown
+ ? "Code is always shown for this slide"
+ : cellShowsCode
+ ? "Hide code (C)"
+ : "Show code (C)"
+ }
+ >
<Button
data-testid="marimo-plugin-slides-toggle-code"
variant="ghost"
size="icon"
+ // Stay hoverable (no `disabled` attr) so the tooltip can
+ // explain why the toggle is inert when code is pinned on.
className={cn(
"text-muted-foreground h-7 w-7",
- codeShown && "text-foreground bg-muted",
+ cellShowsCode && "text-foreground bg-muted",
+ codeAlwaysShown && "opacity-50 cursor-not-allowed",
)}
- aria-pressed={codeShown}
- aria-label={codeShown ? "Hide code" : "Show code"}
+ aria-pressed={cellShowsCode}
+ aria-disabled={codeAlwaysShown}
+ aria-label={
+ codeAlwaysShown
+ ? "Code always shown"
+ : cellShowsCode
+ ? "Hide code"
+ : "Show code"
+ }
onClick={toggleShowCode}
>
<CodeIcon className="h-4 w-4" />
diff --git a/frontend/src/components/slides/slide-cell-view.tsx b/frontend/src/components/slides/slide-cell-view.tsx
index 296bbd775b..73348b99a4 100644
--- a/frontend/src/components/slides/slide-cell-view.tsx
+++ b/frontend/src/components/slides/slide-cell-view.tsx
@@ -3,14 +3,18 @@
import { useMemo, useRef, useState } from "react";
import type { EditorView } from "@codemirror/view";
import { useAtomValue } from "jotai";
+import useEvent from "react-use-event-hook";
import { cellDomProps } from "@/components/editor/common";
import { CellEditor } from "@/components/editor/cell/code/cell-editor";
+import { LanguageToggles } from "@/components/editor/cell/code/language-toggle";
import { CellStatusComponent } from "@/components/editor/cell/CellStatus";
import { RunButton } from "@/components/editor/cell/RunButton";
import { StopButton } from "@/components/editor/cell/StopButton";
import { useRunCell } from "@/components/editor/cell/useRunCells";
import { Slide as CellOutputSlide } from "@/components/slides/slide";
-import { useUserConfig } from "@/core/config/config";
+import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
+import { useCellActions } from "@/core/cells/cells";
+import { autoInstantiateAtom, useUserConfig } from "@/core/config/config";
import {
cellNeedsRun,
cellStatusClasses,
@@ -37,12 +41,24 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {
const { theme } = useTheme();
const runCell = useRunCell(cell.id);
const connection = useAtomValue(connectionAtom);
+ const cellActions = useCellActions();
+ const autoInstantiate = useAtomValue(autoInstantiateAtom);
const editorViewRef = useRef<EditorView | null>(null);
const editorViewParentRef = useRef<HTMLDivElement | null>(null);
const [languageAdapter, setLanguageAdapter] = useState<
LanguageAdapterType | undefined
>();
+ const afterToggleLanguage = useEvent(() => {
+ maybeAddMarimoImport({
+ autoInstantiate,
+ createNewCell: cellActions.createNewCell,
+ });
+ });
+
+ // Must be a stable identity: it feeds the editor's `extensions` memo
+ const showHiddenCode = useEvent(() => undefined);
+
const cellOutputPosition = userConfig.display.cell_output;
const hasOutput = cell.output != null;
@@ -97,6 +113,13 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {
lastRunStartTimestamp={cell.lastRunStartTimestamp}
uninstantiated={uninstantiated}
/>
+ <LanguageToggles
+ code={cell.code}
+ editorView={editorViewRef.current}
+ currentLanguageAdapter={languageAdapter}
+ onAfterToggle={afterToggleLanguage}
+ className="flex items-center gap-1"
+ />
<div className="flex items-center shadow-none gap-1">
<RunButton
edited={cell.edited}
@@ -113,6 +136,7 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {
const editor = (
<div
+ tabIndex={-1}
className={editorWrapperClassName}
{...cellDomProps(cell.id, cell.name)}
>
@@ -134,7 +158,7 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {
hasOutput={hasOutput}
// hide_code is intentionally overridden in the slide view; the editor
// is unmounted entirely when the user toggles code off.
- showHiddenCode={() => undefined}
+ showHiddenCode={showHiddenCode}
languageAdapter={languageAdapter}
setLanguageAdapter={setLanguageAdapter}
showLanguageToggles={false}
diff --git a/frontend/src/components/slides/slide-form.tsx b/frontend/src/components/slides/slide-form.tsx
index bdc326de56..34ff8dca1a 100644
--- a/frontend/src/components/slides/slide-form.tsx
+++ b/frontend/src/components/slides/slide-form.tsx
@@ -10,6 +10,7 @@ import {
PanelRightOpenIcon,
KeyboardIcon,
} from "lucide-react";
+import { Switch } from "@/components/ui/switch";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
Select,
@@ -196,13 +197,22 @@ const SlideConfigForm = ({
setLayout: (layout: SlidesLayout) => void;
cellId: CellId;
}) => {
- const currentSlideType: SlideType =
- layout.cells.get(cellId)?.type ?? DEFAULT_SLIDE_TYPE;
+ const currentConfig = layout.cells.get(cellId);
+ const currentSlideType: SlideType = currentConfig?.type ?? DEFAULT_SLIDE_TYPE;
+ const showCode = currentConfig?.showCode ?? false;
const handleSlideTypeChange = (value: SlideType) => {
- const existingConfig = layout.cells.get(cellId);
const newCells = new Map(layout.cells);
- newCells.set(cellId, { ...existingConfig, type: value });
+ newCells.set(cellId, { ...currentConfig, type: value });
+ setLayout({
+ ...layout,
+ cells: newCells,
+ });
+ };
+
+ const handleShowCodeChange = (checked: boolean) => {
+ const newCells = new Map(layout.cells);
+ newCells.set(cellId, { ...currentConfig, showCode: checked });
setLayout({
...layout,
cells: newCells,
@@ -261,6 +271,18 @@ const SlideConfigForm = ({
);
})}
</RadioGroup>
+ <div className="flex items-center gap-2">
+ <label htmlFor="slide-show-code" className="text-sm">
+ Show code
+ </label>
+ <Switch
+ id="slide-show-code"
+ aria-label="Show code"
+ checked={showCode}
+ onCheckedChange={handleShowCodeChange}
+ size="sm"
+ />
+ </div>
</div>
);
};
diff --git a/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.json b/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.json
index fdda33cca6..b8ad2f2c7c 100644
--- a/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.json
+++ b/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.json
@@ -7,7 +7,8 @@
},
{
"type": "slide",
- "speakerNotes": "We first introduce slides in marimo, and how awesome they are!"
+ "speakerNotes": "We first introduce slides in marimo, and how awesome they are!",
+ "showCode": false
},
{
"type": "fragment",
@@ -23,7 +24,8 @@
},
{
"type": "slide",
- "speakerNotes": "Section A onboard :>"
+ "speakerNotes": "Section A onboard :>",
+ "showCode": true
},
{
"type": "sub-slide",
diff --git a/marimo/_smoke_tests/slides_examples/nested_slides.py b/marimo/_smoke_tests/slides_examples/nested_slides.py
index 2983dd2f75..c6471e74ab 100644
--- a/marimo/_smoke_tests/slides_examples/nested_slides.py
+++ b/marimo/_smoke_tests/slides_examples/nested_slides.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.23.6"
+__generated_with = "0.23.8"
app = marimo.App(
width="medium",
layout_file="layouts/nested_slides.slides.json",