@marimo-team/islands 0.26.1-dev104 → 0.26.1-dev108

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 (106) hide show
  1. package/dist/{ConnectedDataExplorerComponent-BJBdnd0O.js → ConnectedDataExplorerComponent-DQaiOY7w.js} +15 -15
  2. package/dist/{ErrorBoundary-DLR6xE2E.js → ErrorBoundary-BW4TciqU.js} +19 -19
  3. package/dist/{abnfDiagram-VCTEODGH-Ba0MYVW8.js → abnfDiagram-VCTEODGH-Df80tEYq.js} +2 -2
  4. package/dist/{any-language-editor-BNe8do3C.js → any-language-editor-BW-gNmbk.js} +2 -2
  5. package/dist/{architectureDiagram-5GKGNRK7-7MqAehef.js → architectureDiagram-5GKGNRK7-DNNMvKkY.js} +1 -1
  6. package/dist/{assertNever-5vhHGKOK.js → assertNever-B9_7z-dW.js} +13 -13
  7. package/dist/{chat-ui-Bs3rgm2m.js → chat-ui-Be9X-W22.js} +49 -49
  8. package/dist/{check-DUIc04aK.js → check-BqF09bSG.js} +1 -1
  9. package/dist/{chunk-IMKFNOWR-CAWA0HGB.js → chunk-IMKFNOWR-pXqnQ_fj.js} +1 -1
  10. package/dist/{chunk-SHT3W25Y-BIwVQjG5.js → chunk-SHT3W25Y-BWrxB3I2.js} +1 -1
  11. package/dist/{chunk-SVP7TREG-Cux251TB.js → chunk-SVP7TREG-CPdQP8_U.js} +1 -1
  12. package/dist/{chunk-TICWLB2K-DJVQ6khO.js → chunk-TICWLB2K-C5MYCwBz.js} +1 -1
  13. package/dist/{circle-question-mark-evCnVIut.js → circle-question-mark-YmLYXyvS.js} +1 -1
  14. package/dist/{classDiagram-ZZMXUADV-Cwve77ev.js → classDiagram-ZZMXUADV-Ba0SRm01.js} +2 -2
  15. package/dist/{classDiagram-v2-VYDZK3BY-BAeHKXmD.js → classDiagram-v2-VYDZK3BY-DSSzL_Dk.js} +2 -2
  16. package/dist/{code-visibility-BhWW3jkv.js → code-visibility-BKmktPMd.js} +18 -18
  17. package/dist/{common-i4mVHMGl.js → common-CSJAjJGa.js} +169 -169
  18. package/dist/{copy-icon-CmNLxT5_.js → copy-icon-zP4__HPI.js} +2 -2
  19. package/dist/{createReducer-BUQhgLOI.js → createReducer-CArOwUaJ.js} +16 -19
  20. package/dist/{cynefinDiagram-5FMLGOSQ-t4eEkPJh.js → cynefinDiagram-5FMLGOSQ-BOtNvA04.js} +1 -1
  21. package/dist/{dagre-GXQ25YYZ-IuZuI28B.js → dagre-GXQ25YYZ-FpCEOTxX.js} +1 -1
  22. package/dist/{data-grid-overlay-editor-7durYJXa.js → data-grid-overlay-editor-DTibdR4H.js} +1 -1
  23. package/dist/{diagram-S7CK7UJ4-D8R5Q_ok.js → diagram-S7CK7UJ4-Cm1HaBuu.js} +1 -1
  24. package/dist/{diagram-UQ7AKVKN-BGuMPsr-.js → diagram-UQ7AKVKN-D1lA7Ggu.js} +1 -1
  25. package/dist/{diagram-VX7I27RA-BkTtpO8P.js → diagram-VX7I27RA-BX3e-Rue.js} +1 -1
  26. package/dist/{diagram-Z3DM3KII-C0__Mxfm.js → diagram-Z3DM3KII-Dgoj7bPf.js} +1 -1
  27. package/dist/{dialog-BvjfalZ9.js → dialog-DfKgafXJ.js} +30 -30
  28. package/dist/{dropdown-menu-D0DeN-aL.js → dropdown-menu-Dge_SmqE.js} +168 -168
  29. package/dist/{ebnfDiagram-PWID7BFC-CSESPZoz.js → ebnfDiagram-PWID7BFC-B0xWiXrz.js} +2 -2
  30. package/dist/{erDiagram-RLTQ6QDP-DsDTtabH.js → erDiagram-RLTQ6QDP-Cm-GO31-.js} +1 -1
  31. package/dist/{error-banner-CXLjTW24.js → error-banner-CfYrJaIb.js} +91 -91
  32. package/dist/{error-entries-BcAyFIeh.js → error-entries-23Z_1oDM.js} +586 -595
  33. package/dist/{export-context-CkgZeARR.js → export-context-B1jdxzHF.js} +21 -21
  34. package/dist/{feedback-button-CeuzSBrq.js → feedback-button-CPu5SV3b.js} +72 -72
  35. package/dist/{flowDiagram-HODETNUW-qxDPYbfV.js → flowDiagram-HODETNUW-CH6xMlW_.js} +2 -2
  36. package/dist/{formats-CcQrzFo8.js → formats-Y52bg800.js} +1 -1
  37. package/dist/{glide-data-editor-BLGr2vQF.js → glide-data-editor-CC9_NDNi.js} +11 -11
  38. package/dist/{glide-utils-CD8BaFTm.js → glide-utils-BRcuSTCx.js} +2 -2
  39. package/dist/{globals-DorvG5dC.js → globals-BFlYTNoR.js} +3 -3
  40. package/dist/{html-to-image-BmLTjaGw.js → html-to-image-Cw7o1IbE.js} +4300 -4296
  41. package/dist/{infoDiagram-27XIBGKW-B5hq8RM_.js → infoDiagram-27XIBGKW-DbUO63CX.js} +1 -1
  42. package/dist/{ishikawaDiagram-5VMMS53U-DkHc_9ET.js → ishikawaDiagram-5VMMS53U-CfQrrELH.js} +1 -1
  43. package/dist/{kanban-definition-UXKFOSKX-CqkTFXmU.js → kanban-definition-UXKFOSKX-C5SJcu1W.js} +1 -1
  44. package/dist/{loader-CGrYn73j.js → loader-C9-qRO3m.js} +2 -2
  45. package/dist/main.js +6698 -6604
  46. package/dist/{mermaid-pmVHDUQA.js → mermaid-C2alqcd8.js} +34 -34
  47. package/dist/{mindmap-definition-YA3MSWOX-D6cNa__z.js → mindmap-definition-YA3MSWOX-ByVHE0Ax.js} +1 -1
  48. package/dist/{number-overlay-editor-DQAdvZrn.js → number-overlay-editor-qDcRKPE0.js} +1 -1
  49. package/dist/{pegDiagram-XKGWAZYB-CmWJX_s1.js → pegDiagram-XKGWAZYB-DF5FBKZi.js} +2 -2
  50. package/dist/{pencil-CxMgOe04.js → pencil-D7jyZPnP.js} +1 -1
  51. package/dist/{pieDiagram-E7YTZNPT-CAQAxHah.js → pieDiagram-E7YTZNPT-B5n9nBQN.js} +1 -1
  52. package/dist/{process-output-CcNpl5Qu.js → process-output-DdBM0lmd.js} +4 -4
  53. package/dist/{railroadDiagram-O6MQD6OU-jlSsiQg3.js → railroadDiagram-O6MQD6OU-r5t7OYNE.js} +2 -2
  54. package/dist/{requirementDiagram-BXWQKSXE-DkDjfPhn.js → requirementDiagram-BXWQKSXE-D4QtEyZQ.js} +1 -1
  55. package/dist/{reveal-component-B6xeeht1.js → reveal-component-BE1xhtNc.js} +1008 -1008
  56. package/dist/{select-CEnB18uc.js → select-Buk3aXi1.js} +341 -341
  57. package/dist/{sequenceDiagram-WJ2MYXX4-DLywsGCW.js → sequenceDiagram-WJ2MYXX4-CK3Atn-z.js} +1 -1
  58. package/dist/{spec-Dz-Avv1m.js → spec-BEp9O9dy.js} +4 -4
  59. package/dist/{stateDiagram-D77RDMKH-DUmlKwYU.js → stateDiagram-D77RDMKH-C1SxRI8V.js} +2 -2
  60. package/dist/{stateDiagram-v2-MP3YSRHH-D646KiXs.js → stateDiagram-v2-MP3YSRHH-DK5X6bsr.js} +2 -2
  61. package/dist/{static-state-iw0PrHK4.js → static-state-D-aT9dOr.js} +9 -9
  62. package/dist/{swimlanes-42K2YHIH-L7B1GphF.js → swimlanes-42K2YHIH-DdH5TZdu.js} +1 -1
  63. package/dist/{swimlanesDiagram-VR7AAH4N-DEu2wxtC.js → swimlanesDiagram-VR7AAH4N-CWBIvzgR.js} +2 -2
  64. package/dist/{timeline-definition-24CTP7MA-DDPyx1yG.js → timeline-definition-24CTP7MA-DE7-o2zU.js} +1 -1
  65. package/dist/{toast-BTjH6fIf.js → toast-b3k4YxaT.js} +54 -54
  66. package/dist/{tooltip-DyLdBIM4.js → tooltip-D-9pDheN.js} +62 -62
  67. package/dist/{use-restore-focus-DJ_-uSn_.js → use-restore-focus-CCfk-ey2.js} +1 -1
  68. package/dist/{useDateFormatter-HpKD0jEC.js → useDateFormatter-DH0uFwfL.js} +2 -2
  69. package/dist/{useDeepCompareMemoize-CHx-NxMl.js → useDeepCompareMemoize-Dn-ZJVTd.js} +1 -1
  70. package/dist/{useLifecycle-tPpAt-OE.js → useLifecycle-yjK7JsRL.js} +1 -1
  71. package/dist/{vega-component-BzNDFvQf.js → vega-component-BIq0qzhQ.js} +8 -8
  72. package/dist/{vennDiagram-4TSXK5OY-CRwWeb7g.js → vennDiagram-4TSXK5OY-D7yfNz0d.js} +1 -1
  73. package/dist/{wardleyDiagram-VM6X3IG4-DVlG9eoq.js → wardleyDiagram-VM6X3IG4-m5Jcz26Z.js} +1 -1
  74. package/dist/{xychartDiagram-S5SC5T6Z-CM32AISp.js → xychartDiagram-S5SC5T6Z-CA3zV3RW.js} +1 -1
  75. package/package.json +1 -1
  76. package/src/__mocks__/intersection-observer.ts +13 -12
  77. package/src/components/editor/Output.tsx +1 -1
  78. package/src/components/editor/__tests__/cell-renders.test.tsx +17 -1
  79. package/src/components/editor/cell/__tests__/cell-actions.test.tsx +74 -0
  80. package/src/components/editor/cell/cell-action-body.tsx +28 -0
  81. package/src/components/editor/cell/cell-actions.tsx +60 -72
  82. package/src/components/editor/cell/cell-context-menu.tsx +36 -62
  83. package/src/components/editor/chrome/panels/outline/__tests__/outline-keyboard.test.tsx +517 -68
  84. package/src/components/editor/chrome/panels/outline/__tests__/useActiveOutline.test.ts +17 -5
  85. package/src/components/editor/chrome/panels/outline/floating-outline.tsx +29 -59
  86. package/src/components/editor/chrome/panels/outline/useActiveOutline.tsx +333 -133
  87. package/src/components/editor/chrome/panels/outline-panel.tsx +5 -19
  88. package/src/components/editor/navigation/navigation.ts +1 -1
  89. package/src/components/editor/notebook-cell.tsx +263 -267
  90. package/src/core/cells/__tests__/layout.test.ts +1 -1
  91. package/src/core/cells/__tests__/notebook-outline.test.ts +31 -3
  92. package/src/core/cells/__tests__/use-cell-actions.test.tsx +48 -0
  93. package/src/core/cells/actions.ts +68 -89
  94. package/src/core/cells/cells.ts +23 -14
  95. package/src/core/cells/outline.ts +8 -8
  96. package/src/core/codemirror/language/extension.ts +6 -3
  97. package/src/core/codemirror/language/panel/panel.test.tsx +144 -0
  98. package/src/core/codemirror/language/panel/panel.tsx +9 -6
  99. package/src/core/codemirror/react-dom/createPanel.tsx +15 -15
  100. package/src/core/dom/__tests__/outline.test.ts +29 -170
  101. package/src/core/dom/outline.ts +21 -61
  102. package/src/core/executions/atoms.ts +12 -4
  103. package/src/core/islands/components/output-wrapper.tsx +7 -2
  104. package/src/plugins/layout/OutlinePlugin.tsx +5 -17
  105. package/src/utils/__tests__/createReducer.test.tsx +4 -3
  106. package/src/utils/createReducer.ts +19 -12
