@marimo-team/islands 0.26.1-dev112 → 0.26.1-dev119

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{ErrorBoundary-pNKOBKXw.js → ErrorBoundary-CkXMIvMv.js} +1 -1
  2. package/dist/{chat-ui-C9NZA-bk.js → chat-ui-CMKYvKUz.js} +3 -3
  3. package/dist/{code-visibility-B9s3Hl8z.js → code-visibility-IpaMnOoU.js} +2 -2
  4. package/dist/{common-Bn3jx0X6.js → common-CtWT0mmS.js} +4766 -4749
  5. package/dist/{data-grid-overlay-editor-mxwwRaQy.js → data-grid-overlay-editor-DHlHNRoU.js} +1 -1
  6. package/dist/{error-entries-1DC4BiYB.js → error-entries-B4LgfizR.js} +759 -749
  7. package/dist/{feedback-button-BrzbnRTT.js → feedback-button-BK1A2jRH.js} +3 -3
  8. package/dist/{formats-Y52bg800.js → formats-CeuXJ_1f.js} +32 -25
  9. package/dist/{glide-data-editor-Cnsv3NcI.js → glide-data-editor-DCcfshI9.js} +3 -3
  10. package/dist/{globals-BGqfFPx8.js → globals-CG1ka6r5.js} +1 -1
  11. package/dist/{html-to-image-CsvAOgd3.js → html-to-image-CIkwg7mv.js} +1 -1
  12. package/dist/main.js +69 -66
  13. package/dist/{number-overlay-editor-DuSCOMTK.js → number-overlay-editor-Cvv8DaFJ.js} +1 -1
  14. package/dist/{process-output-CtfJ_Gbp.js → process-output-PS9YSLNu.js} +2 -2
  15. package/dist/{reveal-component-DzmiQyN9.js → reveal-component-50jFQHXp.js} +2 -2
  16. package/dist/{useDeepCompareMemoize-Dn-ZJVTd.js → semaphore-8KhQouXt.js} +5 -15
  17. package/dist/{vega-component-BIq0qzhQ.js → vega-component-CoJiBCaS.js} +11 -11
  18. package/package.json +1 -1
  19. package/src/__mocks__/executions.ts +1 -1
  20. package/src/__mocks__/intersection-observer.ts +5 -5
  21. package/src/components/editor/Output.tsx +3 -21
  22. package/src/components/editor/actions/__tests__/pair-with-agent-modal.test.tsx +27 -0
  23. package/src/components/editor/actions/pair-with-agent-modal.tsx +8 -1
  24. package/src/components/editor/output/VegaOutput.tsx +35 -0
  25. package/src/components/find-replace/find-replace.tsx +1 -7
  26. package/src/core/cells/__tests__/cell-errors.test.tsx +179 -0
  27. package/src/core/cells/cells.ts +24 -27
  28. package/src/core/codemirror/find-replace/__tests__/navigate.test.ts +18 -15
  29. package/src/core/codemirror/find-replace/__tests__/search-highlight.test.ts +90 -2
  30. package/src/core/codemirror/find-replace/__tests__/unmounted-cells.test.ts +44 -10
  31. package/src/core/codemirror/find-replace/navigate.ts +4 -1
  32. package/src/core/codemirror/find-replace/search-highlight.ts +54 -58
  33. package/src/core/executions/__tests__/atoms.test.ts +0 -2
  34. package/src/core/executions/__tests__/output-lifecycle.test.ts +16 -0
  35. package/src/core/executions/atoms.ts +33 -36
  36. package/src/core/export/__tests__/output-snapshot.test.tsx +240 -0
  37. package/src/core/export/__tests__/output-subscription.test.tsx +79 -0
  38. package/src/core/export/hooks.ts +29 -13
  39. package/src/core/notebook/replica/frame.ts +8 -2
  40. package/src/core/notebook/replica/index.ts +5 -1
  41. package/src/core/notebook/replica/once-per-frame.ts +4 -3
  42. package/src/core/notebook/replica/resources/executions.ts +16 -1
  43. package/src/utils/shared-intersection-observer.ts +2 -1
