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.

improvement: additional print configuration, fix race conditions in export to pdf (#8038)

Myles Scolnickd82b3f627a5d
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsx
index 436e05bd6a..689f65bbd8 100644
--- a/frontend/src/components/data-table/TableActions.tsx
+++ b/frontend/src/components/data-table/TableActions.tsx
@@ -107,13 +107,13 @@ export const TableActions = <TData,>({
};
return (
- <div className="flex items-center shrink-0 pt-1 no-print">
+ <div className="flex items-center shrink-0 pt-1">
{onSearchQueryChange && enableSearch && (
<Tooltip content="Search">
<Button
variant="text"
size="xs"
- className="mb-0"
+ className="mb-0 print:hidden"
onClick={() => setIsSearchEnabled(!isSearchEnabled)}
>
<SearchIcon className="w-4 h-4 text-muted-foreground" />
@@ -125,7 +125,7 @@ export const TableActions = <TData,>({
<Button
variant="text"
size="xs"
- className="mb-0"
+ className="mb-0 print:hidden"
onClick={toggleDisplayHeader}
>
<ChartSplineIcon className="w-4 h-4 text-muted-foreground" />
@@ -140,6 +140,7 @@ export const TableActions = <TData,>({
variant="text"
size="xs"
onClick={() => togglePanel("row-viewer")}
+ className="print:hidden"
>
<PanelRightIcon
className={cn(
@@ -156,6 +157,7 @@ export const TableActions = <TData,>({
variant="text"
size="xs"
onClick={() => togglePanel("column-explorer")}
+ className="print:hidden"
>
<ChartColumnStacked
className={cn(
diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsx
index 77cd2e3ed1..3b13efe616 100644
--- a/frontend/src/components/data-table/download-actions.tsx
+++ b/frontend/src/components/data-table/download-actions.tsx
@@ -87,7 +87,12 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {
const { locale } = useLocale();
const button = (
- <Button data-testid="download-as-button" size="xs" variant="link">
+ <Button
+ data-testid="download-as-button"
+ size="xs"
+ variant="link"
+ className="print:hidden"
+ >
Download <ChevronDownIcon className="w-3 h-3 ml-1" />
</Button>
);
@@ -146,7 +151,7 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>
- <DropdownMenuContent side="bottom" className="no-print">
+ <DropdownMenuContent side="bottom" className="print:hidden">
{options.map((option) => (
<DropdownMenuItem
key={option.label}
diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsx
index fd25d57dbe..99ccf55c32 100644
--- a/frontend/src/components/data-table/pagination.tsx
+++ b/frontend/src/components/data-table/pagination.tsx
@@ -67,7 +67,7 @@ export const DataTablePagination = <TData,>({
size="xs"
data-testid="select-all-button"
variant="link"
- className="h-4"
+ className="h-4 print:hidden"
onMouseDown={Events.preventFocus}
onClick={() => {
if (onSelectAllRowsChange) {
@@ -91,7 +91,7 @@ export const DataTablePagination = <TData,>({
size="xs"
data-testid="clear-selection-button"
variant="link"
- className="h-4"
+ className="h-4 print:hidden"
onMouseDown={Events.preventFocus}
onClick={() => {
if (!isCellSelection) {
@@ -139,7 +139,7 @@ export const DataTablePagination = <TData,>({
const renderPageSizeSelector = () => {
return (
- <div className="flex items-center gap-1 text-xs whitespace-nowrap mr-1">
+ <div className="flex items-center gap-1 text-xs whitespace-nowrap mr-1 print:hidden">
<Select
value={pageSize.toString()}
onValueChange={(value) => table.setPageSize(Number(value))}
@@ -173,7 +173,7 @@ export const DataTablePagination = <TData,>({
{showPageSizeSelector && renderPageSizeSelector()}
</div>
- <div className="flex items-end space-x-2">
+ <div className="flex items-end space-x-2 print:hidden">
<Button
size="xs"
variant="outline"
diff --git a/frontend/src/components/debug/indicator.tsx b/frontend/src/components/debug/indicator.tsx
index b0b29752e8..605b09db65 100644
--- a/frontend/src/components/debug/indicator.tsx
+++ b/frontend/src/components/debug/indicator.tsx
@@ -5,7 +5,7 @@ export const TailwindIndicator = () => {
}
return (
- <div className="fixed bottom-10 right-0 z-50 flex items-center justify-center bg-gray-800 py-[2px] px-1 font-mono text-[10px] text-white font-semibold">
+ <div className="fixed bottom-10 right-0 z-50 flex items-center justify-center bg-gray-800 py-[2px] px-1 font-mono text-[10px] text-white font-semibold print:hidden">
<div className="block sm:hidden">xs</div>
<div className="hidden sm:block md:hidden lg:hidden xl:hidden 2xl:hidden">
sm
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index 747be5b8eb..9f5eaf5c33 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -70,6 +70,7 @@ import { createShareableLink } from "@/core/wasm/share";
import { isWasm } from "@/core/wasm/utils";
import { copyToClipboard } from "@/utils/copy";
import {
+ ADD_PRINTING_CLASS,
downloadAsPDF,
downloadBlob,
downloadHTMLAsImage,
@@ -219,6 +220,8 @@ export function useNotebookActions() {
await downloadHTMLAsImage({
element: app,
filename: document.title,
+ // Add body.printing ONLY when converting the whole notebook to a screenshot
+ prepare: ADD_PRINTING_CLASS,
});
},
},
@@ -241,8 +244,7 @@ export function useNotebookActions() {
const downloadPDF = async (progress: ProgressState) => {
await updateCellOutputsWithScreenshots({
- takeScreenshots: () =>
- takeScreenshots({ progress, snappy: false }),
+ takeScreenshots: () => takeScreenshots({ progress }),
updateCellOutputs,
});
await downloadAsPDF({
diff --git a/frontend/src/components/editor/chrome/panels/context-aware-panel/context-aware-panel.tsx b/frontend/src/components/editor/chrome/panels/context-aware-panel/context-aware-panel.tsx
index ad9cc31630..93d2f27541 100644
--- a/frontend/src/components/editor/chrome/panels/context-aware-panel/context-aware-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/context-aware-panel/context-aware-panel.tsx
@@ -123,7 +123,7 @@ export const ContextAwarePanel: React.FC = () => {
<>
<PanelResizeHandle
onDragging={handleDragging}
- className="resize-handle border-border z-20 no-print border-l"
+ className="resize-handle border-border z-20 print:hidden border-l"
/>
<Panel defaultSize={20} minSize={15} maxSize={80}>
{renderBody()}
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index 3979a09203..e8ea0552bb 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -227,7 +227,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
<PanelResizeHandle
onDragging={handleDragging}
className={cn(
- "border-border no-print z-10",
+ "border-border print:hidden z-10",
isSidebarOpen ? "resize-handle" : "resize-handle-collapsed",
"vertical",
)}
@@ -238,7 +238,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
<PanelResizeHandle
onDragging={handleDragging}
className={cn(
- "border-border no-print z-20",
+ "border-border print:hidden z-20",
isDeveloperPanelOpen ? "resize-handle" : "resize-handle-collapsed",
"horizontal",
)}
@@ -382,7 +382,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
collapsedSize={0}
collapsible={true}
className={cn(
- "dark:bg-(--slate-1) no-print print:hidden hide-on-fullscreen",
+ "dark:bg-(--slate-1) print:hidden hide-on-fullscreen",
isSidebarOpen && "border-r border-l border-(--slate-7)",
)}
minSize={10}
@@ -427,7 +427,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
collapsedSize={0}
collapsible={true}
className={cn(
- "dark:bg-(--slate-1) no-print print:hidden hide-on-fullscreen",
+ "dark:bg-(--slate-1) print:hidden hide-on-fullscreen",
isDeveloperPanelOpen && "border-t",
)}
minSize={10}
diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsx
index 5412ecd2b8..57bc08c33b 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx
@@ -57,7 +57,7 @@ export const Footer: React.FC = () => {
});
return (
- <footer className="h-10 py-1 gap-1 bg-background flex items-center text-muted-foreground text-md pl-2 pr-1 border-t border-border select-none no-print text-sm z-50 print:hidden hide-on-fullscreen overflow-x-auto overflow-y-hidden scrollbar-thin">
+ <footer className="h-10 py-1 gap-1 bg-background flex items-center text-muted-foreground text-md pl-2 pr-1 border-t border-border select-none print:hidden text-sm z-50 hide-on-fullscreen overflow-x-auto overflow-y-hidden scrollbar-thin">
<FooterItem
className="h-full"
tooltip={
diff --git a/frontend/src/components/editor/chrome/wrapper/sidebar.tsx b/frontend/src/components/editor/chrome/wrapper/sidebar.tsx
index c8dde2d089..a6b1af1669 100644
--- a/frontend/src/components/editor/chrome/wrapper/sidebar.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/sidebar.tsx
@@ -115,7 +115,7 @@ export const Sidebar: React.FC = () => {
]);
return (
- <div className="h-full pt-4 pb-1 px-1 flex flex-col items-start text-muted-foreground text-md select-none no-print text-sm z-50 dark:bg-background print:hidden hide-on-fullscreen">
+ <div className="h-full pt-4 pb-1 px-1 flex flex-col items-start text-muted-foreground text-md select-none text-sm z-50 dark:bg-background print:hidden hide-on-fullscreen">
<ReorderableList<PanelDescriptor>
value={sidebarItems}
setValue={handleSetSidebarItems}
diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsx
index 18beddd3b8..0ea8219fac 100644
--- a/frontend/src/components/editor/controls/Controls.tsx
+++ b/frontend/src/components/editor/controls/Controls.tsx
@@ -212,7 +212,7 @@ const StopControlButton = ({
};
const topRightControls =
- "absolute top-3 right-5 m-0 flex items-center gap-2 min-h-[28px] no-print pointer-events-auto z-30 print:hidden";
+ "absolute top-3 right-5 m-0 flex items-center gap-2 min-h-[28px] print:hidden pointer-events-auto z-30";
const bottomRightControls =
- "absolute bottom-5 right-5 flex flex-col gap-2 items-center no-print pointer-events-auto z-30 print:hidden";
+ "absolute bottom-5 right-5 flex flex-col gap-2 items-center print:hidden pointer-events-auto z-30";
diff --git a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
index 2dbf06fba6..7af741a9a7 100644
--- a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
+++ b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
@@ -111,7 +111,7 @@ export const NotebookMenuDropdown: React.FC<Props> = ({
<DropdownMenuTrigger asChild={true} disabled={disabled}>
{button}
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="no-print w-[240px]">
+ <DropdownMenuContent align="end" className="print:hidden w-[240px]">
{actions.map((action) => {
if (action.hidden || action.redundant) {
return null;
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 073604b4ac..5c390d20be 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -510,7 +510,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
return (
<DropdownMenuContent
align="end"
- className="no-print w-[220px]"
+ className="print:hidden w-[220px]"
onClick={(e) => e.stopPropagation()}
onCloseAutoFocus={(e) => e.preventDefault()}
>
diff --git a/frontend/src/components/editor/header/status.tsx b/frontend/src/components/editor/header/status.tsx
index 9e77b91307..8c0c678e46 100644
--- a/frontend/src/components/editor/header/status.tsx
+++ b/frontend/src/components/editor/header/status.tsx
@@ -34,7 +34,7 @@ export const StatusOverlay: React.FC<{
);
};
-const topLeftStatus = "no-print pointer-events-auto hover:cursor-pointer";
+const topLeftStatus = "print:hidden pointer-events-auto hover:cursor-pointer";
const DisconnectedIcon = () => (
<Tooltip content="App disconnected">
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 777957f944..ddcd6fd7d4 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -41,7 +41,11 @@ import { downloadAsHTML } from "@/core/static/download-html";
import { isStaticNotebook } from "@/core/static/static-state";
import { isWasm } from "@/core/wasm/utils";
import { cn } from "@/utils/cn";
-import { downloadBlob, downloadHTMLAsImage } from "@/utils/download";
+import {
+ ADD_PRINTING_CLASS,
+ downloadBlob,
+ downloadHTMLAsImage,
+} from "@/utils/download";
import { Filenames } from "@/utils/filenames";
import { FloatingOutline } from "../../chrome/panels/outline/floating-outline";
import { cellDomProps } from "../../common";
@@ -185,7 +189,12 @@ const ActionButtons: React.FC<{
if (!app) {
return;
}
- await downloadHTMLAsImage({ element: app, filename: document.title });
+ await downloadHTMLAsImage({
+ element: app,
+ filename: document.title,
+ // Add body.printing ONLY when converting the whole notebook to a screenshot
+ prepare: ADD_PRINTING_CLASS,
+ });
};
const handleDownloadAsHTML = async () => {
@@ -271,7 +280,7 @@ const ActionButtons: React.FC<{
<div
data-testid="notebook-actions-dropdown"
className={cn(
- "right-0 top-0 z-50 m-4 no-print flex gap-2 print:hidden",
+ "right-0 top-0 z-50 m-4 print:hidden flex gap-2",
// If the notebook is static, we have a banner at the top, so
// we can't use fixed positioning. Ideally this is sticky, but the
// current dom structure makes that difficult.
@@ -284,7 +293,7 @@ const ActionButtons: React.FC<{
<MoreHorizontalIcon className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="no-print w-[220px]">
+ <DropdownMenuContent align="end" className="print:hidden w-[220px]">
{actions}
</DropdownMenuContent>
</DropdownMenu>
diff --git a/frontend/src/components/home/components.tsx b/frontend/src/components/home/components.tsx
index 0c5ac006a5..183207244c 100644
--- a/frontend/src/components/home/components.tsx
+++ b/frontend/src/components/home/components.tsx
@@ -80,7 +80,7 @@ export const OpenTutorialDropDown: React.FC = () => {
<CaretDownIcon className="w-3 h-3 ml-1" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent side="bottom" align="end" className="no-print">
+ <DropdownMenuContent side="bottom" align="end" className="print:hidden">
{Objects.entries(TUTORIALS).map(
([tutorialId, [label, Icon, description]]) => (
<DropdownMenuItem
diff --git a/frontend/src/components/static-html/static-banner.tsx b/frontend/src/components/static-html/static-banner.tsx
index 12ea95fbca..7b22f1d066 100644
--- a/frontend/src/components/static-html/static-banner.tsx
+++ b/frontend/src/components/static-html/static-banner.tsx
@@ -36,7 +36,7 @@ export const StaticBanner: React.FC = () => {
return (
<div
- className="px-4 py-2 bg-(--sky-2) border-b border-(--sky-7) text-(--sky-11) flex justify-between items-center gap-4 no-print text-sm"
+ className="px-4 py-2 bg-(--sky-2) border-b border-(--sky-7) text-(--sky-11) flex justify-between items-center gap-4 print:hidden text-sm"
data-testid="static-notebook-banner"
>
<span>
diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsx
index 3758b1df10..c332ae13d5 100644
--- a/frontend/src/components/ui/dropdown-menu.tsx
+++ b/frontend/src/components/ui/dropdown-menu.tsx
@@ -83,7 +83,7 @@ const DropdownMenuContent = React.forwardRef<
sideOffset={sideOffset}
className={cn(
menuContentCommon(),
- "animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ "animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 print:hidden",
scrollable && "overflow-auto",
className,
)}
diff --git a/frontend/src/components/ui/table.tsx b/frontend/src/components/ui/table.tsx
index 0a636f5de8..e4123fc4e9 100644
--- a/frontend/src/components/ui/table.tsx
+++ b/frontend/src/components/ui/table.tsx
@@ -7,7 +7,7 @@ const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
- <div className="w-full overflow-auto scrollbar-thin flex-1">
+ <div className="w-full overflow-auto scrollbar-thin flex-1 print:overflow-hidden">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
diff --git a/frontend/src/core/export/__tests__/hooks.test.ts b/frontend/src/core/export/__tests__/hooks.test.ts
index b267338c57..c89c8ea4bf 100644
--- a/frontend/src/core/export/__tests__/hooks.test.ts
+++ b/frontend/src/core/export/__tests__/hooks.test.ts
@@ -10,6 +10,7 @@ import { CellOutputId } from "@/core/cells/ids";
import type { CellRuntimeState } from "@/core/cells/types";
import { ProgressState } from "@/utils/progress";
import {
+ captureTracker,
updateCellOutputsWithScreenshots,
useEnrichCellOutputs,
} from "../hooks";
@@ -52,6 +53,7 @@ describe("useEnrichCellOutputs", () => {
beforeEach(() => {
vi.clearAllMocks();
store = createStore();
+ captureTracker.reset();
});
const wrapper = ({ children }: { children: ReactNode }) =>
@@ -103,7 +105,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
expect(output).toEqual({});
expect(document.getElementById).not.toHaveBeenCalled();
@@ -135,7 +137,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
expect(document.getElementById).toHaveBeenCalledWith(
CellOutputId.create(cellId),
@@ -152,50 +154,6 @@ describe("useEnrichCellOutputs", () => {
});
});
- it("should pass snappy=true to toPng with includeStyleProperties", async () => {
- const cellId = "cell-1" as CellId;
- const mockElement = document.createElement("div");
- const mockDataUrl = "data:image/png;base64,mockImageData";
-
- // Mock document.getElementById
- vi.spyOn(document, "getElementById").mockReturnValue(mockElement);
- vi.mocked(toPng).mockResolvedValue(mockDataUrl);
-
- setCellsRuntime(
- createMockCellRuntimes({
- [cellId]: {
- output: {
- channel: "output",
- mimetype: "text/html",
- data: "<div>Chart</div>",
- timestamp: 0,
- },
- },
- }),
- );
-
- const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
-
- const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: true });
-
- expect(document.getElementById).toHaveBeenCalledWith(
- CellOutputId.create(cellId),
- );
- // When snappy=true, includeStyleProperties should be set
- expect(toPng).toHaveBeenCalledWith(
- mockElement,
- expect.objectContaining({
- filter: expect.any(Function),
- onImageErrorHandler: expect.any(Function),
- includeStyleProperties: expect.any(Array),
- }),
- );
- expect(output).toEqual({
- [cellId]: ["image/png", mockDataUrl],
- });
- });
-
it("should skip cells where output has not changed", async () => {
const cellId = "cell-1" as CellId;
const mockElement = document.createElement("div");
@@ -224,7 +182,7 @@ describe("useEnrichCellOutputs", () => {
// First call - should capture
let takeScreenshots = result.current;
- let output = await takeScreenshots({ progress, snappy: false });
+ let output = await takeScreenshots({ progress });
expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl] });
expect(toPng).toHaveBeenCalledTimes(1);
@@ -233,7 +191,7 @@ describe("useEnrichCellOutputs", () => {
// Second call with same output - should not capture again
takeScreenshots = result.current;
- output = await takeScreenshots({ progress, snappy: false });
+ output = await takeScreenshots({ progress });
expect(output).toEqual({}); // Empty because output hasn't changed
expect(toPng).toHaveBeenCalledTimes(1); // Still only 1 call
});
@@ -262,7 +220,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
expect(output).toEqual({}); // Failed screenshot should be filtered out
expect(Logger.error).toHaveBeenCalledWith(
@@ -271,6 +229,50 @@ describe("useEnrichCellOutputs", () => {
);
});
+ it("should retry failed screenshots on next call", async () => {
+ const cellId = "cell-1" as CellId;
+ const mockElement = document.createElement("div");
+ const error = new Error("Screenshot failed");
+ const mockDataUrl = "data:image/png;base64,retrySuccess";
+
+ vi.spyOn(document, "getElementById").mockReturnValue(mockElement);
+ // First call fails, second call succeeds
+ vi.mocked(toPng)
+ .mockRejectedValueOnce(error)
+ .mockResolvedValueOnce(mockDataUrl);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result, rerender } = renderHook(() => useEnrichCellOutputs(), {
+ wrapper,
+ });
+
+ // First call - screenshot fails
+ let takeScreenshots = result.current;
+ let output = await takeScreenshots({ progress });
+ expect(output).toEqual({});
+ expect(Logger.error).toHaveBeenCalled();
+
+ rerender();
+
+ // Second call - should retry since the first one failed
+ takeScreenshots = result.current;
+ output = await takeScreenshots({ progress });
+ expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl] });
+ expect(toPng).toHaveBeenCalledTimes(2);
+ });
+
it("should handle missing DOM elements", async () => {
const cellId = "cell-1" as CellId;
@@ -292,7 +294,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
expect(output).toEqual({});
expect(Logger.error).toHaveBeenCalledWith(
@@ -341,7 +343,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
expect(output).toEqual({
[cell1]: ["image/png", mockDataUrl1],
@@ -387,7 +389,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
// Only the successful screenshot should be in the result
expect(output).toEqual({
@@ -429,13 +431,13 @@ describe("useEnrichCellOutputs", () => {
// First screenshot
let takeScreenshots = result.current;
- let output = await takeScreenshots({ progress, snappy: false });
+ let output = await takeScreenshots({ progress });
expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl1] });
// Second call - same output, should not be captured
rerender();
takeScreenshots = result.current;
- output = await takeScreenshots({ progress, snappy: false });
+ output = await takeScreenshots({ progress });
expect(output).toEqual({});
// Third call - output changed, should be captured
@@ -454,7 +456,7 @@ describe("useEnrichCellOutputs", () => {
rerender();
takeScreenshots = result.current;
- output = await takeScreenshots({ progress, snappy: false });
+ output = await takeScreenshots({ progress });
expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl2] });
expect(toPng).toHaveBeenCalledTimes(2);
});
@@ -494,7 +496,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
// None of these should trigger screenshots
expect(output).toEqual({});
@@ -519,7 +521,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
expect(output).toEqual({});
expect(document.getElementById).not.toHaveBeenCalled();
@@ -551,7 +553,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const takeScreenshots = result.current;
- const output = await takeScreenshots({ progress, snappy: false });
+ const output = await takeScreenshots({ progress });
// Verify the exact return type structure
expect(output).toHaveProperty(cellId);
diff --git a/frontend/src/core/export/hooks.ts b/frontend/src/core/export/hooks.ts
index 1448c70a9c..b90050e586 100644
--- a/frontend/src/core/export/hooks.ts
+++ b/frontend/src/core/export/hooks.ts
@@ -1,9 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { atom, useAtom, useAtomValue } from "jotai";
+import { useAtomValue } from "jotai";
import type { MimeType } from "@/components/editor/Output";
import { toast } from "@/components/ui/use-toast";
import { appConfigAtom } from "@/core/config/config";
import { useInterval } from "@/hooks/useInterval";
+import { AsyncCaptureTracker } from "@/utils/async-capture-tracker";
import { getImageDataUrlForCell } from "@/utils/download";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
@@ -67,7 +68,6 @@ export function useAutoExport() {
const screenshotFn = () =>
takeScreenshots({
progress: ProgressState.indeterminate(),
- snappy: true,
});
await updateCellOutputsWithScreenshots({
takeScreenshots: screenshotFn,
@@ -89,9 +89,6 @@ export function useAutoExport() {
);
}
-// We track cells that need screenshots, these will be exported to IPYNB
-const richCellsToOutputAtom = atom<Record<CellId, unknown>>({});
-
// MIME types to capture screenshots for
const MIME_TYPES_TO_CAPTURE_SCREENSHOTS = new Set<MimeType>([
"text/html",
@@ -101,66 +98,109 @@ const MIME_TYPES_TO_CAPTURE_SCREENSHOTS = new Set<MimeType>([
"application/vnd.vega.v6+json",
]);
-type ScreenshotResults = Record<CellId, ["image/png", string]>;
+type ScreenshotResult = ["image/png", string];
+type ScreenshotResults = Record<CellId, ScreenshotResult>;
+
+// Only marks cells as captured after successful screenshot.
+export const captureTracker = new AsyncCaptureTracker<
+ CellId,
+ ScreenshotResult
+>();
+
+interface UseEnrichCellOutputsOptions {
+ progress: ProgressState;
+}
/**
* Take screenshots of cells with HTML outputs. These images will be sent to the backend to be exported to IPYNB.
* @returns A map of cell IDs to their screenshots data.
*/
-export function useEnrichCellOutputs() {
- const [richCellsOutput, setRichCellsOutput] = useAtom(richCellsToOutputAtom);
+export function useEnrichCellOutputs(): (
+ opts: UseEnrichCellOutputsOptions,
+) => Promise<ScreenshotResults> {
const cellRuntimes = useAtomValue(cellsRuntimeAtom);
- return async ({
- progress,
- snappy,
- }: {
- progress: ProgressState;
- snappy: boolean;
- }): Promise<ScreenshotResults> => {
- const trackedCellsOutput: Record<CellId, unknown> = {};
+ return async (
+ opts: UseEnrichCellOutputsOptions,
+ ): Promise<ScreenshotResults> => {
+ const { progress } = opts;
+
+ // Prune tracked state for cells that no longer exist
+ const currentCellIds = new Set(Objects.keys(cellRuntimes));
+ captureTracker.prune(currentCellIds);
const cellsToCaptureScreenshot: [CellId, unknown][] = [];
+ const inFlightWaiters: {
+ cellId: CellId;
+ promise: Promise<ScreenshotResult | undefined>;
+ }[] = [];
+
for (const [cellId, runtime] of Objects.entries(cellRuntimes)) {
const outputData = runtime.output?.data;
- const outputHasChanged = richCellsOutput[cellId] !== outputData;
- // Track latest output for this cell
- trackedCellsOutput[cellId] = outputData;
if (
runtime.output?.mimetype &&
MIME_TYPES_TO_CAPTURE_SCREENSHOTS.has(runtime.output.mimetype) &&
- outputData &&
- outputHasChanged
+ outputData
) {
- cellsToCaptureScreenshot.push([cellId, runtime]);
+ if (captureTracker.needsCapture(cellId, outputData)) {
+ cellsToCaptureScreenshot.push([cellId, outputData]);
+ } else {
+ // If already in-flight with the same value, await its result
+ const promise = captureTracker.waitForInFlight(cellId, outputData);
+ if (promise) {
+ inFlightWaiters.push({ cellId, promise });
+ }
+ }
}
}
- // Always update tracked outputs, this ensures data is fresh for the next run
- setRichCellsOutput(trackedCellsOutput);
- if (cellsToCaptureScreenshot.length === 0) {
+ if (cellsToCaptureScreenshot.length === 0 && inFlightWaiters.length === 0) {
return {};
}
- // Capture screenshots
- const total = cellsToCaptureScreenshot.length;
- progress.addTotal(total);
+ // Start the progress bar for new captures only
+ if (cellsToCaptureScreenshot.length > 0) {
+ progress.addTotal(cellsToCaptureScreenshot.length);
+ }
+
+ // Capture screenshots — each key gets its own AbortSignal so
+ // aborting one cell does not affect the others.
const results: ScreenshotResults = {};
- for (const [cellId] of cellsToCaptureScreenshot) {
+ for (const [cellId, outputData] of cellsToCaptureScreenshot) {
+ const handle = captureTracker.startCapture(cellId, outputData);
try {
- const dataUrl = await getImageDataUrlForCell(cellId, snappy);
+ const dataUrl = await getImageDataUrlForCell(cellId);
+ if (handle.signal.aborted) {
+ continue;
+ }
if (!dataUrl) {
Logger.error(`Failed to capture screenshot for cell ${cellId}`);
+ handle.markFailed();
continue;
}
- results[cellId] = ["image/png", dataUrl];
+ const result: ScreenshotResult = ["image/png", dataUrl];
+ results[cellId] = result;
+ handle.markCaptured(result);
} catch (error) {
Logger.error(`Error screenshotting cell ${cellId}:`, error);
+ handle.markFailed();
} finally {
progress.increment(1);
}
}
+ // Await in-flight captures started by concurrent callers
+ const settled = await Promise.allSettled(
+ inFlightWaiters.map(({ promise }) => promise),
+ );
+ for (const [i, { cellId }] of inFlightWaiters.entries()) {
+ const result =
+ settled[i].status === "fulfilled" ? settled[i].value : undefined;
+ if (result) {
+ results[cellId] = result;
+ }
+ }
+
return results;
};
}
diff --git a/frontend/src/css/app/print.css b/frontend/src/css/app/print.css
index 6336138e2e..8c9b1f64d9 100644
--- a/frontend/src/css/app/print.css
+++ b/frontend/src/css/app/print.css
@@ -1,24 +1,10 @@
@reference "../globals.css";
-/* Hide on print
-To hide an element on print, add the class `no-print` to it.
-When printing, the class `printing` is added to the body element to enable this rule. */
-body.printing .no-print {
- display: none !important;
-}
-
body.printing #App {
/* Full screen print */
height: fit-content !important;
}
-/* When printing the output of a cell, this unset the max-height set by the notebook to capture the full output */
-.printing-output {
- max-height: none !important;
-
- @apply bg-background;
-}
-
@media print {
* {
-webkit-print-color-adjust: exact;
diff --git a/frontend/src/utils/__tests__/async-capture-tracker.test.ts b/frontend/src/utils/__tests__/async-capture-tracker.test.ts
new file mode 100644
index 0000000000..1e84b36e03
--- /dev/null
+++ b/frontend/src/utils/__tests__/async-capture-tracker.test.ts
@@ -0,0 +1,353 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it } from "vitest";
+import { AsyncCaptureTracker } from "../async-capture-tracker";
+
+describe("AsyncCaptureTracker", () => {
+ let tracker: AsyncCaptureTracker<string, string>;
+
+ beforeEach(() => {
+ tracker = new AsyncCaptureTracker();
+ });
+
+ describe("needsCapture", () => {
+ it("should return true for keys not yet captured", () => {
+ expect(tracker.needsCapture("a", "value1")).toBe(true);
+ });
+
+ it("should return false for keys captured with the same value", () => {
+ const handle = tracker.startCapture("a", "value1");
+ handle.markCaptured("result");
+ expect(tracker.needsCapture("a", "value1")).toBe(false);
+ });
+
+ it("should return true for keys captured with a different value", () => {
+ const handle = tracker.startCapture("a", "value1");
+ handle.markCaptured("result");
+ expect(tracker.needsCapture("a", "value2")).toBe(true);
+ });
+
+ it("should return false for keys in-flight with the same value", () => {
+ tracker.startCapture("a", "value1");
+ expect(tracker.needsCapture("a", "value1")).toBe(false);
+ });
+
+ it("should return true for keys in-flight with a different value", () => {
+ tracker.startCapture("a", "value1");
+ expect(tracker.needsCapture("a", "value2")).toBe(true);
+ });
+
+ it("should return true for keys that failed (returned to idle)", () => {
+ const handle = tracker.startCapture("a", "value1");
+ handle.markFailed();
+ expect(tracker.needsCapture("a", "value1")).toBe(true);
+ });
+ });
+
+ describe("startCapture", () => {
+ it("should return a handle with a non-aborted signal", () => {
+ const handle = tracker.startCapture("a", "v");
+ expect(handle.signal.aborted).toBe(false);
+ });
+
+ it("should abort only the same key's previous signal", () => {
+ const handleA = tracker.startCapture("a", "v1");
+ const handleB = tracker.startCapture("b", "v1");
+ const handleA2 = tracker.startCapture("a", "v2");
+
+ expect(handleA.signal.aborted).toBe(true);
+ expect(handleB.signal.aborted).toBe(false);
+ expect(handleA2.signal.aborted).toBe(false);
+
+ // Unrelated key still completes independently
+ handleB.markCaptured("result-b");
+ expect(tracker.needsCapture("b", "v1")).toBe(false);
+ });
+
+ it("should not abort other keys when one is re-captured", () => {
+ tracker.startCapture("a", "v");
+ tracker.startCapture("b", "v");
+ tracker.startCapture("c", "v");
+
+ const handleB2 = tracker.startCapture("b", "v2");
+
+ expect(tracker.needsCapture("a", "v")).toBe(false); // still in-flight
+ expect(tracker.needsCapture("c", "v")).toBe(false); // still in-flight
+ expect(handleB2.signal.aborted).toBe(false);
+ });
+
+ it("should mark key as in-flight", () => {
+ tracker.startCapture("a", "v");
+ expect(tracker.isCapturing).toBe(true);
+ expect(tracker.needsCapture("a", "v")).toBe(false);
+ });
+ });
+
+ describe("handle.markCaptured", () => {
+ it("should remove key from in-flight", () => {
+ const handle = tracker.startCapture("a", "v");
+ expect(tracker.isCapturing).toBe(true);
+ handle.markCaptured("result");
+ expect(tracker.isCapturing).toBe(false);
+ });
+
+ it("should persist the captured value", () => {
+ const handle = tracker.startCapture("a", "value1");
+ handle.markCaptured("result");
+ expect(tracker.needsCapture("a", "value1")).toBe(false);
+ expect(tracker.needsCapture("a", "value2")).toBe(true);
+ });
+
+ it("should update the captured value on re-capture", () => {
+ const h1 = tracker.startCapture("a", "v1");
+ h1.markCaptured("r1");
+
+ const h2 = tracker.startCapture("a", "v2");
+ h2.markCaptured("r2");
+
+ expect(tracker.needsCapture("a", "v1")).toBe(true);
+ expect(tracker.needsCapture("a", "v2")).toBe(false);
+ });
+
+ it("should be a no-op when handle is stale (superseded)", () => {
+ const handle1 = tracker.startCapture("a", "v1");
+ const handle2 = tracker.startCapture("a", "v2");
+
+ // handle1 is stale — markCaptured should not affect state
+ handle1.markCaptured("stale-result");
+
+ // "a" should still be in-flight with v2
+ expect(tracker.needsCapture("a", "v2")).toBe(false); // in-flight
+ expect(tracker.needsCapture("a", "v1")).toBe(true); // not captured
+ expect(tracker.isCapturing).toBe(true);
+
+ // handle2 still works
+ handle2.markCaptured("real-result");
+ expect(tracker.needsCapture("a", "v2")).toBe(false); // captured
+ expect(tracker.isCapturing).toBe(false);
+ });
+ });
+
+ describe("handle.markFailed", () => {
+ it("should remove key from in-flight", () => {
+ const handle = tracker.startCapture("a", "v");
+ handle.markFailed();
+ expect(tracker.isCapturing).toBe(false);
+ });
+
+ it("should not add a captured entry", () => {
+ const handle = tracker.startCapture("a", "v");
+ handle.markFailed();
+ expect(tracker.needsCapture("a", "v")).toBe(true);
+ });
+
+ it("should not clear a previously captured value", () => {
+ const h1 = tracker.startCapture("a", "v1");
+ h1.markCaptured("r1");
+
+ const h2 = tracker.startCapture("a", "v2");
+ h2.markFailed();
+
+ expect(tracker.needsCapture("a", "v1")).toBe(false);
+ expect(tracker.needsCapture("a", "v2")).toBe(true);
+ });
+
+ it("should be a no-op when handle is stale", () => {
+ const handle1 = tracker.startCapture("a", "v1");
+ tracker.startCapture("a", "v2");
+
+ handle1.markFailed();
+
+ // "a" should still be in-flight with v2
+ expect(tracker.isCapturing).toBe(true);
+ expect(tracker.needsCapture("a", "v2")).toBe(false);
+ });
+ });
+
+ describe("waitForInFlight", () => {
+ it("should return a promise for in-flight key with same value", async () => {
+ const handle = tracker.startCapture("a", "v1");
+ const promise = tracker.waitForInFlight("a", "v1");
+ expect(promise).not.toBeNull();
+
+ handle.markCaptured("result-a");
+ const result = await promise;
+ expect(result).toBe("result-a");
+ });
+
+ it("should return null for captured key (not in-flight)", () => {
+ const handle = tracker.startCapture("a", "v1");
+ handle.markCaptured("result");
+ expect(tracker.waitForInFlight("a", "v1")).toBeNull();
+ });
+
+ it("should return null for key not being tracked", () => {
+ expect(tracker.waitForInFlight("a", "v1")).toBeNull();
+ });
+
+ it("should return null for in-flight key with different value", () => {
+ tracker.startCapture("a", "v1");
+ expect(tracker.waitForInFlight("a", "v2")).toBeNull();
+ });
+
+ it("should resolve with undefined when capture fails", async () => {
+ const handle = tracker.startCapture("a", "v1");
+ const promise = tracker.waitForInFlight("a", "v1");
+
+ handle.markFailed();
+ const result = await promise;
+ expect(result).toBeUndefined();
+ });
+
+ it("should resolve with undefined when capture is superseded", async () => {
+ tracker.startCapture("a", "v1");
+ const promise = tracker.waitForInFlight("a", "v1");
+
+ // Supersede with new capture
+ tracker.startCapture("a", "v2");
+ const result = await promise;
+ expect(result).toBeUndefined();
+ });
+
+ it("should resolve with undefined when aborted", async () => {
+ tracker.startCapture("a", "v1");
+ const promise = tracker.waitForInFlight("a", "v1");
+
+ tracker.abort();
+ const result = await promise;
+ expect(result).toBeUndefined();
+ });
+
+ it("should allow multiple waiters on the same key", async () => {
+ const handle = tracker.startCapture("a", "v1");
+ const p1 = tracker.waitForInFlight("a", "v1");
+ const p2 = tracker.waitForInFlight("a", "v1");
+
+ handle.markCaptured("shared-result");
+
+ const [r1, r2] = await Promise.all([p1, p2]);
+ expect(r1).toBe("shared-result");
+ expect(r2).toBe("shared-result");
+ });
+ });
+
+ describe("prune", () => {
+ it("should remove captured entries for keys not in the set", () => {
+ const hA = tracker.startCapture("a", "v1");
+ hA.markCaptured("r1");
+ const hB = tracker.startCapture("b", "v2");
+ hB.markCaptured("r2");
+
+ tracker.prune(new Set(["a"]));
+
+ expect(tracker.needsCapture("a", "v1")).toBe(false);
+ expect(tracker.needsCapture("b", "v2")).toBe(true);
+ });
+
+ it("should abort and remove in-flight entries for pruned keys", () => {
+ const handleA = tracker.startCapture("a", "v");
+ const handleB = tracker.startCapture("b", "v");
+
+ tracker.prune(new Set(["a"]));
+
+ expect(handleA.signal.aborted).toBe(false);
+ expect(handleB.signal.aborted).toBe(true);
+ expect(tracker.needsCapture("b", "v")).toBe(true);
+ });
+
+ it("should resolve pruned in-flight deferreds with undefined", async () => {
+ tracker.startCapture("b", "v");
+ const promise = tracker.waitForInFlight("b", "v");
+
+ tracker.prune(new Set(["a"]));
+ const result = await promise;
+ expect(result).toBeUndefined();
+ });
+
+ it("should do nothing if all keys are current", () => {
+ const hA = tracker.startCapture("a", "v1");
+ hA.markCaptured("r1");
+ const hB = tracker.startCapture("b", "v2");
+ hB.markCaptured("r2");
+
+ tracker.prune(new Set(["a", "b"]));
+
+ expect(tracker.needsCapture("a", "v1")).toBe(false);
+ expect(tracker.needsCapture("b", "v2")).toBe(false);
+ });
+ });
+
+ describe("abort", () => {
+ it("should abort all in-flight signals", () => {
+ const handleA = tracker.startCapture("a", "v");
+ const handleB = tracker.startCapture("b", "v");
+ tracker.abort();
+ expect(handleA.signal.aborted).toBe(true);
+ expect(handleB.signal.aborted).toBe(true);
+ });
+
+ it("should clear in-flight state", () => {
+ tracker.startCapture("a", "v");
+ tracker.abort();
+ expect(tracker.isCapturing).toBe(false);
+ expect(tracker.needsCapture("a", "v")).toBe(true);
+ });
+
+ it("should not clear captured state", () => {
+ const handle = tracker.startCapture("a", "v1");
+ handle.markCaptured("result");
+ tracker.abort();
+ expect(tracker.needsCapture("a", "v1")).toBe(false);
+ });
+ });
+
+ describe("reset", () => {
+ it("should clear all state", () => {
+ const hA = tracker.startCapture("a", "v1");
+ hA.markCaptured("r1");
+ tracker.startCapture("b", "v2");
+
+ tracker.reset();
+
+ expect(tracker.isCapturing).toBe(false);
+ expect(tracker.needsCapture("a", "v1")).toBe(true);
+ expect(tracker.needsCapture("b", "v2")).toBe(true);
+ });
+ });
+
+ describe("isCapturing", () => {
+ it("should be false when nothing is in-flight", () => {
+ expect(tracker.isCapturing).toBe(false);
+ });
+
+ it("should be true when items are in-flight", () => {
+ tracker.startCapture("a", "v");
+ expect(tracker.isCapturing).toBe(true);
+ });
+
+ it("should be false when all items are completed", () => {
+ const hA = tracker.startCapture("a", "v");
+ const hB = tracker.startCapture("b", "v");
+ hA.markCaptured("r");
+ hB.markFailed();
+ expect(tracker.isCapturing).toBe(false);
+ });
+ });
+
+ describe("granular abort", () => {
+ it("should allow independent completion of unrelated keys", () => {
+ const hA = tracker.startCapture("a", "v1");
+ tracker.startCapture("b", "v1");
+ const hC = tracker.startCapture("c", "v1");
+
+ hA.markCaptured("ra");
+ tracker.startCapture("b", "v2"); // abort old "b", start new
+ hC.markCaptured("rc");
+
+ expect(tracker.needsCapture("a", "v1")).toBe(false);
+ expect(tracker.needsCapture("c", "v1")).toBe(false);
+ expect(tracker.needsCapture("b", "v2")).toBe(false); // in-flight
+ expect(tracker.needsCapture("b", "v1")).toBe(true);
+ });
+ });
+});
diff --git a/frontend/src/utils/__tests__/download.test.tsx b/frontend/src/utils/__tests__/download.test.tsx
index 6b03f32f5f..ed6c8d2bb3 100644
--- a/frontend/src/utils/__tests__/download.test.tsx
+++ b/frontend/src/utils/__tests__/download.test.tsx
@@ -166,51 +166,6 @@ describe("getImageDataUrlForCell", () => {
);
});
- it("should add printing classes before capture when snappy is false", async () => {
- vi.mocked(toPng).mockImplementation(async () => {
- // Check classes are applied during capture
- expect(mockElement.classList.contains("printing-output")).toBe(true);
- expect(document.body.classList.contains("printing")).toBe(true);
- expect(mockElement.style.overflow).toBe("auto");
- return mockDataUrl;
- });
-
- await getImageDataUrlForCell("cell-1" as CellId, false);
- });
-
- it("should remove printing classes after capture when snappy is false", async () => {
- vi.mocked(toPng).mockResolvedValue(mockDataUrl);
-
- await getImageDataUrlForCell("cell-1" as CellId, false);
-
- expect(mockElement.classList.contains("printing-output")).toBe(false);
- expect(document.body.classList.contains("printing")).toBe(false);
- });
-
- it("should add printing-output but NOT body.printing when snappy is true", async () => {
- vi.mocked(toPng).mockImplementation(async () => {
- // printing-output should still be added to the element
- expect(mockElement.classList.contains("printing-output")).toBe(true);
- // but body.printing should NOT be added when snappy mode is on
- expect(document.body.classList.contains("printing")).toBe(false);
- expect(mockElement.style.overflow).toBe("auto");
- return mockDataUrl;
- });
-
- await getImageDataUrlForCell("cell-1" as CellId, true);
- });
-
- it("should cleanup printing-output when snappy is true", async () => {
- mockElement.style.overflow = "hidden";
- vi.mocked(toPng).mockResolvedValue(mockDataUrl);
-
- await getImageDataUrlForCell("cell-1" as CellId, true);
-
- expect(mockElement.classList.contains("printing-output")).toBe(false);
- expect(document.body.classList.contains("printing")).toBe(false);
- expect(mockElement.style.overflow).toBe("hidden");
- });
-
it("should restore original overflow style after capture", async () => {
mockElement.style.overflow = "hidden";
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
@@ -234,88 +189,27 @@ describe("getImageDataUrlForCell", () => {
await expect(getImageDataUrlForCell("cell-1" as CellId)).rejects.toThrow();
- expect(mockElement.classList.contains("printing-output")).toBe(false);
expect(document.body.classList.contains("printing")).toBe(false);
expect(mockElement.style.overflow).toBe("scroll");
});
- it("should maintain body.printing during concurrent captures when snappy is false", async () => {
- // Create a second element
- const mockElement2 = document.createElement("div");
- mockElement2.id = CellOutputId.create("cell-2" as CellId);
- document.body.append(mockElement2);
-
- // Track body.printing state during each capture
- const printingStateDuringCaptures: boolean[] = [];
- let resolveFirst: () => void;
- let resolveSecond: () => void;
-
- const firstPromise = new Promise<void>((resolve) => {
- resolveFirst = resolve;
- });
- const secondPromise = new Promise<void>((resolve) => {
- resolveSecond = resolve;
- });
-
- vi.mocked(toPng).mockImplementation(async (element) => {
- printingStateDuringCaptures.push(
- document.body.classList.contains("printing"),
- );
-
- // Simulate async work - first capture takes longer
- await (element.id.includes("cell-1") ? firstPromise : secondPromise);
-
- // Check state again after waiting
- printingStateDuringCaptures.push(
- document.body.classList.contains("printing"),
- );
-
- return mockDataUrl;
- });
-
- // Start both captures concurrently with snappy = false (body.printing should be added)
- const capture1 = getImageDataUrlForCell("cell-1" as CellId, false);
- const capture2 = getImageDataUrlForCell("cell-2" as CellId, false);
-
- // Let second capture complete first
- resolveSecond!();
- await new Promise((r) => setTimeout(r, 0));
-
- // body.printing should still be present because cell-1 is still capturing
- expect(document.body.classList.contains("printing")).toBe(true);
-
- // Now let first capture complete
- resolveFirst!();
- await Promise.all([capture1, capture2]);
-
- // After all captures complete, body.printing should be removed
- expect(document.body.classList.contains("printing")).toBe(false);
-
- // All captures should have seen body.printing = true
- expect(printingStateDuringCaptures.every(Boolean)).toBe(true);
-
- mockElement2.remove();
- });
-
- it("should not interfere with body.printing during concurrent captures when snappy is true", async () => {
+ it("should handle concurrent captures correctly", async () => {
// Create a second element
const mockElement2 = document.createElement("div");
mockElement2.id = CellOutputId.create("cell-2" as CellId);
document.body.append(mockElement2);
vi.mocked(toPng).mockImplementation(async () => {
- // body.printing should never be added when snappy is true
+ // body.printing should not be added during cell captures
expect(document.body.classList.contains("printing")).toBe(false);
return mockDataUrl;
});
- // Start both captures concurrently with snappy = true (body.printing should NOT be added)
- const capture1 = getImageDataUrlForCell("cell-1" as CellId, true);
- const capture2 = getImageDataUrlForCell("cell-2" as CellId, true);
+ const capture1 = getImageDataUrlForCell("cell-1" as CellId);
+ const capture2 = getImageDataUrlForCell("cell-2" as CellId);
await Promise.all([capture1, capture2]);
- // body.printing should still not be present
expect(document.body.classList.contains("printing")).toBe(false);
mockElement2.remove();
@@ -515,9 +409,7 @@ describe("downloadCellOutputAsImage", () => {
it("should apply cell-specific preparation", async () => {
vi.mocked(toPng).mockImplementation(async () => {
// Check that cell-specific classes are applied
- expect(mockElement.classList.contains("printing-output")).toBe(true);
- expect(document.body.classList.contains("printing")).toBe(true);
- expect(mockElement.style.overflow).toBe("auto");
+ expect(mockElement.style.overflow).toBe("visible");
return mockDataUrl;
});
@@ -530,7 +422,6 @@ describe("downloadCellOutputAsImage", () => {
await downloadCellOutputAsImage("cell-1" as CellId, "result");
- expect(mockElement.classList.contains("printing-output")).toBe(false);
expect(document.body.classList.contains("printing")).toBe(false);
expect(mockElement.style.overflow).toBe("visible");
});
diff --git a/frontend/src/utils/async-capture-tracker.ts b/frontend/src/utils/async-capture-tracker.ts
new file mode 100644
index 0000000000..5280cbaaa3
--- /dev/null
+++ b/frontend/src/utils/async-capture-tracker.ts
@@ -0,0 +1,168 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { Deferred } from "./Deferred";
+
+/**
+ * Handle returned by {@link AsyncCaptureTracker.startCapture}.
+ *
+ * The handle is scoped to one capture attempt. If the same key is re-captured
+ * before this handle completes, calling `markCaptured` or `markFailed` on
+ * the stale handle is a safe no-op.
+ */
+export interface CaptureHandle<R> {
+ /** Per-key AbortSignal — check between async steps. */
+ readonly signal: AbortSignal;
+ /** Mark the capture as successful and resolve waiters with the result. */
+ markCaptured(result: R): void;
+ /** Mark the capture as failed — the key returns to idle for retry. */
+ markFailed(): void;
+}
+
+interface InFlightEntry<R> {
+ controller: AbortController;
+ inputValue: unknown;
+ deferred: Deferred<R | undefined>;
+}
+
+/**
+ * Tracks async capture operations to prevent race conditions.
+ *
+ * Each key transitions through states:
+ * - **idle**: Not captured or previously failed — eligible for capture
+ * - **in-flight**: Capture started but not completed — skipped unless value changed
+ * - **captured(value)**: Successfully captured — skipped until value changes
+ *
+ * Abort is per-key: aborting one key's in-flight capture does not affect others.
+ *
+ * Guarantees:
+ * - Items are only marked "captured" after successful async completion
+ * - In-flight items with the same value are skipped (prevents duplicates)
+ * - In-flight items whose value changed are aborted and re-captured
+ * - Failed items return to idle (retried next cycle)
+ * - Concurrent callers can await an in-flight capture via {@link waitForInFlight}
+ * - Stale handles are safe no-ops (checked via entry identity)
+ */
+export class AsyncCaptureTracker<K, R = unknown> {
+ /** Input values for successfully captured keys */
+ private capturedInputs = new Map<K, unknown>();
+ /** Per-key in-flight state */
+ private inFlight = new Map<K, InFlightEntry<R>>();
+
+ /** Abort an in-flight entry and resolve its waiters with `undefined`. */
+ private cancelEntry(entry: InFlightEntry<R>): void {
+ entry.controller.abort();
+ if (entry.deferred.status === "pending") {
+ entry.deferred.resolve(undefined);
+ }
+ }
+
+ /**
+ * Whether a key needs capturing based on its current input value.
+ * Returns false if:
+ * - Already captured with the same value
+ * - In-flight with the same value (let it finish — use {@link waitForInFlight} to get the result)
+ * Returns true if:
+ * - Never captured
+ * - Captured with a different value
+ * - In-flight with a different value (will be aborted on {@link startCapture})
+ */
+ needsCapture(key: K, inputValue: unknown): boolean {
+ if (this.capturedInputs.get(key) === inputValue) {
+ return false;
+ }
+ const flight = this.inFlight.get(key);
+ if (flight && flight.inputValue === inputValue) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * If the key is in-flight with the given input value, returns a promise
+ * that resolves when the capture completes (with the result, or `undefined`
+ * on failure/abort). Returns `null` otherwise.
+ */
+ waitForInFlight(key: K, inputValue: unknown): Promise<R | undefined> | null {
+ const flight = this.inFlight.get(key);
+ if (flight && flight.inputValue === inputValue) {
+ return flight.deferred.promise;
+ }
+ return null;
+ }
+
+ /**
+ * Start capturing a single key. If the key is already in-flight,
+ * aborts only that key's previous capture and resolves its waiters
+ * with `undefined`.
+ *
+ * @returns A {@link CaptureHandle} scoped to this attempt.
+ */
+ startCapture(key: K, inputValue: unknown): CaptureHandle<R> {
+ const prev = this.inFlight.get(key);
+ if (prev) {
+ this.cancelEntry(prev);
+ }
+
+ const controller = new AbortController();
+ const deferred = new Deferred<R | undefined>();
+ const entry: InFlightEntry<R> = { controller, inputValue, deferred };
+ this.inFlight.set(key, entry);
+
+ return {
+ signal: controller.signal,
+ markCaptured: (result: R) => {
+ // No-op if this handle was superseded by a newer startCapture
+ if (this.inFlight.get(key) !== entry) {
+ return;
+ }
+ deferred.resolve(result);
+ this.capturedInputs.set(key, inputValue);
+ this.inFlight.delete(key);
+ },
+ markFailed: () => {
+ if (this.inFlight.get(key) !== entry) {
+ return;
+ }
+ deferred.resolve(undefined);
+ this.inFlight.delete(key);
+ },
+ };
+ }
+
+ /**
+ * Remove tracking for keys not in the given set.
+ * Aborts in-flight captures and resolves their waiters with `undefined`.
+ */
+ prune(currentKeys: Set<K>): void {
+ for (const key of this.capturedInputs.keys()) {
+ if (!currentKeys.has(key)) {
+ this.capturedInputs.delete(key);
+ }
+ }
+ for (const [key, entry] of this.inFlight) {
+ if (!currentKeys.has(key)) {
+ this.cancelEntry(entry);
+ this.inFlight.delete(key);
+ }
+ }
+ }
+
+ /** Whether any captures are currently in-flight. */
+ get isCapturing(): boolean {
+ return this.inFlight.size > 0;
+ }
+
+ /** Abort all in-flight captures. Resolves all waiters with `undefined`. */
+ abort(): void {
+ for (const entry of this.inFlight.values()) {
+ this.cancelEntry(entry);
+ }
+ this.inFlight.clear();
+ }
+
+ /** Reset all state. */
+ reset(): void {
+ this.abort();
+ this.capturedInputs.clear();
+ }
+}
diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.ts
index be6c45c27f..b2bc39bfea 100644
--- a/frontend/src/utils/download.ts
+++ b/frontend/src/utils/download.ts
@@ -46,50 +46,21 @@ function findElementForCell(cellId: CellId): HTMLElement | undefined {
return element;
}
-/**
- * Reference counter for body.printing class to handle concurrent screenshot captures.
- * Only adds the class when count goes 0→1, only removes when count goes 1→0.
- */
-let bodyPrintingRefCount = 0;
-
-function acquireBodyPrinting() {
- bodyPrintingRefCount++;
- if (bodyPrintingRefCount === 1) {
- document.body.classList.add("printing");
- }
-}
-
-function releaseBodyPrinting() {
- bodyPrintingRefCount--;
- if (bodyPrintingRefCount === 0) {
- document.body.classList.remove("printing");
- }
-}
-
/**
* Prepare a cell element for screenshot capture.
*
* @param element - The cell output element to prepare
- * @param snappy - When true, avoids layout shifts and speeds up the capture.
* @returns A cleanup function to restore the element's original state
*/
-function prepareCellElementForScreenshot(
- element: HTMLElement,
- snappy: boolean,
-) {
- element.classList.add("printing-output");
- if (!snappy) {
- acquireBodyPrinting();
- }
+function prepareCellElementForScreenshot(element: HTMLElement) {
const originalOverflow = element.style.overflow;
- element.style.overflow = "auto";
+ const maxHeight = element.style.maxHeight;
+ element.style.overflow = "visible";
+ element.style.maxHeight = "none";
return () => {
- element.classList.remove("printing-output");
- if (!snappy) {
- releaseBodyPrinting();
- }
element.style.overflow = originalOverflow;
+ element.style.maxHeight = maxHeight;
};
}
@@ -99,12 +70,10 @@ const THRESHOLD_TIME_MS = 500;
* Capture a cell output as a PNG data URL.
*
* @param cellId - The ID of the cell to capture
- * @param snappy - When true, uses a faster method to capture the image. Avoids layout shifts.
* @returns The PNG as a data URL, or undefined if the cell element wasn't found
*/
export async function getImageDataUrlForCell(
cellId: CellId,
- snappy = false,
): Promise<string | undefined> {
const element = findElementForCell(cellId);
if (!element) {
@@ -116,11 +85,11 @@ export async function getImageDataUrlForCell(
return iframeDataUrl;
}
- const cleanup = prepareCellElementForScreenshot(element, snappy);
+ const cleanup = prepareCellElementForScreenshot(element);
try {
const startTime = Date.now();
- const dataUrl = await toPng(element, undefined, snappy);
+ const dataUrl = await toPng(element);
const timeTaken = Date.now() - startTime;
if (timeTaken > THRESHOLD_TIME_MS) {
Logger.debug(
@@ -142,25 +111,20 @@ export async function downloadCellOutputAsImage(
cellId: CellId,
filename: string,
) {
- const element = findElementForCell(cellId);
- if (!element) {
- return;
- }
-
- // Cell outputs that are iframes
- const iframeDataUrl = await captureIframeAsImage(element);
- if (iframeDataUrl) {
- downloadByURL(iframeDataUrl, Filenames.toPNG(filename));
+ const dataUrl = await getImageDataUrlForCell(cellId);
+ if (!dataUrl) {
return;
}
-
- await downloadHTMLAsImage({
- element,
- filename,
- prepare: () => prepareCellElementForScreenshot(element, false),
- });
+ return downloadByURL(dataUrl, Filenames.toPNG(filename));
}
+export const ADD_PRINTING_CLASS = (): (() => void) => {
+ document.body.classList.add("printing");
+ return () => {
+ document.body.classList.remove("printing");
+ };
+};
+
export async function downloadHTMLAsImage(opts: {
element: HTMLElement;
filename: string;
@@ -175,10 +139,6 @@ export async function downloadHTMLAsImage(opts: {
let cleanup: (() => void) | undefined;
if (prepare) {
cleanup = prepare(element);
- } else {
- // When no prepare function is provided (e.g., downloading full notebook),
- // add body.printing ourselves
- document.body.classList.add("printing");
}
try {
diff --git a/frontend/src/utils/html-to-image.ts b/frontend/src/utils/html-to-image.ts
index b688b2aa9b..bd1887b393 100644
--- a/frontend/src/utils/html-to-image.ts
+++ b/frontend/src/utils/html-to-image.ts
@@ -113,10 +113,9 @@ export const necessaryStyleProperties = [
"clip-path",
// Overflow & Visibility
- // We don't include overflow properties because they can include scrollbars
- // "overflow",
- // "overflow-x",
- // "overflow-y",
+ "overflow",
+ "overflow-x",
+ "overflow-y",
"visibility",
// SVG
@@ -149,12 +148,11 @@ export const defaultHtmlToImageOptions: HtmlToImageOptions = {
filter: (node) => {
try {
if ("classList" in node) {
- // Filter out matplotlib toolbars
- if (node.classList.contains("mpl-toolbar")) {
- return false;
- }
-
- if (node.classList.contains("no-print")) {
+ const classes = node.classList;
+ if (
+ classes.contains("mpl-toolbar") ||
+ classes.contains("print:hidden")
+ ) {
return false;
}
}
@@ -167,6 +165,7 @@ export const defaultHtmlToImageOptions: HtmlToImageOptions = {
onImageErrorHandler: (event) => {
Logger.error("Error loading image:", event);
},
+ includeStyleProperties: necessaryStyleProperties,
};
/**
@@ -176,11 +175,9 @@ export const defaultHtmlToImageOptions: HtmlToImageOptions = {
export async function toPng(
element: HTMLElement,
options?: HtmlToImageOptions,
- snappy?: boolean,
): Promise<string> {
return htmlToImageToPng(element, {
...defaultHtmlToImageOptions,
- includeStyleProperties: snappy ? necessaryStyleProperties : undefined,
...options,
});
}