@marimo-team/islands 0.26.1-dev27 → 0.26.1-dev29

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 (76) hide show
  1. package/dist/{ErrorBoundary-zpe6C93k.js → ErrorBoundary-CPcZlpvU.js} +1 -1
  2. package/dist/{chat-ui-DOvIzlMA.js → chat-ui-CWmSnBs8.js} +899 -899
  3. package/dist/{code-visibility-BtvMUvQ6.js → code-visibility-CHvnQsso.js} +2 -2
  4. package/dist/{common-B46KECgx.js → common-9OlCmjdr.js} +6565 -6565
  5. package/dist/{config-DL9e-OWE.js → config-1ku0tAiU.js} +27 -28
  6. package/dist/{data-grid-overlay-editor-CLCJ44fs.js → data-grid-overlay-editor-D6x_MBSD.js} +1 -1
  7. package/dist/{dropdown-menu-DYN2RV5d.js → dropdown-menu-D65ZUqka.js} +1983 -1983
  8. package/dist/{error-entries-CncQR572.js → error-entries-DFHEq_SO.js} +515 -519
  9. package/dist/{feedback-button-CnyHlwaY.js → feedback-button-CodkZ3hF.js} +19 -19
  10. package/dist/{glide-data-editor-C3znsea0.js → glide-data-editor-BZxvtSp-.js} +35 -35
  11. package/dist/{globals-DHoGn4Qt.js → globals-DFf-tSyE.js} +1 -1
  12. package/dist/{html-to-image-BU7H-AM1.js → html-to-image-D6Gtk5ik.js} +24005 -23992
  13. package/dist/main.js +864 -864
  14. package/dist/{number-overlay-editor-DwK5S3_f.js → number-overlay-editor-CfwFMv_U.js} +1 -1
  15. package/dist/{process-output-xJm8T5-E.js → process-output-ZBdibqlG.js} +2 -2
  16. package/dist/{reveal-component-Dsp5kSt3.js → reveal-component-CDfNuSFv.js} +3 -3
  17. package/dist/style.css +1 -1
  18. package/dist/{vega-component-DpTyTrz3.js → vega-component-D61CTW1X.js} +1 -1
  19. package/package.json +1 -1
  20. package/src/__mocks__/intersection-observer.ts +45 -0
  21. package/src/components/databases/engine-variable.tsx +2 -2
  22. package/src/components/dependency-graph/panels.tsx +2 -2
  23. package/src/components/editor/actions/useCellActionButton.tsx +2 -8
  24. package/src/components/editor/cell/code/__tests__/code-placeholder.test.tsx +40 -0
  25. package/src/components/editor/cell/code/cell-editor.tsx +41 -104
  26. package/src/components/editor/cell/code/code-placeholder.css +61 -11
  27. package/src/components/editor/cell/code/code-placeholder.tsx +52 -29
  28. package/src/components/editor/cell/useSplitCell.tsx +2 -2
  29. package/src/components/editor/chrome/wrapper/__tests__/pending-ai-cells.test.tsx +6 -10
  30. package/src/components/editor/errors/auto-fix.tsx +8 -7
  31. package/src/components/editor/navigation/__tests__/navigation.test.ts +3 -12
  32. package/src/components/editor/navigation/focus-utils.ts +20 -8
  33. package/src/components/editor/navigation/multi-cell-action-toolbar.tsx +3 -11
  34. package/src/components/editor/navigation/navigation.ts +2 -2
  35. package/src/components/editor/notebook-cell.tsx +15 -24
  36. package/src/components/editor/output/MarimoTracebackOutput.tsx +2 -2
  37. package/src/components/editor/renderers/vertical-layout/__tests__/useFocusFirstEditor.test.ts +6 -9
  38. package/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts +2 -5
  39. package/src/components/find-replace/find-replace.tsx +3 -7
  40. package/src/components/variables/__tests__/variables-table.test.tsx +1 -2
  41. package/src/core/ai/__tests__/staged-cells.test.ts +6 -39
  42. package/src/core/ai/staged-cells.ts +2 -20
  43. package/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts +15 -13
  44. package/src/core/ai/tools/edit-notebook-tool.ts +13 -8
  45. package/src/core/cells/__tests__/cell-editor-view.test.ts +44 -0
  46. package/src/core/cells/__tests__/cells.test.ts +0 -1
  47. package/src/core/cells/__tests__/focus.test.ts +1 -7
  48. package/src/core/cells/__tests__/harness.ts +0 -1
  49. package/src/core/cells/cells.ts +15 -10
  50. package/src/core/cells/focus.ts +1 -1
  51. package/src/core/cells/scrollCellIntoView.ts +4 -14
  52. package/src/core/cells/utils.ts +0 -13
  53. package/src/core/codemirror/__tests__/cell-documents.test.ts +79 -0
  54. package/src/core/codemirror/__tests__/editor-mount-scheduler.test.ts +75 -105
  55. package/src/core/codemirror/__tests__/format.test.ts +85 -63
  56. package/src/core/codemirror/__tests__/use-lazy-editor-mount.test.tsx +193 -0
  57. package/src/core/codemirror/cell-documents.ts +132 -0
  58. package/src/core/codemirror/copilot/__tests__/getCodes.test.ts +0 -1
  59. package/src/core/codemirror/copilot/getCodes.ts +3 -14
  60. package/src/core/codemirror/editor-mount-scheduler.ts +41 -48
  61. package/src/core/codemirror/extensions.ts +2 -2
  62. package/src/core/codemirror/find-replace/__tests__/navigate.test.ts +42 -16
  63. package/src/core/codemirror/find-replace/__tests__/search-highlight.test.ts +30 -0
  64. package/src/core/codemirror/find-replace/__tests__/unmounted-cells.test.ts +145 -0
  65. package/src/core/codemirror/find-replace/navigate.ts +88 -129
  66. package/src/core/codemirror/find-replace/search-highlight.ts +3 -1
  67. package/src/core/codemirror/find-replace/state.ts +7 -2
  68. package/src/core/codemirror/format.ts +25 -31
  69. package/src/core/codemirror/go-to-definition/__tests__/utils.test.ts +8 -9
  70. package/src/core/codemirror/language/cell-code.ts +7 -0
  71. package/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts +25 -0
  72. package/src/core/codemirror/lsp/notebook-lsp.ts +6 -16
  73. package/src/core/codemirror/use-lazy-editor-mount.ts +67 -0
  74. package/src/core/codemirror/utils.ts +2 -6
  75. package/src/utils/__tests__/shared-intersection-observer.test.ts +49 -0
  76. package/src/utils/shared-intersection-observer.ts +53 -0
