@malloy-publisher/sdk 0.0.247 → 0.0.249

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 (98) hide show
  1. package/README.md +32 -17
  2. package/dist/ServerProvider-CcfeBpt3.cjs.js +1 -0
  3. package/dist/{ServerProvider-BxEh3nFI.es.js → ServerProvider-EqBlMMqx.es.js} +1056 -905
  4. package/dist/client/api.d.ts +298 -7
  5. package/dist/client/index.cjs.js +1 -1
  6. package/dist/client/index.es.js +74 -70
  7. package/dist/components/Dashboard/Dashboard.d.ts +49 -0
  8. package/dist/components/Dashboard/DashboardTile.d.ts +48 -0
  9. package/dist/components/Dashboard/index.d.ts +2 -0
  10. package/dist/components/Notebook/Notebook.d.ts +46 -8
  11. package/dist/components/Notebook/NotebookCell.d.ts +37 -3
  12. package/dist/components/Notebook/runPlan.d.ts +29 -0
  13. package/dist/components/Notebook/types.d.ts +10 -0
  14. package/dist/components/Package/ContentTypeIcon.d.ts +17 -1
  15. package/dist/components/Package/Package.d.ts +1 -4
  16. package/dist/components/RenderedResult/RenderedResult.d.ts +7 -1
  17. package/dist/components/RenderedResult/ResultContainer.d.ts +3 -1
  18. package/dist/components/ResultsDialog.d.ts +4 -1
  19. package/dist/components/ServerProvider.d.ts +2 -1
  20. package/dist/components/click_helper.d.ts +10 -1
  21. package/dist/components/drill/index.d.ts +3 -0
  22. package/dist/components/drill/markDrillableCells.d.ts +55 -0
  23. package/dist/components/drill/resolveDrill.d.ts +159 -0
  24. package/dist/components/drill/useDrill.d.ts +63 -0
  25. package/dist/components/given/GivenInput.d.ts +27 -3
  26. package/dist/components/given/GivensPanel.d.ts +36 -7
  27. package/dist/components/given/filterValue.d.ts +117 -0
  28. package/dist/components/given/index.d.ts +1 -1
  29. package/dist/components/given/paramCodec.d.ts +60 -0
  30. package/dist/components/index.d.ts +4 -1
  31. package/dist/components/styles.d.ts +23 -0
  32. package/dist/constants/docLinks.d.ts +6 -0
  33. package/dist/{core-BuvlzSIX.es.js → core-DFBwNhvb.es.js} +1 -1
  34. package/dist/{core-C86Rb7tJ.cjs.js → core-DZk7z7ko.cjs.js} +1 -1
  35. package/dist/hooks/givenValue.d.ts +10 -0
  36. package/dist/hooks/index.d.ts +3 -1
  37. package/dist/hooks/useGivensState.d.ts +64 -0
  38. package/dist/hooks/useSuggestOptions.d.ts +78 -0
  39. package/dist/{index-BdtAZ5k6.es.js → index-CLcRrkxd.es.js} +41221 -39894
  40. package/dist/index-CWQXhe0D.cjs.js +338 -0
  41. package/dist/index.cjs.js +1 -1
  42. package/dist/index.es.js +77 -62
  43. package/dist/theme/types.d.ts +9 -0
  44. package/package.json +3 -1
  45. package/src/components/Connections/AddConnectionDialog.tsx +10 -1
  46. package/src/components/Dashboard/Dashboard.tsx +395 -0
  47. package/src/components/Dashboard/DashboardTile.tsx +150 -0
  48. package/src/components/Dashboard/index.ts +2 -0
  49. package/src/components/Home/Home.tsx +114 -23
  50. package/src/components/Notebook/Notebook.tsx +444 -390
  51. package/src/components/Notebook/NotebookCell.tsx +117 -3
  52. package/src/components/Notebook/runPlan.spec.ts +152 -0
  53. package/src/components/Notebook/runPlan.ts +64 -0
  54. package/src/components/Notebook/types.ts +11 -0
  55. package/src/components/Package/ContentTypeIcon.spec.ts +88 -0
  56. package/src/components/Package/ContentTypeIcon.tsx +77 -6
  57. package/src/components/Package/Package.tsx +148 -38
  58. package/src/components/RenderedResult/RenderedResult.tsx +309 -19
  59. package/src/components/RenderedResult/ResultContainer.tsx +28 -1
  60. package/src/components/ResultsDialog.tsx +5 -0
  61. package/src/components/ServerProvider.tsx +2 -0
  62. package/src/components/click_helper.ts +14 -1
  63. package/src/components/drill/index.ts +25 -0
  64. package/src/components/drill/markDrillableCells.dom.spec.ts +310 -0
  65. package/src/components/drill/markDrillableCells.spec.ts +106 -0
  66. package/src/components/drill/markDrillableCells.ts +311 -0
  67. package/src/components/drill/resolveDrill.spec.ts +446 -0
  68. package/src/components/drill/resolveDrill.ts +372 -0
  69. package/src/components/drill/useDrill.tsx +200 -0
  70. package/src/components/given/GivenInput.spec.tsx +495 -15
  71. package/src/components/given/GivenInput.tsx +562 -30
  72. package/src/components/given/GivensPanel.spec.tsx +172 -0
  73. package/src/components/given/GivensPanel.tsx +139 -32
  74. package/src/components/given/filterValue.spec.ts +361 -0
  75. package/src/components/given/filterValue.ts +204 -0
  76. package/src/components/given/index.ts +5 -1
  77. package/src/components/given/paramCodec.spec.ts +854 -0
  78. package/src/components/given/paramCodec.ts +480 -0
  79. package/src/components/index.ts +4 -1
  80. package/src/components/styles.ts +27 -3
  81. package/src/constants/docLinks.spec.ts +51 -0
  82. package/src/constants/docLinks.ts +26 -0
  83. package/src/hooks/givenValue.ts +10 -0
  84. package/src/hooks/index.ts +6 -4
  85. package/src/hooks/useGivensState.spec.ts +446 -0
  86. package/src/hooks/useGivensState.ts +337 -0
  87. package/src/hooks/useSuggestOptions.spec.ts +109 -0
  88. package/src/hooks/useSuggestOptions.ts +260 -0
  89. package/src/theme/buildTableCssVars.ts +4 -0
  90. package/src/theme/resolveTheme.spec.ts +13 -0
  91. package/src/theme/resolveTheme.ts +3 -0
  92. package/src/theme/types.ts +9 -0
  93. package/test/README.md +16 -10
  94. package/dist/ServerProvider-Dg5S1qBU.cjs.js +0 -1
  95. package/dist/hooks/useGivensForm.d.ts +0 -35
  96. package/dist/index-MES4MGpQ.cjs.js +0 -309
  97. package/src/hooks/useGivensForm.spec.ts +0 -99
  98. package/src/hooks/useGivensForm.ts +0 -107
