@malloy-publisher/sdk 0.0.248 → 0.0.250

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 (202) hide show
  1. package/README.md +37 -17
  2. package/TREE_SHAKING.md +5 -0
  3. package/bunfig.toml +3 -0
  4. package/dist/ServerProvider-CcfeBpt3.cjs.js +1 -0
  5. package/dist/{ServerProvider-BxEh3nFI.es.js → ServerProvider-EqBlMMqx.es.js} +1056 -905
  6. package/dist/client/api.d.ts +306 -9
  7. package/dist/client/index.cjs.js +1 -1
  8. package/dist/client/index.es.js +74 -70
  9. package/dist/components/Dashboard/Dashboard.d.ts +49 -0
  10. package/dist/components/Dashboard/DashboardTile.d.ts +48 -0
  11. package/dist/components/Dashboard/index.d.ts +2 -0
  12. package/dist/components/Notebook/Notebook.d.ts +46 -8
  13. package/dist/components/Notebook/NotebookCell.d.ts +37 -3
  14. package/dist/components/Notebook/runPlan.d.ts +29 -0
  15. package/dist/components/Notebook/types.d.ts +10 -0
  16. package/dist/components/Package/ContentTypeIcon.d.ts +17 -1
  17. package/dist/components/Package/Package.d.ts +1 -4
  18. package/dist/components/RenderedResult/RenderedResult.d.ts +7 -1
  19. package/dist/components/RenderedResult/ResultContainer.d.ts +3 -1
  20. package/dist/components/ResultsDialog.d.ts +4 -1
  21. package/dist/components/ServerProvider.d.ts +2 -1
  22. package/dist/components/click_helper.d.ts +10 -1
  23. package/dist/components/drill/index.d.ts +3 -0
  24. package/dist/components/drill/markDrillableCells.d.ts +55 -0
  25. package/dist/components/drill/resolveDrill.d.ts +139 -0
  26. package/dist/components/drill/useDrill.d.ts +63 -0
  27. package/dist/components/given/GivenInput.d.ts +27 -3
  28. package/dist/components/given/GivensPanel.d.ts +36 -7
  29. package/dist/components/given/filterValue.d.ts +97 -0
  30. package/dist/components/given/index.d.ts +1 -1
  31. package/dist/components/given/paramCodec.d.ts +60 -0
  32. package/dist/components/index.d.ts +4 -1
  33. package/dist/components/styles.d.ts +31 -0
  34. package/dist/constants/docLinks.d.ts +6 -0
  35. package/dist/{core-C86Rb7tJ.cjs.js → core-CVXEUnnm.cjs.js} +1 -1
  36. package/dist/{core-BuvlzSIX.es.js → core-Cr-9Wkp3.es.js} +1 -1
  37. package/dist/hooks/givenValue.d.ts +10 -0
  38. package/dist/hooks/index.d.ts +3 -1
  39. package/dist/hooks/useGivensState.d.ts +64 -0
  40. package/dist/hooks/useSuggestOptions.d.ts +78 -0
  41. package/dist/index-C-KeIwsG.cjs.js +339 -0
  42. package/dist/{index-BdtAZ5k6.es.js → index-DVkelll3.es.js} +40981 -39669
  43. package/dist/index.cjs.js +1 -1
  44. package/dist/index.es.js +77 -62
  45. package/dist/theme/types.d.ts +9 -0
  46. package/dist/utils/malloyString.d.ts +7 -0
  47. package/package.json +3 -1
  48. package/src/client-entry.ts +3 -0
  49. package/src/components/AnalyzePackageButton.tsx +3 -0
  50. package/src/components/ApiErrorDisplay.tsx +3 -0
  51. package/src/components/Connections/AddConnectionDialog.tsx +13 -1
  52. package/src/components/Connections/DeleteConnectionDialog.tsx +3 -0
  53. package/src/components/Connections/EditConnectionDialog.tsx +3 -0
  54. package/src/components/Connections/common.ts +3 -0
  55. package/src/components/DOMElement/DOMElement.tsx +3 -0
  56. package/src/components/DOMElement/index.ts +3 -0
  57. package/src/components/Dashboard/Dashboard.tsx +398 -0
  58. package/src/components/Dashboard/DashboardTile.tsx +153 -0
  59. package/src/components/Dashboard/index.ts +5 -0
  60. package/src/components/DataAppViewer/DataAppViewer.tsx +3 -0
  61. package/src/components/DataAppViewer/index.ts +3 -0
  62. package/src/components/Environment/About.tsx +3 -0
  63. package/src/components/Environment/AddPackageDialog.tsx +3 -0
  64. package/src/components/Environment/ConnectionExplorer.tsx +3 -0
  65. package/src/components/Environment/Connections.tsx +3 -0
  66. package/src/components/Environment/DeletePackageDialog.tsx +3 -0
  67. package/src/components/Environment/EditPackageDialog.tsx +3 -0
  68. package/src/components/Environment/Environment.tsx +3 -0
  69. package/src/components/Environment/Packages.tsx +3 -0
  70. package/src/components/Environment/index.ts +3 -0
  71. package/src/components/Home/AddEnvironmentDialog.tsx +3 -0
  72. package/src/components/Home/DeleteEnvironmentDialog.tsx +3 -0
  73. package/src/components/Home/EditEnvironmentDialog.tsx +3 -0
  74. package/src/components/Home/Home.tsx +113 -23
  75. package/src/components/Home/index.ts +3 -0
  76. package/src/components/Loading.tsx +3 -0
  77. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +3 -0
  78. package/src/components/Materializations/CreateMaterializationDialog.tsx +3 -0
  79. package/src/components/Materializations/DeleteMaterializationDialog.tsx +3 -0
  80. package/src/components/Materializations/EnvironmentMaterializations.tsx +3 -0
  81. package/src/components/Materializations/ManifestView.tsx +3 -0
  82. package/src/components/Materializations/MaterializationDetailDialog.tsx +3 -0
  83. package/src/components/Materializations/MaterializationRunsList.tsx +3 -0
  84. package/src/components/Materializations/Materializations.tsx +3 -0
  85. package/src/components/Materializations/ScheduleCard.tsx +3 -0
  86. package/src/components/Materializations/SectionLabel.tsx +3 -0
  87. package/src/components/Materializations/SetScheduleDialog.tsx +3 -0
  88. package/src/components/Materializations/TriggerChip.tsx +3 -0
  89. package/src/components/Materializations/cron.ts +3 -0
  90. package/src/components/Materializations/index.ts +3 -0
  91. package/src/components/Materializations/utils.ts +3 -0
  92. package/src/components/Model/Model.tsx +3 -0
  93. package/src/components/Model/ModelCell.tsx +3 -0
  94. package/src/components/Model/ModelExplorer.tsx +3 -0
  95. package/src/components/Model/ModelExplorerDialog.tsx +3 -0
  96. package/src/components/Model/SourcesExplorer.tsx +3 -0
  97. package/src/components/Model/index.ts +3 -0
  98. package/src/components/Model/useModelData.ts +3 -0
  99. package/src/components/Notebook/Notebook.tsx +447 -390
  100. package/src/components/Notebook/NotebookCell.tsx +120 -3
  101. package/src/components/Notebook/index.ts +3 -0
  102. package/src/components/Notebook/runPlan.spec.ts +155 -0
  103. package/src/components/Notebook/runPlan.ts +67 -0
  104. package/src/components/Notebook/types.ts +14 -0
  105. package/src/components/Package/ContentTypeIcon.spec.ts +91 -0
  106. package/src/components/Package/ContentTypeIcon.tsx +80 -6
  107. package/src/components/Package/FileTreeView.tsx +3 -0
  108. package/src/components/Package/Models.tsx +3 -0
  109. package/src/components/Package/Package.tsx +151 -38
  110. package/src/components/Package/index.ts +3 -0
  111. package/src/components/QueryResult/QueryResult.tsx +3 -0
  112. package/src/components/QueryResult/index.ts +3 -0
  113. package/src/components/RenderedResult/RenderedResult.tsx +312 -19
  114. package/src/components/RenderedResult/ResultContainer.tsx +31 -1
  115. package/src/components/RenderedResult/index.ts +3 -0
  116. package/src/components/RenderedResult/renderLogs.spec.ts +3 -0
  117. package/src/components/RenderedResult/renderLogs.ts +3 -0
  118. package/src/components/ResultsDialog.tsx +8 -0
  119. package/src/components/ServerProvider.tsx +5 -0
  120. package/src/components/Workbook/BrowserWorkbookStorage.ts +3 -0
  121. package/src/components/Workbook/EditableMalloyCell.tsx +3 -0
  122. package/src/components/Workbook/ModelPicker.tsx +3 -0
  123. package/src/components/Workbook/MutableCell.tsx +3 -0
  124. package/src/components/Workbook/Workbook.tsx +3 -0
  125. package/src/components/Workbook/WorkbookList.tsx +3 -0
  126. package/src/components/Workbook/WorkbookManager.ts +3 -0
  127. package/src/components/Workbook/WorkbookStorage.ts +3 -0
  128. package/src/components/Workbook/WorkbookStorageProvider.tsx +3 -0
  129. package/src/components/Workbook/index.ts +3 -0
  130. package/src/components/click_helper.ts +17 -1
  131. package/src/components/drill/index.ts +28 -0
  132. package/src/components/drill/markDrillableCells.dom.spec.ts +313 -0
  133. package/src/components/drill/markDrillableCells.spec.ts +109 -0
  134. package/src/components/drill/markDrillableCells.ts +314 -0
  135. package/src/components/drill/resolveDrill.spec.ts +449 -0
  136. package/src/components/drill/resolveDrill.ts +375 -0
  137. package/src/components/drill/useDrill.tsx +203 -0
  138. package/src/components/filter/DimensionFilter.tsx +3 -0
  139. package/src/components/filter/index.ts +3 -0
  140. package/src/components/filter/utils.ts +16 -5
  141. package/src/components/given/GivenInput.spec.tsx +498 -15
  142. package/src/components/given/GivenInput.tsx +565 -30
  143. package/src/components/given/GivensPanel.spec.tsx +175 -0
  144. package/src/components/given/GivensPanel.tsx +142 -32
  145. package/src/components/given/filterValue.spec.ts +364 -0
  146. package/src/components/given/filterValue.ts +207 -0
  147. package/src/components/given/index.ts +8 -1
  148. package/src/components/given/paramCodec.spec.ts +857 -0
  149. package/src/components/given/paramCodec.ts +483 -0
  150. package/src/components/given/utils.spec.ts +3 -0
  151. package/src/components/given/utils.ts +3 -0
  152. package/src/components/highlighter.ts +3 -0
  153. package/src/components/index.ts +7 -1
  154. package/src/components/styles.ts +38 -3
  155. package/src/constants/docLinks.spec.ts +54 -0
  156. package/src/constants/docLinks.ts +29 -0
  157. package/src/hooks/givenValue.ts +13 -0
  158. package/src/hooks/index.ts +9 -4
  159. package/src/hooks/useDimensionFilters.ts +4 -7
  160. package/src/hooks/useDimensionFiltersFromSpec.ts +3 -0
  161. package/src/hooks/useDimensionFiltersQuery.ts +4 -7
  162. package/src/hooks/useDimensionalFilterRangeData.ts +4 -7
  163. package/src/hooks/useGivensState.spec.ts +449 -0
  164. package/src/hooks/useGivensState.ts +340 -0
  165. package/src/hooks/useModelGivens.ts +3 -0
  166. package/src/hooks/useQueryWithApiError.ts +3 -0
  167. package/src/hooks/useRawQueryData.ts +3 -0
  168. package/src/hooks/useSuggestOptions.spec.ts +112 -0
  169. package/src/hooks/useSuggestOptions.ts +263 -0
  170. package/src/index.ts +3 -0
  171. package/src/react-app-env.d.ts +3 -0
  172. package/src/theme/ThemeContext.tsx +3 -0
  173. package/src/theme/buildMalloyExplicitTheme.ts +3 -0
  174. package/src/theme/buildTableCssVars.spec.ts +3 -0
  175. package/src/theme/buildTableCssVars.ts +7 -0
  176. package/src/theme/buildVegaThemeOverride.spec.ts +3 -0
  177. package/src/theme/buildVegaThemeOverride.ts +3 -0
  178. package/src/theme/defaults.ts +3 -0
  179. package/src/theme/index.ts +3 -0
  180. package/src/theme/keys.ts +3 -0
  181. package/src/theme/readChartAnnotations.spec.ts +3 -0
  182. package/src/theme/readChartAnnotations.ts +3 -0
  183. package/src/theme/resolveTheme.spec.ts +16 -0
  184. package/src/theme/resolveTheme.ts +6 -0
  185. package/src/theme/types.ts +12 -0
  186. package/src/utils/dataAppEmbed.spec.ts +3 -0
  187. package/src/utils/dataAppEmbed.ts +3 -0
  188. package/src/utils/formatting.spec.ts +3 -0
  189. package/src/utils/formatting.ts +3 -0
  190. package/src/utils/malloyString.spec.ts +24 -0
  191. package/src/utils/malloyString.ts +12 -0
  192. package/src/utils/parsing.spec.ts +3 -0
  193. package/src/utils/parsing.ts +3 -0
  194. package/src/utils/queryClient.ts +3 -0
  195. package/test/README.md +21 -10
  196. package/test/setup.ts +3 -0
  197. package/vite.config.ts +3 -0
  198. package/dist/ServerProvider-Dg5S1qBU.cjs.js +0 -1
  199. package/dist/hooks/useGivensForm.d.ts +0 -35
  200. package/dist/index-MES4MGpQ.cjs.js +0 -309
  201. package/src/hooks/useGivensForm.spec.ts +0 -99
  202. package/src/hooks/useGivensForm.ts +0 -107
