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: preserve slide layouts across display resolutions (#11502)

Shahmir Varqha36354f109dc1
diff --git a/docs/guides/apps.md b/docs/guides/apps.md
index a171d98d5f..0955924006 100644
--- a/docs/guides/apps.md
+++ b/docs/guides/apps.md
@@ -97,6 +97,10 @@ If you prefer a slideshow-like experience, you can use the slides layout. Enable
- Add speaker notes at the bottom of each slide and launch speaker view by pressing `S`.
- Powered by [reveal.js](https://revealjs.com/), so you can use most of its features like keyboard shortcuts, navigation, etc.
+Slides use a fixed 1280×720 canvas that scales to fit the available space,
+preserving the layout when you enter fullscreen or switch displays. Content
+that exceeds this canvas can still be scrolled.
+
#### Export slides
Export a notebook that uses the slides layout as static HTML or WebAssembly HTML:
diff --git a/frontend/e2e-tests/py/layouts/slides_sizing.slides.json b/frontend/e2e-tests/py/layouts/slides_sizing.slides.json
new file mode 100644
index 0000000000..a395ae6020
--- /dev/null
+++ b/frontend/e2e-tests/py/layouts/slides_sizing.slides.json
@@ -0,0 +1,15 @@
+{
+ "type": "slides",
+ "data": {
+ "cells": [
+ {},
+ {},
+ {},
+ {},
+ {
+ "type": "fragment"
+ }
+ ],
+ "deck": {}
+ }
+}
\ No newline at end of file
diff --git a/frontend/e2e-tests/py/slides_sizing.py b/frontend/e2e-tests/py/slides_sizing.py
new file mode 100644
index 0000000000..869ecb893c
--- /dev/null
+++ b/frontend/e2e-tests/py/slides_sizing.py
@@ -0,0 +1,74 @@
+# Copyright 2026 Marimo. All rights reserved.
+# /// script
+# [tool.marimo.runtime]
+# on_cell_change = "autorun"
+# ///
+
+import marimo
+
+__generated_with = "0.25.2"
+app = marimo.App(layout_file="layouts/slides_sizing.slides.json")
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
+def _(mo):
+ parameter = mo.ui.slider(0, 10, value=5, label="Parameter")
+ return (parameter,)
+
+
+def _(mo, parameter):
+ mo.vstack(
+ [
+ mo.md("# Resolution-independent slides"),
+ mo.hstack(
+ [
+ mo.md("""
+ ## Layout
+
+ This paragraph should keep the same line breaks when the
+ presentation moves between the editor, fullscreen, and a
+ projector with a different resolution.
+ """),
+ mo.md(r"""
+ ## Mathematics
+
+ $$f(x) = \sum_{j=1}^{n} \frac{x_j^2}{1 + x_j^2}$$
+ """),
+ ],
+ widths="equal",
+ gap=2,
+ ),
+ parameter,
+ mo.md(f"Parameter value: **{parameter.value}**"),
+ ],
+ gap=1,
+ )
+
+
+def _(mo):
+ mo.vstack(
+ [
+ mo.md("# Overflow before a fragment"),
+ mo.Html('<div style="height: 1000px">Revealed overflow</div>'),
+ ]
+ )
+
+
+def _(mo):
+ mo.md("""
+ This fragment has not been revealed yet.
+ """)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/e2e-tests/slides-sizing.spec.ts b/frontend/e2e-tests/slides-sizing.spec.ts
new file mode 100644
index 0000000000..36ce1c822d
--- /dev/null
+++ b/frontend/e2e-tests/slides-sizing.spec.ts
@@ -0,0 +1,226 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { expect, test, type Locator } from "@playwright/test";
+import { copyFile, mkdir } from "node:fs/promises";
+import path from "node:path";
+import { getAppUrl } from "../playwright.config";
+import { openCommandPalette, pressShortcut } from "./helper";
+
+async function measureLayout(deck: Locator) {
+ return deck.evaluate((el) => {
+ const canvas = el.querySelector<HTMLElement>(".slides");
+ const content = canvas?.querySelector<HTMLElement>(
+ "section.present .mo-slide-content",
+ );
+ const scroll = canvas?.querySelector<HTMLElement>(
+ "section.present [data-testid='slide-scroll-container']",
+ );
+ const paragraph = content?.querySelector<HTMLElement>(".paragraph, p");
+ const formula = content
+ ?.querySelector("marimo-tex")
+ ?.shadowRoot?.querySelector<HTMLElement>(".katex-html");
+ if (!canvas || !content || !scroll || !paragraph || !formula) {
+ throw new Error("Slide content is not ready");
+ }
+ const scale = canvas.getBoundingClientRect().width / canvas.offsetWidth;
+ return {
+ canvas: { width: canvas.offsetWidth, height: canvas.offsetHeight },
+ content: { width: content.offsetWidth, height: content.offsetHeight },
+ paragraph: {
+ width: paragraph.offsetWidth,
+ height: paragraph.offsetHeight,
+ },
+ formula: { width: formula.offsetWidth, height: formula.offsetHeight },
+ overflowing:
+ scroll.scrollHeight > scroll.clientHeight + 1 ||
+ scroll.scrollWidth > scroll.clientWidth + 1,
+ fitsViewport:
+ canvas.getBoundingClientRect().width <= el.clientWidth + 1 &&
+ canvas.getBoundingClientRect().height <= el.clientHeight + 1,
+ scale,
+ };
+ });
+}
+
+test.beforeEach(async ({ page }, testInfo) => {
+ const notebook = testInfo.outputPath(`slides_sizing_${Date.now()}.py`);
+ const layoutDirectory = testInfo.outputPath("layouts");
+ await mkdir(layoutDirectory, { recursive: true });
+ await copyFile(new URL("./py/slides_sizing.py", import.meta.url), notebook);
+ await copyFile(
+ new URL("./py/layouts/slides_sizing.slides.json", import.meta.url),
+ path.join(layoutDirectory, "slides_sizing.slides.json"),
+ );
+ const url = new URL(getAppUrl("slides_sizing.py"));
+ url.searchParams.set("file", notebook);
+ await page.goto(url.toString(), { waitUntil: "domcontentloaded" });
+ await page
+ .locator(".marimo-cell, [role='button'][data-cell-id]")
+ .first()
+ .waitFor();
+ await openCommandPalette({ page, command: "Re-run all cells" });
+ if (!(await page.locator(".reveal.mo-slides-theme").isVisible())) {
+ await openCommandPalette({ page, command: "Present as Slides" });
+ }
+});
+
+test("slides preserve layout when the viewport and fullscreen state change", async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1600, height: 1000 });
+
+ const deck = page.locator(".reveal.mo-slides-theme");
+ await expect(deck.locator("section.present .katex-html")).toBeVisible();
+ await page.evaluate(() => document.fonts.ready);
+
+ const initial = await measureLayout(deck);
+ expect(initial.canvas.width / initial.canvas.height).toBeCloseTo(16 / 9, 2);
+ expect(initial.overflowing).toBe(false);
+ expect(initial.fitsViewport).toBe(true);
+
+ const { scale: initialScale, ...initialLayout } = initial;
+ const sidebar = page.getByRole("complementary", {
+ name: "Slide configuration",
+ });
+ await sidebar.getByRole("button", { name: "Collapse panel" }).click();
+ await expect
+ .poll(async () => {
+ const { scale, ...layout } = await measureLayout(deck);
+ return { layout, grew: scale > initialScale };
+ })
+ .toEqual({ layout: initialLayout, grew: true });
+ await sidebar.getByRole("button", { name: "Expand panel" }).click();
+ await expect
+ .poll(async () => (await measureLayout(deck)).scale)
+ .toBeCloseTo(initialScale, 2);
+
+ for (const viewport of [
+ { width: 1024, height: 768 },
+ { width: 800, height: 600 },
+ { width: 1920, height: 1080 },
+ ]) {
+ await page.setViewportSize(viewport);
+ await expect
+ .poll(async () => {
+ const { scale, ...layout } = await measureLayout(deck);
+ return { layout, scaleChanged: Math.abs(scale - initialScale) > 0.01 };
+ })
+ .toEqual({ layout: initialLayout, scaleChanged: true });
+ }
+
+ await page.getByTestId("marimo-plugin-slides-fullscreen").click();
+ await expect
+ .poll(() => page.evaluate(() => document.fullscreenElement !== null))
+ .toBe(true);
+ await expect
+ .poll(async () => {
+ const { scale: _scale, ...layout } = await measureLayout(deck);
+ return layout;
+ })
+ .toEqual(initialLayout);
+
+ await page.evaluate(() => document.exitFullscreen());
+ await expect
+ .poll(() => page.evaluate(() => document.fullscreenElement === null))
+ .toBe(true);
+ await expect
+ .poll(async () => {
+ const { scale: _scale, ...layout } = await measureLayout(deck);
+ return layout;
+ })
+ .toEqual(initialLayout);
+
+ const track = deck.getByTestId("track");
+ const trackBounds = await track.boundingBox();
+ if (!trackBounds) {
+ throw new Error("Slider track is not visible");
+ }
+ await track.click({
+ position: { x: trackBounds.width * 0.6, y: trackBounds.height / 2 },
+ });
+ await expect(
+ deck.getByRole("slider", { name: "Parameter", exact: true }),
+ ).toHaveAttribute("aria-valuenow", "6");
+ await expect(
+ deck.getByTestId("slide-scroll-container").getByText("Parameter value:"),
+ ).toHaveText("Parameter value: 6");
+});
+
+test("scroll hint accounts for scaled unrevealed fragments", async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1024, height: 768 });
+
+ const deck = page.locator(".reveal.mo-slides-theme");
+ await deck.press("ArrowRight");
+ const slide = deck.locator("section.present");
+ await expect(
+ slide.getByRole("heading", { name: "Overflow before a fragment" }),
+ ).toBeVisible();
+ await expect(slide.locator(".fragment:not(.visible)")).toHaveCount(1);
+ await expect(slide.getByTestId("slide-scroll-hint")).toBeVisible();
+ await slide.getByTestId("slide-scroll-container").evaluate((el) => {
+ el.scrollTop = 100;
+ });
+ await expect(slide.getByTestId("slide-scroll-hint")).toHaveCount(0);
+});
+
+test("new cell output preserves its preview layout after navigation", async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1024, height: 768 });
+ const thumbnails = page.locator("[role='button'][data-cell-id]");
+ await thumbnails
+ .nth(2)
+ .getByRole("button", { name: "Add Python cell" })
+ .click();
+ await expect(thumbnails).toHaveCount(6);
+ await thumbnails.nth(3).click();
+ const editor = page.locator(".cm-content:visible");
+ await expect(editor).toHaveCount(1);
+ await editor.fill(
+ 'mo.md("New output keeps the same line breaks across preview and presentation. " * 20)',
+ );
+ await pressShortcut(page, "cell.run");
+ await expect(
+ page.getByText("New output keeps", { exact: false }).last(),
+ ).toBeVisible();
+ await expect(editor).toBeFocused();
+ await page.getByRole("button", { name: "Hide code", exact: true }).click();
+
+ const preview = page.getByTestId("slide-preview-canvas");
+ await expect(preview).toBeVisible();
+ const measure = (root: Locator) =>
+ root
+ .locator(".paragraph, p")
+ .first()
+ .evaluate((el) => ({
+ width: el.clientWidth,
+ height: el.clientHeight,
+ screenWidth: el.getBoundingClientRect().width,
+ }));
+ const initialPreview = await measure(preview);
+ await page.setViewportSize({ width: 800, height: 600 });
+ await expect
+ .poll(async () => {
+ const current = await measure(preview);
+ return {
+ width: current.width,
+ height: current.height,
+ scaledDown: current.screenWidth < initialPreview.screenWidth,
+ };
+ })
+ .toEqual({
+ width: initialPreview.width,
+ height: initialPreview.height,
+ scaledDown: true,
+ });
+ const previewLayout = await measure(preview);
+ const deck = page.locator(".reveal.mo-slides-theme").first();
+ await deck.press("ArrowLeft");
+ await expect(preview).toHaveCount(0);
+ await deck.press("ArrowRight");
+ await expect
+ .poll(() => measure(deck.locator("section.present")))
+ .toEqual(previewLayout);
+});
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index ef5f022f2c..5d34818198 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -45,6 +45,7 @@ const appToOptions = {
"stdin.py": { command: "edit" },
"layout_grid_with_sidebar.py": { command: "edit" },
"slides.py": { command: "edit" },
+ "slides_sizing.py": { command: "edit" },
"visual_tokens.py": { command: "edit" },
// Custom server for shutdown
"shutdown.py": { command: "edit", port: port() },
diff --git a/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx b/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx
index 4eaac6cdd6..5d0d2a9bd4 100644
--- a/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx
+++ b/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx
@@ -195,4 +195,41 @@ describe("SlideScrollContainer", () => {
expect(screen.queryByTestId("slide-scroll-hint")).toBeNull();
});
+
+ it.each([
+ { scale: 0.5, fragmentOffset: 1000, expected: true },
+ { scale: 2, fragmentOffset: 500, expected: false },
+ ])(
+ "measures revealed content in canvas coordinates at scale $scale",
+ ({ scale, fragmentOffset, expected }) => {
+ render(
+ <SlideScrollContainer>
+ <div>revealed content</div>
+ <div className="fragment">unrevealed content</div>
+ </SlideScrollContainer>,
+ );
+
+ const container = screen.getByTestId("slide-scroll-container");
+ const fragment = container.querySelector<HTMLElement>(".fragment");
+ if (!fragment) {
+ throw new Error("Missing fragment");
+ }
+ stubOverflow(container, { scrollHeight: 1200, clientHeight: 720 });
+ Object.defineProperty(container, "offsetHeight", { value: 720 });
+ vi.spyOn(container, "getBoundingClientRect").mockReturnValue(
+ DOMRect.fromRect({ y: 100, height: 720 * scale }),
+ );
+ vi.spyOn(fragment, "getBoundingClientRect").mockReturnValue(
+ DOMRect.fromRect({ y: 100 + fragmentOffset * scale }),
+ );
+
+ act(() => {
+ for (const observer of resizeObservers) {
+ observer.callback([], observer as unknown as ResizeObserver);
+ }
+ });
+
+ expect(screen.queryByTestId("slide-scroll-hint") !== null).toBe(expected);
+ },
+ );
});
diff --git a/frontend/src/components/slides/reveal-component.tsx b/frontend/src/components/slides/reveal-component.tsx
index 5a3c283f54..50dd0839fc 100644
--- a/frontend/src/components/slides/reveal-component.tsx
+++ b/frontend/src/components/slides/reveal-component.tsx
@@ -69,6 +69,8 @@ import {
} from "./speaker-view";
const ASPECT_RATIO = 16 / 9;
+const SLIDE_WIDTH = 1280;
+const SLIDE_HEIGHT = SLIDE_WIDTH / ASPECT_RATIO;
const CODE_TOGGLE_KEY_CODE = 67;
// Reveal retains custom key bindings after initialization. Replace the `C`
@@ -133,8 +135,11 @@ function classifyNavKey(event: KeyboardEvent): 1 | -1 | 0 {
return 0;
}
-function useSlideDimensions(ref: React.RefObject<HTMLDivElement | null>) {
- const [dims, setDims] = useState({ width: 960, height: 540 });
+function useSlideViewportSize(ref: React.RefObject<HTMLDivElement | null>) {
+ const [dims, setDims] = useState({
+ width: SLIDE_WIDTH,
+ height: SLIDE_HEIGHT,
+ });
useEffect(() => {
const el = ref.current;
@@ -482,8 +487,21 @@ const RevealSlidesComponent = ({
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const deckRef = useRef<RevealApi | null>(null);
- const { width, height } = useSlideDimensions(containerRef);
+ const { width, height } = useSlideViewportSize(containerRef);
const isFullscreen = useFullScreenElement() != null;
+ const [slideScale, setSlideScale] = useState(1);
+
+ useEffect(() => {
+ // Embedded decks also resize when panels change, without a window resize.
+ const frame = requestAnimationFrame(() => {
+ const deck = deckRef.current;
+ if (deck) {
+ deck.layout();
+ setSlideScale(deck.getScale());
+ }
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [width, height, isFullscreen]);
// A receiver frame cannot spawn another speaker view. WebAssembly exports
// also omit the plugin because each receiver would start another runtime.
@@ -589,10 +607,10 @@ const RevealSlidesComponent = ({
const revealConfig: RevealConfig = useMemo(
() => ({
embedded: true,
- width,
- height,
+ width: SLIDE_WIDTH,
+ height: SLIDE_HEIGHT,
center: false,
- minScale: 0.2,
+ minScale: 0,
maxScale: 2,
transition: deckTransition,
keyboardCondition: (event: KeyboardEvent) => !Events.fromInput(event),
@@ -602,7 +620,7 @@ const RevealSlidesComponent = ({
// `@revealjs/react` owns, which crashes on `reveal.sync()` re-renders.
scrollActivationWidth: 0,
}),
- [width, height, deckTransition, kioskUrl],
+ [deckTransition, kioskUrl],
);
const navigateDeckToActiveCell = useEvent((deck: RevealApi) => {
@@ -703,6 +721,7 @@ const RevealSlidesComponent = ({
});
const handleDeckReady = useEvent((deck: RevealApi) => {
+ setSlideScale(deck.getScale());
navigateDeckToActiveCell(deck);
if (canResolveInitialHash) {
reportDeckCell(deck);
@@ -829,22 +848,33 @@ const RevealSlidesComponent = ({
<span>{parkedPreviewLabel}</span>
</div>
)}
- <div className="flex-1 overflow-auto flex">
- <div
- className={
- parkedShowsSource
- ? "mo-slide-content flex flex-col gap-3"
- : "mo-slide-content"
- }
- style={slideContentStyle}
- >
- <ParkedPreviewContent
- cell={parkedPreviewCell}
- isNoOutputPreview={isNoOutputPreview}
- isEditable={isEditable}
- showCode={parkedShowCode}
- />
- </div>
+ <div
+ className="reveal mo-slides-theme prose-slides absolute left-1/2 top-1/2"
+ data-testid="slide-preview-canvas"
+ style={{
+ position: "absolute",
+ width: SLIDE_WIDTH,
+ height: SLIDE_HEIGHT,
+ transform: `translate(-50%, -50%) scale(${slideScale})`,
+ }}
+ >
+ <SlideScrollContainer>
+ <div
+ className={
+ parkedShowsSource
+ ? "mo-slide-content flex flex-col gap-3"
+ : "mo-slide-content"
+ }
+ style={slideContentStyle}
+ >
+ <ParkedPreviewContent
+ cell={parkedPreviewCell}
+ isNoOutputPreview={isNoOutputPreview}
+ isEditable={isEditable}
+ showCode={parkedShowCode}
+ />
+ </div>
+ </SlideScrollContainer>
</div>
</div>
)}
diff --git a/frontend/src/components/slides/reveal-slides.css b/frontend/src/components/slides/reveal-slides.css
index 92e2547f93..5b58dc8f95 100644
--- a/frontend/src/components/slides/reveal-slides.css
+++ b/frontend/src/components/slides/reveal-slides.css
@@ -1,5 +1,10 @@
@import "reveal.js/reveal.css";
+/* Reveal scales the canvas; responsive rem sizes would reflow its content. */
+html:has(.reveal.mo-slides-theme) {
+ font-size: 100%;
+}
+
/* Neutralize reveal-viewport styles so the slides inherit marimo's defaults */
.reveal-viewport {
background-color: transparent;
@@ -11,10 +16,6 @@
.reveal-viewport:fullscreen {
background-color: var(--background);
}
-.reveal-viewport:fullscreen .mo-slide-content {
- padding-left: 2rem;
- padding-right: 2rem;
-}
.reveal-viewport::backdrop {
background-color: var(--background);
}
diff --git a/frontend/src/components/slides/slide-scroll-hint.tsx b/frontend/src/components/slides/slide-scroll-hint.tsx
index cb9ec32c7f..e4dd2a682d 100644
--- a/frontend/src/components/slides/slide-scroll-hint.tsx
+++ b/frontend/src/components/slides/slide-scroll-hint.tsx
@@ -41,8 +41,10 @@ function measureRevealedHeight(el: HTMLElement): number {
if (!firstUnrevealed) {
return el.scrollHeight;
}
+ const bounds = el.getBoundingClientRect();
+ const scale = el.offsetHeight > 0 ? bounds.height / el.offsetHeight : 1;
const fragmentTop = firstUnrevealed.getBoundingClientRect().top;
- return fragmentTop - el.getBoundingClientRect().top + el.scrollTop;
+ return (fragmentTop - bounds.top) / (scale || 1) + el.scrollTop;
}
/**