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

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-BsbtzE4_.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-XN_3KbPf.js} +2 -2
  4. package/dist/{common-B46KECgx.js → common-LxQtzU-2.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-DOgicOan.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-Bdpv5VWt.js} +19 -19
  10. package/dist/{glide-data-editor-C3znsea0.js → glide-data-editor-CZTp4A6s.js} +35 -35
  11. package/dist/{globals-DHoGn4Qt.js → globals-CI6U88UW.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-D8MSe8ZJ.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-CNHAgCQ4.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
@@ -3,9 +3,9 @@
3
3
  import { SearchQuery } from "@codemirror/search";
4
4
  import { EditorSelection } from "@codemirror/state";
5
5
  import { EditorView } from "@codemirror/view";
6
- import { getAllEditorViews } from "@/core/cells/cells";
7
- import { replaceEditorContent } from "@/core/codemirror/replace-editor-content";
6
+ import type { CellId } from "@/core/cells/ids";
8
7
  import { store } from "@/core/state/jotai";
8
+ import { getCellDocuments, writeCellCode } from "../cell-documents";
9
9
  import { scrollOwnerCell } from "../utils";
10
10
  import { asQueryCreator, type QueryType } from "./query";
11
11
  import { findReplaceAtom } from "./state";
@@ -28,75 +28,66 @@ function searchCommand<T>(
28
28
  };
29
29
  }
30
30
 