@@ -1,21 +1,15 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import { useAtomValue } from "jotai";
4
3
  import React from "react";
5
- import { notebookOutline } from "@/core/cells/cells";
6
- import type { OutlineItem } from "@/core/cells/outline";
7
4
  import { cn } from "@/utils/cn";
8
5
  import {
9
- findOutlineElements,
10
- scrollToOutlineItem,
6
+ type OutlineEntry,
7
+ scrollToOutlineEntry,
11
8
  useActiveOutline,
12
9
  } from "./useActiveOutline";
13
10
 
14
11
  export const FloatingOutline: React.FC = () => {
15
- const { items } = useAtomValue(notebookOutline);
16
- const { activeHeaderId, activeOccurrences } = useActiveOutline(
17
- findOutlineElements(items),
18
- );
12
+ const outline = useActiveOutline(2);
19
13
  const [isHovered, setIsHovered] = React.useState(false);
20
14
  const [isFocused, setIsFocused] = React.useState(false);
21
15
  const isVisible = isHovered || isFocused;
@@ -23,7 +17,7 @@ export const FloatingOutline: React.FC = () => {
23
17
  // Hide if < 2 items
24
18
  // It's kinda useless to have an outline with only one item
25
19
  // and Notion does the same
26
- if (items.length < 2) {
20
+ if (outline.entries.length < 2) {
27
21
  return null;
28
22
  }
29
23
 
@@ -49,51 +43,40 @@ export const FloatingOutline: React.FC = () => {
49
43
  "-top-4 max-h-[70vh] bg-background rounded-lg shadow-lg absolute overflow-auto transition-all duration-300 w-[300px] border",
50
44
  isVisible ? "left-[-280px] opacity-100" : "left-[300px] opacity-0",
51
45
  )}
52
- items={items}
53
- activeHeaderId={activeHeaderId}
54
- activeOccurrences={activeOccurrences}
55
- />
56
- <MiniMap
57
- items={items}
58
- activeHeaderId={activeHeaderId}
59
- activeOccurrences={activeOccurrences}
46
+ {...outline}
60
47
  />
48
+ <MiniMap {...outline} />
61
49
  </div>
62
50
  );
63
51
  };