@@ -1,35 +1,22 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
1
4
  import "@malloydata/malloy-explorer/styles.css";
2
- import * as Malloy from "@malloydata/malloy-interfaces";
3
- import { Box, Paper, Stack, Typography } from "@mui/material";
4
- import {
5
- MouseEvent,
6
- useCallback,
7
- useEffect,
8
- useMemo,
9
- useRef,
10
- useState,
11
- } from "react";
12
- import { RawNotebook, Source } from "../../client";
13
- import {
14
- getDimensionKey,
15
- useDimensionalFilterRangeData,
16
- } from "../../hooks/useDimensionalFilterRangeData";
17
- import {
18
- FilterSelection,
19
- useDimensionFilters,
20
- } from "../../hooks/useDimensionFilters";
21
- import { GivenValue, useGivensForm } from "../../hooks/useGivensForm";
5
+ import { Stack, Typography } from "@mui/material";
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
+ import { planRun } from "./runPlan";
8
+ import { RawNotebook } from "../../client";
9
+ import { GivenValue } from "../../hooks/givenValue";
10
+ import { useGivensState } from "../../hooks/useGivensState";
22
11
  import { useModelGivens } from "../../hooks/useModelGivens";
23
12
  import { useQueryWithApiError } from "../../hooks/useQueryWithApiError";
