@marimo-team/islands 0.26.1-dev25 → 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-Bs2ehxEI.js → ErrorBoundary-CPcZlpvU.js} +1 -1
  2. package/dist/{chat-ui-DOvIzlMA.js → chat-ui-CWmSnBs8.js} +899 -899
  3. package/dist/{code-visibility-BnMkbydx.js → code-visibility-CHvnQsso.js} +2 -2
  4. package/dist/{common-CQur5dRA.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-BXEY35Xl.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-BAOp7zqu.js → feedback-button-CodkZ3hF.js} +19 -19
  10. package/dist/{glide-data-editor-Ce94qTW7.js → glide-data-editor-BZxvtSp-.js} +35 -35
  11. package/dist/{globals-Uqg4j5z5.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-Br_Vp3Ws.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-B7TgfbYJ.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
@@ -3,7 +3,7 @@ import { g as t, h as n, m as r, s as i } from "./button-Z2R2272J.js";
3
3
  import { t as a } from "./react-Bgs_wQh3.js";
4
4
  import { t as o } from "./compiler-runtime-C5KHtL5D.js";
5
5
  import { t as s } from "./tooltip-DSWC_Td_.js";
6
- import { l as c, t as l } from "./config-DL9e-OWE.js";
6
+ import { l as c, t as l } from "./config-1ku0tAiU.js";
7
7
  import { t as u } from "./jsx-runtime-D8btoEHk.js";
8
8
  import { d } from "./use-restore-focus-ocw7t85i.js";
9
9
  import { n as f } from "./error-banner-D-AC7pQx.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marimo-team/islands",
3
- "version": "0.26.1-dev25",
3
+ "version": "0.26.1-dev29",
4
4
  "main": "dist/main.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -0,0 +1,45 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+ import { vi } from "vitest";
3
+
4
+ export function mockIntersectionObservers() {
5
+ const observers: ReturnType<typeof createObserver>[] = [];
6
+ function createObserver(callback: IntersectionObserverCallback) {
7
+ const observer = {
8
+ root: null,
9
+ rootMargin: "0px",
10
+ scrollMargin: "0px",
11
+ thresholds: [0],
12
+ observe: vi.fn(),
13
+ unobserve: vi.fn(),
14
+ disconnect: vi.fn(),
15
+ takeRecords: () => [],
16
+ emit(target: Element, visible: boolean) {
17
+ const rect = new DOMRect();
18
+ callback(
19
+ [
20
+ {
21
+ target,
22
+ isIntersecting: visible,
23
+ intersectionRatio: visible ? 1 : 0,
24
+ time: 0,
25
+ boundingClientRect: rect,
26
+ intersectionRect: rect,
27
+ rootBounds: rect,
28
+ },
29
+ ],
30
+ observer,
31
+ );
32
+ },
33
+ };
34
+ return observer;
35
+ }
36
+ vi.stubGlobal(
37
+ "IntersectionObserver",
38
+ vi.fn(function (callback: IntersectionObserverCallback) {
39
+ const observer = createObserver(callback);
40
+ observers.push(observer);
41
+ return observer;
42
+ }),
43
+ );
44
+ return observers;
45
+ }
@@ -1,5 +1,5 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
- import { getCellEditorView } from "@/core/cells/cells";
2
+ import { ensureCellEditorView } from "@/core/cells/cells";
3
3
  import type { CellId } from "@/core/cells/ids";
4
4
  import { goToVariableDefinition } from "@/core/codemirror/go-to-definition/commands";
5
5
  import { store } from "@/core/state/jotai";
@@ -22,7 +22,7 @@ export const EngineVariable: React.FC<Props> = ({
22
22
  if (!cellId) {
23
23
  return;
24
24
  }
25
- const editorView = getCellEditorView(cellId);
25
+ const editorView = ensureCellEditorView(cellId);
26
26
  if (editorView) {
27
27
  goToVariableDefinition(editorView, variableName);
28
28
  }
@@ -14,7 +14,7 @@ import {
14
14
  } from "lucide-react";
15
15
  import React, { memo, useId } from "react";
16
16
  import { type Edge, Panel } from "reactflow";
17
- import { getCellEditorView } from "@/core/cells/cells";
17
+ import { ensureCellEditorView } from "@/core/cells/cells";
18
18
  import { useCellActions } from "@/core/cells/actions";
19
19
  import type { CellId } from "@/core/cells/ids";
20
20
  import { goToVariableDefinition } from "@/core/codemirror/go-to-definition/commands";
@@ -133,7 +133,7 @@ export const GraphSelectionPanel: React.FC<{
133
133
 
134
134
  // Highlight the variable in the cell editor
135
135
  const highlightInCell = (cellId: CellId, variableName: string) => {
136
- const editorView = getCellEditorView(cellId);
136
+ const editorView = ensureCellEditorView(cellId);
137
137
  if (editorView) {
138
138
  goToVariableDefinition(editorView, variableName);
139
139
  }
@@ -44,7 +44,7 @@ import { showHiddenCodeAtom } from "@/core/cells/editor";
44
44
  import { type CellId, SETUP_CELL_ID } from "@/core/cells/ids";
45
45
  import { useNotebookDocumentEdit } from "@/core/notebook/document";
46
46
  import type { CellData } from "@/core/cells/types";
47
- import { formatEditorViews } from "@/core/codemirror/format";
47
+ import { formatCells } from "@/core/codemirror/format";
48
48
  import {
49
49
  getCurrentLanguageAdapter,
50
50
  toggleToLanguage,
@@ -185,13 +185,7 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
185
185
  icon: <Code2Icon size={13} strokeWidth={1.5} />,
186
186
  label: "Format",
187
187
  hotkey: "cell.format",
188
- handle: () => {
189
- const editorView = getEditorView();
190
- if (!editorView) {
191
- return;
192
- }
193
- formatEditorViews({ [cellId]: editorView });
194
- },
188
+ handle: () => formatCells([cellId]),
195
189
  },
196
190
  {
197
191
  icon: config.hide_code ? (
@@ -0,0 +1,40 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+ import { render, cleanup } from "@testing-library/react";
3
+ import { afterEach, expect, it } from "vitest";
4
+ import { CodePlaceholder } from "../code-placeholder";
5
+
6
+ afterEach(cleanup);
7
+
8
+ it("keeps every line searchable, highlighted, and escaped without an editor", () => {
9
+ const code = Array.from({ length: 100 }, (_, i) => `x${i} = "<script>"`).join(
10
+ "\n",
11
+ );
12
+ const { container } = render(<CodePlaceholder code={code} />);
13
+ expect(container.textContent).toBe(code);
14
+ expect(container.querySelector(".tok-string")).not.toBeNull();
15
+ expect(container.querySelector("script")).toBeNull();
16
+ expect(container.querySelector(".cm-editor")).toBeNull();
17
+ });
18
+
19
+ it("shows markdown editor text instead of its Python wrapper", () => {
20
+ const { container } = render(
21
+ <CodePlaceholder code={'mo.md(r"""hello""")'} />,
22
+ );
23
+ expect(container.textContent).toBe("hello");
24
+ });
25
+
26
+ it("renders a bounded number of lines and keeps the rest of a long cell as height", () => {
27
+ const code = Array.from({ length: 5000 }, (_, i) => `x${i} = ${i}`).join(
28
+ "\n",
29
+ );
30
+ const { container } = render(<CodePlaceholder code={code} />);
31
+ const placeholder = container.querySelector<HTMLElement>(
32
+ ".mo-code-placeholder",
33
+ );
34
+
35
+ expect(container.textContent?.split("\n")).toHaveLength(200);
36
+ expect(container.textContent?.startsWith("x0 = 0\n")).toBe(true);
37
+ expect(placeholder?.style.getPropertyValue("--mo-hidden-lines")).toBe("4800");
38
+ expect(placeholder?.style.getPropertyValue("--mo-gutter-digits")).toBe("4");
39
+ expect(container.querySelector(".mo-code-placeholder-rest")).not.toBeNull();
40
+ });
@@ -2,9 +2,8 @@
2
2
  import { historyField } from "@codemirror/commands";
3
3
  import { EditorState, type Extension, StateEffect } from "@codemirror/state";
4
4
  import { EditorView, ViewPlugin } from "@codemirror/view";
5
- import { useIntersectionObserver } from "@uidotdev/usehooks";
6
5
  import { useAtom, useAtomValue, useSetAtom } from "jotai";
7
- import React, { memo, useEffect, useMemo, useRef, useState } from "react";
6
+ import React, { memo, useEffect, useMemo, useRef } from "react";
8
7
  import useEvent from "react-use-event-hook";
9
8
  import { aiCompletionCellAtom } from "@/core/ai/state";
10
9
  import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
@@ -23,7 +22,7 @@ import type { CellData } from "@/core/cells/types";
23
22
  import type { CellRunStatus } from "@/core/executions";
24
23
  import { setupCodeMirror } from "@/core/codemirror/cm";
25
24
  import { acceptCompletionOnEnterAtom } from "@/core/codemirror/completion/accept-on-enter-atom";
26
- import { editorMountScheduler } from "@/core/codemirror/editor-mount-scheduler";
25
+ import { useLazyEditorMount } from "@/core/codemirror/use-lazy-editor-mount";
27
26
  import {
28
27
  getInitialLanguageAdapter,
29
28
  languageAdapterState,
@@ -326,18 +325,6 @@ const CellEditorInternal = ({
326
325
  saveOrNameNotebook,
327
326
  ]);
328
327
 
329
- const handleInitializeEditor = useEvent(() => {
330
- // Create a new editor
331
- const ev = new EditorView({
332
- state: EditorState.create({ doc: code, extensions }),
333
- });
334
- setEditorView(ev);
335
- // Initialize the language adapter
336
- switchLanguage(ev, {
337
- language: getInitialLanguageAdapter(ev.state).type,
338
- });
339
- });
340
-
341
328
  const handleReconfigureEditor = useEvent(() => {
342
329
  invariant(editorViewRef.current !== null, "Editor view is not initialized");
343
330
 
@@ -358,92 +345,44 @@ const CellEditorInternal = ({
358
345
  });
359
346
  });
360
347
 
361
- const handleDeserializeEditor = useEvent(() => {
362
- invariant(serializedEditorState, "Editor view is not initialized");
363
-
364
- const ev = new EditorView({
365
- state: EditorState.fromJSON(
366
- serializedEditorState,
367
- { doc: code, extensions },
368
- { history: historyField },
369
- ),
370
- });
371
- // Initialize the language adapter
372
- switchLanguage(ev, {
373
- language: getInitialLanguageAdapter(ev.state).type,
374
- });
375
- setEditorView(ev);
376
- // The restored state is used once; the next mount builds a fresh editor.
377
- takeRestoredEditorState({ cellId });
378
- });
379
- const [isEditorMounted, setIsEditorMounted] = useState(
380
- serializedEditorState !== null,
381
- );
382
-
383
- // Build the editor. Deserialize eagerly; otherwise queue an async build so
384
- // large notebooks stay responsive while editors come online progressively.
385
- useEffect(() => {
386
- if (editorViewRef.current !== null) {
387
- setIsEditorMounted(true);
388
- return;
389
- }
390
- setIsEditorMounted(false);
391
- if (serializedEditorState !== null) {
392
- handleDeserializeEditor();
393
- setIsEditorMounted(true);
394
- return;
395
- }
396
- editorMountScheduler.request(cellId, () => {
397
- if (editorViewRef.current !== null) {
398
- return;
399
- }
400
- handleInitializeEditor();
401
- setIsEditorMounted(true);
402
- });
403
- return () => editorMountScheduler.cancel(cellId);
404
- }, [
348
+ const {
349
+ elementRef: intersectionRef,
350
+ mounted: isEditorMounted,
351
+ promote,
352
+ } = useLazyEditorMount({
405
353
  cellId,
406
354
  editorViewRef,
407
- handleDeserializeEditor,
408
- handleInitializeEditor,
409
- serializedEditorState,
410
- ]);
355
+ hidden: Boolean(hidden && hasOutput),
356
+ build: () => {
357
+ const config = { doc: code, extensions };
358
+ const state =
359
+ serializedEditorState === null
360
+ ? EditorState.create(config)
361
+ : EditorState.fromJSON(serializedEditorState, config, {
362
+ history: historyField,
363
+ });
364
+ const view = new EditorView({ state });
365
+ switchLanguage(view, { language: getInitialLanguageAdapter(state).type });
366
+ setEditorView(view);
367
+ if (serializedEditorState !== null) {
368
+ takeRestoredEditorState({ cellId });
369
+ }
370
+ },
371
+ });
411
372
 
412
373
  useEffect(() => {
413
- if (editorViewRef.current === null) {
414
- return;
374
+ if (editorViewRef.current !== null) {
375
+ handleReconfigureEditor();
415
376
  }
416
- handleReconfigureEditor();
417
377
  }, [handleReconfigureEditor, extensions, editorViewRef]);
418
378
 
419
- // Destroy the editor when the component is unmounted. Read the ref in cleanup
420
- // (not setup) so Activity hide/show cycles don't leave a stale destroyed view.
379
+ // An AI edit applies to the editor, which a dormant cell does not have yet.
380
+ const isAiCompletionTarget = aiCompletionCell?.cellId === cellId;
421
381
  useEffect(() => {
422
- return () => {
423
- editorViewRef.current?.destroy();
424
- editorViewRef.current = null;
425
- };
426
- }, [editorViewRef]);
427
-
428
- // Prioritize building this cell's editor when it scrolls into view, so the
429
- // visible region fills in first instead of waiting for the top-to-bottom
430
- // queue. The margin builds cells just before they reach the viewport.
431
- // uidotdev sets threshold default to 1. Set it 0 so cells are prioritized
432
- // at 300px.
433
- const [intersectionRef, intersection] = useIntersectionObserver({
434
- rootMargin: "300px 0px",
435
- threshold: 0,
436
- });
437
- useEffect(() => {
438
- if (isEditorMounted) {
439
- return;
382
+ if (isAiCompletionTarget) {
383
+ promote();
440
384
  }
441
- if (intersection?.isIntersecting) {
442
- editorMountScheduler.prioritize(cellId);
443
- } else {
444
- editorMountScheduler.deprioritize(cellId);
445
- }
446
- }, [isEditorMounted, intersection?.isIntersecting, cellId]);
385
+ }, [isAiCompletionTarget, promote]);
447
386
 
448
387
  const navigationProps = useCellEditorNavigationProps(cellId, editorViewRef);
449
388
 
@@ -454,7 +393,7 @@ const CellEditorInternal = ({
454
393
  } else if (hidden) {
455
394
  // Shortens the editor and hides the cell panels
456
395
  editorClassName =
457
- "opacity-20 h-8 [&>div.cm-editor]:h-full [&>div.cm-editor]:overflow-hidden [&_.cm-panels]:hidden";
396
+ "opacity-20 h-8 overflow-hidden [&>div.cm-editor]:h-full [&_.cm-panels]:hidden";
458
397
  }
459
398
 
460
399
  return (
@@ -494,14 +433,20 @@ const CellEditorInternal = ({
494
433
  className="relative w-full"
495
434
  ref={intersectionRef}
496
435
  {...navigationProps}
436
+ onPointerDownCapture={promote}
437
+ onFocusCapture={promote}
438
+ onDoubleClick={(e) => {
439
+ if (hidden) {
440
+ e.stopPropagation();
441
+ showHiddenCode({ focus: true });
442
+ }
443
+ }}
497
444
  >
498
445
  {isEditorMounted ? (
499
446
  <CellCodeMirrorEditor
500
447
  className={editorClassName}
501
448
  editorView={editorViewRef.current}
502
449
  ref={editorViewParentRef}
503
- hidden={hidden}
504
- showHiddenCode={showHiddenCode}
505
450
  />
506
451
  ) : (
507
452
  !isCollapsed && (
@@ -529,12 +474,10 @@ const CellCodeMirrorEditor = React.forwardRef(
529
474
  props: {
530
475
  className?: string;
531
476
  editorView: EditorView | null;
532
- hidden?: boolean;
533
- showHiddenCode?: (opts?: { focus?: boolean }) => void;
534
477
  },
535
478
  ref?: React.Ref<HTMLDivElement>,
536
479
  ) => {
537
- const { className, editorView, hidden, showHiddenCode } = props;
480
+ const { className, editorView } = props;
538
481
  const internalRef = useRef<HTMLDivElement>(null);
539
482
 
540
483
  // If this gets unmounted/remounted, we need to re-append the editorView
@@ -554,12 +497,6 @@ const CellCodeMirrorEditor = React.forwardRef(
554
497
  return (
555
498
  <div
556
499
  className={cn("cm mathjax_ignore", className)}
557
- onDoubleClick={(e) => {
558
- if (hidden && showHiddenCode) {
559
- e.stopPropagation();
560
- showHiddenCode({ focus: true });
561
- }
562
- }}
563
500
  ref={(r) => {
564
501
  if (ref) {
565
502
  mergeRefs(ref, internalRef)(r);
@@ -1,18 +1,68 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ /* Colors mirror core/codemirror/theme/{light,dark}.ts so building the editor does not recolor the code. */
4
+
5
+ /* The editor's line-number gutter pushes its text right; leave the same room so the code does not jump. */
2
6
  .mo-code-placeholder {
3
- --mo-skeleton-bar: color-mix(in srgb, var(--muted), var(--foreground) 18%);
4
- cursor: default;
5
- padding: 4px 10px;
6
- font-size: var(--cm-font-size, 0.875rem);
7
+ --mo-gutter-digits: 2;
8
+
9
+ cursor: text;
10
+ padding: 8px 29px 8px
11
+ calc(
12
+ 53.5px + min(var(--mo-gutter-digits) - 1, 1) * 3.1px + max(var(--mo-gutter-digits) - 2, 0) *
13
+ 7.56px
14
+ );
15
+ font-size: var(--marimo-code-editor-font-size, 0.9rem);
16
+ font-family: var(--monospace-font);
17
+ line-height: 1.4;
18
+ white-space: pre-wrap;
19
+ overflow-wrap: anywhere;
20
+ tab-size: 4;
21
+ color: light-dark(#000, #abb2bf);
22
+ }
23
+
24
+ .mo-code-placeholder-rest {
25
+ height: calc(
26
+ var(--mo-hidden-lines) * 1.4 * var(--marimo-code-editor-font-size, 0.9rem)
27
+ );
28
+ }
29
+
30
+ .mo-code-placeholder .tok-keyword {
31
+ color: light-dark(#708, #c678dd);
32
+ font-weight: 500;
33
+ }
34
+
35
+ .mo-code-placeholder .tok-string,
36
+ .mo-code-placeholder .tok-string2 {
37
+ color: light-dark(#a11, #98c379);
38
+ }
39
+
40
+ .mo-code-placeholder .tok-number {
41
+ color: light-dark(#164, #d19a66);
42
+ }
43
+
44
+ .mo-code-placeholder .tok-bool,
45
+ .mo-code-placeholder .tok-atom {
46
+ color: light-dark(#219, #d19a66);
47
+ }
48
+
49
+ .mo-code-placeholder .tok-operator {
50
+ color: light-dark(#a2f, #56b6c2);
51
+ font-weight: 500;
52
+ }
53
+
54
+ .mo-code-placeholder .tok-className {
55
+ color: light-dark(#00f, #61afef);
56
+ }
57
+
58
+ .mo-code-placeholder .tok-typeName {
59
+ color: light-dark(#085, #56b6c2);
7
60
  }
8
61
 
9
- .mo-code-placeholder-line {
10
- display: flex;
11
- align-items: center;
12
- height: 1.5em;
62
+ .mo-code-placeholder .tok-propertyName {
63
+ color: light-dark(#05a, #e5c07b);
13
64
  }
14
65
 
15
- .mo-code-placeholder-bar {
16
- height: 0.7em;
17
- background-color: var(--mo-skeleton-bar);
66
+ .mo-code-placeholder .tok-comment {
67
+ color: var(--cm-comment);
18
68
  }
@@ -1,5 +1,11 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
  import "./code-placeholder.css";
3
+ import { markdownLanguage } from "@codemirror/lang-markdown";
4
+ import { pythonLanguage } from "@codemirror/lang-python";
5
+ import { SQLDialect } from "@codemirror/lang-sql";
6
+ import { classHighlighter, highlightTree } from "@lezer/highlight";
7
+ import { type CSSProperties, type ReactNode, useMemo } from "react";
8
+ import { parseCellCode } from "@/core/codemirror/language/cell-code";
3
9
  import { cn } from "@/utils/cn";
4
10
 
5
11
  interface CodePlaceholderProps {
@@ -7,43 +13,60 @@ interface CodePlaceholderProps {
7
13
  className?: string;
8
14
  }
9
15
 
10
- // Bound the rendered bars so a very long cell does not create excessive nodes.
11
- const MAX_LINES = 50;
12
- const MIN_LINE_WIDTH_CH = 4;
13
- const MAX_LINE_WIDTH_CH = 60;
16
+ const parsers = {
17
+ python: pythonLanguage.parser,
18
+ markdown: markdownLanguage.parser,
19
+ sql: SQLDialect.define({}).language.parser,
20
+ };
14
21
 
15
- function getLineWidthCh(length: number): number {
16
- return Math.min(MAX_LINE_WIDTH_CH, Math.max(MIN_LINE_WIDTH_CH, length));
17
- }
22
+ // Rendering every line of every offscreen cell is unbounded work. The rest of a
23
+ // long cell is a spacer, so the layout still matches the editor.
24
+ const MAX_RENDERED_LINES = 200;
18
25
 
19
- /**
20
- * Stand-in shown while a cell's CodeMirror editor has not been built yet.
21
- * one skeleton bar per code line, so the final render doesn't cause a big jump.
22
- *
23
- * The bars are static: a large notebook shows thousands of them at once, and
24
- * animating each one makes every stylesheet change restyle all of them.
25
- */
26
26
  export const CodePlaceholder = ({ code, className }: CodePlaceholderProps) => {
27
- const lines = code.split("\n", MAX_LINES);
27
+ const { content, gutterDigits, hiddenLines } = useMemo(() => {
28
+ const { adapter, text: fullText } = parseCellCode(code);
29
+ const lines = fullText.split("\n");
30
+ const text = lines.slice(0, MAX_RENDERED_LINES).join("\n");
31
+ const hiddenLines = Math.max(0, lines.length - MAX_RENDERED_LINES);
32
+ const parser = parsers[adapter.type];
33
+ const nodes: ReactNode[] = [];
34
+ let position = 0;
35
+ highlightTree(parser.parse(text), classHighlighter, (from, to, classes) => {
36
+ if (from > position) {
37
+ nodes.push(text.slice(position, from));
38
+ }
39
+ nodes.push(
40
+ <span key={from} className={classes}>
41
+ {text.slice(from, to)}
42
+ </span>,
43
+ );
44
+ position = to;
45
+ });
46
+ nodes.push(text.slice(position));
47
+ // A final newline needs a following character to occupy its own line.
48
+ if (!text || text.endsWith("\n")) {
49
+ nodes.push("\u200b");
50
+ }
51
+ return {
52
+ content: nodes,
53
+ gutterDigits: String(lines.length).length,
54
+ hiddenLines,
55
+ };
56
+ }, [code]);
28
57
  return (
29
58
  <div
30
59
  className={cn("cm", "mo-code-placeholder", className)}
31
60
  data-testid="cell-editor-placeholder"
32
- aria-hidden={true}
61
+ style={
62
+ {
63
+ "--mo-gutter-digits": gutterDigits,
64
+ "--mo-hidden-lines": hiddenLines,
65
+ } as CSSProperties
66
+ }
33
67
  >
34
- {lines.map((line, index) => {
35
- const length = line.trimEnd().length;
36
- return (
37
- <div key={index} className="mo-code-placeholder-line">
38
- {length > 0 && (
39
- <div
40
- className="mo-code-placeholder-bar rounded-md"
41
- style={{ width: `${getLineWidthCh(length)}ch` }}
42
- />
43
- )}
44
- </div>
45
- );
46
- })}
68
+ {content}
69
+ {hiddenLines > 0 && <div className="mo-code-placeholder-rest" />}
47
70
  </div>
48
71
  );
49
72
  };
@@ -3,7 +3,7 @@
3
3
  import useEvent from "react-use-event-hook";
4
4
  import { UndoButton } from "@/components/buttons/undo-button";
5
5
  import { toast } from "@/components/ui/use-toast";
6
- import { getCellEditorView } from "@/core/cells/cells";
6
+ import { ensureCellEditorView } from "@/core/cells/cells";
7
7
  import { useCellActions } from "@/core/cells/actions";
8
8
  import type { CellId } from "@/core/cells/ids";
9
9
  import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
@@ -13,7 +13,7 @@ export function useSplitCellCallback() {
13
13
 
14
14
  return useEvent((opts: { cellId: CellId }): CellId | null => {
15
15
  // Save snapshot of code for undo
16
- const cellEditorView = getCellEditorView(opts.cellId);
16
+ const cellEditorView = ensureCellEditorView(opts.cellId);
17
17
  if (!cellEditorView) {
18
18
  return null;
19
19
  }
@@ -17,19 +17,16 @@ import { PendingAICells } from "../pending-ai-cells";
17
17
  import { PendingAIChangesBadge } from "../pending-ai-changes-badge";
18
18
 
19
19
  const deleteCell = vi.hoisted(() => vi.fn());
20
- const setCellCode = vi.hoisted(() => vi.fn());
20
+ const writeCellCode = vi.hoisted(() => vi.fn());
21
21
 
22
22
  vi.mock("@/components/editor/cell/useDeleteCell", () => ({
23
23
  useDeleteCellCallback: () => deleteCell,
24
24
  }));
25
25
 
26
- vi.mock("@/core/cells/cells", () => ({
27
- getCellEditorView: vi.fn(),
28
- }));
26
+ vi.mock("@/core/codemirror/cell-documents", () => ({ writeCellCode }));
29
27
  vi.mock("@/core/cells/actions", () => ({
30
28
  useCellActions: () => ({
31
29
  createCell: vi.fn(),
32
- setCellCode,
33
30
  }),
34
31
  }));
35
32
 
@@ -243,8 +240,8 @@ it("clears the panel badge when all pending changes are accepted", () => {
243
240
  expect(screen.queryByText("1 pending AI change")).not.toBeInTheDocument();
244
241
  });
245
242
 
246
- it("discards an edit to a cell whose editor is not mounted", () => {
247
- setCellCode.mockClear();
243
+ it("restores the previous code when an edit is discarded", () => {
244
+ writeCellCode.mockClear();
248
245
  const store = createStore();
249
246
  const collapsed = cellId("collapsed-cell");
250
247
  store.set(
@@ -257,9 +254,8 @@ it("discards an edit to a cell whose editor is not mounted", () => {
257
254
  </Provider>,
258
255
  );
259
256
  fireEvent.click(screen.getByRole("button", { name: "Discard" }));
260
- expect(setCellCode).toHaveBeenCalledWith({
261
- cellId: collapsed,
262
- code: "x = 1",
257
+ expect(writeCellCode).toHaveBeenCalledWith(collapsed, "x = 1", {
258
+ initialize: true,
263
259
  });
264
260
  expect(store.get(stagedAICellsAtom).size).toBe(0);
265
261
  });