@@ -1,6 +1,6 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import { useAtomValue, useSetAtom, useStore } from "jotai";
3
+ import { useAtomValue, useSetAtom } from "jotai";
4
4
  import {
5
5
  CheckIcon,
6
6
  ChevronDownIcon,
@@ -18,7 +18,7 @@ import {
18
18
  } from "@/components/ui/dropdown-menu";
19
19
  import { Tooltip } from "@/components/ui/tooltip";
20
20
  import { aiCompletionCellAtom } from "@/core/ai/state";
21
- import { notebookAtom } from "@/core/cells/cells";
21
+ import { ensureCellEditorView } from "@/core/cells/cells";
22
22
  import { useCellActions } from "@/core/cells/actions";
23
23
  import type { CellId } from "@/core/cells/ids";
24
24
  import { aiFeaturesEnabledAtom } from "@/core/config/config";
@@ -26,6 +26,7 @@ import { getAutoFixes } from "@/core/errors/errors";
26
26
  import type { MarimoError } from "@/core/kernel/messages";
27
27
  import { cn } from "@/utils/cn";
28
28
  import { useOpenAiAssistant } from "../chrome/wrapper/useOpenAiAssistant";
29
+ import { focusEditor } from "../navigation/focus-utils";
29
30
  import { type FixMode, useFixMode } from "./fix-mode";
30
31
 
31
32
  export function buildFixInChatPrompt(
@@ -51,7 +52,6 @@ export const AutoFixButton = ({
51
52
  cellId: CellId;
52
53
  className?: string;
53
54
  }) => {
54
- const store = useStore();
55
55
  const { createCell } = useCellActions();
56
56
  const aiFeaturesEnabled = useAtomValue(aiFeaturesEnabledAtom);
57
57
  const autoFixes = errors.flatMap((error) =>
@@ -69,8 +69,8 @@ export const AutoFixButton = ({
69
69
  const firstFix = autoFixes[0];
70
70
 
71
71
  const handleFix = (triggerFix: boolean) => {
72
- const editorView =
73
- store.get(notebookAtom).cellHandles[cellId].current?.editorView;
72
+ // A hidden cell with output never scrolls its editor into view.
73
+ const editorView = ensureCellEditorView(cellId);
74
74
  firstFix.onFix({
75
75
  addCodeBelow: (code: string) => {
76
76
  createCell({ after: cellId, code, focus: false });
@@ -82,8 +82,9 @@ export const AutoFixButton = ({
82
82
  triggerFix,
83
83
  },
84
84
  });
85
- // Focus the editor
86
- editorView?.focus();
85
+ if (editorView) {
86
+ focusEditor(editorView);
87
+ }
87
88
  };
88
89
 
89
90
  const openAISidebar = () => {
@@ -393,10 +393,7 @@ describe("useCellNavigationProps", () => {
393
393
  result.current.onKeyDown?.(mockEvent);
394
394
  });
395
395
 
396
- expect(focusCellEditor).toHaveBeenCalledWith(
397
- expect.anything(),
398
- mockCellId,
399
- );
396
+ expect(focusCellEditor).toHaveBeenCalledWith(mockCellId);
400
397
  expect(mockEvent.preventDefault).toHaveBeenCalled();
401
398
  });
402
399
 
@@ -614,10 +611,7 @@ describe("useCellNavigationProps", () => {
614
611
  result.current.onKeyDown?.(mockEvent);
615
612
  });
616
613
 
617
- expect(focusCellEditor).toHaveBeenCalledWith(
618
- expect.anything(),
619
- mockCellId,
620
- );
614
+ expect(focusCellEditor).toHaveBeenCalledWith(mockCellId);
621
615
  expect(mockEvent.preventDefault).toHaveBeenCalled();
622
616
  });
623
617
  });
@@ -711,10 +705,7 @@ describe("useCellNavigationProps", () => {
711
705
  result.current.onKeyDown?.(mockEvent);
712
706
  });
713
707
 
714
- expect(focusCellEditor).toHaveBeenCalledWith(
715
- expect.anything(),
716
- mockCellId,
717
- );
708
+ expect(focusCellEditor).toHaveBeenCalledWith(mockCellId);
718
709
  expect(mockEvent.preventDefault).toHaveBeenCalled();
719
710
  });
720
711
  });
