@marimo-team/islands 0.23.10-dev51 → 0.23.10-dev53

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.
package/dist/main.js CHANGED
@@ -22,17 +22,17 @@ import { _ as Logger, c as Objects, g as cn, h as Events, i as NOT_SET, l as use
22
22
  import { t as require_react } from "./react-DA-nE2FX.js";
23
23
  import { t as require_compiler_runtime } from "./compiler-runtime-CEbnTgxf.js";
24
24
  import { n as Copy, r as toast, t as copyToClipboard } from "./copy-UqRYxiOg.js";
25
- import { $ as reducer, B as safeExtractSetUIElementMessageBuffers, Bn as CircleAlert, Bt as DATA_TYPE_ICON, C as AccordionContent, Cn as Root2$1, Ct as Checkbox, Dn as Table2, Dt as PathBuilder, E as BorderAllIcon, En as Trash2, F as base64ToDataView, Fn as Eye, H as getMarimoExportContext, Ht as require_client, It as jotaiJsonStorage, J as getCellNames, Jt as requestClientAtom, K as createActions, Kt as convertStatsName, L as dataViewToBase64, Ln as Database, Mn as Layers, Mt as generateUUID, Nn as Info, On as PaintRoller, Ot as Paths, Pn as FileText, Pt as repl, Q as numColumnsAtom, Rn as Columns2, S as Accordion, Sn as Item$1, St as normalizeName, T as AccordionTrigger, Tt as MarkdownLanguageAdapter, U as hasTrustedExportContext, V as renderHTML, Vn as Braces, W as hasRunAnyCellAtom, X as notebookAtom, Xt as isUninstantiated, Y as hasOnlyOneCellAtom, Yt as useRequestClient, Z as notebookOutline, _n as atomWithStorage, a as useCellFocusActions, an as parseDataset, bt as getValidName, cn as HTMLCellId, ct as initialModeAtom, dn as findCellId, et as useCellActions, f as isOutputEmpty, fn as OBJECT_ID_ATTR, ft as outputIsLoading, gn as atomWithReducer, ht as headingToIdentifier, i as LazyAnyLanguageCodeMirror, in as parseAttrValue, jn as LoaderCircle, jt as DeferredRequestRegistry, k as ChevronDownIcon, lt as kioskModeAtom, mn as jsonParseWithSpecialChar, mt as isErrorMime, n as Spinner, o as useLastFocusedCellId, on as parseInitialValue, p as useExpandedConsoleOutput, pn as RANDOM_ID_ATTR, pt as outputIsStale, qt as getRequestClient, rt as createCell, s as maybeAddAltairImport, st as getInitialAppMode, tn as NotebookScopedLocalStorage, tt as useCellIds, un as UIElementId, vn as selectAtom, w as AccordionItem, wn as Trigger2, wt as customPythonLanguageSupport, xn as Content2, xt as isInternalCellName, zt as PluralWords, __tla as __tla_0 } from "./html-to-image-DXSdAI_Y.js";
25
+ import { $ as reducer, B as safeExtractSetUIElementMessageBuffers, Bn as CircleAlert, Bt as DATA_TYPE_ICON, C as AccordionContent, Cn as Root2$1, Ct as Checkbox, Dn as Table2, Dt as PathBuilder, E as BorderAllIcon, En as Trash2, F as base64ToDataView, Fn as Eye, H as getMarimoExportContext, Ht as require_client, It as jotaiJsonStorage, J as getCellNames, Jt as requestClientAtom, K as createActions, Kt as convertStatsName, L as dataViewToBase64, Ln as Database, Mn as Layers, Mt as generateUUID, Nn as Info, On as PaintRoller, Ot as Paths, Pn as FileText, Pt as repl, Q as numColumnsAtom, Rn as Columns2, S as Accordion, Sn as Item$1, St as normalizeName, T as AccordionTrigger, Tt as MarkdownLanguageAdapter, U as hasTrustedExportContext, V as renderHTML, Vn as Braces, W as hasRunAnyCellAtom, X as notebookAtom, Xt as isUninstantiated, Y as hasOnlyOneCellAtom, Yt as useRequestClient, Z as notebookOutline, _n as atomWithStorage, a as useCellFocusActions, an as parseDataset, bt as getValidName, cn as HTMLCellId, ct as initialModeAtom, dn as findCellId, et as useCellActions, f as isOutputEmpty, fn as OBJECT_ID_ATTR, ft as outputIsLoading, gn as atomWithReducer, ht as headingToIdentifier, i as LazyAnyLanguageCodeMirror, in as parseAttrValue, jn as LoaderCircle, jt as DeferredRequestRegistry, k as ChevronDownIcon, lt as kioskModeAtom, mn as jsonParseWithSpecialChar, mt as isErrorMime, n as Spinner, o as useLastFocusedCellId, on as parseInitialValue, p as useExpandedConsoleOutput, pn as RANDOM_ID_ATTR, pt as outputIsStale, qt as getRequestClient, rt as createCell, s as maybeAddAltairImport, st as getInitialAppMode, tn as NotebookScopedLocalStorage, tt as useCellIds, un as UIElementId, vn as selectAtom, w as AccordionItem, wn as Trigger2, wt as customPythonLanguageSupport, xn as Content2, xt as isInternalCellName, zt as PluralWords, __tla as __tla_0 } from "./html-to-image-BEeeScWH.js";
26
26
  import { __tla as __tla_1 } from "./chunk-5FQGJX7Z-BbqSm5gU.js";
27
27
  import { o as useSize, s as Root$1, u as createLucideIcon } from "./dist-Dk6PV_d3.js";
28
28
  import { A as SquareFunction, C as DEFAULT_COLOR_SCHEME, D as SCALE_TYPE_DESCRIPTIONS, E as EMPTY_VALUE$1, O as TIME_UNIT_DESCRIPTIONS, S as DEFAULT_AGGREGATION, T as DEFAULT_TIME_UNIT, _ as AGGREGATION_TYPE_DESCRIPTIONS, a as AGGREGATION_FNS$1, b as COLOR_SCHEMES, c as COLOR_BY_FIELDS, d as NONE_VALUE, f as SELECTABLE_DATA_TYPES, g as TIME_UNITS, h as STRING_AGGREGATION_FNS, i as convertDataTypeToSelectable, j as ChartColumn, k as escapeFieldName, l as COMBINED_TIME_UNITS, m as SORT_TYPES, n as createSpecWithoutData, o as BIN_AGGREGATION, p as SINGLE_TIME_UNITS, r as isFieldSet, s as CHART_TYPES, t as augmentSpecWithData, u as ChartType, v as AGGREGATION_TYPE_ICON, w as DEFAULT_MAX_BINS_FACET, x as COUNT_FIELD, y as CHART_TYPE_ICON } from "./spec-X7FwLJni.js";
29
- import { $ as contextAwarePanelOpen, $t as $fae977aafc393c5c$export$6b862160d295c8e, A as prettifyRowCount, At as SELECT_COLUMN_ID, B as DatePicker, Bt as TabsContent, C as downloadSizeLimitAtom, Ct as DelayMount, D as ErrorState, Dt as loadTableAndRawData, E as EmptyState, Et as getPageIndexForRow, F as ContextMenuSeparator, Ft as Maps, G as CommandEmpty, Gt as ChartLoadingState, H as Combobox, Ht as TabsTrigger, I as ContextMenuTrigger, It as dateToLocalISODate, J as CommandList, Jt as RenderTextWithLinks, K as CommandInput, Kt as LazyVegaEmbed, L as useInternalStateWithSync, Lt as dateToLocalISODateTime, M as ContextMenu, Mt as toFieldTypes, N as ContextMenuContent, Nt as getMimeValues, O as LoadingState, Ot as loadTableData, P as ContextMenuItem, Pt as isNullishFilter, Q as PANEL_TYPES, Qt as $fae977aafc393c5c$export$588937bcd60ade55, R as useSelectList, Rt as dateToLocalISOTime, S as Filenames, St as ColumnChartSpecModel, T as ColumnPreviewContainer, Tt as usePrevious$1, U as ComboboxItem, Ut as ChartErrorState, V as DateRangePicker, Vt as TabsList, W as Command, Wt as ChartInfoState, X as smartMatch, Xt as HtmlOutput, Y as CommandSeparator, Yt as Kbd, Z as ContextAwarePanelItem, Zt as EmotionCacheProvider, _ as ADD_PRINTING_CLASS, _t as NAMELESS_COLUMN_PREFIX, an as Ellipsis, at as Toggle, b as downloadHTMLAsImage, bt as renderCellValue, c as Slide, cn as ChevronsUpDown, d as RadioGroupItem, dn as ChevronsDownUp, dt as Table, en as TextWrap, et as contextAwarePanelOwner, f as JsonOutput, fn as ChevronLeft, ft as TableBody, g as InstallPackageButton, gt as TableRow, h as DataTable, ht as TableHeader, it as slotsController, j as getColumnCountForDisplay, jt as TOO_MANY_ROWS, k as prettifyRowColumnCount, kt as INDEX_COLUMN_NAME, l as Switch, ln as ChevronsRight, lt as Fill, m as OutputRenderer, mt as TableHead, n as marimoVersionAtom, nn as Funnel, nt as isCellAwareAtom, o as SLIDE_TYPE_OPTIONS_BY_VALUE, on as Download, p as OutputArea, pn as ArrowDownWideNarrow, pt as TableCell, q as CommandItem, qt as useOverflowDetection, r as showCodeInRunModeAtom, rn as EyeOff, rt as SlotNames, sn as Code, t as useNotebookCodeAvailable, tn as GripHorizontal, tt as contextAwarePanelType, u as RadioGroup, un as ChevronsLeft, ut as Provider$1, v as downloadBlob, vt as generateColumns, w as ColumnName, wt as useIntersectionObserver, x as Progress, xt as ColumnChartContext, y as downloadByURL, yt as inferFieldTypes, z as CompactChipRow, zt as Tabs, __tla as __tla_2 } from "./code-visibility-B5jSPI0-.js";
29
+ import { $ as contextAwarePanelOpen, $t as $fae977aafc393c5c$export$6b862160d295c8e, A as prettifyRowCount, At as SELECT_COLUMN_ID, B as DatePicker, Bt as TabsContent, C as downloadSizeLimitAtom, Ct as DelayMount, D as ErrorState, Dt as loadTableAndRawData, E as EmptyState, Et as getPageIndexForRow, F as ContextMenuSeparator, Ft as Maps, G as CommandEmpty, Gt as ChartLoadingState, H as Combobox, Ht as TabsTrigger, I as ContextMenuTrigger, It as dateToLocalISODate, J as CommandList, Jt as RenderTextWithLinks, K as CommandInput, Kt as LazyVegaEmbed, L as useInternalStateWithSync, Lt as dateToLocalISODateTime, M as ContextMenu, Mt as toFieldTypes, N as ContextMenuContent, Nt as getMimeValues, O as LoadingState, Ot as loadTableData, P as ContextMenuItem, Pt as isNullishFilter, Q as PANEL_TYPES, Qt as $fae977aafc393c5c$export$588937bcd60ade55, R as useSelectList, Rt as dateToLocalISOTime, S as Filenames, St as ColumnChartSpecModel, T as ColumnPreviewContainer, Tt as usePrevious$1, U as ComboboxItem, Ut as ChartErrorState, V as DateRangePicker, Vt as TabsList, W as Command, Wt as ChartInfoState, X as smartMatch, Xt as HtmlOutput, Y as CommandSeparator, Yt as Kbd, Z as ContextAwarePanelItem, Zt as EmotionCacheProvider, _ as ADD_PRINTING_CLASS, _t as NAMELESS_COLUMN_PREFIX, an as Ellipsis, at as Toggle, b as downloadHTMLAsImage, bt as renderCellValue, c as Slide, cn as ChevronsUpDown, d as RadioGroupItem, dn as ChevronsDownUp, dt as Table, en as TextWrap, et as contextAwarePanelOwner, f as JsonOutput, fn as ChevronLeft, ft as TableBody, g as InstallPackageButton, gt as TableRow, h as DataTable, ht as TableHeader, it as slotsController, j as getColumnCountForDisplay, jt as TOO_MANY_ROWS, k as prettifyRowColumnCount, kt as INDEX_COLUMN_NAME, l as Switch, ln as ChevronsRight, lt as Fill, m as OutputRenderer, mt as TableHead, n as marimoVersionAtom, nn as Funnel, nt as isCellAwareAtom, o as SLIDE_TYPE_OPTIONS_BY_VALUE, on as Download, p as OutputArea, pn as ArrowDownWideNarrow, pt as TableCell, q as CommandItem, qt as useOverflowDetection, r as showCodeInRunModeAtom, rn as EyeOff, rt as SlotNames, sn as Code, t as useNotebookCodeAvailable, tn as GripHorizontal, tt as contextAwarePanelType, u as RadioGroup, un as ChevronsLeft, ut as Provider$1, v as downloadBlob, vt as generateColumns, w as ColumnName, wt as useIntersectionObserver, x as Progress, xt as ColumnChartContext, y as downloadByURL, yt as inferFieldTypes, z as CompactChipRow, zt as Tabs, __tla as __tla_2 } from "./code-visibility-k6uasT7Y.js";
30
30
  import { c as Calendar, i as createReducerAndAtoms, n as useOnUnmount, o as ToggleLeft, t as useOnMount } from "./useLifecycle-00mO3OSS.js";
31
31
  import { t as Check } from "./check-BCaJeT-J.js";
32
32
  import { A as Icon, C as logNever, D as $18f2051aff69b9bf$export$a54013f0d02a8f82, E as $18f2051aff69b9bf$export$43bb16f9c6d9e3f7, F as createCollection, I as X, M as clamp$2, N as usePrevious$2, P as useDirection, R as ChevronDown, S as assertNever, a as SelectGroup, c as SelectSeparator, d as NativeSelect, i as SelectContent, j as Trigger$1, l as SelectTrigger, n as capitalize, o as SelectItem, r as Select, s as SelectLabel, t as Strings, u as SelectValue, w as $a916eb452884faea$export$b7a616150fdb9f44 } from "./strings-J57tzLr3.js";
33
33
  import { B as $64fa3d84918910a7$export$4d86445c2cf5e3, C as DropdownMenuTrigger, Ft as $65484d02dcb7eb3e$export$457c3d6518dd4c6f, It as $3ef42575df84b30b$export$9d1611c77c2fe928, W as $64fa3d84918910a7$export$df3a06d6289f983e, Wt as $ff5963eb1fccf552$export$e08e3b67e392101e, X as useDebouncedCallback, Y as useDebounceControlledState, a as NumberField, d as roundToFractionDigits, f as DropdownMenu, g as DropdownMenuLabel, gn as ChevronRight, h as DropdownMenuItem, hn as Circle, i as OnBlurredInput, l as prettyNumber, m as DropdownMenuGroup, n as DebouncedNumberInput, o as maxFractionDigitsForSteps, ot as $f7dceffc5ad7768b$export$4e328f61c538687f, p as DropdownMenuContent, pt as $6179b936705e76d3$export$ae780daf29e6d456, r as Input, st as $701a24aa0da5b062$export$ea18c227d4417cc3, t as DebouncedInput, u as prettyScientificNumber, v as DropdownMenuSeparator, xt as $458b0a5536c1a7cf$export$40bfa8c7b0832715, y as DropdownMenuShortcut, z as $64fa3d84918910a7$export$29f1550f4b0d4415 } from "./input-OdWHkobi.js";
34
34
  import { _ as isWasm, c as asRemoteURL, d as isStaticNotebook, f as appendQueryParams, g as Deferred, m as require_cuid2, u as getStaticVirtualFiles, v as CircleQuestionMark } from "./toDate-d8RCRrRd.js";
35
- import { a as MarimoIncomingMessageEvent, c as MarimoValueUpdateEvent, d as Square, f as File, i as PythonIcon, l as createInputEvent, n as blobToString, o as MarimoValueInputEvent, r as filesToBase64, s as MarimoValueReadyEvent, t as processOutput, u as deserializeBlob } from "./process-output-uozPQhBl.js";
35
+ import { a as MarimoIncomingMessageEvent, c as MarimoValueUpdateEvent, d as Square, f as File, i as PythonIcon, l as createInputEvent, n as blobToString, o as MarimoValueInputEvent, r as filesToBase64, s as MarimoValueReadyEvent, t as processOutput, u as deserializeBlob } from "./process-output-CO5geDQU.js";
36
36
  import { n as Trash, r as Pencil, t as BulkEdit } from "./types-ChtMFmZ2.js";
37
37
  import { n as require_prop_types, r as Plus, t as ErrorBoundary } from "./ErrorBoundary-DpbaKVv7.js";
38
38
  import { t as require_react_dom } from "./react-dom-BTJzcVJ9.js";
@@ -8558,7 +8558,7 @@ let __tla = Promise.all([
8558
8558
  };
8559
8559
  }
8560
8560
  };