@@ -1,35 +1,19 @@
1
1
  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";
2
+ import { Stack, Typography } from "@mui/material";
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { planRun } from "./runPlan";
5
+ import { RawNotebook } from "../../client";
6
+ import { GivenValue } from "../../hooks/givenValue";
7
+ import { useGivensState } from "../../hooks/useGivensState";
22
8
  import { useModelGivens } from "../../hooks/useModelGivens";
23
9
  import { useQueryWithApiError } from "../../hooks/useQueryWithApiError";
10
+ import { useSuggestOptions } from "../../hooks/useSuggestOptions";
24
11
  import { parseResourceUri } from "../../utils/formatting";
25
12
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
26
- import { DimensionFilter, RetrievalFunction } from "../filter/DimensionFilter";
27
- import {
28
- extractDimensionSpecs,
29
- parseAllSourceInfos,
30
- parseNotebookFilterAnnotation,
31
- } from "../filter/utils";
13
+ import type { NavigationClick } from "../click_helper";
14
+ import { encodeDrillValue, type DrillNavigation } from "../drill";
32
15
  import { GivensPanel } from "../given";
16
+ import { givensToRequest } from "../given/paramCodec";
33
17
  import { Loading } from "../Loading";
34
18
  import { useServer } from "../ServerProvider";
35
19
  import { CleanNotebookContainer, CleanNotebookSection } from "../styles";
@@ -39,23 +23,96 @@ import { EnhancedNotebookCell } from "./types";
39
23
  // Maximum number of concurrent cell executions to avoid overwhelming the server
40
24
  const MAX_CONCURRENT = 4;
41
25
 