@@ -10,7 +10,7 @@ import { createCell } from "@/core/cells/types";
10
10
  import { store } from "@/core/state/jotai";
11
11
  import { cellIdState } from "../../config/extension";
12
12
  import { editorMountScheduler } from "../../editor-mount-scheduler";
13
- import { findNext, getMatches, replaceAll } from "../navigate";
13
+ import { findNext, findPrev, getMatches, replaceAll } from "../navigate";
14
14
  import { findReplaceAtom } from "../state";
15
15
 
16
16
  const { writes } = vi.hoisted(() => ({ writes: vi.fn() }));
@@ -56,28 +56,59 @@ afterEach(() => {
56
56
  writes.mockReset();
57
57
  store.set(notebookAtom, initialNotebookState());
58
58
  store.set(findReplaceAtom, { type: "clearCurrentView" });
59
+ store.set(findReplaceAtom, { type: "setRegex", regexp: false });
59
60
  });
60
61
 
61
62
  it("counts matches in cells without editors and builds only the navigation target", () => {
62
- const [a, b] = [cellId("a"), cellId("b")];
63
+ const [a, b, c] = [cellId("a"), cellId("b"), cellId("c")];
63
64
  setNotebook([
64
65
  [a, "x = 1", withoutEditor],
65
66
  [b, 'mo.md(r"""needle""")', withoutEditor],
67
+ [c, "needle = 2", withoutEditor],
66
68
  ]);
67
- const view = new EditorView({ state: EditorState.create({ doc: "needle" }) });
69
+ const views = [
70
+ new EditorView({ doc: "needle", extensions: cellIdState.of(b) }),
71
+ new EditorView({ doc: "needle = 2", extensions: cellIdState.of(c) }),
72
+ ];
73
+ const [view, otherView] = views;
68
74
  const build = vi.fn(() => {
69
75
  store.get(notebookAtom).cellHandles[b].current = {
70
76
  editorView: view,
71
77
  };
72
78
  });
79
+ const buildOther = vi.fn(() => {
80
+ store.get(notebookAtom).cellHandles[c].current = {
81
+ editorView: otherView,
82
+ };
83
+ });
73
84
  editorMountScheduler.register(b, build);
74
- store.set(findReplaceAtom, { type: "setFind", find: "needle" });
85
+ editorMountScheduler.register(c, buildOther);
86
+ store.set(findReplaceAtom, { type: "setFind", find: "n[e]+dle" });
87
+ store.set(findReplaceAtom, { type: "setRegex", regexp: true });
75
88
 
76
- expect(getMatches()).toMatchObject({ count: 1 });
89
+ expect(getMatches()).toEqual({
90
+ count: 2,
91
+ position: new Map([
92
+ [b, new Map([["0:6", 0]])],
93
+ [c, new Map([["0:6", 1]])],
94
+ ]),
95
+ });
77
96
  expect(build).not.toHaveBeenCalled();
97
+ expect(buildOther).not.toHaveBeenCalled();
78
98
  expect(findNext()).toMatchObject({ from: 0, to: 6 });
79
- expect(build).toHaveBeenCalledTimes(1);
80
- view.destroy();
99
+ expect(store.get(findReplaceAtom).currentView?.cellId).toBe(b);
100
+ expect(build).toHaveBeenCalledOnce();
101
+ expect(buildOther).not.toHaveBeenCalled();
102
+
103
+ expect(findNext()).toMatchObject({ from: 0, to: 6 });
104
+ expect(store.get(findReplaceAtom).currentView?.cellId).toBe(c);
105
+ expect(buildOther).toHaveBeenCalledOnce();
106
+ expect(findPrev()).toMatchObject({ from: 0, to: 6 });
107
+ expect(store.get(findReplaceAtom).currentView?.cellId).toBe(b);
108
+ expect(build).toHaveBeenCalledOnce();
109
+ for (const editor of views) {
110
+ editor.destroy();
111
+ }
81
112
  });
82
113
 