13
+ import { useSuggestOptions } from "../../hooks/useSuggestOptions";
24
14
  import { parseResourceUri } from "../../utils/formatting";
25
15
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
26
- import { DimensionFilter, RetrievalFunction } from "../filter/DimensionFilter";
27
- import {
28
- extractDimensionSpecs,
29
- parseAllSourceInfos,
30
- parseNotebookFilterAnnotation,
31
- } from "../filter/utils";
16
+ import type { NavigationClick } from "../click_helper";
17
+ import { encodeDrillValue, type DrillNavigation } from "../drill";
32
18
  import { GivensPanel } from "../given";
19
+ import { givensToRequest } from "../given/paramCodec";
33
20
  import { Loading } from "../Loading";
34
21
  import { useServer } from "../ServerProvider";
35
22
  import { CleanNotebookContainer, CleanNotebookSection } from "../styles";
@@ -39,23 +26,96 @@ import { EnhancedNotebookCell } from "./types";
39
26
  // Maximum number of concurrent cell executions to avoid overwhelming the server
40
27
  const MAX_CONCURRENT = 4;
41
28
 
29
+ /**
30
+ * How long a changed parameter has to stay changed before the notebook runs.
31
+ *
32
+ * Aborting the superseded run is not enough on its own: an abort cancels the
33
+ * HTTP request, but the cells already dispatched have reached the server and go
34
+ * on compiling and running against the customer's warehouse, and their answers
35
+ * are then thrown away. So autorun on a text control put one wave of doomed
36
+ * queries on that warehouse per keystroke. `origin/main` bounded the load by
37
+ * refusing to start a second run at all, which dropped the newest values;
38
+ * waiting for the value to settle bounds it without making that trade.
39
+ */
40
+ const GIVEN_SETTLE_MS = 400;
41
+
42
+ /**
43
+ * The server's own explanation of why a cell would not run.
44
+ *
45
+ * Publisher answers a refused query with `{code, message}`, and that message is
46
+ * the useful half: "filter 'state' is required", say. Falls back through the
47
+ * generic axios message to a fixed string, so a cell always has something to
48
+ * show rather than rendering an empty error box.
49
+ */
50
+ function cellErrorMessage(error: unknown): string {
51
+ const body = (
52
+ error as { response?: { data?: { message?: unknown } } } | undefined
53
+ )?.response?.data?.message;
54
+ if (typeof body === "string" && body !== "") return body;
55
+ if (error instanceof Error && error.message !== "") return error.message;
56
+ return "The server did not say why.";
57
+ }
58
+
42
59
  interface NotebookProps {
43
60
  resourceUri: string;
44
61
  maxResultSize?: number;
45
- /** Optional retrieval function for semantic search filters */
46
- retrievalFn?: RetrievalFunction;
47
- /** Optional SPA navigation handler for links inside the notebook. When
62
+ /**
63
+ * Parameter values from the host, typically its URL query parameters: the
64
+ * same contract `Dashboard` takes, so a link into a filtered notebook works
65
+ * the way a link into a filtered dashboard does.
66
+ */
67
+ givens?: Record<string, string>;
68
+ /**
69
+ * Applied parameter values, for a host that wants them in its URL. Fires
70
+ * with what the cells actually ran with, which is what makes the URL a link
71
+ * that reproduces the view.
72
+ *
73
+ * That is every committed change. Under `## autorun=false` a change is
74
+ * committed on Apply, so reports are batched; otherwise every change is
75
+ * committed and typing in a text control reports per keystroke. It does NOT
76
+ * run per keystroke: a changed value waits
77
+ * `GIVEN_SETTLE_MS` before anything is dispatched, so a burst of typing
78
+ * produces one run. A run that does start supersedes and aborts the one
79
+ * before it. The REPORTS are still per keystroke, so a host doing something
80
+ * expensive per call should debounce.
81
+ *
82
+ * `managed` names every given this notebook declares, set or not. A host
83
+ * writing to a shared query string needs it: `givens` alone says which
84
+ * parameters to write but not which to *remove*, and a host that guesses by
85
+ * removing everything it did not just receive deletes the unrelated
86
+ * parameters it has no business touching.
87
+ */
88
+ onGivensChange?: (
89
+ givens: Record<string, string>,
90
+ managed: readonly string[],
91
+ ) => void;
92
+ /**
93
+ * Optional SPA navigation handler for links inside the notebook. When
48
94
  * omitted, in-notebook links fall back to plain absolute anchors, so no
49
- * react-router context is required to render a notebook. */
50
- onNavigate?: (to: string, event?: MouseEvent) => void;
95
+ * react-router context is required to render a notebook.
96
+ *
97
+ * It does NOT carry drill. A `# drill { to=self }` filters this notebook
98
+ * through `given:` state and needs no handler at all, and a drill naming a
99
+ * dashboard goes through {@link onDrillNavigate}, which takes a destination
100
+ * rather than a URL.
101
+ */
102
+ onNavigate?: (to: string, event?: NavigationClick) => void;
103
+ /**
104
+ * Opens a `# drill { to=<dashboard> }` from a cell, seeded with the clicked
105
+ * value. Omitted on a host with no dashboard route, which leaves those
106
+ * destinations inert AND unmarked rather than painting a dead link.
107
+ */
108
+ onDrillNavigate?: (target: DrillNavigation, event?: MouseEvent) => void;
51
109
  }
52
110
 
53
111
  // Requires PackageProvider