26
+ /**
27
+ * How long a changed parameter has to stay changed before the notebook runs.
28
+ *
29
+ * Aborting the superseded run is not enough on its own: an abort cancels the
30
+ * HTTP request, but the cells already dispatched have reached the server and go
31
+ * on compiling and running against the customer's warehouse, and their answers
32
+ * are then thrown away. So autorun on a text control put one wave of doomed
33
+ * queries on that warehouse per keystroke. `origin/main` bounded the load by
34
+ * refusing to start a second run at all, which dropped the newest values;
35
+ * waiting for the value to settle bounds it without making that trade.
36
+ */
37
+ const GIVEN_SETTLE_MS = 400;
38
+
39
+ /**
40
+ * The server's own explanation of why a cell would not run.
41
+ *
42
+ * Publisher answers a refused query with `{code, message}`, and that message is
43
+ * the useful half: "filter 'state' is required", say. Falls back through the
44
+ * generic axios message to a fixed string, so a cell always has something to
45
+ * show rather than rendering an empty error box.
46
+ */
47
+ function cellErrorMessage(error: unknown): string {
48
+ const body = (
49
+ error as { response?: { data?: { message?: unknown } } } | undefined
50
+ )?.response?.data?.message;
51
+ if (typeof body === "string" && body !== "") return body;
52
+ if (error instanceof Error && error.message !== "") return error.message;
53
+ return "The server did not say why.";
54
+ }
55
+
42
56
  interface NotebookProps {
43
57
  resourceUri: string;
44
58
  maxResultSize?: number;
45
- /** Optional retrieval function for semantic search filters */
46
- retrievalFn?: RetrievalFunction;
47
- /** Optional SPA navigation handler for links inside the notebook. When
59
+ /**
60
+ * Parameter values from the host, typically its URL query parameters: the
61
+ * same contract `Dashboard` takes, so a link into a filtered notebook works
62
+ * the way a link into a filtered dashboard does.
63
+ */
64
+ givens?: Record<string, string>;
65
+ /**
66
+ * Applied parameter values, for a host that wants them in its URL. Fires
67
+ * with what the cells actually ran with, which is what makes the URL a link
68
+ * that reproduces the view.
69
+ *
70
+ * That is every committed change. Under `## autorun=false` a change is
71
+ * committed on Apply, so reports are batched; otherwise every change is
72
+ * committed and typing in a text control reports per keystroke. It does NOT
73
+ * run per keystroke: a changed value waits
74
+ * `GIVEN_SETTLE_MS` before anything is dispatched, so a burst of typing
75
+ * produces one run. A run that does start supersedes and aborts the one
76
+ * before it. The REPORTS are still per keystroke, so a host doing something
77
+ * expensive per call should debounce.
78
+ *
79
+ * `managed` names every given this notebook declares, set or not. A host
80
+ * writing to a shared query string needs it: `givens` alone says which
81
+ * parameters to write but not which to *remove*, and a host that guesses by
82
+ * removing everything it did not just receive deletes the unrelated
83
+ * parameters it has no business touching.
84
+ */
85
+ onGivensChange?: (
86
+ givens: Record<string, string>,
87
+ managed: readonly string[],
88
+ ) => void;
89
+ /**
90
+ * Optional SPA navigation handler for links inside the notebook. When
48
91
  * 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;
92
+ * react-router context is required to render a notebook.
93
+ *
94
+ * It does NOT carry drill. A `# drill { to=self }` filters this notebook
95
+ * through `given:` state and needs no handler at all, and a drill naming a
96
+ * dashboard goes through {@link onDrillNavigate}, which takes a destination
97
+ * rather than a URL.
98
+ */
99
+ onNavigate?: (to: string, event?: NavigationClick) => void;
100
+ /**
101
+ * Opens a `# drill { to=<dashboard> }` from a cell, seeded with the clicked
102
+ * value. Omitted on a host with no dashboard route, which leaves those
103
+ * destinations inert AND unmarked rather than painting a dead link.
104
+ */
105
+ onDrillNavigate?: (target: DrillNavigation, event?: MouseEvent) => void;
51
106
  }
52
107
 
53
108
  // Requires PackageProvider