64
52
 
65
- export const MiniMap: React.FC<{
66
- items: OutlineItem[];
67
- activeHeaderId: string | undefined;
68
- activeOccurrences: number | undefined;
69
- }> = ({ items, activeHeaderId, activeOccurrences }) => {
70
- // Map of selector to its occurrences
71
- const seen = new Map<string, number>();
53
+ interface OutlineEntriesProps {
54
+ entries: OutlineEntry[];
55
+ activeKey: string | undefined;
56
+ }
57
+
58
+ export const MiniMap: React.FC<OutlineEntriesProps> = ({
59
+ entries,
60
+ activeKey,
61
+ }) => {
72
62
  return (
73
63
  <div className="flex flex-col gap-4 items-end max-h-[70vh] overflow-hidden">
74
- {items.map((item) => {
75
- const identifier = "id" in item.by ? item.by.id : item.by.path;
76
- const selector = JSON.stringify(item.by);
77
- // Keep track of how many times we've seen this selector
78
- const occurrences = seen.get(selector) ?? 0;
79
- seen.set(selector, occurrences + 1);
80
-
64
+ {entries.map((entry) => {
65
+ const { item, key } = entry;
81
66
  return (
82
67
  <button
83
68
  type="button"
84
69
  aria-label={item.name}
85
- key={`${selector}-${occurrences}`}
70
+ key={key}
86
71
  className={cn(
87
72
  "h-[2px] bg-muted-foreground/60 focus-visible:outline focus-visible:outline-ring",
88
73
  item.level === 1 && "w-5",
89
74
  item.level === 2 && "w-4",
90
75
  item.level === 3 && "w-3",
91
76
  item.level === 4 && "w-2",
92
- occurrences === activeOccurrences &&
93
- activeHeaderId === identifier &&
94
- "bg-foreground",
77
+ activeKey === key && "bg-foreground",
95
78
  )}
96
- onClick={() => scrollToOutlineItem(item, occurrences)}
79
+ onClick={() => scrollToOutlineEntry(entry)}
97
80
  />
98
81
  );
99
82
  })}
@@ -101,28 +84,17 @@ export const MiniMap: React.FC<{
101
84
  );
102
85
  };
103
86
 
104
- export const OutlineList: React.FC<{
105
- className?: string;
106
- inert?: boolean;
107
- items: OutlineItem[];
108
- activeHeaderId: string | undefined;
109
- activeOccurrences: number | undefined;
110
- }> = ({ items, activeHeaderId, activeOccurrences, className, inert }) => {
111
- // Map of selector to its occurrences
112
- const seen = new Map<string, number>();
87
+ export const OutlineList: React.FC<
88
+ OutlineEntriesProps & { className?: string; inert?: boolean }
89
+ > = ({ entries, activeKey, className, inert }) => {
113
90
  return (
114
91
  <div
92
+ data-outline-list=""
115
93
  inert={inert}
116
94
  className={cn("flex flex-col overflow-auto py-4 pl-2", className)}
117
95
  >
118
- {items.map((item) => {
119
- const identifier = "id" in item.by ? item.by.id : item.by.path;
120
- const selector = JSON.stringify(item.by);
121
- // Keep track of how many times we've seen this selector
122
- const occurrences = seen.get(selector) ?? 0;
123
- seen.set(selector, occurrences + 1);
124
-
125
- const key = `${selector}-${occurrences}`;
96
+ {entries.map((entry) => {
97
+ const { item, key } = entry;
126
98
  const sharedProps = {
127
99
  role: "link",
128
100
  tabIndex: 0,
@@ -132,15 +104,13 @@ export const OutlineList: React.FC<{
132
104
  item.level === 2 && "ml-3",
133
105
  item.level === 3 && "ml-6",
134
106
  item.level === 4 && "ml-9",
135
- occurrences === activeOccurrences &&
136
- activeHeaderId === identifier &&
137
- "text-accent-foreground",
107
+ activeKey === key && "text-accent-foreground",
138
108
  ),
139
- onClick: () => scrollToOutlineItem(item, occurrences),
109
+ onClick: () => scrollToOutlineEntry(entry),
140
110
  onKeyDown: (e: React.KeyboardEvent) => {
141
111
  if (e.target === e.currentTarget && e.key === "Enter") {
142
112
  e.preventDefault();
143
- scrollToOutlineItem(item, occurrences);
113
+ scrollToOutlineEntry(entry);
144
114
  }
145
115
  },
146
116
  };
@@ -1,173 +1,373 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import { useEffect, useRef, useState } from "react";
4
- import type { OutlineItem } from "@/core/cells/outline";
5
- import { headingToIdentifier } from "@/core/dom/outline";
3
+ import { dequal } from "dequal";
4
+ import { atom, useAtomValue } from "jotai";
5
+ import { selectAtom } from "jotai/utils";
6
+ import { useMemo, useSyncExternalStore } from "react";
7
+ import { notebookOutline } from "@/core/cells/cells";
8
+ import { CellOutputId } from "@/core/cells/ids";
9
+ import type { NotebookOutlineItem } from "@/core/cells/outline";
10
+ import { OUTLINE_HEADING_TAGS, OUTLINE_TARGETS } from "@/core/dom/outline";
6
11
  import { getInitialAppMode } from "@/core/mode";
12
+ import { Functions } from "@/utils/functions";
7
13
  import { Logger } from "@/utils/Logger";
14
+ import { createSharedSubscription } from "@/utils/shared-resource";
8
15
 
9
- function getRootScrollableElement() {
10
- // HACK: this is a bit leaky
11
- // this gets the root element that contains the scrollable content
12
- return getInitialAppMode() === "edit"
13
- ? document.getElementById("App")
14
- : undefined;
16
+ interface OutlineTarget {
17
+ key: string;
18
+ element: Element | undefined;
15
19
  }
16
20
 
17
- /**
18
- * React hook to find the active header in the outline
19
- */
20
- export function useActiveOutline(
21
- headerElements: (readonly [HTMLElement, string])[],
21
+ export interface OutlineEntry extends OutlineTarget {
22
+ item: NotebookOutlineItem;
23
+ }
24
+
25
+ const OUTPUT_ROOT = '[data-cell-role="output"]';
26
+
27
+ // An outline widget may render rich labels inside a cell's own output.
28
+ const OUTPUT_TARGETS = `${OUTPUT_ROOT} ${OUTLINE_TARGETS}:not([data-outline-list] *)`;
29
+
30
+ function outlineTargetKey(
31
+ outputId: string,
32
+ id: string | undefined,
33
+ tag: string,
34
+ text: string,
22
35
  ) {
23
- const [activeHeaderId, setActiveHeaderId] = useState<string | undefined>(
24
- undefined,
25
- );
26
- const [activeOccurrences, setActiveOccurrences] = useState<
27
- number | undefined
28
- >(undefined);
29
- const observerRef = useRef<IntersectionObserver | null>(null);
30
- const topmostHeader = useRef<HTMLElement | null>(null);
31
-
32
- const occurrences = useRef<Map<HTMLElement, number>>(
33
- new Map<HTMLElement, number>(),
34
- );
36
+ return JSON.stringify([outputId, id ? `id:${id}` : `${tag}:${text}`]);
37
+ }
38
+
39
+ export function outlineLocators(items: NotebookOutlineItem[]) {
40
+ const occurrences = new Map<string, number>();
41
+ return items.map((item) => {
42
+ const group = outlineTargetKey(
43
+ CellOutputId.create(item.cellId),
44
+ item.id,
45
+ `h${item.level}`,
46
+ item.name,
47
+ );
48
+ const occurrence = occurrences.get(group) ?? 0;
49
+ occurrences.set(group, occurrence + 1);
50
+ return { group, key: `${group}:${occurrence}` };
51
+ });
52
+ }
35
53
 
36
- useEffect(() => {
37
- if (headerElements.length === 0) {
38
- return;
54
+ type OutlineLocators = ReturnType<typeof outlineLocators>;
55
+
56
+ function elementTargetKey(element: Element) {
57
+ if (element.id || OUTLINE_HEADING_TAGS.has(element.localName)) {
58
+ const output = element.parentElement?.closest(OUTPUT_ROOT);
59
+ if (output) {
60
+ return outlineTargetKey(
61
+ output.id,
62
+ element.id,
63
+ element.localName,
64
+ element.id ? "" : (element.textContent ?? ""),
65
+ );
39
66
  }
67
+ }
68
+ }
40
69
 
41
- const callback: IntersectionObserverCallback = (entries) => {
42
- let needsUpdate = false;
43
-
44
- entries.forEach((entry) => {
45
- const element = entry.target as HTMLElement;
46
- if (entry.isIntersecting) {
47
- if (
48
- !topmostHeader.current ||
49
- element.getBoundingClientRect().top <
50
- topmostHeader.current.getBoundingClientRect().top
51
- ) {
52
- topmostHeader.current = element;
53
- needsUpdate = true;
54
- }
55
- } else if (element === topmostHeader.current) {
56
- topmostHeader.current = null;
57
- needsUpdate = true;
58
- }
59
- });
70
+ export function resolveOutlineTargets(
71
+ locators: OutlineLocators,
72
+ ): OutlineTarget[] {
73
+ const groups = new Map<
74
+ string,
75
+ { targets: OutlineTarget[]; nextOccurrence: number }
76
+ >();
77
+ const targets = locators.map(({ group: targetGroup, key }) => {
78
+ let group = groups.get(targetGroup);
79
+ if (!group) {
80
+ group = { targets: [], nextOccurrence: 0 };
81
+ groups.set(targetGroup, group);
82
+ }
83
+ const target: OutlineTarget = {
84
+ key,
85
+ element: undefined,
86
+ };
87
+ group.targets.push(target);
88
+ return target;
89
+ });
90
+
91
+ for (const element of document.querySelectorAll(OUTPUT_TARGETS)) {
92
+ const key = elementTargetKey(element);
93
+ const group = key === undefined ? undefined : groups.get(key);
94
+ if (group && group.nextOccurrence < group.targets.length) {
95
+ group.targets[group.nextOccurrence].element = element;
96
+ group.nextOccurrence += 1;
97
+ }
98
+ }
99
+
100
+ return targets;
101
+ }
102
+
103
+ function subtreeContainsTarget(
104
+ node: Node,
105
+ isTarget: (element: Element) => boolean,
106
+ ) {
107
+ if (!(node instanceof Element)) {
108
+ return false;
109
+ }
110
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_ELEMENT);
111
+ for (let element: Node | null = node; element; element = walker.nextNode()) {
112
+ if (element instanceof Element && isTarget(element)) {
113
+ return true;
114
+ }
115
+ }
116
+ return false;
117
+ }
60
118
 
61
- if (needsUpdate && topmostHeader.current) {
62
- const identifier = headingToIdentifier(topmostHeader.current);
63
- const id = "id" in identifier ? identifier.id : identifier.path;
64
- setActiveHeaderId(id);
65
- setActiveOccurrences(occurrences.current.get(topmostHeader.current));
119
+ function observeOutlineTargets(
120
+ locators: OutlineLocators,
121
+ onTargets: (targets: OutlineTarget[]) => void,
122
+ ) {
123
+ const requestedKeys = new Set(locators.map(({ group }) => group));
124
+ const targetKeys = new Map<Element, string>();
125
+ const refresh = () => {
126
+ const targets = resolveOutlineTargets(locators);
127
+ targetKeys.clear();
128
+ for (const [index, { element }] of targets.entries()) {
129
+ if (element) {
130
+ targetKeys.set(element, locators[index].group);
131
+ }
132
+ }
133
+ onTargets(targets);
134
+ };
135
+
136
+ const requestedTargetKey = (element: Element) => {
137
+ const key = elementTargetKey(element);
138
+ if (
139
+ key !== undefined &&
140
+ requestedKeys.has(key) &&
141
+ element.isConnected &&
142
+ element.matches(OUTPUT_TARGETS)
143
+ ) {
144
+ return key;
145
+ }
146
+ };
147
+
148
+ const hasChangedKey = (element: Element) =>
149
+ targetKeys.get(element) !== requestedTargetKey(element);
150
+
151
+ const affectsTargets = ({
152
+ target,
153
+ type,
154
+ attributeName,
155
+ addedNodes,
156
+ removedNodes,
157
+ }: MutationRecord) => {
158
+ if (type === "attributes") {
159
+ if (!(target instanceof Element)) {
160
+ return false;
161
+ }
162
+ if (attributeName === "data-cell-role" || target.matches(OUTPUT_ROOT)) {
163
+ return subtreeContainsTarget(target, hasChangedKey);
164
+ }
165
+ return hasChangedKey(target);
166
+ }
167
+
168
+ for (
169
+ let element = target instanceof Element ? target : target.parentElement;
170
+ element;
171
+ element = element.parentElement
172
+ ) {
173
+ if (
174
+ !element.id &&
175
+ OUTLINE_HEADING_TAGS.has(element.localName) &&
176
+ hasChangedKey(element)
177
+ ) {
178
+ return true;
179
+ }
180
+ }
181
+
182
+ return (
183
+ [...removedNodes].some((node) =>
184
+ subtreeContainsTarget(node, (element) => targetKeys.has(element)),
185
+ ) ||
186
+ [...addedNodes].some((node) =>
187
+ subtreeContainsTarget(
188
+ node,
189
+ (element) => requestedTargetKey(element) !== undefined,
190
+ ),
191
+ )
192
+ );
193
+ };
194
+
195
+ refresh();
196
+ const observer = new MutationObserver((changes) => {
197
+ if (changes.some(affectsTargets)) {
198
+ refresh();
199
+ }
200
+ });
201
+ observer.observe(document, {
202
+ subtree: true,
203
+ childList: true,
204
+ characterData: true,
205
+ attributeFilter: ["id", "data-cell-role"],
206
+ });
207
+ return () => observer.disconnect();
208
+ }
209
+
210
+ function observeActiveHeading(
211
+ elements: Iterable<Element>,
212
+ onActiveHeading: (element: Element) => void,
213
+ ) {
214
+ const visible = new Set<Element>();
215
+ let isObserving = true;
216
+ const observer = new IntersectionObserver(
217
+ (changes) => {
218
+ if (!isObserving) {
219
+ return;
220
+ }
221
+ for (const { target, isIntersecting } of changes) {
222
+ if (isIntersecting) {
223
+ visible.add(target);
224
+ } else {
225
+ visible.delete(target);
226
+ }
66
227
  }
67
- };
68
228
 
69
- observerRef.current = new IntersectionObserver(callback, {
70
- root: getRootScrollableElement(),
229
+ let topmost: Element | undefined;
230
+ let top = Infinity;
231
+ for (const element of visible) {
232
+ if (!element.isConnected) {
233
+ continue;
234
+ }
235
+ const position = element.getBoundingClientRect().top;
236
+ if (position < top) {
237
+ topmost = element;
238
+ top = position;
239
+ }
240
+ }
241
+ if (topmost) {
242
+ onActiveHeading(topmost);
243
+ }
244
+ },
245
+ {
246
+ root:
247
+ getInitialAppMode() === "edit"
248
+ ? document.getElementById("App")
249
+ : undefined,
71
250
  rootMargin: "0px",
72
251
  threshold: 0,
73
- });
252
+ },
253
+ );
254
+ for (const element of elements) {
255
+ observer.observe(element);
256
+ }
74
257
 
75
- headerElements.forEach((element) => {
76
- if (element) {
77
- const identifier: OutlineItem["by"] = headingToIdentifier(element[0]);
78
- const idxOfEl: number = headerElements
79
- .map(([el]: readonly [HTMLElement, string]) => el)
80
- .filter((el: HTMLElement) =>
81
- "id" in identifier
82
- ? el.id === identifier.id
83
- : el.textContent === element[0].textContent,
84
- )
85
- .indexOf(element[0]);
86
- occurrences.current.set(element[0], idxOfEl);
87
- observerRef.current?.observe(element[0]);
258
+ return () => {
259
+ isObserving = false;
260
+ observer.disconnect();
261
+ };
262
+ }
263
+
264
+ interface OutlineSnapshot {
265
+ targets: OutlineTarget[];
266
+ activeKey: string | undefined;
267
+ }
268
+
269
+ const EMPTY_OUTLINE: OutlineSnapshot = { targets: [], activeKey: undefined };
270
+
271
+ function createOutlineTracker(locators: OutlineLocators) {
272
+ let snapshot = EMPTY_OUTLINE;
273
+ const subscribe = createSharedSubscription((notify) => {
274
+ let activeHeading: Element | undefined;
275
+ let stopTrackingActive: (() => void) | undefined;
276
+ const stopTrackingTargets = observeOutlineTargets(locators, (targets) => {
277
+ if (
278
+ targets.length === snapshot.targets.length &&
279
+ targets.every(
280
+ (target, i) => target.element === snapshot.targets[i].element,
281
+ )
282
+ ) {
283
+ return;
284
+ }
285
+ stopTrackingActive?.();
286
+
287
+ const keysByElement = new Map<Element, string>();
288
+ for (const { element, key } of targets) {
289
+ if (element) {
290
+ keysByElement.set(element, key);
291
+ }
292
+ }
293
+ const activeKey = activeHeading && keysByElement.get(activeHeading);
294
+ if (activeKey === undefined) {
295
+ activeHeading = undefined;
88
296
  }
297
+ snapshot = { targets, activeKey };
298
+ notify();
299
+
300
+ stopTrackingActive =
301
+ keysByElement.size === 0
302
+ ? undefined
303
+ : observeActiveHeading(keysByElement.keys(), (element) => {
304
+ const activeKey = keysByElement.get(element);
305
+ if (activeKey !== undefined && activeKey !== snapshot.activeKey) {
306
+ activeHeading = element;
307
+ snapshot = { targets, activeKey };
308
+ notify();
309
+ }
310
+ });
89
311
  });
90
312
 
91
313
  return () => {
92
- if (observerRef.current) {
93
- observerRef.current.disconnect();
94
- }
95
- topmostHeader.current = null;
314
+ stopTrackingTargets();
315
+ stopTrackingActive?.();
316
+ snapshot = EMPTY_OUTLINE;
96
317
  };
97
- }, [headerElements]);
318
+ });
98
319
 
99
- return { activeHeaderId, activeOccurrences };
320
+ return { locators, subscribe, getSnapshot: () => snapshot };
100
321
  }
101
322
 
102
- /**
103
- * Finds all the outline elements in the document
104
- */
105
- export function findOutlineElements(items: OutlineItem[]) {
106
- if (items.length === 0) {
107
- return [];
108
- }
109
-
110
- // Map of selector to its occurrences
111
- const seen = new Map<string, number>();
323
+ const emptySnapshot = () => EMPTY_OUTLINE;
324
+ const inactiveTracker = {
325
+ subscribe: () => Functions.NOOP,
326
+ getSnapshot: emptySnapshot,
327
+ };
112
328
 
113
- return items
114
- .map((item) => {
115
- const identifier = "id" in item.by ? item.by.id : item.by.path;
116
- const selector = JSON.stringify(item.by);
117
- // Keep track of how many times we've seen this selector
118
- const occurrences = seen.get(selector) ?? 0;
119
- seen.set(selector, occurrences + 1);
329
+ const outlineLocatorsAtom = selectAtom(
330
+ notebookOutline,
331
+ ({ items }) => outlineLocators(items),
332
+ dequal,
333
+ );
334
+ const outlineTrackerAtom = atom((get) =>
335
+ createOutlineTracker(get(outlineLocatorsAtom)),
336
+ );
120
337
 
121
- const el = findOutlineItem(item, occurrences);
122
- if (!el) {
123
- return null;
124
- }
338
+ export function useActiveOutline(minItems = 1) {
339
+ const { items } = useAtomValue(notebookOutline);
340
+ const tracker = useAtomValue(outlineTrackerAtom);
341
+ const { locators } = tracker;
342
+ const { subscribe, getSnapshot } =
343
+ locators.length < minItems ? inactiveTracker : tracker;
344
+ const outline = useSyncExternalStore(subscribe, getSnapshot, emptySnapshot);
125
345
 
126
- return [el, identifier] as const;
127
- })
128
- .filter(Boolean);
346
+ const entries = useMemo(() => {
347
+ if (locators.length < minItems) {
348
+ return [];
349
+ }
350
+ return locators.map(({ key }, index) => {
351
+ const target = outline.targets[index];
352
+ return {
353
+ key,
354
+ item: items[index],
355
+ element: target?.key === key ? target.element : undefined,
356
+ };
357
+ });
358
+ }, [items, locators, minItems, outline.targets]);
359
+ return { entries, activeKey: outline.activeKey };
129
360
  }
130
361
 
131
- /**
132
- * Scrolls to the outline item in the document
133
- */
134
- export function scrollToOutlineItem(item: OutlineItem, index: number) {
135
- const element = findOutlineItem(item, index);
136
- if (!element) {
362
+ export function scrollToOutlineEntry({ element, item }: OutlineEntry) {
363
+ if (!element?.isConnected) {
137
364
  Logger.warn("Could not find element for outline item", item);
138
365
  return;
139
366
  }
140
367
 
141
368
  element.scrollIntoView({ behavior: "smooth", block: "start" });
142
-
143
- // Add underline to the element for a few seconds
144
369
  element.classList.add("outline-item-highlight");
145
370
  setTimeout(() => {
146
371
  element.classList.remove("outline-item-highlight");
147
372
  }, 3000);
148
373
  }
149
-
150
- /**
151
- * Finds the element in the document that matches the outline item
152
- */
153
- export function findOutlineItem(
154
- item: OutlineItem,
155
- index: number,
156
- ): HTMLElement | null {
157
- if ("id" in item.by) {
158
- // Selectors may be duplicated, so we need to use querySelectorAll
159
- // IDs that start with a number are invalid, so we need to escape them
160
- const elems = document.querySelectorAll<HTMLElement>(
161
- `[id="${CSS.escape(item.by.id)}"]`,
162
- );
163
- return elems[index];
164
- }
165
- const el = document.evaluate(
166
- item.by.path,
167
- document,
168
- null,
169
- XPathResult.FIRST_ORDERED_NODE_TYPE,
170
- null,
171
- ).singleNodeValue as HTMLElement;
172
- return el;
173
- }