31
- /**
32
- * Move the selection to the first match (next or previous) after the global selection.
33
- * Will wrap around to the start of the document when it reaches the end.
34
- *
35
- * This is a modified version of the original findNext/findPrev function,
36
- * that searches through all views, instead of just the current one.
37
- */
38
- const findInDirection = (direction: "next" | "prev") =>
39
- searchCommand(({ query }) => {
40
- const views = getAllEditorViews();
41
- // Get starting view from the store
42
- const currentView = store.get(findReplaceAtom).currentView || {
43
- view: views[0],
44
- range: { from: 0, to: 0 },
45
- };
46
-
47
- let startingPosition: number | null = currentView.range.to;
48
-
49
- // We are going backwards so update the starting position and views to search
50
- if (direction === "prev") {
51
- views.reverse();
52
- startingPosition = currentView.range.from;
53
- }
54
-
55
- let startingViewIndex = views.indexOf(currentView.view);
56
- if (startingViewIndex < 0) {
57
- startingViewIndex = 0;
31
+ /** Search document text first; construct only the matching cell's editor. */
32
+ function findMatch(
33
+ query: QueryType,
34
+ direction: "next" | "prev",
35
+ includeCurrent = false,
36
+ ) {
37
+ const documents = getCellDocuments();
38
+ const current = store.get(findReplaceAtom).currentView;
39
+ const startingCellId = current?.cellId ?? documents[0]?.cellId;
40
+ let position: number | undefined = current
41
+ ? direction === "prev" || includeCurrent
42
+ ? current.range.from
43
+ : current.range.to
44
+ : 0;
45
+ if (direction === "prev") {
46
+ documents.reverse();
47
+ }
48
+ const start = Math.max(
49
+ 0,
50
+ documents.findIndex((doc) => doc.cellId === startingCellId),
51
+ );
52
+ for (const document of [...documents, ...documents].slice(start)) {
53
+ const { state } = document;
54
+ const match =
55
+ direction === "next"
56
+ ? query.nextMatch(state, 0, position ?? 0)
57
+ : query.prevMatch(
58
+ state,
59
+ position ?? state.doc.length,
60
+ state.doc.length,
61
+ );
62
+ const view = match ? document.ensureView() : undefined;
63
+ if (match && view) {
64
+ return { view, match };
58
65
  }
66
+ position = undefined;
67
+ document.view?.dispatch({ selection: EditorSelection.single(0) });
68
+ }
69
+ }
59
70
 
60
- const viewsToSearch = [...views, ...views].slice(startingViewIndex);
61
-
62
- for (const view of viewsToSearch) {
63
- const next =
64
- direction === "next"
65
- ? query.nextMatch(view.state, 0, startingPosition ?? 0)
66
- : query.prevMatch(
67
- view.state,
68
- startingPosition ?? view.state.doc.length,
69
- view.state.doc.length,
70
- );
71
-
72
- if (!next) {
73
- startingPosition = null; // Unset the starting position
74
- // If no match found in this view, continue to the next one
75
- // and remove the selection
76
- view.dispatch({
77
- selection: EditorSelection.single(0),
78
- });
79
- continue;
80
- }
81
-
82
- // Set selection
83
- const selection = EditorSelection.single(next.from, next.to);
84
- view.dispatch({
85
- selection,
86
- effects: [EditorView.scrollIntoView(selection.main, { y: "center" })],
87
- userEvent: "select.search",
88
- });
89
- scrollOwnerCell(view);
90
- store.set(findReplaceAtom, {
91
- type: "setCurrentView",
92
- view,
93
- range: { from: next.from, to: next.to },
94
- });
95
-
96
- return next; // If a match is found, stop searching and return true
71
+ const findInDirection = (direction: "next" | "prev") =>
72
+ searchCommand(({ query }) => {
73
+ const found = findMatch(query, direction);
74
+ if (!found) {
75
+ return false;
97
76
  }
98
-
99
- return false; // If no matches are found in any view, return false
77
+ const { view, match } = found;
78
+ const selection = EditorSelection.single(match.from, match.to);
79
+ view.dispatch({
80
+ selection,
81
+ effects: [EditorView.scrollIntoView(selection.main, { y: "center" })],
82
+ userEvent: "select.search",
83
+ });
84
+ scrollOwnerCell(view);
85
+ store.set(findReplaceAtom, {
86
+ type: "setCurrentView",
87
+ view,
88
+ range: { from: match.from, to: match.to },
89
+ });
90
+ return match;
100
91
  });
101
92
 
102
93
  /**
@@ -112,14 +103,14 @@ export const findPrev = findInDirection("prev");
112
103
  * Replace the next match after the global selection.
113
104
  */
114
105
  export const replaceAll = searchCommand(({ query }) => {
115
- const views = getAllEditorViews();
116
106
  const undoHandlers: (() => void)[] = [];
117
- for (const view of views) {
118
- if (view.state.readOnly) {
107
+ for (const document of getCellDocuments()) {
108
+ const { state } = document;
109
+ if (state.readOnly) {
119
110
  continue;
120
111
  }
121
112
 
122
- const changes = query.matchAll(view.state, 1e9)?.map((match) => {
113
+ const changes = query.matchAll(state, 1e9)?.map((match) => {
123
114
  const { from, to } = match;
124
115
  return { from, to, insert: query.getReplacement(match) };
125
116
  });
@@ -128,17 +119,11 @@ export const replaceAll = searchCommand(({ query }) => {
128
119
  continue;
129
120
  }
130
121
 
131
- const prevDoc = view.state.doc.toString();
122
+ const { cellId, code: previousCode } = document;
132
123
  undoHandlers.push(() => {
133
- replaceEditorContent(view, prevDoc, {
134
- userEvent: "input.replace.all",
135
- });
136
- });
137
-
138
- view.dispatch({
139
- changes,
140
- userEvent: "input.replace.all",
124
+ writeCellCode(cellId, previousCode, { userEvent: "input.replace.all" });
141
125
  });
126
+ document.applyChanges(changes, "input.replace.all");
142
127
  }
143
128
 
144
129
  const handleUndo = () => {
@@ -154,65 +139,39 @@ export const replaceAll = searchCommand(({ query }) => {
154
139
  * Replace the next match after the global selection.
155
140
  */
156
141
  export const replaceNext = searchCommand(({ query }) => {
157
- const views = getAllEditorViews();
158
- // Get starting view from the store
159
- const currentView = store.get(findReplaceAtom).currentView || {
160
- view: views[0],
161
- range: { from: 0, to: 0 },
162
- };
163
-
164
- // Start from the start of the selection to include the current match
165
- let startingPosition: number | null = currentView.range.from;
166
-
167
- let startingViewIndex = views.indexOf(currentView.view);
168
- if (startingViewIndex < 0) {
169
- startingViewIndex = 0;
142
+ const found = findMatch(query, "next", true);
143
+ if (!found) {
144
+ return false;
170
145
  }
171
- const viewsToSearch = [...views, ...views].slice(startingViewIndex);
172
-
173
- for (const view of viewsToSearch) {
174
- const next = query.nextMatch(view.state, 0, startingPosition ?? 0);
175
-
176
- if (!next) {
177
- startingPosition = null; // Unset the starting position
178
- // If no match found in this view, continue to the next one
179
- // and remove the selection
180
- view.dispatch({
181
- selection: EditorSelection.single(0),
182
- });
183
- continue;
184
- }
185
-
186
- // Replace the match
187
- const replacement = view.state.toText(query.getReplacement(next));
188
- view.dispatch({
189
- changes: [{ from: next.from, to: next.to, insert: replacement }],
190
- userEvent: "input.replace",
191
- });
192
-
193
- // Find next match
194
- return findNext();
195
- }
196
-
197
- return false; // If no matches are found in any view, return false
146
+ const { view, match } = found;
147
+ view.dispatch({
148
+ changes: [
149
+ {
150
+ from: match.from,
151
+ to: match.to,
152
+ insert: view.state.toText(query.getReplacement(match)),
153
+ },
154
+ ],
155
+ userEvent: "input.replace",
156
+ });
157
+ return findNext();
198
158
  });
199
159
 
200
160
  /**
201
161
  * @returns The number of matches in the document for each view.
202
162
  */
203
163
  export const getMatches = searchCommand(({ query }) => {
204
- const views = getAllEditorViews();
205
164
  let count = 0;
206
165
 
207
- // Position in the document, keyed by view and then by to:from
208
- const position = new Map<EditorView, Map<string, number>>();
209
- for (const view of views) {
210
- const matches = query.matchAll(view.state, 1e9) || [];
166
+ // Position in the document, keyed by cell and then by to:from
167
+ const position = new Map<CellId, Map<string, number>>();
168
+ for (const { cellId, state } of getCellDocuments()) {
169
+ const matches = query.matchAll(state, 1e9) || [];
211
170
  for (const match of matches) {
212
171
  const { from, to } = match;
213
- const viewPosition = position.get(view) || new Map<string, number>();
214
- viewPosition.set(`${from}:${to}`, count++);
215
- position.set(view, viewPosition);
172
+ const cellPosition = position.get(cellId) || new Map<string, number>();
173
+ cellPosition.set(`${from}:${to}`, count++);
174
+ position.set(cellId, cellPosition);
216
175
  }
217
176
  }
218
177
 
@@ -57,8 +57,10 @@ export function clearGlobalSearchQuery() {
57
57
  export const searchState: StateField<QueryType> = StateField.define<QueryType>({
58
58
  create() {
59
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.
60
62
  const search = new SearchQuery({
61
- search: state.findText,
63
+ search: state.isOpen ? state.findText : "",
62
64
  caseSensitive: state.caseSensitive,
63
65
  regexp: state.regexp,
64
66
  replace: state.replaceText,
@@ -2,7 +2,9 @@
2
2
 
3
3
  import type { EditorView } from "@codemirror/view";
4
4
  import { atomWithReducer } from "jotai/utils";
5
+ import type { CellId } from "@/core/cells/ids";
5
6
  import { store } from "@/core/state/jotai";
7
+ import { cellIdState } from "../config/extension";
6
8
 
7
9
  interface FindReplaceState {
8
10
  findText: string;
@@ -12,7 +14,7 @@ interface FindReplaceState {
12
14
  regexp: boolean;
13
15
  isOpen: boolean;
14
16
  currentView?: {
15
- view: EditorView;
17
+ cellId: CellId;
16
18
  range: { from: number; to: number };
17
19
  };
18
20
  }
@@ -82,7 +84,10 @@ export const findReplaceAtom = atomWithReducer<FindReplaceState, Action>(
82
84
  case "setCurrentView":
83
85
  return {
84
86
  ...state,
85
- currentView: { view: action.view, range: action.range },
87
+ currentView: {
88
+ cellId: action.view.state.facet(cellIdState),
89
+ range: action.range,
90
+ },
86
91
  };
87
92
  case "clearCurrentView":
88
93
  return { ...state, currentView: undefined };
@@ -9,53 +9,48 @@ import { Logger } from "@/utils/Logger";
9
9
  import { Objects } from "../../utils/objects";
10
10
  import { getNotebook } from "../cells/cells";
11
11
  import type { CellId } from "../cells/ids";
12
- import { notebookCellEditorViews } from "../cells/utils";
13
12
  import { getResolvedMarimoConfig } from "../config/config";
14
13
  import type { ConnectionName } from "../datasets/engines";
15
14
  import { getRequestClient } from "../network/requests";
15
+ import { store } from "../state/jotai";
16
+ import { writeCellCode } from "./cell-documents";
17
+ import { notebookCellCodes } from "./copilot/getCodes";
16
18
  import { languageAdapterState } from "./language/extension";
17
19
  import { SCHEMA_CACHE } from "./language/languages/sql/completion-store";
18
20
  import { isKnownDialect } from "./language/languages/sql/utils";
19
- import { prepareCellCodeUpdate } from "./language/cell-code";
20
- import { getEditorCodeAsPython } from "./language/utils";
21
21
  import { replaceEditorContent } from "./replace-editor-content";
22
22
 
23
23
  export const formattingChangeEffect = StateEffect.define<boolean>();
24
24
 
25
25
  /**
26
- * Format the code in the editor views via the marimo server,
27
- * and update the editor views with the formatted code.
26
+ * Format cells via the marimo server and write back the cells that changed.
27
+ * Cells without an editor are formatted from the notebook document.
28
28
  */
29
- export async function formatEditorViews(views: Record<CellId, EditorView>) {
30
- const { sendFormat } = getRequestClient();
31
- const codes = Objects.mapValues(views, (view) => getEditorCodeAsPython(view));
32
-
33
- const formatResponse = await sendFormat({
29
+ export async function formatCells(cellIds: readonly CellId[]) {
30
+ const allCodes = store.get(notebookCellCodes);
31
+ const codes = Objects.fromEntries(
32
+ cellIds
33
+ .filter((cellId) => cellId in allCodes)
34
+ .map((cellId) => [cellId, allCodes[cellId]]),
35
+ );
36
+
37
+ const { codes: formattedCodes } = await getRequestClient().sendFormat({
34
38
  codes,
35
39
  lineLength: getResolvedMarimoConfig().formatting.line_length,
36
40
  });
37
41
 
38
- for (const [cellIdString, formattedCode] of Objects.entries(
39
- formatResponse.codes,
40
- )) {
41
- const cellId = cellIdString as CellId;
42
- const originalCode = codes[cellId];
43
- const view = views[cellId];
44
-
45
- if (!view) {
46
- continue;
47
- }
48
-
49
- // Only update the editor view if the formatted code is different
50
- // from the original code
51
- if (formattedCode === originalCode) {
42
+ const currentCodes = store.get(notebookCellCodes);
43
+ for (const cellId of Objects.keys(codes)) {
44
+ const formattedCode = formattedCodes[cellId];
45
+ const unchanged =
46
+ formattedCode === undefined || formattedCode === codes[cellId];
47
+ const editedSinceRequest = currentCodes[cellId] !== codes[cellId];
48
+ if (unchanged || editedSinceRequest) {
52
49
  continue;
53
50
  }
54
-
55
- const update = prepareCellCodeUpdate(view.state, formattedCode);
56
- if (update) {
57
- view.dispatch(update, { effects: formattingChangeEffect.of(true) });
58
- }
51
+ writeCellCode(cellId, formattedCode, {
52
+ effects: [formattingChangeEffect.of(true)],
53
+ });
59
54
  }
60
55
  }
61
56
 
@@ -63,8 +58,7 @@ export async function formatEditorViews(views: Record<CellId, EditorView>) {
63
58
  * Format all cells in the notebook.
64
59
  */
65
60
  export function formatAll() {
66
- const views = notebookCellEditorViews(getNotebook());
67
- return formatEditorViews(views);
61
+ return formatCells(getNotebook().cellIds);
68
62
  }
69
63
 
70
64
  /**
@@ -58,10 +58,10 @@ describe("goToDefinitionAtCursorPosition", () => {
58
58
 
59
59
  const notebook = initialNotebookState();
60
60
  notebook.cellHandles[definingCell] = {
61
- current: { editorView: definingView, editorViewOrNull: definingView },
61
+ current: { editorView: definingView },
62
62
  };
63
63
  notebook.cellHandles[usageCell] = {
64
- current: { editorView: usageView, editorViewOrNull: usageView },
64
+ current: { editorView: usageView },
65
65
  };
66
66
 
67
67
  store.set(notebookAtom, notebook);
@@ -95,10 +95,10 @@ def test():
95
95
 
96
96
  const notebook = initialNotebookState();
97
97
  notebook.cellHandles[globalCell] = {
98
- current: { editorView: globalView, editorViewOrNull: globalView },
98
+ current: { editorView: globalView },
99
99
  };
100
100
  notebook.cellHandles[localCell] = {
101
- current: { editorView: localView, editorViewOrNull: localView },
101
+ current: { editorView: localView },
102
102
  };
103
103
 
104
104
  store.set(notebookAtom, notebook);
@@ -151,10 +151,10 @@ print(mymodule)`;
151
151
 
152
152
  const notebook = initialNotebookState();
153
153
  notebook.cellHandles[moduleCell] = {
154
- current: { editorView: moduleView, editorViewOrNull: moduleView },
154
+ current: { editorView: moduleView },
155
155
  } as never;
156
156
  notebook.cellHandles[usageCell] = {
157
- current: { editorView: usageView, editorViewOrNull: usageView },
157
+ current: { editorView: usageView },
158
158
  } as never;
159
159
 
160
160
  store.set(notebookAtom, notebook);
@@ -186,17 +186,16 @@ print(mymodule)`;
186
186
  // The defining cell's editor build still waits in the mount queue, the
187
187
  // state right after a large notebook opens.
188
188
  const handle: { current: CellHandle | null } = { current: null };
189
- editorMountScheduler.request(definingCell, () => {
189
+ editorMountScheduler.register(definingCell, () => {
190
190
  handle.current = {
191
191
  editorView: definingView,
192
- editorViewOrNull: definingView,
193
192
  };
194
193
  });
195
194
 
196
195
  const notebook = initialNotebookState();
197
196
  notebook.cellHandles[definingCell] = handle;
198
197
  notebook.cellHandles[usageCell] = {
199
- current: { editorView: usageView, editorViewOrNull: usageView },
198
+ current: { editorView: usageView },
200
199
  };
201
200
 
202
201
  store.set(notebookAtom, notebook);
@@ -18,6 +18,13 @@ import { LanguageAdapters } from "./LanguageAdapters";
18
18
  import { sqlDialectEffect } from "./languages/sql/sql";
19
19
  import { languageMetadataField, setLanguageMetadata } from "./metadata";
20
20
 
21
+ /** What an editor would show for cell source: the language and its text. */
22
+ export function parseCellCode(source: string) {
23
+ const adapter = languageAdapterFromCode(source);
24
+ const [text, , metadata] = adapter.transformIn(source);
25
+ return { adapter, text, metadata };
26
+ }
27
+
21
28
  /** The Python source represented by the editor's text and language metadata. */
22
29
  export function getCellCode(state: EditorState): string {
23
30
  const text = state.doc.toString();
@@ -37,6 +37,21 @@ type TestLanguageServerClient = ILanguageServerClient & {
37
37
 
38
38
  type GetNotebookEditors = () => Record<CellId, EditorView | null | undefined>;
39
39
 
40
+ // The notebook the mocked store reports, so writes find the same editors.
41
+ let mountedEditors: ReturnType<GetNotebookEditors> = {};
42
+
43
+ function notebookWithMountedEditors() {
44
+ return {
45
+ ...initialNotebookState(),
46
+ cellHandles: Object.fromEntries(
47
+ Object.entries(mountedEditors).map(([cellId, view]) => [
48
+ cellId,
49
+ { current: { editorView: view } },
50
+ ]),
51
+ ),
52
+ };
53
+ }
54
+
40
55
  function replaceNotebookEditors(
41
56
  client: NotebookLanguageServerClient,
42
57
  getNotebookEditors: GetNotebookEditors,
@@ -45,6 +60,7 @@ function replaceNotebookEditors(
45
60
  getNotebookEditors: GetNotebookEditors;
46
61
  };
47
62
  mutableClient.getNotebookEditors = getNotebookEditors;
63
+ mountedEditors = getNotebookEditors();
48
64
  }
49
65
 
50
66
  function isPublishDiagnosticsNotification(
@@ -339,6 +355,9 @@ describe("NotebookLanguageServerClient", () => {
339
355
 
340
356
  // Mock the atom instead of the instance method
341
357
  vi.spyOn(store, "get").mockImplementation((atom) => {
358
+ if (atom === notebookAtom) {
359
+ return notebookWithMountedEditors();
360
+ }
342
361
  if (atom === topologicalCodesAtom) {
343
362
  return {
344
363
  cellIds: [Cells.cell1, Cells.cell2, Cells.cell3],
@@ -1370,6 +1389,9 @@ describe("NotebookLanguageServerClient", () => {
1370
1389
 
1371
1390
  // Update the mock to return the correct codes
1372
1391
  vi.spyOn(store, "get").mockImplementation((atom) => {
1392
+ if (atom === notebookAtom) {
1393
+ return notebookWithMountedEditors();
1394
+ }
1373
1395
  if (atom === topologicalCodesAtom) {
1374
1396
  return {
1375
1397
  cellIds: [Cells.cell1, Cells.cell2, Cells.cell3],
@@ -1481,6 +1503,9 @@ describe("NotebookLanguageServerClient", () => {
1481
1503
 
1482
1504
  // Update the mock to return the correct codes
1483
1505
  vi.spyOn(store, "get").mockImplementation((atom) => {
1506
+ if (atom === notebookAtom) {
1507
+ return notebookWithMountedEditors();
1508
+ }
1484
1509
  if (atom === topologicalCodesAtom) {
1485
1510
  return {
1486
1511
  cellIds: [Cells.cell1, Cells.cell2],
@@ -10,9 +10,9 @@ import { Logger } from "@/utils/Logger";
10
10
  import { LRUCache } from "@/utils/lru";
11
11
  import { Objects } from "@/utils/objects";
12
12
  import { isRecord } from "@/utils/records";
13
+ import { writeCellCode } from "../cell-documents";
13
14
  import { getPositionAtWordBounds } from "../completion/hints";
14
15
  import { topologicalCodesAtom } from "../copilot/getCodes";
15
- import { prepareCellCodeUpdate } from "../language/cell-code";
16
16
  import { getEditorCodeAsPython } from "../language/utils";
17
17
  import { createNotebookLens, type NotebookLens } from "./lens";
18
18
  import { normalizeLspDocumentation } from "./normalize-markdown-math";
@@ -88,7 +88,7 @@ class Snapshotter {
88
88
 
89
89
  const defaultGetNotebookEditors = () => {
90
90
  const evs = getNotebook().cellHandles;
91
- return Objects.mapValues(evs, (r) => r.current?.editorViewOrNull);
91
+ return Objects.mapValues(evs, (r) => r.current?.editorView);
92
92
  };
93
93
 
94
94
  function normalizeTextDocumentation(
@@ -756,22 +756,12 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
756
756
  continue;
757
757
  }
758
758
 
759
- if (!ev) {
760
- Logger.warn(
761
- "[lsp] No editor view for cell during rename",
762
- currentCellId,
763
- );
764
- failedCells.push(currentCellId);
765
- continue;
766
- }
767
-
768
759
  // Only update if it has changed
769
- const code = getEditorCodeAsPython(ev);
760
+ const code = ev
761
+ ? getEditorCodeAsPython(ev)
762
+ : getNotebook().cellData[currentCellId]?.code;
770
763
  if (code !== newCode) {
771
- const update = prepareCellCodeUpdate(ev.state, newCode);
772
- if (update) {
773
- ev.dispatch(update);
774
- }
764
+ writeCellCode(currentCellId, newCode);
775
765
  updatedCount++;
776
766
  }
777
767
  }
@@ -0,0 +1,67 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+ import type { EditorView } from "@codemirror/view";
3
+ import { useEffect, useRef, useState, type RefObject } from "react";
4
+ import useEvent from "react-use-event-hook";
5
+ import { createSharedIntersectionObserver } from "@/utils/shared-intersection-observer";
6
+ import { editorMountScheduler } from "./editor-mount-scheduler";
7
+
8
+ const observeEditor = createSharedIntersectionObserver({
9
+ rootMargin: "300px 0px",
10
+ threshold: 0,
11
+ });
12
+
13
+ /**
14
+ * Owns registration, viewport eligibility, and the editor's entire lifetime.
15
+ * `build` must assign `editorViewRef`; construct inside it so a deferred
16
+ * editor starts from the latest code and configuration.
17
+ */
18
+ export function useLazyEditorMount({
19
+ cellId,
20
+ editorViewRef,
21
+ build,
22
+ hidden,
23
+ }: {
24
+ cellId: string;
25
+ editorViewRef: RefObject<EditorView | null>;
26
+ build: () => void;
27
+ hidden: boolean;
28
+ }) {
29
+ const elementRef = useRef<HTMLDivElement>(null);
30
+ const [mounted, setMounted] = useState(false);
31
+ const buildLatest = useEvent(() => {
32
+ build();
33
+ setMounted(true);
34
+ });
35
+
36
+ useEffect(() => {
37
+ setMounted(false);
38
+ const cancel = editorMountScheduler.register(cellId, buildLatest);
39
+ return () => {
40
+ cancel();
41
+ editorViewRef.current?.destroy();
42
+ editorViewRef.current = null;
43
+ };
44
+ }, [cellId, buildLatest, editorViewRef]);
45
+
46
+ const awaitsVisibility = !mounted && !hidden;
47
+ useEffect(() => {
48
+ const element = elementRef.current;
49
+ if (!awaitsVisibility || !element) {
50
+ return;
51
+ }
52
+ const release = observeEditor(element, (visible) => {
53
+ if (visible) {
54
+ editorMountScheduler.prioritize(cellId);
55
+ } else {
56
+ editorMountScheduler.deprioritize(cellId);
57
+ }
58
+ });
59
+ return () => {
60
+ release();
61
+ editorMountScheduler.deprioritize(cellId);
62
+ };
63
+ }, [cellId, awaitsVisibility]);
64
+
65
+ const promote = useEvent(() => editorMountScheduler.promote(cellId));
66
+ return { elementRef, mounted, promote };
67
+ }
@@ -66,13 +66,9 @@ export function focusInputAndMoveToEnd(
66
66
  * https://github.com/marimo-team/marimo/issues/10222
67
67
  */
68
68
  export function scrollOwnerCell(view: EditorView): void {
69
- const cell = view.dom.closest(".marimo-cell");
70
- if (!cell) {
71
- return;
72
- }
73
-
69
+ // Look the cell up in the frame: a freshly built editor is attached later.
74
70
  requestAnimationFrame(() => {
75
- cell.scrollIntoView({
71
+ view.dom.closest(".marimo-cell")?.scrollIntoView({
76
72
  behavior: "instant",
77
73
  block: "nearest",
78
74
  inline: "nearest",