54
109
  export default function Notebook({
55
110
  resourceUri,
56
111
  maxResultSize = 0,
57
- retrievalFn,
112
+ givens,
113
+ onGivensChange,
58
114
  onNavigate,
115
+ onDrillNavigate,
59
116
  }: NotebookProps) {
60
117
  const { apiClients } = useServer();
61
118
  const {
@@ -89,265 +146,262 @@ export default function Notebook({
89
146
  [],
90
147
  );
91
148
  const [isExecuting, setIsExecuting] = useState(false);
149
+ // A run is scheduled but its settle window has not elapsed. Separate from
150
+ // `isExecuting`, which covers only a run actually in flight.
151
+ const [runScheduled, setRunScheduled] = useState(false);
152
+ // The document the last run belonged to, for abandoning its requests when
153
+ // the reader moves to another notebook without this component unmounting.
154
+ const lastDocumentRef = useRef<string | undefined>(undefined);
92
155
  const [executionError, setExecutionError] = useState<Error | null>(null);
93
156
 
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],
157
+ // Model-level `given:` declarations, and the state behind their controls.
158
+ // The same hook the dashboard viewer uses, so both surfaces get URL-
159
+ // addressable parameters, Apply batching, and `to=self` drill from one
160
+ // implementation rather than two that drift.
161
+ const declaredGivens = useModelGivens(notebook);
162
+ const declaredTypes = useMemo(
163
+ () =>
164
+ new Map(
165
+ declaredGivens
166
+ .filter((given) => given.name !== undefined)
167
+ .map((given) => [given.name as string, given.type]),
168
+ ),
169
+ [declaredGivens],
109
170
  );
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
171
 
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,
172
+ // Silent until the notebook has actually loaded. Which givens exist is not
173
+ // known before then: `useModelGivens(undefined)` is empty, so a report in
174
+ // that window says "no values, and I manage nothing", which a host reasonably
175
+ // reads as "clear what you wrote". During an in-app navigation from one
176
+ // notebook to another that window sits between the two, and the parameters it
177
+ // would clear can belong to the notebook now ARRIVING. A notebook that
178
+ // genuinely declares no givens still reports, because by then the empty set
179
+ // is the answer rather than the absence of one.
180
+ const reportGivens = useCallback(
181
+ (next: Record<string, string>) => {
182
+ if (!isSuccess) return;
183
+ onGivensChange?.(next, Array.from(declaredTypes.keys()));
223
184
  },
185
+ [isSuccess, onGivensChange, declaredTypes],
224
186
  );
225
187
 
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
- );
188
+ // Read off the notebook now that the server derives it: a file-level
189
+ // `## autorun=false` arrives as `RawNotebook.autorun`, the same field with
190
+ // the same default that a dashboard's `# artifact { autorun=false }`
191
+ // produces. This was hardcoded true while nothing populated the field, on
192
+ // the grounds that a spec declaring one nothing produces is a spec that
193
+ // lies; the reader has landed, so this is the follow-up that comment named.
194
+ //
195
+ // Absent means autorun, so only an explicit `false` batches. Batching
196
+ // matters more here than on a dashboard: one control change re-runs every
197
+ // cell in the document.
198
+ const autorun = notebook?.autorun !== false;
199
+ const { draft, applied, setGiven, reset, apply, pending } = useGivensState({
200
+ declaredTypes,
201
+ // Where the controls start, from a file-level `## givens { … }`. A URL
202
+ // beats them, so a shared link still shows what the sender saw.
203
+ startingValues: notebook?.startingGivens,
204
+ params: givens,
205
+ // Withheld until the notebook has loaded, rather than accepted and
206
+ // dropped. `useGivensState` records what it last reported BEFORE calling
207
+ // out, so a report the callback throws away is remembered as delivered
208
+ // and never retried, leaving a parameter stranded in the host's URL.
209
+ // Passing undefined makes the hook skip the report entirely, which leaves
210
+ // its record untouched and the next real change still reportable.
211
+ onParamsChange: isSuccess ? reportGivens : undefined,
212
+ // Which notebook these edits belong to. Navigating between notebooks
213
+ // reuses this component, so without it one notebook's applied values
214
+ // carried into the next whenever both started from the same values.
215
+ documentKey: resourceUri,
216
+ autorun,
217
+ });
232
218
 
233
- // Extract model-level givens declared via `given:` and manage user overrides
234
- const declaredGivens = useModelGivens(notebook);
219
+ // A notebook's model path is the notebook itself: `suggest` queries run
220
+ // against the same model the cells do.
235
221
  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);