83
114
  it("moves past a match whose editor cannot be built", () => {
@@ -127,19 +158,22 @@ it("replaces and undoes matches in markdown without building its editor", () =>
127
158
  setNotebook([[id, code, withoutEditor]]);
128
159
  const build = vi.fn();
129
160
  const release = editorMountScheduler.register(id, build);
130
- store.set(findReplaceAtom, { type: "setFind", find: "needle" });
131
- store.set(findReplaceAtom, { type: "setReplace", replace: "updated" });
161
+ store.set(findReplaceAtom, { type: "setFind", find: "(need)le" });
162
+ store.set(findReplaceAtom, { type: "setRegex", regexp: true });
163
+ store.set(findReplaceAtom, { type: "setReplace", replace: "$1ed" });
132
164
 
133
165
  const undo = replaceAll();
134
166
  expect(writes).toHaveBeenLastCalledWith({
135
167
  cellId: id,
136
- code: expect.stringContaining("updated"),
168
+ code: expect.stringContaining("needed"),
137
169
  });
170
+ expect(getMatches()).toMatchObject({ count: 0 });
138
171
  expect(typeof undo).toBe("function");
139
172
  if (undo) {
140
173
  undo();
141
174
  }
142
175
  expect(writes).toHaveBeenLastCalledWith({ cellId: id, code });
176
+ expect(getMatches()).toMatchObject({ count: 1 });
143
177
  expect(build).not.toHaveBeenCalled();
144
178
  release();
145
179
  });
@@ -49,6 +49,7 @@ function findMatch(
49
49
  0,
50
50
  documents.findIndex((doc) => doc.cellId === startingCellId),
51
51
  );
52
+ const startOfDocument = EditorSelection.single(0);
52
53
  for (const document of [...documents, ...documents].slice(start)) {
53
54
  const { state } = document;
54
55
  const match =
@@ -64,7 +65,9 @@ function findMatch(
64
65
  return { view, match };
65
66
  }
66
67
  position = undefined;
67
- document.view?.dispatch({ selection: EditorSelection.single(0) });
68
+ if (document.view && !state.selection.eq(startOfDocument, true)) {
69
+ document.view.dispatch({ selection: startOfDocument });
70
+ }
68
71
  }
69
72
  }
70
73
 
@@ -8,71 +8,43 @@ import {
8
8
  ViewPlugin,
9
9
  type ViewUpdate,
10
10
  } from "@codemirror/view";
11
- import { getAllEditorViews } from "@/core/cells/cells";
11
+ import { atomWithSelectedInputs } from "@/core/state/atom-with-selected-inputs";
12
12
  import { store } from "@/core/state/jotai";
13
+ import { createSharedIntersectionObserver } from "@/utils/shared-intersection-observer";
14
+ import { createSharedSubscription } from "@/utils/shared-resource";
13
15
  import { asQueryCreator, type QueryType } from "./query";
14
16
  import { findReplaceAtom } from "./state";
15
17
 