@@ -1,18 +1,30 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import type { createStore } from "jotai";
4
- import { getCellEditorView } from "@/core/cells/cells";
3
+ import type { EditorView } from "@codemirror/view";
4
+ import { ensureCellEditorView } from "@/core/cells/cells";
5
5
  import { type CellId, HTMLCellId } from "@/core/cells/ids";
6
6
  import { scrollCellIntoView } from "@/core/cells/scrollCellIntoView";
7
7
  import { Logger } from "@/utils/Logger";
8
+ import { retryWithTimeout } from "@/utils/timeout";
8
9
 
9
- export function focusCellEditor(
10
- store: ReturnType<typeof createStore>,
11
- cellId: CellId,
12
- ): void {
13
- const editor = getCellEditorView(cellId);
10
+ /**
11
+ * Focus an editor that may have just been built. It is attached to the page
12
+ * only after React renders, so a single focus call would be ignored.
13
+ */
14
+ export function focusEditor(editor: EditorView): void {
15
+ retryWithTimeout(
16
+ () => {
17
+ editor.focus();
18
+ return editor.hasFocus;
19
+ },
20
+ { retries: 5, delay: 20 },
21
+ );
22
+ }
23
+
24
+ export function focusCellEditor(cellId: CellId): void {
25
+ const editor = ensureCellEditorView(cellId);
14
26
  if (editor) {
15
- editor.focus();
27
+ focusEditor(editor);
16
28
  } else {
17
29
  Logger.warn(
18
30
  `[CellFocusManager] focusCellEditor: element not found: ${cellId}`,
@@ -1,6 +1,5 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import type { EditorView } from "@codemirror/view";
4
3
  import { useAtomValue } from "jotai";
5
4
  import {
6
5
  AlertTriangleIcon,
@@ -30,13 +29,13 @@ import {
30
29
  DropdownMenuSeparator,
31
30
  DropdownMenuTrigger,
32
31
  } from "@/components/ui/dropdown-menu";
33
- import { getCellEditorView, hasOnlyOneCellAtom } from "@/core/cells/cells";
32
+ import { hasOnlyOneCellAtom } from "@/core/cells/cells";
34
33
  import { useCellActions } from "@/core/cells/actions";
35
34
  import { columnOf, layoutAtom } from "@/core/cells/layout";
36
35
  import { useNotebookDocumentEdit } from "@/core/notebook/document";
37
36
  import type { CellId } from "@/core/cells/ids";
38
37
  import { usePendingDeleteService } from "@/core/cells/pending-delete-service";
39
- import { formatEditorViews } from "@/core/codemirror/format";
38
+ import { formatCells } from "@/core/codemirror/format";
40
39
  import { userConfigAtom } from "@/core/config/config";
41
40
  import type { HotkeyAction } from "@/core/hotkeys/hotkeys";
42
41
  import type { CellConfig } from "@/core/network/types";
@@ -176,14 +175,7 @@ export function useMultiCellActionButtons(cellIds: CellId[]) {
176
175
  });
177
176
 
178
177
  const formatSelectedCells = useEvent((cellIds: CellId[]) => {
179
- const editorViews: Record<CellId, EditorView> = {};
180
- cellIds.forEach((cellId) => {
181
- const editorView = getCellEditorView(cellId);
182
- if (editorView) {
183
- editorViews[cellId] = editorView;
184
- }
185
- });
186
- formatEditorViews(editorViews);
178
+ formatCells(cellIds);
187
179
  });
188
180
 
189
181
  const clearSelectedCellsOutput = useEvent((cellIds: CellId[]) => {
@@ -360,7 +360,7 @@ export function useCellNavigationProps(
360
360
  // Enter will focus the cell editor.
361
361
  Enter: () => {
362
362
  showHiddenCode({ cellId });
363
- focusCellEditor(store, cellId);
363
+ focusCellEditor(cellId);
364
364
  selectionActions.clear();
365
365
  return true;
366
366
  },
@@ -480,7 +480,7 @@ export function useCellNavigationProps(
480
480
  editorView.current?.contentDOM.blur();
481
481
  focusCell(cellId);
482
482
  } else {
483
- focusCellEditor(store, cellId);
483
+ focusCellEditor(cellId);
484
484
  }
485
485
  }
486
486
 
@@ -12,6 +12,7 @@ import {
12
12
  useCallback,
13
13
  useEffect,
14
14
  useImperativeHandle,
15
+ useMemo,
15
16
  useRef,
16
17
  useState,
17
18
  } from "react";
@@ -31,6 +32,7 @@ import { isOutputEmpty } from "@/core/cells/outputs";
31
32
  import { useIsPendingCut } from "@/core/cells/pending-cut-service";
32
33
  import { autocompletionKeymap } from "@/core/codemirror/cm";
33
34
  import { clearCellBreakpoints } from "@/core/codemirror/cells/debugger-state";
35
+ import { parseCellCode } from "@/core/codemirror/language/cell-code";
34
36
  import type { LanguageAdapterType } from "@/core/codemirror/language/types";
35
37
  import { CSSClasses } from "@/core/constants";
36
38
  import { canCollapseOutline } from "@/core/dom/outline";
@@ -92,6 +94,7 @@ import { useDeleteCellCallback } from "./cell/useDeleteCell";
92
94
  import { useRunCell } from "./cell/useRunCells";
93
95
  import { cellDomProps } from "./common";
94
96
  import { SqlValidationErrorBanner } from "./errors/sql-validation-errors";
97
+ import { focusCellEditor } from "./navigation/focus-utils";
95
98
  import { useCellNavigationProps } from "./navigation/navigation";
96
99
  import { type OnRefactorWithAI, OutputArea } from "./Output";
97
100
  import { ConsoleOutput } from "./output/console/ConsoleOutput";
@@ -163,13 +166,10 @@ function useCellHiddenLogic({
163
166
  cellId,
164
167
  cellConfig,
165
168
  languageAdapter,
166
- editorView,
167
169
  }: {
168
170
  cellId: CellId;
169
171
  cellConfig: CellConfig;
170
172
  languageAdapter: LanguageAdapterType | undefined;
171
- editorView: React.RefObject<EditorView | null>;
172
- editorViewParentRef: React.RefObject<HTMLDivElement | null>;
173
173
  }) {
174
174
  const showsHiddenCode = useShowsHiddenCode(cellId);
175
175
  const showHiddenCodeNow = useSetAtom(showHiddenCodeAtom);
@@ -192,7 +192,7 @@ function useCellHiddenLogic({
192
192
  showHiddenCodeNow({ cellId });
193
193
 
194
194
  if (focus) {
195
- editorView.current?.focus();
195
+ focusCellEditor(cellId);
196
196
  }
197
197
 
198
198
  // Undoing happens in editor/focus/focus.ts, when the cell is blurred.
@@ -229,15 +229,8 @@ export type CellComponentActions = Pick<
229
229
  * Imperative interface of the cell.
230
230
  */
231
231
  export interface CellHandle {
232
- /**
233
- * The CodeMirror editor view.
234
- * TODO: merge this with editorViewOrNull
235
- */
232
+ /** The CodeMirror editor view, or null until it is built. */
236
233
  editorView: EditorView | null;
237
- /**
238
- * The CodeMirror editor view, or null if it is not yet mounted.
239
- */
240
- editorViewOrNull: EditorView | null;
241
234
  }
242
235
 
243
236
  export interface CellProps {
@@ -281,9 +274,6 @@ const CellComponent = (props: CellProps) => {
281
274
  get editorView() {
282
275
  return editorView.current;
283
276
  },
284
- get editorViewOrNull() {
285
- return editorView.current;
286
- },
287
277
  }),
288
278
  [editorView],
289
279
  );
@@ -407,7 +397,14 @@ const EditableCellComponent = ({
407
397
  const answerPrompt = useAnswerPrompt(cellId);
408
398
  const isPendingCut = useIsPendingCut(cellId);
409
399
 
410
- const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();
400
+ // The editor reports its language once built; until then it follows the code.
401
+ const [editorLanguageAdapter, setLanguageAdapter] =
402
+ useState<LanguageAdapterType>();
403
+ const parsedCode = useMemo(
404
+ () => parseCellCode(cellData.code),
405
+ [cellData.code],
406
+ );
407
+ const languageAdapter = editorLanguageAdapter ?? parsedCode.adapter.type;
411
408
 
412
409
  const uninstantiated = isUninstantiated(execution);
413
410
 
@@ -461,8 +458,6 @@ const EditableCellComponent = ({
461
458
  cellId,
462
459
  cellConfig: cellData.config,
463
460
  languageAdapter,
464
- editorView,
465
- editorViewParentRef,
466
461
  });
467
462
 
468
463
  // Hotkey and focus props
@@ -486,10 +481,8 @@ const EditableCellComponent = ({
486
481
  const [isCellStatusInline, setIsCellStatusInline] = useState(false);
487
482
  const [isCellButtonsInline, setIsCellButtonsInline] = useState(false);
488
483
 
489
- // For markdown cells, get the inner content directly from the editor
490
- // (editorView.state.doc contains the transformed markdown, not the mo.md(...) wrapper)
491
- const isEmptyMarkdownContent =
492
- isMarkdown && editorView.current?.state.doc.toString().trim() === "";
484
+ // The notebook code wraps markdown in mo.md(...); emptiness is about its content.
485
+ const isEmptyMarkdownContent = isMarkdown && parsedCode.text.trim() === "";
493
486
 
494
487
  useResizeObserver({
495
488
  ref: cellContainerRef,
@@ -1010,8 +1003,6 @@ const SetupCellComponent = ({
1010
1003
  cellId,
1011
1004
  cellConfig: cellData.config,
1012
1005
  languageAdapter: "python",
1013
- editorView,
1014
- editorViewParentRef,
1015
1006
  });
1016
1007
 
1017
1008
  // Use the extracted hooks
@@ -21,7 +21,7 @@ import {
21
21
  } from "@/components/ui/dropdown-menu";
22
22
  import { Kbd } from "@/components/ui/kbd";
23
23
  import { Tooltip } from "@/components/ui/tooltip";
24
- import { getCellEditorView } from "@/core/cells/cells";
24
+ import { ensureCellEditorView } from "@/core/cells/cells";
25
25
  import { buildErrorReport } from "@/core/cells/error-report";
26
26
  import type { CellId } from "@/core/cells/ids";
27
27
  import { SCRATCH_CELL_ID } from "@/core/cells/ids";
@@ -257,7 +257,7 @@ export const replaceTracebackFilenames = (domNode: DOMNode) => {
257
257
  toggleBreakpoint(info.cellId, info.lineNumber);
258
258
  return;
259
259
  }
260
- const view = getCellEditorView(info.cellId);
260
+ const view = ensureCellEditorView(info.cellId);
261
261
  if (view) {
262
262
  insertDebuggerAtLine(view, info.lineNumber);
263
263
  }
@@ -65,7 +65,7 @@ describe("useFocusFirstEditor", () => {
65
65
  cellIds: [cellId],
66
66
  cellHandles: {
67
67
  [cellId]: {
68
- current: { editorView: editor, editorViewOrNull: editor },
68
+ current: { editorView: editor },
69
69
  },
70
70
  },
71
71
  });
@@ -134,15 +134,11 @@ describe("useFocusFirstEditor", () => {
134
134
  .spyOn(document, "querySelector")
135
135
  .mockReturnValue(mockElement as unknown as HTMLElement);
136
136
 
137
- // Mock getNotebook
137
+ // The target cell may be offscreen, so its editor is built on demand.
138
138
  const mockEditor = { focus: vi.fn() };
139
- vi.spyOn(cellsModule, "getNotebook").mockReturnValue({
140
- cellIds: [],
141
- cellData: {},
142
- cellHandles: {
143
- "cell-123": { current: { editorView: mockEditor } },
144
- },
145
- } as unknown as cellsModule.NotebookState);
139
+ const ensureSpy = vi
140
+ .spyOn(cellsModule, "ensureCellEditorView")
141
+ .mockReturnValue(mockEditor as unknown as EditorView);
146
142
 
147
143
  renderHook(() => useFocusFirstEditor());
148
144
 
@@ -157,6 +153,7 @@ describe("useFocusFirstEditor", () => {
157
153
  expect(mockElement.scrollIntoView).toHaveBeenCalled();
158
154
  // oxlint-disable-next-line typescript/unbound-method
159
155
  expect(mockElement.focus).toHaveBeenCalled();
156
+ expect(ensureSpy).toHaveBeenCalledWith("cell-123");
160
157
  expect(mockEditor.focus).toHaveBeenCalled();
161
158
 
162
159
  // Restore original hash
@@ -1,5 +1,6 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
+ import { focusCellEditor } from "@/components/editor/navigation/focus-utils";
3
4
  import { getNotebook } from "@/core/cells/cells";
4
5
  import type { CellId } from "@/core/cells/ids";
5
6
  import { useOnMount } from "@/hooks/useLifecycle";
@@ -98,7 +99,6 @@ function focusCellByName(cellName: string) {
98
99
  cellElement.focus();
99
100
 
100
101
  // Look for an editor to focus
101
- const { cellHandles } = getNotebook();
102
102
  const cellId = extractCellIdFromDomElement(cellElement);
103
103
 
104
104
  if (!cellId) {
@@ -106,10 +106,7 @@ function focusCellByName(cellName: string) {
106
106
  return;
107
107
  }
108
108
 
109
- const editor = cellHandles[cellId]?.current?.editorView;
110
- if (editor) {
111
- editor.focus();
112
- }
109
+ focusCellEditor(cellId);
113
110
  }
114
111
  } else {
115
112
  Logger.warn(
@@ -1,6 +1,4 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
-
3
- import type { EditorView } from "@codemirror/view";
4
2
  import { useAtom, useAtomValue } from "jotai";
5
3
  import {
6
4
  ArrowLeftIcon,
@@ -41,10 +39,8 @@ import { toast } from "../ui/use-toast";
41
39
  export const FindReplace: React.FC = () => {
42
40
  const [isFocused, setIsFocused] = useState(false);
43
41
  const [state, dispatch] = useAtom(findReplaceAtom);
44
- const [matches, setMatches] = useState<{
45
- count: number;
46
- position: Map<EditorView, Map<string, number>>;
47
- }>();
42
+ const [matches, setMatches] =
43
+ useState<Exclude<ReturnType<typeof getMatches>, false>>();
48
44
  const findInputRef = useRef<HTMLInputElement>(null);
49
45
  const hotkeys = useAtomValue(hotkeysAtom);
50
46
 
@@ -101,7 +97,7 @@ export const FindReplace: React.FC = () => {
101
97
  const currentMatch =
102
98
  selection && matches
103
99
  ? matches.position
104
- .get(selection.view)
100
+ .get(selection.cellId)
105
101
  ?.get(`${selection.range.from}:${selection.range.to}`)
106
102
  : undefined;
107
103
 
@@ -58,10 +58,9 @@ describe("VariableTable cell links", () => {
58
58
  // state right after a large notebook opens.
59
59
  const handle: { current: CellHandle | null } = { current: null };
60
60
  notebook.cellHandles[definingCell] = handle;
61
- editorMountScheduler.request(definingCell, () => {
61
+ editorMountScheduler.register(definingCell, () => {
62
62
  handle.current = {
63
63
  editorView: definingView,
64
- editorViewOrNull: definingView,
65
64
  };
66
65
  });
67
66
  store.set(notebookAtom, notebook);
@@ -17,30 +17,14 @@ import {
17
17
  const { createActions, reducer, initialState } = visibleForTesting;
18
18
 
19
19
  // Mock the dependencies
20
- const mockSetCellCode = vi.fn();
21
20
  const mockDeleteCellCallback = vi.fn();
21
+ const { writeCellCode } = vi.hoisted(() => ({ writeCellCode: vi.fn() }));
22
22
 
23
- // Mock cell handle with editor view
24
- const mockCellHandle = {
25
- current: {
26
- editorViewOrNull: {
27
- dispatch: vi.fn(),
28
- },
29
- },
30
- };
31
-
32
- vi.mock("../../cells/actions", () => ({
33
- useCellActions: () => ({
34
- setCellCode: mockSetCellCode,
35
- }),
36
- }));
37
23
  vi.mock("../../cells/cells", async () => {
38
24
  const { atom } = await import("jotai");
39
- return {
40
- notebookAtom: atom({ cellData: {}, cellIds: [] }),
41
- getCellEditorView: vi.fn(() => mockCellHandle.current.editorViewOrNull),
42
- };
25
+ return { notebookAtom: atom({ cellData: {}, cellIds: [] }) };
43
26
  });
27
+ vi.mock("../../codemirror/cell-documents", () => ({ writeCellCode }));
44
28
 
45
29
  vi.mock("@/components/editor/cell/useDeleteCell", () => ({
46
30
  useDeleteCellCallback: () => mockDeleteCellCallback,
@@ -50,10 +34,6 @@ vi.mock("@/core/network/requests", () => ({
50
34
  getRequestClient: () => ({}),
51
35
  }));
52
36
 
53
- vi.mock("../../codemirror/language/cell-code", () => ({
54
- prepareCellCodeUpdate: vi.fn(() => ({ effects: [] })),
55
- }));
56
-
57
37
  describe("staged-cells", () => {
58
38
  let store: ReturnType<typeof getDefaultStore>;
59
39
  let cellId1: CellId;
@@ -287,23 +267,10 @@ describe("staged-cells", () => {
287
267
  const edit: Edit = { type: "update_cell", previousCode: "x = 1" };
288
268
  stage(cellId1, edit);
289
269
  result.current.rejectStagedCell(cellId1, edit);
290
- expect(
291
- mockCellHandle.current.editorViewOrNull.dispatch,
292
- ).toHaveBeenCalled();
293
- expect(store.get(stagedAICellsAtom).size).toBe(0);
294
- });
295
-
296
- it("writes to the document when the editor is not mounted", async () => {
297
- const { getCellEditorView } = await import("../../cells/cells");
298
- vi.mocked(getCellEditorView).mockReturnValueOnce(undefined);
299
- const { result } = renderHook(() => useStagedCells());
300
- const edit: Edit = { type: "update_cell", previousCode: "x = 1" };
301
- stage(cellId1, edit);
302
- result.current.rejectStagedCell(cellId1, edit);
303
- expect(mockSetCellCode).toHaveBeenCalledWith({
304
- cellId: cellId1,
305
- code: "x = 1",
270
+ expect(writeCellCode).toHaveBeenCalledWith(cellId1, "x = 1", {
271
+ initialize: true,
306
272
  });
273
+ expect(store.get(stagedAICellsAtom).size).toBe(0);
307
274
  });
308
275
 
309
276
  it("deletes an added cell and leaves a proposed deletion in place when discarded", () => {
@@ -6,9 +6,7 @@ import { useMemo } from "react";
6
6
  import { useDeleteCellCallback } from "@/components/editor/cell/useDeleteCell";
7
7
  import type { CellId } from "@/core/cells/ids";
8
8
  import { createReducerAndAtoms } from "@/utils/createReducer";
9
- import { getCellEditorView } from "../cells/cells";
10
- import { useCellActions } from "../cells/actions";
11
- import { prepareCellCodeUpdate } from "../codemirror/language/cell-code";
9
+ import { writeCellCode } from "../codemirror/cell-documents";
12
10
  import type { EditType } from "./tools/edit-notebook-tool";
13
11
 
14
12
  /** Pending AI edits shared by chat and agent workflows. */
@@ -74,24 +72,8 @@ export function useStagedAICell(cellId: CellId | undefined): Edit | undefined {
74
72
  /** Keep or discard staged cells, whichever AI workflow staged them. */
75
73
  export function useStagedCells() {
76
74
  const { removeStagedCell } = useStagedAICellsActions();
77
- const { setCellCode } = useCellActions();
78
75
  const deleteCellCallback = useDeleteCellCallback();
79
76
 
80
- // Only a mounted editor infers the cell's language; otherwise use the document.
81
- const writeCellCode = (cellId: CellId, code: string) => {
82
- const editorView = getCellEditorView(cellId);
83
- if (editorView) {
84
- const update = prepareCellCodeUpdate(editorView.state, code, {
85
- initialize: true,
86
- });
87
- if (update) {
88
- editorView.dispatch(update);
89
- }
90
- } else {
91
- setCellCode({ cellId, code });
92
- }
93
- };
94
-
95
77
  const deleteStagedCell = (cellId: CellId) => {
96
78
  removeStagedCell(cellId);
97
79
  deleteCellCallback({ cellId });
@@ -108,7 +90,7 @@ export function useStagedCells() {
108
90
  const rejectStagedCell = (cellId: CellId, edit: Edit) => {
109
91
  switch (edit.type) {
110
92
  case "update_cell":
111
- writeCellCode(cellId, edit.previousCode);
93
+ writeCellCode(cellId, edit.previousCode, { initialize: true });
112
94
  removeStagedCell(cellId);
113
95
  break;
114
96
  case "add_cell":
@@ -669,27 +669,29 @@ describe("EditNotebookTool", () => {
669
669
  ).rejects.toThrow("Cell not found");
670
670
  });
671
671
 
672
- it("should throw error when cell editor not found", async () => {
672
+ it("stages a cell without building its editor", async () => {
673
673
  const notebook = MockNotebook.notebookState({
674
674
  cellData: {
675
675
  [cellId1]: { code: "x = 1" },
676
676
  },
677
677
  });
678
- // Don't set editorView
679
- notebook.cellHandles[cellId1] = { current: null } as never;
678
+ notebook.cellHandles[cellId1] = { current: { editorView: null } };
680
679
  store.set(notebookAtom, notebook);
681
680
 
682
- await expect(
683
- tool.handler(
684
- {
685
- edit: {
686
- type: "delete_cell",
687
- position: { cellId: cellId1 },
688
- },
681
+ await tool.handler(
682
+ {
683
+ edit: {
684
+ type: "delete_cell",
685
+ position: { cellId: cellId1 },
689
686
  },
690
- toolContext as never,
691
- ),
692
- ).rejects.toThrow("Cell editor not found");
687
+ },
688
+ toolContext as never,
689
+ );
690
+
691
+ expect(store.get(stagedAICellsAtom).get(cellId1)).toEqual({
692
+ type: "delete_cell",
693
+ previousCode: "x = 1",
694
+ });
693
695
  });
694
696
 
695
697
  it("should throw error when cellId is missing for delete_cell", async () => {
@@ -6,7 +6,12 @@ import { scrollAndHighlightCell } from "@/components/editor/links/cell-link";
6
6
  import { type NotebookState, notebookAtom } from "@/core/cells/cells";
7
7
  import type { CreateCellOptions } from "@/core/cells/actions";
8
8
  import { CellId } from "@/core/cells/ids";
9
- import { prepareCellCodeUpdate } from "@/core/codemirror/language/cell-code";
9
+ import { editorMountScheduler } from "@/core/codemirror/editor-mount-scheduler";
10
+ import { getCellPythonCode } from "@/core/codemirror/cell-documents";
11
+ import {
12
+ getCellCode,
13
+ prepareCellCodeUpdate,
14
+ } from "@/core/codemirror/language/cell-code";
10
15
  import {
11
16
  type CellColumnId,
12
17
  type Layout,
@@ -129,7 +134,7 @@ export class EditNotebookTool implements AiTool<
129
134
 
130
135
  // If previous code exists, we don't want to replace it, it means there is a new edit on top of the previous update
131
136
  // Keep the original code
132
- const currentCellCode = editorView.state.doc.toString();
137
+ const currentCellCode = getCellCode(editorView.state);
133
138
  const previousCode =
134
139
  existingStagedCell?.previousCode ?? currentCellCode;
135
140
 
@@ -243,8 +248,7 @@ export class EditNotebookTool implements AiTool<
243
248
  const notebook = store.get(notebookAtom);
244
249
  this.validateCellIdExists(cellId, notebook);
245
250
 
246
- const editorView = this.getCellEditorView(cellId, notebook);
247
- const currentCellCode = editorView.state.doc.toString();
251
+ const currentCellCode = getCellPythonCode(cellId, notebook);
248
252
 
249
253
  // Add to staged AICells - don't actually delete the cell yet
250
254
  addStagedCell({
@@ -293,15 +297,16 @@ export class EditNotebookTool implements AiTool<
293
297
  cellId: CellId,
294
298
  notebook: NotebookState,
295
299
  ): EditorView {
296
- const cellHandles = notebook.cellHandles;
297
- const cellHandle = cellHandles[cellId].current;
298
- if (!cellHandle?.editorView) {
300
+ // A cell the user has not scrolled to has no editor until it is built.
301
+ editorMountScheduler.promote(cellId);
302
+ const editorView = notebook.cellHandles[cellId]?.current?.editorView;
303
+ if (!editorView) {
299
304
  throw new ToolExecutionError("Cell editor not found", {
300
305
  code: "CELL_EDITOR_NOT_FOUND",
301
306
  isRetryable: false,
302
307
  suggestedFix: "Internal error, ask the user to report this error",
303
308
  });
304
309
  }
305
- return cellHandle.editorView;
310
+ return editorView;
306
311
  }
307
312
  }