222
+ options: givenOptions,
223
+ isLoading: givenOptionsLoading,
224
+ failed: givenOptionsFailed,
225
+ } = useSuggestOptions(
226
+ environmentName,
227
+ packageName,
228
+ notebookPath,
229
+ declaredGivens,
230
+ );
231
+
232
+ // The declared names, indexed case-insensitively, so a drill tag resolves
233
+ // whichever way the two were spelled.
234
+ //
235
+ // Neither convention can be assumed. `# drill` defaults the given name to
236
+ // the DIMENSION's name, which is conventionally lower_snake, while givens
237
+ // are conventionally SHOUTED (both in-repo examples declare `REGION` and
238
+ // `MIN_AMOUNT`). An exact match therefore failed for the common case, and
239
+ // upper-casing the dimension name, which is what this did first, only moved
240
+ // the failure onto models that spell their givens in lower case. Folding
241
+ // case resolves both instead of picking a side.
242
+ const givenNamesByFold = useMemo(() => {
243
+ const byFold = new Map<string, string>();
244
+ for (const name of declaredTypes.keys()) {
245
+ // First declaration wins, so a model with `REGION` and `region` keeps
246
+ // the one it declared first rather than silently flipping.
247
+ if (!byFold.has(name.toLowerCase()))
248
+ byFold.set(name.toLowerCase(), name);
247
249
  }
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
- });
250
+ return byFold;
251
+ }, [declaredTypes]);
252
+
253
+ /** The declared given a drill tag's name refers to, or undefined. */
254
+ const resolveGiven = useCallback(
255
+ (given: string) =>
256
+ declaredTypes.has(given)
257
+ ? given
258
+ : givenNamesByFold.get(given.toLowerCase()),
259
+ [declaredTypes, givenNamesByFold],
260
+ );
263
261
 
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;
262
+ // `to=self` filters in place, which only works for a given this notebook
263
+ // actually declares: sending one it cannot bind would fail every cell. The
264
+ // mismatch is reported to the author rather than issued: same rule, same
265
+ // wording, as the dashboard viewer.
266
+ // Asked before a cell is painted as drillable, so the affordance matches what
267
+ // a click can actually do. The refusal below still stands as a backstop for a
268
+ // caller that does not ask.
269
+ const canDrillSelf = useCallback(
270
+ (given: string) => resolveGiven(given) !== undefined,
271
+ [resolveGiven],
272
+ );
273
273
 
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
- }
274
+ const onDrillSelf = useCallback(
275
+ (given: string, rawValue: unknown) => {
276
+ const declared = resolveGiven(given);
277
+ if (declared === undefined) {
278
+ console.warn(
279
+ `# drill { to=self } tried to set '${given}', which ` +
280
+ `'${notebookPath}' does not declare as a given. Name the ` +
281
+ `given with 'given=' on the drill tag.`,
282
+ );
283
+ return;
290
284
  }
291
- return Object.keys(params).length > 0
292
- ? JSON.stringify(params)
293
- : undefined;
285
+ // Encoded against the declared type of the given being set, which is
286
+ // knowable here and is not knowable at the click. Set under the name
287
+ // the MODEL declares, not the one the tag spelled, so the value goes
288
+ // into the URL and the request under the one name the server knows.
289
+ const declaredType = declaredTypes.get(declared);
290
+ const value = encodeDrillValue(rawValue, declaredType);
291
+ if (value === undefined) {
292
+ // Say so. Returning in silence left a whole column painted as
293
+ // clickable while every click did nothing, and a `given=` pointing
294
+ // at a type the clicked value cannot become is an authoring
295
+ // mistake the author has no other way to see. The sibling refusal
296
+ // in `resolveDrill` warns for the same reason.
297
+ console.warn(
298
+ `Drill declined: ${JSON.stringify(rawValue)} cannot be a value for given "${declared}"` +
299
+ (declaredType ? ` of type ${declaredType}` : ""),
300
+ );
301
+ return;
302
+ }
303
+ setGiven(declared, value);
294
304
  },
295
- [],
305
+ [declaredTypes, notebookPath, resolveGiven, setGiven],
296
306
  );
297
307
 
298
308
  /**
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.
309
+ * The `givens` query param for the notebook-cell GET: the same map the
310
+ * dashboard's POST body carries, JSON-encoded because this endpoint takes it
311
+ * in the URL. Built by the shared codec so a given is encoded identically
312
+ * whichever surface runs it.
303
313
  */
304
314
  const buildGivens = useCallback(
305
315
  (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)
316
+ const request = givensToRequest(values, declaredTypes);
317
+ return Object.keys(request).length > 0
318
+ ? JSON.stringify(request)
319
319
  : undefined;
320
320
  },
321
- [],
321
+ [declaredTypes],
322
322
  );