8561
- var LazyChatbot = import_react.lazy(() => import("./chat-ui-BxwraqS-.js").then((e) => ({
8561
+ var LazyChatbot = import_react.lazy(() => import("./chat-ui-BHx9bULO.js").then((e) => ({
8562
8562
  default: e.Chatbot
8563
8563
  }))), messageSchema = array(object({
8564
8564
  id: string(),
@@ -36187,7 +36187,7 @@ ${c}
36187
36187
  function _temp2$2(e) {
36188
36188
  e.target === e.currentTarget && e.key === "Enter" && (e.preventDefault(), e.stopPropagation(), e.currentTarget.click());
36189
36189
  }
36190
- var LazySlidesComponent = import_react.lazy(() => import("./reveal-component-CBonF0Hv.js"));
36190
+ var LazySlidesComponent = import_react.lazy(() => import("./reveal-component-CnhpfF5l.js"));
36191
36191
  const SlidesLayoutRenderer = ({ layout: e, setLayout: r, cells: c, mode: l }) => {
36192
36192
  var _a3;
36193
36193
  let u = useAtomValue(kioskModeAtom), d = l === "read" || u, f = useAtomValue(numColumnsAtom) > 1, [p, m] = (0, import_react.useState)(null), { slideCells: h, skippedIds: g, noOutputIds: _, slideTypes: v, startCellIndex: y } = (0, import_react.useMemo)(() => computeSlideCellsInfo(c, e), [
@@ -1,6 +1,6 @@
1
1
  import { s as __toESM } from "./chunk-BNovOVIE.js";
2
2
  import { t as require_compiler_runtime } from "./compiler-runtime-CEbnTgxf.js";
3
- import { at as parseHtmlContent, it as ansiToPlainText } from "./html-to-image-DXSdAI_Y.js";
3
+ import { at as parseHtmlContent, it as ansiToPlainText } from "./html-to-image-BEeeScWH.js";
4
4
  import { u as createLucideIcon } from "./dist-Dk6PV_d3.js";
5
5
  import { t as Strings } from "./strings-J57tzLr3.js";
6
6
  import { t as require_jsx_runtime } from "./jsx-runtime-DebpN0FN.js";
@@ -6,10 +6,10 @@ import { s as __toESM } from "./chunk-BNovOVIE.js";
6
6
  import { _ as Logger, g as cn, h as Events, l as useEventListener, t as Button } from "./button-C5K9fIPF.js";
7
7
  import { t as require_react } from "./react-DA-nE2FX.js";
8
8
  import { t as require_compiler_runtime } from "./compiler-runtime-CEbnTgxf.js";
9
- import { lt as kioskModeAtom } from "./html-to-image-DXSdAI_Y.js";
9
+ import { lt as kioskModeAtom } from "./html-to-image-BEeeScWH.js";
10
10
  import "./chunk-5FQGJX7Z-BbqSm5gU.js";
11
11
  import { u as createLucideIcon } from "./dist-Dk6PV_d3.js";
12
- import { a as DEFAULT_SLIDE_TYPE, c as Slide, ct as PanelResizeHandle, i as DEFAULT_DECK_TRANSITION, in as Expand, ot as Panel, rn as EyeOff, s as SlideSidebar, sn as Code, st as PanelGroup, t as useNotebookCodeAvailable } from "./code-visibility-B5jSPI0-.js";
12
+ import { a as DEFAULT_SLIDE_TYPE, c as Slide, ct as PanelResizeHandle, i as DEFAULT_DECK_TRANSITION, in as Expand, ot as Panel, rn as EyeOff, s as SlideSidebar, sn as Code, st as PanelGroup, t as useNotebookCodeAvailable } from "./code-visibility-k6uasT7Y.js";
13
13
  import { X as useDebouncedCallback } from "./input-OdWHkobi.js";
14
14
  import "./toDate-d8RCRrRd.js";
15
15
  import "./react-dom-BTJzcVJ9.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marimo-team/islands",
3
- "version": "0.23.10-dev51",
3
+ "version": "0.23.10-dev53",
4
4
  "main": "dist/main.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -20,6 +20,22 @@ globalThis.ResizeObserver ??= class {
20
20
  }
21
21
  } as never;
22
22
 
23
+ // mock implementation because jsdom doesn't support IntersectionObserver
24
+ globalThis.IntersectionObserver ??= class {
25
+ observe(_target: Element) {
26
+ /* noop */
27
+ }
28
+ unobserve(_target: Element) {
29
+ /* noop */
30
+ }
31
+ disconnect() {
32
+ /* noop */
33
+ }
34
+ takeRecords() {
35
+ return [];
36
+ }
37
+ } as never;
38
+
23
39
  // Global setup for all tests
24
40
  beforeEach(() => {
25
41
  // Reset all mocks before each test
@@ -2,8 +2,9 @@
2
2
  import { historyField } from "@codemirror/commands";
3
3
  import { EditorState, StateEffect } from "@codemirror/state";
4
4
  import { EditorView, ViewPlugin } from "@codemirror/view";
5
+ import { useIntersectionObserver } from "@uidotdev/usehooks";
5
6
  import { useAtom, useAtomValue } from "jotai";
6
- import React, { memo, useEffect, useMemo, useRef } from "react";
7
+ import React, { memo, useEffect, useMemo, useRef, useState } from "react";
7
8
  import useEvent from "react-use-event-hook";
8
9
  import { Button } from "@/components/ui/button";
9
10
  import { DelayMount } from "@/components/utils/delay-mount";
@@ -14,6 +15,7 @@ import { usePendingDeleteService } from "@/core/cells/pending-delete-service";
14
15
  import type { CellData, CellRuntimeState } from "@/core/cells/types";
15
16
  import { setupCodeMirror } from "@/core/codemirror/cm";
16
17
  import { acceptCompletionOnEnterAtom } from "@/core/codemirror/completion/accept-on-enter-atom";
18
+ import { editorMountScheduler } from "@/core/codemirror/editor-mount-scheduler";
17
19
  import {
18
20
  getInitialLanguageAdapter,
19
21
  languageAdapterState,
@@ -45,6 +47,7 @@ import {
45
47
  } from "../../navigation/navigation";
46
48
  import { useDeleteCellCallback } from "../useDeleteCell";
47
49
  import { useSplitCellCallback } from "../useSplitCell";
50
+ import { CodePlaceholder } from "./code-placeholder";
48
51
  import { LanguageToggles } from "./language-toggle";
49
52
 
50
53
  export interface CellEditorProps
@@ -405,38 +408,45 @@ const CellEditorInternal = ({
405
408
  // Clear the serialized state so that we don't re-create the editor next time
406
409
  cellActions.clearSerializedEditorState({ cellId });
407
410
  });
411
+ const [isEditorMounted, setIsEditorMounted] = useState(
412
+ serializedEditorState !== null,
413
+ );
408
414
 
415
+ // Build the editor. Deserialize eagerly; otherwise queue an async build so
416
+ // large notebooks stay responsive while editors come online progressively.
409
417
  useEffect(() => {
410
- if (serializedEditorState === null) {
411
- if (editorViewRef.current === null) {
412
- handleInitializeEditor();
413
- } else {
414
- // If the editor already exists, reconfigure it with the new extensions.
415
- handleReconfigureEditor();
416
- }
417
- } else {
418
- handleDeserializeEditor();
418
+ if (editorViewRef.current !== null) {
419
+ setIsEditorMounted(true);
420
+ return;
419
421
  }
420
-
421
- if (
422
- editorViewRef.current !== null &&
423
- editorViewParentRef &&
424
- editorViewParentRef.current !== null
425
- ) {
426
- // Always replace the children in case the editor view was re-created.
427
- editorViewParentRef.current.replaceChildren(editorViewRef.current.dom);
422
+ if (serializedEditorState !== null) {
423
+ handleDeserializeEditor();
424
+ setIsEditorMounted(true);
425
+ return;
428
426
  }
427
+ editorMountScheduler.request(cellId, () => {
428
+ if (editorViewRef.current !== null) {
429
+ return;
430
+ }
431
+ handleInitializeEditor();
432
+ setIsEditorMounted(true);
433
+ });
434
+ return () => editorMountScheduler.cancel(cellId);
429
435
  }, [
430
- handleInitializeEditor,
431
- handleReconfigureEditor,
432
- handleDeserializeEditor,
436
+ cellId,
433
437
  editorViewRef,
434
- editorViewParentRef,
438
+ handleDeserializeEditor,
439
+ handleInitializeEditor,
435
440
  serializedEditorState,
436
- // Props to trigger reconfiguration
437
- extensions,
438
441
  ]);
439
442
 
443
+ useEffect(() => {
444
+ if (editorViewRef.current === null) {
445
+ return;
446
+ }
447
+ handleReconfigureEditor();
448
+ }, [handleReconfigureEditor, extensions, editorViewRef]);
449
+
440
450
  // Destroy the editor when the component is unmounted
441
451
  useEffect(() => {
442
452
  const ev = editorViewRef.current;
@@ -445,6 +455,23 @@ const CellEditorInternal = ({
445
455
  };
446
456
  }, [editorViewRef]);
447
457
 
458
+ // Prioritize building this cell's editor when it scrolls into view, so the
459
+ // visible region fills in first instead of waiting for the top-to-bottom
460
+ // queue. The margin builds cells just before they reach the viewport.
461
+ const [intersectionRef, intersection] = useIntersectionObserver({
462
+ rootMargin: "300px 0px",
463
+ });
464
+ useEffect(() => {
465
+ if (isEditorMounted) {
466
+ return;
467
+ }
468
+ if (intersection?.isIntersecting) {
469
+ editorMountScheduler.prioritize(cellId);
470
+ } else {
471
+ editorMountScheduler.deprioritize(cellId);
472
+ }
473
+ }, [isEditorMounted, intersection?.isIntersecting, cellId]);
474
+
448
475
  const navigationProps = useCellEditorNavigationProps(cellId, editorViewRef);
449
476
 
450
477
  let editorClassName = "";
@@ -489,14 +516,22 @@ const CellEditorInternal = ({
489
516
  runCell={handleRunCell}
490
517
  outputArea={outputArea}
491
518
  >
492
- <div className="relative w-full" {...navigationProps}>
493
- <CellCodeMirrorEditor
494
- className={editorClassName}
495
- editorView={editorViewRef.current}
496
- ref={editorViewParentRef}
497
- hidden={hidden}
498
- showHiddenCode={showHiddenCode}
499
- />
519
+ <div
520
+ className="relative w-full"
521
+ ref={intersectionRef}
522
+ {...navigationProps}
523
+ >
524
+ {isEditorMounted ? (
525
+ <CellCodeMirrorEditor
526
+ className={editorClassName}
527
+ editorView={editorViewRef.current}
528
+ ref={editorViewParentRef}
529
+ hidden={hidden}
530
+ showHiddenCode={showHiddenCode}
531
+ />
532
+ ) : (
533
+ <CodePlaceholder code={code} className={editorClassName} />
534
+ )}
500
535
  {!hidden && showLanguageToggles && (
501
536
  <div className="absolute top-1 right-5">
502
537
  <LanguageToggles
@@ -0,0 +1,17 @@
1
+ .mo-code-placeholder {
2
+ --mo-skeleton-bar: color-mix(in srgb, var(--muted), var(--foreground) 18%);
3
+ cursor: default;
4
+ padding: 4px 10px;
5
+ font-size: var(--cm-font-size, 0.875rem);
6
+ }
7
+
8
+ .mo-code-placeholder-line {
9
+ display: flex;
10
+ align-items: center;
11
+ height: 1.5em;
12
+ }
13
+
14
+ .mo-code-placeholder-bar {
15
+ height: 0.7em;
16
+ background-color: var(--mo-skeleton-bar);
17
+ }
@@ -0,0 +1,46 @@
1
+ import "./code-placeholder.css";
2
+ import { Skeleton } from "@/components/ui/skeleton";
3
+ import { cn } from "@/utils/cn";
4
+
5
+ interface CodePlaceholderProps {
6
+ code: string;
7
+ className?: string;
8
+ }
9
+
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;
14
+
15
+ function getLineWidthCh(length: number): number {
16
+ return Math.min(MAX_LINE_WIDTH_CH, Math.max(MIN_LINE_WIDTH_CH, length));
17
+ }
18
+
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
+ export const CodePlaceholder = ({ code, className }: CodePlaceholderProps) => {
24
+ const lines = code.split("\n", MAX_LINES);
25
+ return (
26
+ <div
27
+ className={cn("cm", "mo-code-placeholder", className)}
28
+ data-testid="cell-editor-placeholder"
29
+ aria-hidden={true}
30
+ >
31
+ {lines.map((line, index) => {
32
+ const length = line.trimEnd().length;
33
+ return (
34
+ <div key={index} className="mo-code-placeholder-line">
35
+ {length > 0 && (
36
+ <Skeleton
37
+ className="mo-code-placeholder-bar"
38
+ style={{ width: `${getLineWidthCh(length)}ch` }}
39
+ />
40
+ )}
41
+ </div>
42
+ );
43
+ })}
44
+ </div>
45
+ );
46
+ };
@@ -7,6 +7,7 @@ import {
7
7
  import type { CellHandle } from "@/components/editor/notebook-cell";
8
8
  import { retryWithTimeout } from "@/utils/timeout";
9
9
  import { Logger } from "../../utils/Logger";
10
+ import { editorMountScheduler } from "../codemirror/editor-mount-scheduler";
10
11
  import { scrollActiveLineIntoView } from "../codemirror/extensions";
11
12
  import { goToVariableDefinition } from "../codemirror/go-to-definition/commands";
12
13
  import { getCellEditorView } from "./cells";
@@ -48,6 +49,9 @@ export function focusAndScrollCellIntoView({
48
49
  // https://github.com/marimo-team/marimo/issues/2940
49
50
  tryFocus(element);
50
51
  } else {
52
+ // Build this cell's editor now if it is still queued, so focus can land in
53
+ // it instead of the placeholder.
54
+ editorMountScheduler.promote(cellId);
51
55
  const editor = cell.current?.editorView;
52
56
  if (!editor) {
53
57
  Logger.warn("scrollCellIntoView: editor not found", cellId);
@@ -0,0 +1,142 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createEditorMountScheduler } from "../editor-mount-scheduler";
3
+
4
+ function makeManualSchedule() {
5
+ let pending: (() => void) | null = null;
6
+ const schedule = (cb: () => void) => {
7
+ pending = cb;
8
+ };
9
+ const flush = () => {
10
+ const cb = pending;
11
+ pending = null;
12
+ cb?.();
13
+ };
14
+ return { schedule, flush, hasPending: () => pending !== null };
15
+ }
16
+
17
+ describe("createEditorMountScheduler", () => {
18
+ it("builds one queued editor per tick in FIFO order, rescheduling between", () => {
19
+ const { schedule, flush, hasPending } = makeManualSchedule();
20
+ const built: string[] = [];
21
+ const s = createEditorMountScheduler(schedule);
22
+ s.request("a", () => built.push("a"));
23
+ s.request("b", () => built.push("b"));
24
+ flush();
25
+ expect(built).toEqual(["a"]);
26
+ expect(hasPending()).toBe(true);
27
+ flush();
28
+ expect(built).toEqual(["a", "b"]);
29
+ });
30
+
31
+ it("stops rescheduling once the queue is empty", () => {
32
+ const { schedule, flush, hasPending } = makeManualSchedule();
33
+ const built: string[] = [];
34
+ const s = createEditorMountScheduler(schedule);
35
+ s.request("a", () => built.push("a"));
36
+ flush();
37
+ expect(built).toEqual(["a"]);
38
+ expect(hasPending()).toBe(false);
39
+ });
40
+
41
+ it("promote builds immediately and removes from the queue", () => {
42
+ const { schedule, flush } = makeManualSchedule();
43
+ const built: string[] = [];
44
+ const s = createEditorMountScheduler(schedule);
45
+ s.request("a", () => built.push("a"));
46
+ s.request("b", () => built.push("b"));
47
+ s.promote("b");
48
+ expect(built).toEqual(["b"]);
49
+ flush();
50
+ expect(built).toEqual(["b", "a"]);
51
+ });
52
+
53
+ it("cancel prevents a queued build", () => {
54
+ const { schedule, flush } = makeManualSchedule();
55
+ const built: string[] = [];
56
+ const s = createEditorMountScheduler(schedule);
57
+ s.request("a", () => built.push("a"));
58
+ s.cancel("a");
59
+ flush();
60
+ expect(built).toEqual([]);
61
+ });
62
+
63
+ it("builds prioritized cells before earlier-queued ones", () => {
64
+ const { schedule, flush } = makeManualSchedule();
65
+ const built: string[] = [];
66
+ const s = createEditorMountScheduler(schedule);
67
+ s.request("a", () => built.push("a"));
68
+ s.request("b", () => built.push("b"));
69
+ s.request("c", () => built.push("c"));
70
+ s.prioritize("c");
71
+ flush();
72
+ flush();
73
+ flush();
74
+ expect(built).toEqual(["c", "a", "b"]);
75
+ });
76
+
77
+ it("builds multiple prioritized cells in prioritization order, then FIFO", () => {
78
+ const { schedule, flush } = makeManualSchedule();
79
+ const built: string[] = [];
80
+ const s = createEditorMountScheduler(schedule);
81
+ s.request("a", () => built.push("a"));
82
+ s.request("b", () => built.push("b"));
83
+ s.request("c", () => built.push("c"));
84
+ s.request("d", () => built.push("d"));
85
+ s.prioritize("d");
86
+ s.prioritize("b");
87
+ flush();
88
+ flush();
89
+ flush();
90
+ flush();
91
+ expect(built).toEqual(["d", "b", "a", "c"]);
92
+ });
93
+
94
+ it("ignores prioritize for a cell that is not queued", () => {
95
+ const { schedule, flush } = makeManualSchedule();
96
+ const built: string[] = [];
97
+ const s = createEditorMountScheduler(schedule);
98
+ s.request("a", () => built.push("a"));
99
+ s.prioritize("not-queued");
100
+ flush();
101
+ expect(built).toEqual(["a"]);
102
+ });
103
+
104
+ it("deprioritize reverts a cell to FIFO order without dropping it", () => {
105
+ const { schedule, flush } = makeManualSchedule();
106
+ const built: string[] = [];
107
+ const s = createEditorMountScheduler(schedule);
108
+ s.request("a", () => built.push("a"));
109
+ s.request("b", () => built.push("b"));
110
+ s.prioritize("b");
111
+ s.deprioritize("b");
112
+ flush();
113
+ flush();
114
+ expect(built).toEqual(["a", "b"]);
115
+ });
116
+
117
+ it("keeps draining the queue after a build throws", () => {
118
+ const { schedule, flush } = makeManualSchedule();
119
+ const built: string[] = [];
120
+ const s = createEditorMountScheduler(schedule);
121
+ s.request("a", () => {
122
+ throw new Error("boom");
123
+ });
124
+ s.request("b", () => built.push("b"));
125
+ expect(() => flush()).toThrow("boom");
126
+ flush();
127
+ expect(built).toEqual(["b"]);
128
+ });
129
+
130
+ it("cancel removes a prioritized cell", () => {
131
+ const { schedule, flush } = makeManualSchedule();
132
+ const built: string[] = [];
133
+ const s = createEditorMountScheduler(schedule);
134
+ s.request("a", () => built.push("a"));
135
+ s.request("b", () => built.push("b"));
136
+ s.prioritize("b");
137
+ s.cancel("b");
138
+ flush();
139
+ flush();
140
+ expect(built).toEqual(["a"]);
141
+ });
142
+ });
@@ -0,0 +1,100 @@
1
+ import {
2
+ scheduleTask as defaultScheduleTask,
3
+ type ScheduleTaskFn,
4
+ } from "@/utils/schedule-task";
5
+
6
+ type BuildFn = () => void;
7
+
8
+ export interface EditorMountScheduler {
9
+ /** Queue a cell's editor build to run on a future task. */
10
+ request(cellId: string, build: BuildFn): void;
11
+ /** Build a queued cell's editor synchronously, right now (e.g. on focus). */
12
+ promote(cellId: string): void;
13
+ /**
14
+ * Mark a queued cell to build ahead of un-prioritized ones, keeping the
15
+ * one-build-per-task pacing (e.g. when the cell scrolls into view).
16
+ */
17
+ prioritize(cellId: string): void;
18
+ /** Drop a cell's prioritized mark, reverting it to plain FIFO order. */
19
+ deprioritize(cellId: string): void;
20
+ /** Remove a cell's queued build entirely. */
21
+ cancel(cellId: string): void;
22
+ }
23
+
24
+ /**
25
+ * Drains a FIFO queue of editor builds, one per macrotask, so constructing many
26
+ * CodeMirror instances never blocks the main thread in a single long task. The
27
+ * scheduler yields between every build to keep the page responsive. Cells can
28
+ * be prioritized (e.g. when they scroll into view) to jump ahead of the queue
29
+ * without breaking the one-build-per-macrotask pacing.
30
+ */
31
+ export function createEditorMountScheduler(
32
+ scheduleTask: ScheduleTaskFn = defaultScheduleTask,
33
+ ): EditorMountScheduler {
34
+ const queue = new Map<string, BuildFn>();
35
+ const priority = new Set<string>();
36
+ let isProcessingScheduled = false;
37
+
38
+ function scheduleProcessing(): void {
39
+ if (isProcessingScheduled || queue.size === 0) {
40
+ return;
41
+ }
42
+ isProcessingScheduled = true;
43
+ scheduleTask(processNext);
44
+ }
45
+
46
+ // Prioritized cells first, in the order they were prioritized; then FIFO.
47
+ function nextCellId(): string | undefined {
48
+ for (const cellId of priority) {
49
+ if (queue.has(cellId)) {
50
+ return cellId;
51
+ }
52
+ priority.delete(cellId);
53
+ }
54
+ return queue.keys().next().value;
55
+ }
56
+
57
+ function processNext(): void {
58
+ isProcessingScheduled = false;
59
+ try {
60
+ const cellId = nextCellId();
61
+ if (cellId !== undefined) {
62
+ const build = queue.get(cellId);
63
+ queue.delete(cellId);
64
+ priority.delete(cellId);
65
+ build?.();
66
+ }
67
+ } finally {
68
+ scheduleProcessing();
69
+ }
70
+ }
71
+
72
+ return {
73
+ request(cellId, build) {
74
+ queue.set(cellId, build);
75
+ scheduleProcessing();
76
+ },
77
+ promote(cellId) {
78
+ const build = queue.get(cellId);
79
+ if (build) {
80
+ queue.delete(cellId);
81
+ priority.delete(cellId);
82
+ build();
83
+ }
84
+ },
85
+ prioritize(cellId) {
86
+ if (queue.has(cellId)) {
87
+ priority.add(cellId);
88
+ }
89
+ },
90
+ deprioritize(cellId) {
91
+ priority.delete(cellId);
92
+ },
93
+ cancel(cellId) {
94
+ queue.delete(cellId);
95
+ priority.delete(cellId);
96
+ },
97
+ };
98
+ }
99
+
100
+ export const editorMountScheduler = createEditorMountScheduler();
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Schedules `callback` to run as a fresh task once the current task finishes,
3
+ * letting the browser paint and handle input in between. Used to spread heavy
4
+ * work across the event loop instead of blocking it in one long task.
5
+ */
6
+ export type ScheduleTaskFn = (callback: () => void) => void;
7
+
8
+ /**
9
+ * Picks the best available "yield to the event loop" primitive, preferring
10
+ * ones that impose no artificial delay between tasks:
11
+ *
12
+ * 1. `scheduler.postTask` — the purpose-built Prioritized Task Scheduling API.
13
+ * `user-visible` runs promptly while still yielding to user-blocking input.
14
+ * 2. `MessageChannel` — a plain macrotask with no minimum-delay clamp (nested
15
+ * `setTimeout` is floored at ~4ms by the spec, which would add up over many
16
+ * tasks).
17
+ * 3. `setTimeout` — universal fallback; correct, just clamped when nested.
18
+ *
19
+ * The backend is chosen once, at module load, since it cannot change within a
20
+ * session.
21
+ */
22
+ // `scheduler` (the Prioritized Task Scheduling API) is not in this repo's
23
+ // lib.dom typings, so it is feature-detected behind this minimal cast.
24
+ interface PostTaskScheduler {
25
+ postTask: (
26
+ callback: () => void,
27
+ options?: { priority?: "user-blocking" | "user-visible" | "background" },
28
+ ) => Promise<unknown>;
29
+ }
30
+
31
+ function createScheduleTask(): ScheduleTaskFn {
32
+ const scheduler = (globalThis as { scheduler?: PostTaskScheduler }).scheduler;
33
+ if (typeof scheduler?.postTask === "function") {
34
+ return (cb) => {
35
+ // postTask rejects when the callback throws. Rethrow on a fresh task so a
36
+ // thrown callback surfaces as an uncaught error, matching the
37
+ // MessageChannel/setTimeout backends, instead of an unhandledrejection.
38
+ void scheduler
39
+ .postTask(cb, { priority: "user-visible" })
40
+ .catch((error) => {
41
+ setTimeout(() => {
42
+ throw error;
43
+ });
44
+ });
45
+ };
46
+ }
47
+
48
+ if (typeof MessageChannel === "function") {
49
+ // Both ports live on this thread and no data is sent: posting a message is
50
+ // just the cheapest way to enqueue a macrotask that yields for paint. The
51
+ // queue lets multiple callbacks be in flight at once (one per message).
52
+ const pending: Array<() => void> = [];
53
+ const channel = new MessageChannel();
54
+ channel.port1.onmessage = () => {
55
+ pending.shift()?.();
56
+ };
57
+
58
+ return (cb) => {
59
+ pending.push(cb);
60
+ channel.port2.postMessage(null);
61
+ };
62
+ }
63
+
64
+ return (cb) => {
65
+ setTimeout(cb, 0);
66
+ };
67
+ }
68
+
69
+ /** Shared task scheduler using the best primitive this environment offers. */
70
+ export const scheduleTask = createScheduleTask();