54
112
  export default function Notebook({
55
113
  resourceUri,
56
114
  maxResultSize = 0,
57
- retrievalFn,
115
+ givens,
116
+ onGivensChange,
58
117
  onNavigate,
118
+ onDrillNavigate,
59
119
  }: NotebookProps) {
60
120
  const { apiClients } = useServer();
61
121
  const {
@@ -89,265 +149,262 @@ export default function Notebook({
89
149
  [],
90
150
  );
91
151
  const [isExecuting, setIsExecuting] = useState(false);
152
+ // A run is scheduled but its settle window has not elapsed. Separate from
153
+ // `isExecuting`, which covers only a run actually in flight.
154
+ const [runScheduled, setRunScheduled] = useState(false);
155
+ // The document the last run belonged to, for abandoning its requests when
156
+ // the reader moves to another notebook without this component unmounting.
157
+ const lastDocumentRef = useRef<string | undefined>(undefined);
92
158
  const [executionError, setExecutionError] = useState<Error | null>(null);
93
159
 
94
- // Parse filter configuration from notebook annotations (legacy ##(filters) approach)
95
- const filterConfig = useMemo(() => {
96
- if (!notebook) return null;
97
- return parseNotebookFilterAnnotation(notebook.annotations);
98
- }, [notebook]);
99
-
100
- // Parse all SourceInfos from notebook cells and create a map
101
- const sourceData = useMemo(() => {
102
- if (!notebook?.notebookCells) return null;
103
- return parseAllSourceInfos(notebook.notebookCells);
104
- }, [notebook]);
105
-
106
- const sourceInfoMap = useMemo(
107
- () => sourceData?.sourceInfoMap ?? new Map<string, Malloy.SourceInfo>(),
108
- [sourceData],
160
+ // Model-level `given:` declarations, and the state behind their controls.
161
+ // The same hook the dashboard viewer uses, so both surfaces get URL-
162
+ // addressable parameters, Apply batching, and `to=self` drill from one
163
+ // implementation rather than two that drift.
164
+ const declaredGivens = useModelGivens(notebook);
165
+ const declaredTypes = useMemo(
166
+ () =>
167
+ new Map(
168
+ declaredGivens
169
+ .filter((given) => given.name !== undefined)
170
+ .map((given) => [given.name as string, given.type]),
171
+ ),
172
+ [declaredGivens],
109
173
  );
110
- const modelPath = sourceData?.modelPath ?? null;
111
-
112
- // Extract server-side filter definitions from notebook sources
113
- // These come from #(filter) annotations parsed by the server
114
- const serverFilters = useMemo(() => {
115
- const result = new Map<string, Source["filters"]>();
116
- if (!notebook?.sources) return result;
117
- for (const source of notebook.sources as Source[]) {
118
- if (source.name && source.filters && source.filters.length > 0) {
119
- // Exclude implicit filters from the UI
120
- const visibleFilters = source.filters.filter((f) => !f.implicit);
121
- if (visibleFilters.length > 0) {
122
- result.set(source.name, visibleFilters);
123
- }
124
- }
125
- }
126
- return result;
127
- }, [notebook]);
128
-
129
- // Determine if we're using server-driven filters (#(filter)) or legacy (##(filters))
130
- const useServerFilters = serverFilters.size > 0;
131
-
132
- // Build dimension specs from filter config and source info map
133
- // Each spec includes source and model for proper query routing
134
- const dimensionSpecs = useMemo(() => {
135
- if (useServerFilters && modelPath) {
136
- // Server-driven: build specs from #(filter) metadata
137
- const specs: import("../../hooks/useDimensionalFilterRangeData").DimensionSpec[] =
138
- [];
139
- for (const [sourceName, filters] of serverFilters) {
140
- for (const filter of filters ?? []) {
141
- if (!filter.dimension || !filter.type) continue;
142
-
143
- // Choose widget type based on the dimension's data type first,
144
- // then fall back to the annotation's comparator type
145
- type FT =
146
- import("../../hooks/useDimensionalFilterRangeData").FilterType;
147
- let filterType: FT;
148
- const dimType = filter.dimensionType;
149
- if (dimType === "boolean") {
150
- filterType = "Boolean";
151
- } else if (
152
- dimType === "date" ||
153
- dimType === "timestamp" ||
154
- dimType === "timestamptz"
155
- ) {
156
- filterType = "DateMinMax";
157
- } else if (dimType === "number") {
158
- filterType =
159
- filter.type === "equal" || filter.type === "in"
160
- ? "Star"
161
- : "MinMax";
162
- } else {
163
- const filterTypeMap: Record<string, FT> = {
164
- equal: "Star",
165
- in: "Star",
166
- like: "Star",
167
- greater_than: "MinMax",
168
- less_than: "MinMax",
169
- };
170
- filterType = filterTypeMap[filter.type] ?? "Star";
171
- }
172
174
 
173
- // Derive the match type from the #(filter) annotation type so
174
- // the UI never needs to show a match-type dropdown.
175
- type MT = import("../../hooks/useDimensionFilters").MatchType;
176
- const matchTypeMap: Record<string, MT> = {
177
- equal: "Equals",
178
- in: "Equals",
179
- like: "Contains",
180
- greater_than:
181
- filterType === "DateMinMax" ? "After" : "Greater Than",
182
- less_than:
183
- filterType === "DateMinMax" ? "Before" : "Less Than",
184
- };
185
- const defaultMatchType: MT | undefined =
186
- matchTypeMap[filter.type!];
187
-
188
- const filterLabel =
189
- filter.name !== filter.dimension ? filter.name : undefined;
190
- specs.push({
191
- source: sourceName,
192
- model: modelPath,
193
- dimensionName: filter.dimension!,
194
- filterType,
195
- label: filterLabel,
196
- filterName: filter.name ?? filter.dimension!,
197
- defaultMatchType,
198
- required: filter.required ?? false,
199
- });
200
- }
201
- }
202
- return specs;
203
- }
204
- // Legacy: use ##(filters) + #(filter) annotation approach
205
- if (!filterConfig || sourceInfoMap.size === 0 || !modelPath) return [];
206
- return extractDimensionSpecs(
207
- sourceInfoMap,
208
- filterConfig.filters,
209
- modelPath,
210
- );
211
- }, [
212
- useServerFilters,
213
- serverFilters,
214
- filterConfig,
215
- sourceInfoMap,
216
- modelPath,
217
- ]);
218
-
219
- // Initialize dimension filters hook
220
- const { filterStates, updateFilter, getActiveFilters } = useDimensionFilters(
221
- {
222
- dimensionSpecs,
175
+ // Silent until the notebook has actually loaded. Which givens exist is not
176
+ // known before then: `useModelGivens(undefined)` is empty, so a report in
177
+ // that window says "no values, and I manage nothing", which a host reasonably
178
+ // reads as "clear what you wrote". During an in-app navigation from one
179
+ // notebook to another that window sits between the two, and the parameters it
180
+ // would clear can belong to the notebook now ARRIVING. A notebook that
181
+ // genuinely declares no givens still reports, because by then the empty set
182
+ // is the answer rather than the absence of one.
183
+ const reportGivens = useCallback(
184
+ (next: Record<string, string>) => {
185
+ if (!isSuccess) return;
186
+ onGivensChange?.(next, Array.from(declaredTypes.keys()));
223
187
  },
188
+ [isSuccess, onGivensChange, declaredTypes],
224
189
  );
225
190
 
226
- // Get active filters - include filterStates in deps to ensure updates when individual items change
227
- const activeFilters = useMemo(
228
- () => getActiveFilters(),
229
- // eslint-disable-next-line react-hooks/exhaustive-deps
230
- [filterStates, getActiveFilters],
231
- );
191
+ // Read off the notebook now that the server derives it: a file-level
192
+ // `## autorun=false` arrives as `RawNotebook.autorun`, the same field with
193
+ // the same default that a dashboard's `# artifact { autorun=false }`
194
+ // produces. This was hardcoded true while nothing populated the field, on
195
+ // the grounds that a spec declaring one nothing produces is a spec that
196
+ // lies; the reader has landed, so this is the follow-up that comment named.
197
+ //
198
+ // Absent means autorun, so only an explicit `false` batches. Batching
199
+ // matters more here than on a dashboard: one control change re-runs every
200
+ // cell in the document.
201
+ const autorun = notebook?.autorun !== false;
202
+ const { draft, applied, setGiven, reset, apply, pending } = useGivensState({
203
+ declaredTypes,
204
+ // Where the controls start, from a file-level `## givens { … }`. A URL
205
+ // beats them, so a shared link still shows what the sender saw.
206
+ startingValues: notebook?.startingGivens,
207
+ params: givens,
208
+ // Withheld until the notebook has loaded, rather than accepted and
209
+ // dropped. `useGivensState` records what it last reported BEFORE calling
210
+ // out, so a report the callback throws away is remembered as delivered
211
+ // and never retried, leaving a parameter stranded in the host's URL.
212
+ // Passing undefined makes the hook skip the report entirely, which leaves
213
+ // its record untouched and the next real change still reportable.
214
+ onParamsChange: isSuccess ? reportGivens : undefined,
215
+ // Which notebook these edits belong to. Navigating between notebooks
216
+ // reuses this component, so without it one notebook's applied values
217
+ // carried into the next whenever both started from the same values.
218
+ documentKey: resourceUri,
219
+ autorun,
220
+ });
232
221
 
233
- // Extract model-level givens declared via `given:` and manage user overrides
234
- const declaredGivens = useModelGivens(notebook);
222
+ // A notebook's model path is the notebook itself: `suggest` queries run
223
+ // against the same model the cells do.
235
224
  const {
236
- givenValues,
237
- updateGiven,
238
- clearAll: clearAllGivens,
239
- } = useGivensForm(declaredGivens);
240
-
241
- // Create a map of dimension key -> source name for quick lookup (used by filter UI)
242
- const _dimensionToSourceMap = useMemo(() => {
243
- const map = new Map<string, string>();
244
- for (const spec of dimensionSpecs) {
245
- const key = getDimensionKey(spec);
246
- map.set(key, spec.source);
225
+ options: givenOptions,
226
+ isLoading: givenOptionsLoading,
227
+ failed: givenOptionsFailed,
228
+ } = useSuggestOptions(
229
+ environmentName,
230
+ packageName,
231
+ notebookPath,
232
+ declaredGivens,
233
+ );
234
+
235
+ // The declared names, indexed case-insensitively, so a drill tag resolves
236
+ // whichever way the two were spelled.
237
+ //
238
+ // Neither convention can be assumed. `# drill` defaults the given name to
239
+ // the DIMENSION's name, which is conventionally lower_snake, while givens
240
+ // are conventionally SHOUTED (both in-repo examples declare `REGION` and
241
+ // `MIN_AMOUNT`). An exact match therefore failed for the common case, and
242
+ // upper-casing the dimension name, which is what this did first, only moved
243
+ // the failure onto models that spell their givens in lower case. Folding
244
+ // case resolves both instead of picking a side.
245
+ const givenNamesByFold = useMemo(() => {
246
+ const byFold = new Map<string, string>();
247
+ for (const name of declaredTypes.keys()) {
248
+ // First declaration wins, so a model with `REGION` and `region` keeps
249
+ // the one it declared first rather than silently flipping.
250
+ if (!byFold.has(name.toLowerCase()))
251
+ byFold.set(name.toLowerCase(), name);
247
252
  }
248
- return map;
249
- }, [dimensionSpecs]);
250
-
251
- // Fetch filter range data when we have dimension specs.
252
- // Do NOT pass activeFilters here — the index query should return all
253
- // possible values for each dimension, not just those matching the
254
- // current selection. Otherwise selecting "FORD" would hide every other
255
- // manufacturer from the dropdown.
256
- const { data: filterValuesData } = useDimensionalFilterRangeData({
257
- environment: environmentName,
258
- package: packageName,
259
- dimensionSpecs,
260
- versionId,
261
- enabled: dimensionSpecs.length > 0,
262
- });
253
+ return byFold;
254
+ }, [declaredTypes]);
255
+
256
+ /** The declared given a drill tag's name refers to, or undefined. */
257
+ const resolveGiven = useCallback(
258
+ (given: string) =>
259
+ declaredTypes.has(given)
260
+ ? given
261
+ : givenNamesByFold.get(given.toLowerCase()),
262
+ [declaredTypes, givenNamesByFold],
263
+ );
263
264
 
264
- /**
265
- * Convert active FilterSelections into a flat { filterName: value } map
266
- * suitable for the server's filter_params parameter.
267
- * Uses filterName from the selection (propagated from the spec) as the
268
- * API param key, falling back to dimensionName.
269
- */
270
- const buildFilterParams = useCallback(
271
- (filtersToApply: FilterSelection[]): string | undefined => {
272
- if (filtersToApply.length === 0) return undefined;
265
+ // `to=self` filters in place, which only works for a given this notebook
266
+ // actually declares: sending one it cannot bind would fail every cell. The
267
+ // mismatch is reported to the author rather than issued: same rule, same
268
+ // wording, as the dashboard viewer.
269
+ // Asked before a cell is painted as drillable, so the affordance matches what
270
+ // a click can actually do. The refusal below still stands as a backstop for a
271
+ // caller that does not ask.
272
+ const canDrillSelf = useCallback(
273
+ (given: string) => resolveGiven(given) !== undefined,
274
+ [resolveGiven],
275
+ );
273
276
 
274
- const toParamString = (v: unknown): string => {
275
- if (v instanceof Date) {
276
- return v.toISOString().slice(0, 10);
277
- }
278
- return String(v);
279
- };
280
-
281
- const params: { [key: string]: string | string[] } = {};
282
- for (const f of filtersToApply) {
283
- const paramName = f.filterName ?? f.dimensionName;
284
- const val = f.value;
285
- if (Array.isArray(val)) {
286
- params[paramName] = val.map(toParamString);
287
- } else if (val !== undefined && val !== null) {
288
- params[paramName] = toParamString(val);
289
- }
277
+ const onDrillSelf = useCallback(
278
+ (given: string, rawValue: unknown) => {
279
+ const declared = resolveGiven(given);
280
+ if (declared === undefined) {
281
+ console.warn(
282
+ `# drill { to=self } tried to set '${given}', which ` +
283
+ `'${notebookPath}' does not declare as a given. Name the ` +
284
+ `given with 'given=' on the drill tag.`,
285
+ );
286
+ return;
290
287
  }
291
- return Object.keys(params).length > 0
292
- ? JSON.stringify(params)
293
- : undefined;
288
+ // Encoded against the declared type of the given being set, which is
289
+ // knowable here and is not knowable at the click. Set under the name
290
+ // the MODEL declares, not the one the tag spelled, so the value goes
291
+ // into the URL and the request under the one name the server knows.
292
+ const declaredType = declaredTypes.get(declared);
293
+ const value = encodeDrillValue(rawValue, declaredType);
294
+ if (value === undefined) {
295
+ // Say so. Returning in silence left a whole column painted as
296
+ // clickable while every click did nothing, and a `given=` pointing
297
+ // at a type the clicked value cannot become is an authoring
298
+ // mistake the author has no other way to see. The sibling refusal
299
+ // in `resolveDrill` warns for the same reason.
300
+ console.warn(
301
+ `Drill declined: ${JSON.stringify(rawValue)} cannot be a value for given "${declared}"` +
302
+ (declaredType ? ` of type ${declaredType}` : ""),
303
+ );
304
+ return;
305
+ }
306
+ setGiven(declared, value);
294
307
  },
295
- [],
308
+ [declaredTypes, notebookPath, resolveGiven, setGiven],
296
309
  );
297
310
 
298
311
  /**
299
- * Serialize given-value overrides into the JSON-encoded string the server
300
- * expects on the notebook-cell GET endpoint's `givens` query param.
301
- * Date values are rendered as YYYY-MM-DD; everything else passes through
302
- * the standard JSON encoder.
312
+ * The `givens` query param for the notebook-cell GET: the same map the
313
+ * dashboard's POST body carries, JSON-encoded because this endpoint takes it
314
+ * in the URL. Built by the shared codec so a given is encoded identically
315
+ * whichever surface runs it.
303
316
  */
304
317
  const buildGivens = useCallback(
305
318
  (values: Map<string, GivenValue>): string | undefined => {
306
- if (values.size === 0) return undefined;
307
- const encode = (v: GivenValue): unknown => {
308
- if (v instanceof Date) return v.toISOString().slice(0, 10);
309
- if (Array.isArray(v)) return v.map((item) => encode(item));
310
- return v;
311
- };
312
- const params: Record<string, unknown> = {};
313
- values.forEach((value, name) => {
314
- if (value === null || value === undefined) return;
315
- params[name] = encode(value);
316
- });
317
- return Object.keys(params).length > 0
318
- ? JSON.stringify(params)
319
+ const request = givensToRequest(values, declaredTypes);
320
+ return Object.keys(request).length > 0
321
+ ? JSON.stringify(request)
319
322
  : undefined;
320
323
  },
321
- [],
324
+ [declaredTypes],
322
325
  );
323
326
 
324
- // Unified cell execution function
325
- // Executes all notebook cells, passing server-side filter params and givens
326
- // Runs up to 4 requests in parallel for better performance
327
+ /**
328
+ * Run every code cell with one set of given values, up to
329
+ * {@link MAX_CONCURRENT} at a time.
330
+ *
331
+ * Each run takes a number from `runIdRef`, and a run that is no longer the
332
+ * current one drops its results on the floor. Cells resolve independently
333
+ * and out of order, so without that a slow cell from the previous values
334
+ * would land after the new run's and leave a stale number on screen under a
335
+ * control row claiming otherwise.
336
+ */
337
+ const runIdRef = useRef(0);
338
+ const inFlightRef = useRef<AbortController | null>(null);
339
+ const lastRunRef = useRef<string | null>(null);
340
+ /** The run waiting out {@link GIVEN_SETTLE_MS}, so a re-render does not restart its clock. */
341
+ const pendingRunRef = useRef<
342
+ { key: string; timer: ReturnType<typeof setTimeout> } | undefined
343
+ >(undefined);
344
+
345
+ // Cancel whatever is in flight when this component goes away, so navigating
346
+ // off a twelve-cell notebook does not leave twelve requests to complete and be
347
+ // thrown away.
348
+ //
349
+ // Its OWN effect, with an empty dependency list, and that is the whole point:
350
+ // as the run effect's cleanup this ran on every dependency change instead. The
351
+ // host echoes each reported parameter back, which gives `applied` a new
352
+ // identity with identical content, so the cleanup fired and aborted the run
353
+ // the control change had just started, while the run effect's `runKey` guard
354
+ // saw an unchanged key and refused to start a replacement. Every cell was left
355
+ // blank, with no result, no error and no spinner, until a reload. Measured on
356
+ // `governed-analytics/orders.malloynb`: 4 rendered results before a control
357
+ // change, 0 after.
358
+ useEffect(
359
+ () => () => {
360
+ inFlightRef.current?.abort();
361
+ // Forget which run was last started, so a component that comes back
362
+ // runs again instead of trusting a key whose run was just cancelled.
363
+ // The case it is reasoned from, and NOT one I could reproduce: React's
364
+ // StrictMode mounts, cleans up, and mounts again in development, and
365
+ // refs survive that. A first mount that already had the notebook
366
+ // cached would start a run, this cleanup would abort it, and the
367
+ // second mount would see an unchanged `runKey` and decline to start a
368
+ // replacement. I could not get a browser into that state, so treat the
369
+ // reset as belt-and-braces rather than a measured fix. It is right on
370
+ // its own terms either way: a key that says "this run happened" must
371
+ // not outlive the run being cancelled.
372
+ lastRunRef.current = null;
373
+ clearTimeout(pendingRunRef.current?.timer);
374
+ pendingRunRef.current = undefined;
375
+ },
376
+ [],
377
+ );
327
378
  const executeCells = useCallback(
328
- async (
329
- filtersToApply: FilterSelection[] = [],
330
- givensToApply: Map<string, GivenValue> = new Map(),
331
- ) => {
379
+ async (givensToApply: Map<string, GivenValue> = new Map()) => {
332
380
  if (!isSuccess || !notebook?.notebookCells) return;
333
381
 
334
- // Initialize or reset cells
335
- setEnhancedCells((prev) => {
336
- if (prev.length === 0) {
337
- return notebook.notebookCells.map((cell) => ({ ...cell }));
338
- }
339
- return prev.map((cell) => ({
340
- ...cell,
341
- result: undefined,
342
- }));
343
- });
382
+ const runId = ++runIdRef.current;
383
+
384
+ // Cancel the run this one supersedes rather than just ignoring its
385
+ // results. Discarding results alone keeps the requests in flight, so
386
+ // three quick control changes on a twelve-cell notebook put three full
387
+ // runs on the server and use the answers from one. `origin/main`
388
+ // refused to start a second run at all, which was the wrong trade,
389
+ // it dropped the newest values, but it did bound the load, and
390
+ // nothing replaced that bound.
391
+ inFlightRef.current?.abort();
392
+ const controller = new AbortController();
393
+ inFlightRef.current = controller;
394
+
395
+ // Rebuilt from the notebook being run, never carried over from the
396
+ // previous render's cells. Reusing them kept the OLD document's
397
+ // `text` and `type` while the new document's results were written in
398
+ // on top, so navigating between two notebooks rendered one's prose
399
+ // with the other's charts, and a shorter second notebook left the
400
+ // first one's trailing cells on screen. Nothing worth preserving
401
+ // survived that branch anyway: `result` and `error` were cleared, and
402
+ // `newSources` is re-derived from the raw cell below.
403
+ setEnhancedCells(notebook.notebookCells.map((cell) => ({ ...cell })));
344
404
 
345
405
  setIsExecuting(true);
346
406
  setExecutionError(null);
347
407
 
348
- const filterParams = useServerFilters
349
- ? buildFilterParams(filtersToApply)
350
- : undefined;
351
408
  const givensParam = buildGivens(givensToApply);
352
409
 
353
410
  try {
@@ -365,7 +422,12 @@ export default function Notebook({
365
422
 
366
423
  const executeCell = async () => {
367
424
  try {
368
- // Use notebook cell execution API with optional filter_params and givens
425
+ // `filterParams` and `bypassFilters` go over as undefined:
426
+ // the `#(filter)` panel this component used to render is
427
+ // gone, replaced by `given:`. The server still enforces a
428
+ // `required` filter, so a model that has one now fails
429
+ // here: visibly, via `error` below, rather than as the
430
+ // blank cell it used to be. See RELEASE_NOTES.
369
431
  const response =
370
432
  await apiClients.notebooks.executeNotebookCell(
371
433
  environmentName,
@@ -373,11 +435,14 @@ export default function Notebook({
373
435
  notebookPath,
374
436
  cellIndex,
375
437
  versionId,
376
- filterParams,
438
+ undefined,
377
439
  undefined,
378
440
  givensParam,
441
+ { signal: controller.signal },
379
442
  );
380
443
 
444
+ if (runIdRef.current !== runId) return;
445
+
381
446
  const executedCell = response.data;
382
447
  const result = executedCell.result;
383
448
  const newSources =
@@ -397,10 +462,29 @@ export default function Notebook({
397
462
  return next;
398
463
  });
399
464
  } catch (cellError) {
465
+ // A superseded or cancelled run is not a failure to
466
+ // report; its cells are about to be re-run.
467
+ if (
468
+ controller.signal.aborted ||
469
+ runIdRef.current !== runId
470
+ )
471
+ return;
400
472
  console.error(
401
473
  `Error executing cell ${cellIndex}:`,
402
474
  cellError,
403
475
  );
476
+ const message = cellErrorMessage(cellError);
477
+ setEnhancedCells((prev) => {
478
+ const next = [...prev];
479
+ if (!next[cellIndex]) {
480
+ next[cellIndex] = { ...rawCell };
481
+ }
482
+ next[cellIndex] = {
483
+ ...next[cellIndex],
484
+ error: message,
485
+ };
486
+ return next;
487
+ });
404
488
  }
405
489
  };
406
490
 
@@ -424,17 +508,19 @@ export default function Notebook({
424
508
  // Wait for remaining tasks to complete
425
509
  await Promise.all(executing);
426
510
  } catch (error) {
511
+ if (controller.signal.aborted || runIdRef.current !== runId) return;
427
512
  console.error("Error executing notebook cells:", error);
428
513
  setExecutionError(error as Error);
429
514
  } finally {
430
- setIsExecuting(false);
515
+ if (runIdRef.current === runId) {
516
+ setIsExecuting(false);
517
+ inFlightRef.current = null;
518
+ }
431
519
  }
432
520
  },
433
521
  [
434
522
  isSuccess,
435
523
  notebook,
436
- useServerFilters,
437
- buildFilterParams,
438
524
  buildGivens,
439
525
  environmentName,
440
526
  packageName,
@@ -444,149 +530,110 @@ export default function Notebook({
444
530
  ],
445
531
  );
446
532
 
447
- // Execute cells when notebook is loaded (no filters or givens initially)
448
- useEffect(() => {
449
- if (!isSuccess || !notebook?.notebookCells) return;
450
- executeCells([], new Map());
451
- }, [isSuccess, notebook, executeCells]);
452
-
453
- // Re-execute when filters or givens change
454
- // Track previous input shape to detect actual value changes (not just reference changes)
455
- const prevInputsRef = useRef<string>("");
533
+ // Run the cells on load, and again whenever the applied parameters change.
534
+ // Applied, not draft: under `## autorun=false` the cells wait for Apply.
535
+ //
536
+ // One effect covers both, keyed on exactly what would go over the wire plus
537
+ // which notebook it is. Keying on the encoded givens means a change that
538
+ // encodes identically does not re-run, and a link carrying parameters runs
539
+ // once with them rather than running bare and running again when they land.
540
+ // A run already in flight is superseded rather than waited on, which the
541
+ // generation guard in `executeCells` makes safe.
542
+ //
543
+ // The notebook's own identity is part of that key. Its content can change
544
+ // under an open tab: a package reload, and react-query hands over a new
545
+ // object only when the content actually differs, so identity is exactly the
546
+ // "has this document changed" signal. Keying on `resourceUri` alone silently
547
+ // dropped that: a reloaded notebook kept rendering the previous run's
548
+ // results forever, because the URI and the givens were unchanged.
549
+ const notebookGenRef = useRef(0);
550
+ const seenNotebookRef = useRef<RawNotebook | undefined>(undefined);
551
+ if (seenNotebookRef.current !== notebook) {
552
+ seenNotebookRef.current = notebook;
553
+ notebookGenRef.current += 1;
554
+ }
555
+ const notebookGen = notebookGenRef.current;
456
556
 
457
557
  useEffect(() => {
458
- // Serialize activeFilters + givenValues to detect actual value changes.
459
- // Encode dates to the same YYYY-MM-DD granularity buildGivens sends on the
460
- // wire — otherwise JSON.stringify renders Date as a full ISO timestamp, so
461
- // two times on the same day would look like a change and trigger a
462
- // redundant re-run even though the sent value is identical.
463
- const serialized = JSON.stringify({
464
- filters: activeFilters.map((f) => ({
465
- dim: f.dimensionName,
466
- type: f.matchType,
467
- val: f.value,
468
- val2: f.value2,
469
- })),
470
- givens: Array.from(givenValues.entries())
471
- .sort(([a], [b]) => a.localeCompare(b))
472
- .map(([name, v]) => [
473
- name,
474
- v instanceof Date ? v.toISOString().slice(0, 10) : v,
475
- ]),
476
- });
477
-
478
- // Skip if no actual change
479
- if (serialized === prevInputsRef.current) {
480
- return;
481
- }
482
-
483
- // Skip the initial render when both inputs are empty
558
+ const documentKey = `${resourceUri}|${notebookGen}`;
559
+ const runKey = `${documentKey}|${buildGivens(applied) ?? ""}`;
560
+
561
+ // Abandon the previous notebook's requests when the document changes.
562
+ // The abort-on-unmount effect does not cover this: navigating from one
563
+ // notebook to another REUSES this component, so nothing unmounts and a
564
+ // twelve-cell notebook left twelve requests running against a document
565
+ // the reader had already left.
484
566
  if (
485
- prevInputsRef.current === "" &&
486
- activeFilters.length === 0 &&
487
- givenValues.size === 0
567
+ lastDocumentRef.current !== undefined &&
568
+ lastDocumentRef.current !== documentKey
488
569
  ) {
489
- prevInputsRef.current = serialized;
490
- return;
570
+ inFlightRef.current?.abort();
571
+ inFlightRef.current = null;
491
572
  }
573
+ lastDocumentRef.current = documentKey;
574
+
575
+ const plan = planRun({
576
+ ready: isSuccess && !!notebook?.notebookCells,
577
+ lastRunKey: lastRunRef.current,
578
+ pendingKey: pendingRunRef.current?.key,
579
+ runKey,
580
+ documentKey,
581
+ });
492
582
 
493
- // Don't consume the change until we can act on it. If a run is already in
494
- // flight, leave prevInputsRef stale and bail: this effect re-runs when
495
- // isExecuting flips back to false (it's a dependency), and will then pick
496
- // up the latest inputs. Updating prevInputsRef here instead would mark the
497
- // change "seen" and drop it — a given/filter edited mid-run would never
498
- // re-execute.
499
- if (isExecuting) {
500
- return;
583
+ if (plan.cancelPending) {
584
+ clearTimeout(pendingRunRef.current?.timer);
585
+ pendingRunRef.current = undefined;
586
+ setRunScheduled(false);
501
587
  }
588
+ if (plan.dispatch === "none") return;
502
589
 
503
- prevInputsRef.current = serialized;
504
- executeCells(activeFilters, givenValues);
505
- }, [activeFilters, givenValues, isExecuting, executeCells]);
506
-
507
- // Handle filter change using composite key
508
- const handleFilterChange = useCallback(
509
- (key: string) => (selection: FilterSelection | null) => {
510
- updateFilter(key, selection);
511
- },
512
- [updateFilter],
513
- );
590
+ const start = () => {
591
+ pendingRunRef.current = undefined;
592
+ setRunScheduled(false);
593
+ lastRunRef.current = runKey;
594
+ void executeCells(applied);
595
+ };
514
596
 
515
- // Check if retrieval is supported
516
- const hasRetrievalFilters = dimensionSpecs.some(
517
- (spec) => spec.filterType === "Retrieval",
518
- );
519
- const _retrievalSupported = !hasRetrievalFilters || !!retrievalFn;
597
+ if (plan.dispatch === "now") {
598
+ start();
599
+ return;
600
+ }
601
+ // Flagged while the settle timer runs, so the cells say a run is coming.
602
+ // Without it the window was invisible: `isExecuting` is false until the
603
+ // timer fires, so a changed control sat above the PREVIOUS values with
604
+ // nothing on screen to say they were stale, and a reader who kept typing
605
+ // kept extending the window.
606
+ setRunScheduled(true);
607
+ pendingRunRef.current = {
608
+ key: runKey,
609
+ timer: setTimeout(start, GIVEN_SETTLE_MS),
610
+ };
611
+ }, [
612
+ isSuccess,
613
+ notebook,
614
+ notebookGen,
615
+ resourceUri,
616
+ applied,
617
+ buildGivens,
618
+ executeCells,
619
+ ]);
520
620
 
521
621
  return (
522
622
  <CleanNotebookContainer>
523
623
  <CleanNotebookSection>
524
624
  <Stack spacing={3} component="section">
525
- {/* Givens Panel — runtime parameters declared via `given:` */}
625
+ {/* Parameters panel: the controls for `given:` declarations */}
526
626
  <GivensPanel
527
627
  givens={declaredGivens}
528
- values={givenValues}
529
- onChange={updateGiven}
530
- onClearAll={clearAllGivens}
628
+ values={draft}
629
+ onChange={setGiven}
630
+ onReset={reset}
631
+ options={givenOptions}
632
+ optionsLoading={givenOptionsLoading}
633
+ optionsFailed={givenOptionsFailed}
634
+ apply={autorun ? undefined : { onApply: apply, pending }}
531
635
  />
532
636
 
533
- {/* Filter Panel */}
534
- {dimensionSpecs.length > 0 && filterValuesData && (
535
- <Paper
536
- elevation={0}
537
- sx={{
538
- p: 3,
539
- backgroundColor: "transparent",
540
- border: "none",
541
- boxShadow: "none",
542
- }}
543
- >
544
- <Typography
545
- variant="subtitle2"
546
- sx={{
547
- fontWeight: 600,
548
- mb: 2,
549
- color: "#333",
550
- }}
551
- >
552
- Filters
553
- </Typography>
554
- <Box
555
- sx={{
556
- display: "grid",
557
- gridTemplateColumns:
558
- "repeat(auto-fill, minmax(250px, 1fr))",
559
- gap: 3,
560
- }}
561
- >
562
- {dimensionSpecs.map((spec) => {
563
- const key = getDimensionKey(spec);
564
- const values = filterValuesData.get(key) || [];
565
- const filterState = filterStates.get(key);
566
- // Skip Retrieval filters if no retrievalFn provided
567
- if (
568
- spec.filterType === "Retrieval" &&
569
- !retrievalFn
570
- ) {
571
- return null;
572
- }
573
-
574
- return (
575
- <Box key={key}>
576
- <DimensionFilter
577
- spec={spec}
578
- values={values}
579
- selection={filterState?.selection}
580
- onChange={handleFilterChange(key)}
581
- retrievalFn={retrievalFn}
582
- />
583
- </Box>
584
- );
585
- })}
586
- </Box>
587
- </Paper>
588
- )}
589
-
590
637
  {/* Loading State */}
591
638
  {!isSuccess && !isError && (
592
639
  <Loading text={"Fetching Notebook..."} />
@@ -605,7 +652,17 @@ export default function Notebook({
605
652
  resourceUri={resourceUri}
606
653
  maxResultSize={maxResultSize}
607
654
  isExecuting={isExecuting}
655
+ // Distinct from `isExecuting`: the cell's spinner is
656
+ // gated on `!cell.result`, so feeding this through it
657
+ // showed nothing on a re-run, which is the only case
658
+ // the settle window has to signal.
659
+ pendingRerun={runScheduled}
608
660
  onNavigate={onNavigate}
661
+ onDrillNavigate={onDrillNavigate}
662
+ onDrillSelf={
663
+ declaredGivens.length > 0 ? onDrillSelf : undefined
664
+ }
665
+ canDrillSelf={canDrillSelf}
609
666
  />
610
667
  ))}
611
668