16
- const setSearchQuery = StateEffect.define<SearchQuery>();
17
-
18
- /**
19
- * Set the global search query to the current find/replace state.
20
- */
21
- export function setGlobalSearchQuery() {
22
- const state = store.get(findReplaceAtom);
23
- const views = getAllEditorViews();
24
- for (const view of views) {
25
- if (view.state.readOnly) {
26
- continue;
27
- }
28
- view.dispatch({
29
- effects: setSearchQuery.of(
30
- new SearchQuery({
31
- search: state.findText,
32
- caseSensitive: state.caseSensitive,
33
- regexp: state.regexp,
34
- replace: state.replaceText,
35
- wholeWord: state.wholeWord,
36
- }),
37
- ),
38
- });
39
- }
40
- }
41
-
42
- /**
43
- * Clear the global search query.
44
- */
45
- export function clearGlobalSearchQuery() {
46
- const views = getAllEditorViews();
47
- for (const view of views) {
48
- if (view.state.readOnly) {
49
- continue;
50
- }
51
- view.dispatch({
52
- effects: setSearchQuery.of(new SearchQuery({ search: "" })),
53
- });
54
- }
55
- }
56
-
57
- export const searchState: StateField<QueryType> = StateField.define<QueryType>({
58
- create() {
59
- const state = store.get(findReplaceAtom);
60
- // Editors are built on demand, so one built after the panel closed must
61
- // not highlight the previous search.
62
- const search = new SearchQuery({
63
- search: state.isOpen ? state.findText : "",
64
- caseSensitive: state.caseSensitive,
65
- regexp: state.regexp,
66
- replace: state.replaceText,
67
- wholeWord: state.wholeWord,
68
- });
69
-
70
- return asQueryCreator(search).create();
71
- },
18
+ const emptyQuery = asQueryCreator(new SearchQuery({ search: "" })).create();
19
+
20
+ const highlightQueryAtom = atomWithSelectedInputs(
21
+ findReplaceAtom,
22
+ ({ isOpen, findText, caseSensitive, regexp, wholeWord }) =>
23
+ [isOpen ? findText : "", caseSensitive, regexp, wholeWord] as const,
24
+ ([search, caseSensitive, regexp, wholeWord]) =>
25
+ search
26
+ ? asQueryCreator(
27
+ new SearchQuery({ search, caseSensitive, regexp, wholeWord }),
28
+ ).create()
29
+ : emptyQuery,
30
+ );
31
+
32
+ // A zero-area intersection can still touch the viewport edge.
33
+ const observeViewport = createSharedIntersectionObserver(
34
+ { threshold: Number.EPSILON },
35
+ (entry) => entry.intersectionRatio > 0,
36
+ );
37
+ const subscribeToQuery = createSharedSubscription((notify) =>
38
+ store.sub(highlightQueryAtom, notify),
39
+ );
40
+ const setSearchQuery = StateEffect.define<QueryType>();
41
+
42
+ export const searchState = StateField.define<QueryType>({
43
+ create: () => store.get(highlightQueryAtom),
72
44
  update(value, tr) {
73
45
  for (const effect of tr.effects) {
74
46
  if (effect.is(setSearchQuery)) {
75
- value = asQueryCreator(effect.value).create();
47
+ value = effect.value;
76
48
  }
77
49
  }
78
50
  return value;
@@ -94,10 +66,34 @@ export const searchHighlighter = ViewPlugin.fromClass(
94
66
  class {
95
67
  public decorations: DecorationSet;
96
68
  public readonly view: EditorView;
69
+ private readonly unobserve: () => void;
70
+ private unsubscribe?: () => void;
97
71
 
98
72
  public constructor(view: EditorView) {
99
73
  this.view = view;
100
74
  this.decorations = this.highlight(view.state.field(searchState));
75
+
76
+ const syncQuery = () => {
77
+ const query = store.get(highlightQueryAtom);
78
+ if (!view.state.readOnly && query !== view.state.field(searchState)) {
79
+ view.dispatch({ effects: setSearchQuery.of(query) });
80
+ }
81
+ };
82
+
83
+ this.unobserve = observeViewport(view.dom, (isVisible) => {
84
+ if (isVisible) {
85
+ this.unsubscribe ??= subscribeToQuery(syncQuery);
86
+ syncQuery();
87
+ } else {
88
+ this.unsubscribe?.();
89
+ this.unsubscribe = undefined;
90
+ }
91
+ });
92
+ }
93
+
94
+ public destroy() {
95
+ this.unobserve();
96
+ this.unsubscribe?.();
101
97
  }
102
98
 
103
99
  public update(update: ViewUpdate) {
@@ -19,7 +19,6 @@ import {
19
19
  cellExecutionInputsAtom,
20
20
  cellExecutionAtom,
21
21
  cellOutputAtom,
22
- cellOutputsAtom,
23
22
  scratchOutputAtom,
24
23
  cellOutputInputsAtom,
25
24
  cellOutlineAtom,
@@ -264,7 +263,6 @@ it.each([25, 500])(
264
263
  }
265
264
  onTestFinished(() => releaseCellOutputAtoms(id));
266
265
  }
267
- onTestFinished(store.sub(cellOutputsAtom, () => undefined));
268
266
  onTestFinished(store.sub(scratchOutputAtom, () => undefined));
269
267
  scratchView.mockClear();
270
268
  executionView.mockClear();
@@ -241,6 +241,22 @@ describe("output lifetime", () => {
241
241
  }
242
242
  });
243
243
 
244
+ it.each([text("43"), { mimetype: "text/html", data: "42" }])(
245
+ "keeps equivalent output cleared until the media changes to %o",
246
+ async (changed) => {
247
+ const { store, emit, snapshot } = await setup();
248
+ const [result, output] = MockExecutions.shown(C1, text("42"));
249
+ snapshot([result, output]);
250
+ clearCellOutputs(store, [C1]);
251
+
252
+ emit(MockExecutions.output(result, text("42")));
253
+ expect(store.get(cellOutputAtom(C1))).toBeNull();
254
+
255
+ emit(MockExecutions.output(result, changed));
256
+ expect(store.get(cellOutputAtom(C1))).toMatchObject(changed);
257
+ },
258
+ );
259
+
244
260
  it("keeps a changed display visible after its execution retires", async () => {
245
261
  const { store, replica, emit, remove, snapshot } = await setup();
246
262
  const [result, output] = MockExecutions.shown(C1, text("A"));
@@ -12,11 +12,10 @@ import {
12
12
  ConnectionState,
13
13
  type Executions,
14
14
  type NotebookReplica,
15
- type ReplicaFrame,
15
+ type FrameSource,
16
16
  type Results,
17
17
  } from "@/core/notebook/replica";
18
18
  import { atomWithSelectedInputs } from "@/core/state/atom-with-selected-inputs";
19
- import { arrayShallowEquals } from "@/utils/arrays";
20
19
  import {
21
20
  activeNotebookReplicaAtom,
22
21
  activeNotebookFrameAtom,
@@ -26,7 +25,7 @@ import { type CellFreshnessInputs, freshnessOf } from "./freshness";
26
25
  import {
27
26
  type CellOutputInputs,
28
27
  type ClearedOutput,
29
- type CellOutput,
28
+ cellOutputsView,
30
29
  resultOutput,
31
30
  shownCellExecution,
32
31
  shownExecution,
@@ -112,7 +111,7 @@ function current<T>(marks: Marks<T>, shown: ShownNotebook | null, empty: T): T {
112
111
  : empty;
113
112
  }
114
113
 
115
- type ReplicaSource = Atom<ReplicaFrame | null>;
114
+ type ReplicaSource = Atom<FrameSource | null>;
116
115
 
117
116
  function createShownNotebookAtom(source: ReplicaSource) {
118
117
  return atom((get): ShownNotebook | null => {
@@ -250,41 +249,39 @@ const displayedNotebookAtom = atom((get): ShownNotebook | null => {
250
249
  };
251
250
  });
252
251
 
253
- /** What every cell's output derives from. Pair with `cellOutputView`. */
254
- export const cellOutputInputsAtom = atom((get): CellOutputInputs => {
255
- const frame = get(activeNotebookFrameAtom);
256
- return {
257
- executions: frame === null ? NO_EXECUTIONS : get(frame.executionsAtom),
258
- results: frame === null ? NO_RESULTS : get(frame.resultsAtom),
259
- cleared: current(
260
- get(clearedOutputsAtom),
261
- get(displayedNotebookAtom),
262
- NO_CLEARED,
263
- ),
264
- cells:
265
- frame === null ? NO_CELLS : (get(frame.documentAtom)?.cells ?? NO_CELLS),
266
- };
267
- });
252
+ function createOutputInputsAtom(
253
+ source: ReplicaSource,
254
+ notebookAtom: Atom<ShownNotebook | null>,
255
+ ) {
256
+ return atom((get): CellOutputInputs => {
257
+ const state = get(source);
258
+ return {
259
+ executions: state === null ? NO_EXECUTIONS : get(state.executionsAtom),
260
+ results: state === null ? NO_RESULTS : get(state.resultsAtom),
261
+ cleared: current(get(clearedOutputsAtom), get(notebookAtom), NO_CLEARED),
262
+ cells:
263
+ state === null
264
+ ? NO_CELLS
265
+ : (get(state.documentAtom)?.cells ?? NO_CELLS),
266
+ };
267
+ });
268
+ }
268
269
 
269
- /** What every cell shows, by cell id. Pair with `cellOutputAtom` for one cell. */
270
- const outputCellIdsAtom = selectAtom(
271
- cellOutputInputsAtom,
272
- (inputs) => [
273
- ...new Set([...inputs.results.keys(), ...inputs.executions.latest.keys()]),
274
- ],
275
- arrayShallowEquals,
270
+ /** What each cell shows in the last published frame. */
271
+ export const cellOutputInputsAtom = createOutputInputsAtom(
272
+ activeNotebookFrameAtom,
273
+ displayedNotebookAtom,
276
274
  );
277
275
 
278
- export const cellOutputsAtom = atom((get) => {
279
- const outputs = new Map<CellId, CellOutput>();
280
- for (const id of get(outputCellIdsAtom)) {
281
- const output = get(cellOutputAtom(id));
282
- if (output !== null) {
283
- outputs.set(id, output);
284
- }
285
- }
286
- return outputs;
287
- });
276
+ const immediateOutputInputsAtom = createOutputInputsAtom(
277
+ activeNotebookReplicaAtom,
278
+ shownNotebookAtom,
279
+ );
280
+
281
+ /** Read at export time, including output received since the last display frame. */
282
+ export const cellOutputsAtom = atom((get) =>
283
+ cellOutputsView(get(immediateOutputInputsAtom)),
284
+ );
288
285
 
289
286
  function latestFor(executions: Executions, id: Protocol.CellId) {
290
287
  const latest = executions.latest.get(id);
@@ -0,0 +1,240 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { act, fireEvent, renderHook, waitFor } from "@testing-library/react";
4
+ import { createStore, Provider } from "jotai";
5
+ import type { ComponentType, ReactNode } from "react";
6
+ import { describe, expect, it, onTestFinished, vi } from "vitest";
7
+ import { mockAnimationFrames } from "@/__mocks__/animation-frames";
8
+ import { MockModules } from "@/__mocks__/common";
9
+ import { MockExecutions } from "@/__mocks__/executions";
10
+ import { MockRequestClient } from "@/__mocks__/requests";
11
+ import { cellId } from "@/__tests__/branded";
12
+ import {
13
+ DEFAULT_EXPORT_OPTIONS,
14
+ exportOptionsAtom,
15
+ } from "@/components/editor/actions/export-dialog/state";
16
+ import { useExportDialog } from "@/components/editor/actions/export-dialog/use-export-dialog";
17
+ import { OutputRenderer } from "@/components/editor/Output";
18
+ import { CellOutputId } from "@/core/cells/ids";
19
+ import { releaseCellOutputAtoms, useCellOutput } from "@/core/executions";
20
+ import { connectionAtom } from "@/core/network/connection";
21
+ import { requestClientAtom } from "@/core/network/requests";
22
+ import { document as notebookDocument } from "@/core/notebook/document/__tests__/fixtures";
23
+ import { createReplicaFrame } from "@/core/notebook/replica";
24
+ import { executions } from "@/core/notebook/replica/resources/executions";
25
+ import { filenameAtom } from "@/core/saving/file-state";
26
+ import { activeNotebookFrameAtom } from "@/core/session/active-notebook";
27
+ import { ConnectionState } from "@/core/session/types";
28
+ import { Deferred } from "@/utils/Deferred";
29
+ import { ProgressState } from "@/utils/progress";
30
+ import { toPng } from "@/utils/html-to-image";
31
+ import { captureTracker, useAutoExport, useEnrichCellOutputs } from "../hooks";
32
+
33
+ interface ChartProps {
34
+ onEmbed: () => void;
35
+ "data-marimo-vega-ready"?: boolean;
36
+ }
37
+ const chartModule = new Deferred<{ default: ComponentType<ChartProps> }>();
38
+ vi.mock("@/components/charts/lazy", async () => {
39
+ const { lazy } = await import("react");
40
+ return { LazyVegaEmbed: lazy(() => chartModule.promise) };
41
+ });
42
+
43
+ vi.mock(
44
+ "@/components/ui/use-toast",
45
+ () => MockModules.toastWithControls().mock,
46
+ );
47
+
48
+ vi.mock("@/utils/html-to-image", () => ({
49
+ toPng: vi.fn(),
50
+ }));
51
+
52
+ vi.mock("@/utils/download", async (importOriginal) => ({
53
+ ...(await importOriginal<typeof import("@/utils/download")>()),
54
+ downloadExportedFile: vi.fn(),
55
+ }));
56
+
57
+ const CELL_ID = cellId("c1");
58
+ const OUTPUT_ID = CellOutputId.create(CELL_ID);
59
+ const OLD_OUTPUT = "previous output";
60
+ const NEW_OUTPUT = "latest output";
61
+
62
+ function png(text: string) {
63
+ return `data:image/png;base64,${btoa(text)}`;
64
+ }
65
+
66
+ function Output() {
67
+ const output = useCellOutput(CELL_ID);
68
+ return (
69
+ <div id={OUTPUT_ID}>
70
+ {output && <OutputRenderer cellId={CELL_ID} message={output} />}
71
+ </div>
72
+ );
73
+ }
74
+
75
+ interface ExportTrigger {
76
+ isAvailable: boolean;
77
+ start: () => void;
78
+ }
79
+
80
+ function useManualExport(): ExportTrigger {
81
+ const dialog = useExportDialog({ initialFormat: "ipynb", onClose: vi.fn() });
82
+ return {
83
+ isAvailable: dialog.selected.status.available,
84
+ start: dialog.submit,
85
+ };
86
+ }
87
+
88
+ function useAutomaticExport(): ExportTrigger {
89
+ useAutoExport();
90
+ return {
91
+ isAvailable: true,
92
+ start: () => fireEvent(document, new Event("visibilitychange")),
93
+ };
94
+ }
95
+
96
+ describe("IPYNB output snapshots", () => {
97
+ it("retries the same chart after its module and view finish loading", async () => {
98
+ const store = createStore();
99
+ const chart = vi.fn((props: ChartProps) => (
100
+ <div data-marimo-vega-ready={props["data-marimo-vega-ready"]}>
101
+ rendered chart
102
+ </div>
103
+ ));
104
+ captureTracker.reset();
105
+ onTestFinished(() => {
106
+ releaseCellOutputAtoms(CELL_ID);
107
+ captureTracker.reset();
108
+ });
109
+ const showChart = (mark: string) =>
110
+ MockExecutions.seed(store, [
111
+ MockExecutions.shown(CELL_ID, {
112
+ mimetype: "application/vnd.vegalite.v5+json",
113
+ data: JSON.stringify({ mark }),
114
+ }),
115
+ ]);
116
+ showChart("point");
117
+ vi.mocked(toPng)
118
+ .mockClear()
119
+ .mockImplementation(async (node) => png(node.textContent ?? ""));
120
+ const { result } = renderHook(useEnrichCellOutputs, {
121
+ wrapper: ({ children }: { children: ReactNode }) => (
122
+ <Provider store={store}>
123
+ <Output />
124
+ {children}
125
+ </Provider>
126
+ ),
127
+ });
128
+ const capture = () =>
129
+ result.current({ progress: ProgressState.indeterminate() });
130
+ expect(document.getElementById(OUTPUT_ID)).toHaveTextContent(
131
+ "Loading chart",
132
+ );
133
+ expect(await capture()).toEqual({});
134
+ await act(async () => chartModule.resolve({ default: chart }));
135
+ expect(await capture()).toEqual({});
136
+ expect(toPng).not.toHaveBeenCalled();
137
+ act(() => chart.mock.lastCall![0].onEmbed());
138
+ expect(await capture()).toEqual({
139
+ [CELL_ID]: ["image/png", png("rendered chart")],
140
+ });
141
+ expect(await capture()).toEqual({});
142
+ expect(toPng).toHaveBeenCalledOnce();
143
+
144
+ act(() => {
145
+ showChart("bar");
146
+ });
147
+ expect(await capture()).toEqual({});
148
+ expect(toPng).toHaveBeenCalledOnce();
149
+ });
150
+
151
+ it.each([
152
+ { mode: "manual", useExport: useManualExport, request: "exportAsIPYNB" },
153
+ {
154
+ mode: "automatic",
155
+ useExport: useAutomaticExport,
156
+ request: "autoExportAsIPYNB",
157
+ },
158
+ ] as const)(
159
+ "uploads the latest browser output before $mode export while a display frame is pending",
160
+ async ({ useExport, request }) => {
161
+ captureTracker.reset();
162
+ const advanceFrame = mockAnimationFrames();
163
+ const lifetime = new AbortController();
164
+ onTestFinished(() => {
165
+ lifetime.abort();
166
+ releaseCellOutputAtoms(CELL_ID);
167
+ captureTracker.reset();
168
+ });
169
+ const store = createStore();
170
+ const notebook = notebookDocument();
171
+ notebook.revision.app_config = { auto_download: ["ipynb"] };
172
+ const running = MockExecutions.running(CELL_ID);
173
+ const previous = MockExecutions.output(running, {
174
+ mimetype: "text/plain",
175
+ data: OLD_OUTPUT,
176
+ });
177
+ const replica = MockExecutions.seed(
178
+ store,
179
+ [running, previous],
180
+ null,
181
+ notebook,
182
+ );
183
+ store.set(
184
+ activeNotebookFrameAtom,
185
+ createReplicaFrame(store, replica, { signal: lifetime.signal }),
186
+ );
187
+ store.set(connectionAtom, { state: ConnectionState.OPEN });
188
+ store.set(filenameAtom, "notebook.py");
189
+ store.set(exportOptionsAtom, {
190
+ ...DEFAULT_EXPORT_OPTIONS,
191
+ ipynb: { ...DEFAULT_EXPORT_OPTIONS.ipynb, includeOutputs: true },
192
+ });
193
+ const requests = MockRequestClient.create();
194
+ store.set(requestClientAtom, requests);
195
+ const uploaded = new Deferred<null>();
196
+ requests.updateCellOutputs.mockReturnValueOnce(uploaded.promise);
197
+ vi.mocked(toPng).mockImplementation(async (node) =>
198
+ png(node.textContent ?? ""),
199
+ );
200
+
201
+ const { result } = renderHook(useExport, {
202
+ wrapper: ({ children }: { children: ReactNode }) => (
203
+ <Provider store={store}>
204
+ <Output />
205
+ {children}
206
+ </Provider>
207
+ ),
208
+ });
209
+ await waitFor(() => expect(result.current.isAvailable).toBe(true));
210
+
211
+ const output = MockExecutions.output(running, {
212
+ mimetype: "text/html",
213
+ data: `<strong>${NEW_OUTPUT}</strong>`,
214
+ });
215
+ act(() => {
216
+ store.set(replica.executionsAtom, (state) =>
217
+ executions.on.output!(
218
+ state,
219
+ { event: "output", id: "2", data: { output } },
220
+ { phase: "live" },
221
+ ),
222
+ );
223
+ });
224
+ expect(document.getElementById(OUTPUT_ID)).toHaveTextContent(OLD_OUTPUT);
225
+
226
+ await act(async () => {
227
+ result.current.start();
228
+ });
229
+ expect(requests.updateCellOutputs).toHaveBeenCalledExactlyOnceWith({
230
+ cellIdsToOutput: { [CELL_ID]: ["image/png", png(NEW_OUTPUT)] },
231
+ });
232
+ expect(requests[request]).not.toHaveBeenCalled();
233
+
234
+ await act(async () => uploaded.resolve(null));
235
+ expect(requests[request]).toHaveBeenCalledOnce();
236
+ act(advanceFrame);
237
+ expect(document.getElementById(OUTPUT_ID)).toHaveTextContent(NEW_OUTPUT);
238
+ },
239
+ );
240
+ });