323
323
 
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
324
+ /**
325
+ * Run every code cell with one set of given values, up to
326
+ * {@link MAX_CONCURRENT} at a time.
327
+ *
328
+ * Each run takes a number from `runIdRef`, and a run that is no longer the
329
+ * current one drops its results on the floor. Cells resolve independently
330
+ * and out of order, so without that a slow cell from the previous values
331
+ * would land after the new run's and leave a stale number on screen under a
332
+ * control row claiming otherwise.
333
+ */
334
+ const runIdRef = useRef(0);
335
+ const inFlightRef = useRef<AbortController | null>(null);
336
+ const lastRunRef = useRef<string | null>(null);
337
+ /** The run waiting out {@link GIVEN_SETTLE_MS}, so a re-render does not restart its clock. */
338
+ const pendingRunRef = useRef<
339
+ { key: string; timer: ReturnType<typeof setTimeout> } | undefined
340
+ >(undefined);
341
+
342
+ // Cancel whatever is in flight when this component goes away, so navigating
343
+ // off a twelve-cell notebook does not leave twelve requests to complete and be
344
+ // thrown away.
345
+ //
346
+ // Its OWN effect, with an empty dependency list, and that is the whole point:
347
+ // as the run effect's cleanup this ran on every dependency change instead. The
348
+ // host echoes each reported parameter back, which gives `applied` a new
349
+ // identity with identical content, so the cleanup fired and aborted the run
350
+ // the control change had just started, while the run effect's `runKey` guard
351
+ // saw an unchanged key and refused to start a replacement. Every cell was left
352
+ // blank, with no result, no error and no spinner, until a reload. Measured on
353
+ // `governed-analytics/orders.malloynb`: 4 rendered results before a control
354
+ // change, 0 after.
355
+ useEffect(
356
+ () => () => {
357
+ inFlightRef.current?.abort();
358
+ // Forget which run was last started, so a component that comes back
359
+ // runs again instead of trusting a key whose run was just cancelled.
360
+ // The case it is reasoned from, and NOT one I could reproduce: React's
361
+ // StrictMode mounts, cleans up, and mounts again in development, and
362
+ // refs survive that. A first mount that already had the notebook
363
+ // cached would start a run, this cleanup would abort it, and the
364
+ // second mount would see an unchanged `runKey` and decline to start a
365
+ // replacement. I could not get a browser into that state, so treat the
366
+ // reset as belt-and-braces rather than a measured fix. It is right on
367
+ // its own terms either way: a key that says "this run happened" must
368
+ // not outlive the run being cancelled.
369
+ lastRunRef.current = null;
370
+ clearTimeout(pendingRunRef.current?.timer);
371
+ pendingRunRef.current = undefined;
372
+ },
373
+ [],
374
+ );
327
375
  const executeCells = useCallback(
328
- async (
329
- filtersToApply: FilterSelection[] = [],
330
- givensToApply: Map<string, GivenValue> = new Map(),
331
- ) => {
376
+ async (givensToApply: Map<string, GivenValue> = new Map()) => {
332
377
  if (!isSuccess || !notebook?.notebookCells) return;
333
378
 
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
- });
379
+ const runId = ++runIdRef.current;
380
+
381
+ // Cancel the run this one supersedes rather than just ignoring its
382
+ // results. Discarding results alone keeps the requests in flight, so
383
+ // three quick control changes on a twelve-cell notebook put three full
384
+ // runs on the server and use the answers from one. `origin/main`
385
+ // refused to start a second run at all, which was the wrong trade,
386
+ // it dropped the newest values, but it did bound the load, and
387
+ // nothing replaced that bound.
388
+ inFlightRef.current?.abort();
389
+ const controller = new AbortController();
390
+ inFlightRef.current = controller;
391
+
392
+ // Rebuilt from the notebook being run, never carried over from the
393
+ // previous render's cells. Reusing them kept the OLD document's
394
+ // `text` and `type` while the new document's results were written in
395
+ // on top, so navigating between two notebooks rendered one's prose
396
+ // with the other's charts, and a shorter second notebook left the
397
+ // first one's trailing cells on screen. Nothing worth preserving
398
+ // survived that branch anyway: `result` and `error` were cleared, and
399
+ // `newSources` is re-derived from the raw cell below.
400
+ setEnhancedCells(notebook.notebookCells.map((cell) => ({ ...cell })));
344
401
 
345
402
  setIsExecuting(true);
346
403
  setExecutionError(null);
347
404
 
348
- const filterParams = useServerFilters
349
- ? buildFilterParams(filtersToApply)
350
- : undefined;
351
405
  const givensParam = buildGivens(givensToApply);
352
406
 
353
407
  try {
@@ -365,7 +419,12 @@ export default function Notebook({
365
419
 
366
420
  const executeCell = async () => {
367
421
  try {
368
- // Use notebook cell execution API with optional filter_params and givens
422
+ // `filterParams` and `bypassFilters` go over as undefined:
423
+ // the `#(filter)` panel this component used to render is
424
+ // gone, replaced by `given:`. The server still enforces a
425
+ // `required` filter, so a model that has one now fails
426
+ // here: visibly, via `error` below, rather than as the
427
+ // blank cell it used to be. See RELEASE_NOTES.
369
428
  const response =
370
429
  await apiClients.notebooks.executeNotebookCell(
371
430
  environmentName,
@@ -373,11 +432,14 @@ export default function Notebook({
373
432
  notebookPath,
374
433
  cellIndex,
375
434
  versionId,
376
- filterParams,
435
+ undefined,
377
436
  undefined,
378
437
  givensParam,
438
+ { signal: controller.signal },
379
439
  );
380
440
 
441
+ if (runIdRef.current !== runId) return;
442
+
381
443
  const executedCell = response.data;
382
444
  const result = executedCell.result;
383
445
  const newSources =
@@ -397,10 +459,29 @@ export default function Notebook({
397
459
  return next;
398
460
  });
399
461
  } catch (cellError) {
462
+ // A superseded or cancelled run is not a failure to
463
+ // report; its cells are about to be re-run.
464
+ if (
465
+ controller.signal.aborted ||
466
+ runIdRef.current !== runId
467
+ )
468
+ return;
400
469
  console.error(
401
470
  `Error executing cell ${cellIndex}:`,
402
471
  cellError,
403
472
  );
473
+ const message = cellErrorMessage(cellError);
474
+ setEnhancedCells((prev) => {
475
+ const next = [...prev];
476
+ if (!next[cellIndex]) {
477
+ next[cellIndex] = { ...rawCell };
478
+ }
479
+ next[cellIndex] = {
480
+ ...next[cellIndex],
481
+ error: message,
482
+ };
483
+ return next;
484
+ });
404
485
  }
405
486
  };
406
487
 
@@ -424,17 +505,19 @@ export default function Notebook({
424
505
  // Wait for remaining tasks to complete
425
506
  await Promise.all(executing);
426
507
  } catch (error) {
508
+ if (controller.signal.aborted || runIdRef.current !== runId) return;
427
509
  console.error("Error executing notebook cells:", error);
428
510
  setExecutionError(error as Error);
429
511
  } finally {
430
- setIsExecuting(false);
512
+ if (runIdRef.current === runId) {
513
+ setIsExecuting(false);
514
+ inFlightRef.current = null;
515
+ }
431
516
  }
432
517
  },
433
518
  [
434
519
  isSuccess,
435
520
  notebook,
436
- useServerFilters,
437
- buildFilterParams,
438
521
  buildGivens,
439
522
  environmentName,
440
523
  packageName,
@@ -444,149 +527,110 @@ export default function Notebook({
444
527
  ],
445
528
  );
446
529
 
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>("");
530
+ // Run the cells on load, and again whenever the applied parameters change.
531
+ // Applied, not draft: under `## autorun=false` the cells wait for Apply.
532
+ //
533
+ // One effect covers both, keyed on exactly what would go over the wire plus
534
+ // which notebook it is. Keying on the encoded givens means a change that
535
+ // encodes identically does not re-run, and a link carrying parameters runs
536
+ // once with them rather than running bare and running again when they land.
537
+ // A run already in flight is superseded rather than waited on, which the
538
+ // generation guard in `executeCells` makes safe.
539
+ //
540
+ // The notebook's own identity is part of that key. Its content can change
541
+ // under an open tab: a package reload, and react-query hands over a new
542
+ // object only when the content actually differs, so identity is exactly the
543
+ // "has this document changed" signal. Keying on `resourceUri` alone silently
544
+ // dropped that: a reloaded notebook kept rendering the previous run's
545
+ // results forever, because the URI and the givens were unchanged.
546
+ const notebookGenRef = useRef(0);
547
+ const seenNotebookRef = useRef<RawNotebook | undefined>(undefined);
548
+ if (seenNotebookRef.current !== notebook) {
549
+ seenNotebookRef.current = notebook;
550
+ notebookGenRef.current += 1;
551
+ }
552
+ const notebookGen = notebookGenRef.current;
456
553
 
457
554
  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
555
+ const documentKey = `${resourceUri}|${notebookGen}`;
556
+ const runKey = `${documentKey}|${buildGivens(applied) ?? ""}`;
557
+
558
+ // Abandon the previous notebook's requests when the document changes.
559
+ // The abort-on-unmount effect does not cover this: navigating from one
560
+ // notebook to another REUSES this component, so nothing unmounts and a
561
+ // twelve-cell notebook left twelve requests running against a document
562
+ // the reader had already left.
484
563
  if (
485
- prevInputsRef.current === "" &&
486
- activeFilters.length === 0 &&
487
- givenValues.size === 0
564
+ lastDocumentRef.current !== undefined &&
565
+ lastDocumentRef.current !== documentKey
488
566
  ) {
489
- prevInputsRef.current = serialized;
490
- return;
567
+ inFlightRef.current?.abort();
568
+ inFlightRef.current = null;
491
569
  }
570
+ lastDocumentRef.current = documentKey;
571
+
572
+ const plan = planRun({
573
+ ready: isSuccess && !!notebook?.notebookCells,
574
+ lastRunKey: lastRunRef.current,
575
+ pendingKey: pendingRunRef.current?.key,
576
+ runKey,
577
+ documentKey,
578
+ });
492
579
 
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;
580
+ if (plan.cancelPending) {
581
+ clearTimeout(pendingRunRef.current?.timer);
582
+ pendingRunRef.current = undefined;
583
+ setRunScheduled(false);
501
584
  }
585
+ if (plan.dispatch === "none") return;
502
586
 
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
- );
587
+ const start = () => {
588
+ pendingRunRef.current = undefined;
589
+ setRunScheduled(false);
590
+ lastRunRef.current = runKey;
591
+ void executeCells(applied);
592
+ };
514
593
 
515
- // Check if retrieval is supported
516
- const hasRetrievalFilters = dimensionSpecs.some(
517
- (spec) => spec.filterType === "Retrieval",
518
- );
519
- const _retrievalSupported = !hasRetrievalFilters || !!retrievalFn;
594
+ if (plan.dispatch === "now") {
595
+ start();
596
+ return;
597
+ }
598
+ // Flagged while the settle timer runs, so the cells say a run is coming.
599
+ // Without it the window was invisible: `isExecuting` is false until the
600
+ // timer fires, so a changed control sat above the PREVIOUS values with
601
+ // nothing on screen to say they were stale, and a reader who kept typing
602
+ // kept extending the window.
603
+ setRunScheduled(true);
604
+ pendingRunRef.current = {
605
+ key: runKey,
606
+ timer: setTimeout(start, GIVEN_SETTLE_MS),
607
+ };
608
+ }, [
609
+ isSuccess,
610
+ notebook,
611
+ notebookGen,
612
+ resourceUri,
613
+ applied,
614
+ buildGivens,
615
+ executeCells,
616
+ ]);
520
617
 
521
618
  return (
522
619
  <CleanNotebookContainer>
523
620
  <CleanNotebookSection>
524
621
  <Stack spacing={3} component="section">
525
- {/* Givens Panel — runtime parameters declared via `given:` */}
622
+ {/* Parameters panel: the controls for `given:` declarations */}
526
623
  <GivensPanel
527
624
  givens={declaredGivens}
528
- values={givenValues}
529
- onChange={updateGiven}
530
- onClearAll={clearAllGivens}
625
+ values={draft}
626
+ onChange={setGiven}
627
+ onReset={reset}
628
+ options={givenOptions}
629
+ optionsLoading={givenOptionsLoading}
630
+ optionsFailed={givenOptionsFailed}
631
+ apply={autorun ? undefined : { onApply: apply, pending }}
531
632
  />
532
633
 
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
634
  {/* Loading State */}
591
635
  {!isSuccess && !isError && (
592
636
  <Loading text={"Fetching Notebook..."} />
@@ -605,7 +649,17 @@ export default function Notebook({
605
649
  resourceUri={resourceUri}
606
650
  maxResultSize={maxResultSize}
607
651
  isExecuting={isExecuting}
652
+ // Distinct from `isExecuting`: the cell's spinner is
653
+ // gated on `!cell.result`, so feeding this through it
654
+ // showed nothing on a re-run, which is the only case
655
+ // the settle window has to signal.
656
+ pendingRerun={runScheduled}
608
657
  onNavigate={onNavigate}
658
+ onDrillNavigate={onDrillNavigate}
659
+ onDrillSelf={
660
+ declaredGivens.length > 0 ? onDrillSelf : undefined
661
+ }
662
+ canDrillSelf={canDrillSelf}
609
663
  />
610
664
  ))}
611
665