@malloy-publisher/sdk 0.0.382-dev → 0.2.0

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 (277) hide show
  1. package/README.md +115 -95
  2. package/TREE_SHAKING.md +16 -11
  3. package/bunfig.toml +7 -0
  4. package/dist/ServerProvider-CTopDUWW.cjs.js +1 -0
  5. package/dist/ServerProvider-DUFPY6Rv.es.js +4072 -0
  6. package/dist/client/api.d.ts +3718 -1507
  7. package/dist/client/configuration.d.ts +1 -1
  8. package/dist/client/index.cjs.js +1 -1
  9. package/dist/client/index.d.ts +1 -1
  10. package/dist/client/index.es.js +85 -59
  11. package/dist/components/Connections/EditConnectionDialog.d.ts +2 -1
  12. package/dist/components/Connections/common.d.ts +8 -2
  13. package/dist/components/Dashboard/Dashboard.d.ts +49 -0
  14. package/dist/components/Dashboard/DashboardTile.d.ts +48 -0
  15. package/dist/components/Dashboard/index.d.ts +2 -0
  16. package/dist/components/DataAppViewer/DataAppViewer.d.ts +23 -0
  17. package/dist/components/DataAppViewer/index.d.ts +1 -0
  18. package/dist/components/Environment/Environment.d.ts +6 -0
  19. package/dist/components/Environment/index.d.ts +2 -0
  20. package/dist/components/Home/AddEnvironmentDialog.d.ts +1 -0
  21. package/dist/components/Home/DeleteEnvironmentDialog.d.ts +5 -0
  22. package/dist/components/Home/EditEnvironmentDialog.d.ts +7 -0
  23. package/dist/components/Home/Home.d.ts +2 -2
  24. package/dist/components/Materializations/CreateEnvMaterializationDialog.d.ts +14 -0
  25. package/dist/components/Materializations/CreateMaterializationDialog.d.ts +10 -0
  26. package/dist/components/Materializations/DeleteMaterializationDialog.d.ts +7 -0
  27. package/dist/components/Materializations/EnvironmentMaterializations.d.ts +7 -0
  28. package/dist/components/Materializations/ManifestView.d.ts +13 -0
  29. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +9 -0
  30. package/dist/components/Materializations/MaterializationRunsList.d.ts +15 -0
  31. package/dist/components/Materializations/Materializations.d.ts +7 -0
  32. package/dist/components/Materializations/ScheduleCard.d.ts +20 -0
  33. package/dist/components/Materializations/SectionLabel.d.ts +10 -0
  34. package/dist/components/Materializations/SetScheduleDialog.d.ts +11 -0
  35. package/dist/components/Materializations/TriggerChip.d.ts +10 -0
  36. package/dist/components/Materializations/cron.d.ts +23 -0
  37. package/dist/components/Materializations/index.d.ts +2 -0
  38. package/dist/components/Materializations/utils.d.ts +46 -0
  39. package/dist/components/Notebook/Notebook.d.ts +47 -4
  40. package/dist/components/Notebook/NotebookCell.d.ts +37 -1
  41. package/dist/components/Notebook/runPlan.d.ts +29 -0
  42. package/dist/components/Notebook/types.d.ts +10 -0
  43. package/dist/components/Package/ContentTypeIcon.d.ts +31 -0
  44. package/dist/components/Package/Package.d.ts +1 -4
  45. package/dist/components/RenderedResult/RenderedResult.d.ts +7 -1
  46. package/dist/components/RenderedResult/ResultContainer.d.ts +5 -1
  47. package/dist/components/RenderedResult/renderLogs.d.ts +6 -0
  48. package/dist/components/ResultsDialog.d.ts +6 -1
  49. package/dist/components/ServerProvider.d.ts +28 -4
  50. package/dist/components/click_helper.d.ts +10 -1
  51. package/dist/components/drill/index.d.ts +3 -0
  52. package/dist/components/drill/markDrillableCells.d.ts +55 -0
  53. package/dist/components/drill/resolveDrill.d.ts +139 -0
  54. package/dist/components/drill/useDrill.d.ts +63 -0
  55. package/dist/components/given/GivenInput.d.ts +52 -0
  56. package/dist/components/given/GivensPanel.d.ts +47 -0
  57. package/dist/components/given/filterValue.d.ts +97 -0
  58. package/dist/components/given/index.d.ts +2 -0
  59. package/dist/components/given/paramCodec.d.ts +60 -0
  60. package/dist/components/given/utils.d.ts +17 -0
  61. package/dist/components/highlighter.d.ts +6 -1
  62. package/dist/components/index.d.ts +7 -2
  63. package/dist/components/styles.d.ts +47 -0
  64. package/dist/constants/docLinks.d.ts +12 -0
  65. package/dist/{core-YNpOLuB1.cjs.js → core-hLahnv0W.cjs.js} +1 -1
  66. package/dist/{core-CjeTkq8O.es.js → core-lb28vQkR.es.js} +1 -1
  67. package/dist/github-dark-BKL9xNgN.cjs.js +1 -0
  68. package/dist/github-dark-DenFmJkN.es.js +4 -0
  69. package/dist/hooks/givenValue.d.ts +10 -0
  70. package/dist/hooks/index.d.ts +4 -0
  71. package/dist/hooks/useDimensionFiltersFromSpec.d.ts +3 -3
  72. package/dist/hooks/useDimensionFiltersQuery.d.ts +3 -3
  73. package/dist/hooks/useDimensionalFilterRangeData.d.ts +4 -4
  74. package/dist/hooks/useGivensState.d.ts +64 -0
  75. package/dist/hooks/useModelGivens.d.ts +10 -0
  76. package/dist/hooks/useSuggestOptions.d.ts +78 -0
  77. package/dist/index-DvEanVgc.cjs.js +339 -0
  78. package/dist/{index-DRDu9kIV.es.js → index-txw04ZbN.es.js} +40531 -27964
  79. package/dist/index.cjs.js +1 -1
  80. package/dist/index.d.ts +4 -1
  81. package/dist/index.es.js +79 -48
  82. package/dist/malloy-explorer.css +12 -1
  83. package/dist/sdk.css +1 -1
  84. package/dist/theme/ThemeContext.d.ts +45 -0
  85. package/dist/theme/buildMalloyExplicitTheme.d.ts +34 -0
  86. package/dist/theme/buildTableCssVars.d.ts +25 -0
  87. package/dist/theme/buildVegaThemeOverride.d.ts +16 -0
  88. package/dist/theme/defaults.d.ts +7 -0
  89. package/dist/theme/index.d.ts +8 -0
  90. package/dist/theme/keys.d.ts +20 -0
  91. package/dist/theme/readChartAnnotations.d.ts +23 -0
  92. package/dist/theme/resolveTheme.d.ts +22 -0
  93. package/dist/theme/types.d.ts +70 -0
  94. package/dist/utils/dataAppEmbed.d.ts +44 -0
  95. package/dist/utils/formatting.d.ts +1 -1
  96. package/dist/utils/malloyString.d.ts +7 -0
  97. package/dist/utils/parsing.d.ts +2 -2
  98. package/dist/utils/queryClient.d.ts +5 -0
  99. package/package.json +19 -8
  100. package/src/client-entry.ts +3 -0
  101. package/src/components/AnalyzePackageButton.tsx +9 -3
  102. package/src/components/ApiErrorDisplay.tsx +3 -0
  103. package/src/components/Connections/AddConnectionDialog.tsx +30 -2
  104. package/src/components/Connections/DeleteConnectionDialog.tsx +14 -3
  105. package/src/components/Connections/EditConnectionDialog.tsx +33 -4
  106. package/src/components/Connections/common.ts +64 -1
  107. package/src/components/DOMElement/DOMElement.tsx +3 -0
  108. package/src/components/DOMElement/index.ts +3 -0
  109. package/src/components/Dashboard/Dashboard.tsx +398 -0
  110. package/src/components/Dashboard/DashboardTile.tsx +153 -0
  111. package/src/components/Dashboard/index.ts +5 -0
  112. package/src/components/DataAppViewer/DataAppViewer.tsx +214 -0
  113. package/src/components/DataAppViewer/index.ts +4 -0
  114. package/src/components/{Project → Environment}/About.tsx +11 -4
  115. package/src/components/Environment/AddPackageDialog.tsx +202 -0
  116. package/src/components/{Project → Environment}/ConnectionExplorer.tsx +17 -14
  117. package/src/components/Environment/Connections.tsx +391 -0
  118. package/src/components/{Project → Environment}/DeletePackageDialog.tsx +8 -4
  119. package/src/components/{Project → Environment}/EditPackageDialog.tsx +21 -13
  120. package/src/components/Environment/Environment.tsx +89 -0
  121. package/src/components/Environment/Packages.tsx +206 -0
  122. package/src/components/Environment/index.ts +5 -0
  123. package/src/components/Home/{AddProjectDialog.tsx → AddEnvironmentDialog.tsx} +25 -19
  124. package/src/components/Home/{DeleteProjectDialog.tsx → DeleteEnvironmentDialog.tsx} +20 -15
  125. package/src/components/Home/{EditProjectDialog.tsx → EditEnvironmentDialog.tsx} +35 -28
  126. package/src/components/Home/Home.tsx +386 -408
  127. package/src/components/Home/index.ts +3 -0
  128. package/src/components/Loading.tsx +3 -0
  129. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +179 -0
  130. package/src/components/Materializations/CreateMaterializationDialog.tsx +112 -0
  131. package/src/components/Materializations/DeleteMaterializationDialog.tsx +109 -0
  132. package/src/components/Materializations/EnvironmentMaterializations.tsx +267 -0
  133. package/src/components/Materializations/ManifestView.tsx +87 -0
  134. package/src/components/Materializations/MaterializationDetailDialog.tsx +259 -0
  135. package/src/components/Materializations/MaterializationRunsList.tsx +256 -0
  136. package/src/components/Materializations/Materializations.tsx +355 -0
  137. package/src/components/Materializations/ScheduleCard.tsx +231 -0
  138. package/src/components/Materializations/SectionLabel.tsx +30 -0
  139. package/src/components/Materializations/SetScheduleDialog.tsx +162 -0
  140. package/src/components/Materializations/TriggerChip.tsx +44 -0
  141. package/src/components/Materializations/cron.ts +124 -0
  142. package/src/components/Materializations/index.ts +5 -0
  143. package/src/components/Materializations/utils.ts +145 -0
  144. package/src/components/Model/Model.tsx +44 -2
  145. package/src/components/Model/ModelCell.tsx +14 -5
  146. package/src/components/Model/ModelExplorer.tsx +3 -0
  147. package/src/components/Model/ModelExplorerDialog.tsx +4 -1
  148. package/src/components/Model/SourcesExplorer.tsx +9 -6
  149. package/src/components/Model/index.ts +3 -0
  150. package/src/components/Model/useModelData.ts +6 -3
  151. package/src/components/Notebook/Notebook.tsx +475 -339
  152. package/src/components/Notebook/NotebookCell.tsx +264 -25
  153. package/src/components/Notebook/index.ts +3 -0
  154. package/src/components/Notebook/runPlan.spec.ts +155 -0
  155. package/src/components/Notebook/runPlan.ts +67 -0
  156. package/src/components/Notebook/types.ts +14 -0
  157. package/src/components/Package/ContentTypeIcon.spec.ts +91 -0
  158. package/src/components/Package/ContentTypeIcon.tsx +177 -0
  159. package/src/components/Package/FileTreeView.tsx +3 -0
  160. package/src/components/Package/Models.tsx +7 -4
  161. package/src/components/Package/Package.tsx +666 -59
  162. package/src/components/Package/index.ts +3 -0
  163. package/src/components/QueryResult/QueryResult.tsx +17 -8
  164. package/src/components/QueryResult/index.ts +3 -0
  165. package/src/components/RenderedResult/RenderedResult.tsx +685 -67
  166. package/src/components/RenderedResult/ResultContainer.tsx +71 -2
  167. package/src/components/RenderedResult/index.ts +3 -0
  168. package/src/components/RenderedResult/renderLogs.spec.ts +58 -0
  169. package/src/components/RenderedResult/renderLogs.ts +43 -0
  170. package/src/components/ResultsDialog.tsx +13 -1
  171. package/src/components/ServerProvider.tsx +175 -51
  172. package/src/components/Workbook/BrowserWorkbookStorage.ts +3 -0
  173. package/src/components/Workbook/EditableMalloyCell.tsx +3 -0
  174. package/src/components/Workbook/ModelPicker.tsx +7 -4
  175. package/src/components/Workbook/MutableCell.tsx +10 -5
  176. package/src/components/Workbook/Workbook.tsx +8 -5
  177. package/src/components/Workbook/WorkbookList.tsx +3 -0
  178. package/src/components/Workbook/WorkbookManager.ts +3 -0
  179. package/src/components/Workbook/WorkbookStorage.ts +3 -0
  180. package/src/components/Workbook/WorkbookStorageProvider.tsx +3 -0
  181. package/src/components/Workbook/index.ts +3 -0
  182. package/src/components/click_helper.ts +17 -1
  183. package/src/components/drill/index.ts +28 -0
  184. package/src/components/drill/markDrillableCells.dom.spec.ts +313 -0
  185. package/src/components/drill/markDrillableCells.spec.ts +109 -0
  186. package/src/components/drill/markDrillableCells.ts +314 -0
  187. package/src/components/drill/resolveDrill.spec.ts +449 -0
  188. package/src/components/drill/resolveDrill.ts +375 -0
  189. package/src/components/drill/useDrill.tsx +203 -0
  190. package/src/components/filter/DimensionFilter.tsx +3 -0
  191. package/src/components/filter/index.ts +3 -0
  192. package/src/components/filter/utils.ts +16 -5
  193. package/src/components/given/GivenInput.spec.tsx +689 -0
  194. package/src/components/given/GivenInput.tsx +801 -0
  195. package/src/components/given/GivensPanel.spec.tsx +175 -0
  196. package/src/components/given/GivensPanel.tsx +195 -0
  197. package/src/components/given/filterValue.spec.ts +364 -0
  198. package/src/components/given/filterValue.ts +207 -0
  199. package/src/components/given/index.ts +9 -0
  200. package/src/components/given/paramCodec.spec.ts +857 -0
  201. package/src/components/given/paramCodec.ts +483 -0
  202. package/src/components/given/utils.spec.ts +60 -0
  203. package/src/components/given/utils.ts +79 -0
  204. package/src/components/highlighter.ts +22 -5
  205. package/src/components/index.ts +10 -2
  206. package/src/components/styles.ts +82 -33
  207. package/src/constants/docLinks.spec.ts +54 -0
  208. package/src/constants/docLinks.ts +46 -0
  209. package/src/hooks/givenValue.ts +13 -0
  210. package/src/hooks/index.ts +13 -0
  211. package/src/hooks/useDimensionFilters.ts +4 -7
  212. package/src/hooks/useDimensionFiltersFromSpec.ts +8 -5
  213. package/src/hooks/useDimensionFiltersQuery.ts +10 -13
  214. package/src/hooks/useDimensionalFilterRangeData.ts +11 -14
  215. package/src/hooks/useGivensState.spec.ts +449 -0
  216. package/src/hooks/useGivensState.ts +340 -0
  217. package/src/hooks/useModelGivens.ts +29 -0
  218. package/src/hooks/useQueryWithApiError.ts +3 -0
  219. package/src/hooks/useRawQueryData.ts +6 -3
  220. package/src/hooks/useSuggestOptions.spec.ts +112 -0
  221. package/src/hooks/useSuggestOptions.ts +263 -0
  222. package/src/index.ts +10 -1
  223. package/src/react-app-env.d.ts +3 -0
  224. package/src/theme/ThemeContext.tsx +86 -0
  225. package/src/theme/buildMalloyExplicitTheme.ts +61 -0
  226. package/src/theme/buildTableCssVars.spec.ts +67 -0
  227. package/src/theme/buildTableCssVars.ts +67 -0
  228. package/src/theme/buildVegaThemeOverride.spec.ts +56 -0
  229. package/src/theme/buildVegaThemeOverride.ts +47 -0
  230. package/src/theme/defaults.ts +78 -0
  231. package/src/theme/index.ts +11 -0
  232. package/src/theme/keys.ts +32 -0
  233. package/src/theme/readChartAnnotations.spec.ts +58 -0
  234. package/src/theme/readChartAnnotations.ts +69 -0
  235. package/src/theme/resolveTheme.spec.ts +160 -0
  236. package/src/theme/resolveTheme.ts +121 -0
  237. package/src/theme/types.ts +79 -0
  238. package/src/utils/dataAppEmbed.spec.ts +63 -0
  239. package/src/utils/dataAppEmbed.ts +84 -0
  240. package/src/utils/formatting.spec.ts +25 -21
  241. package/src/utils/formatting.ts +11 -7
  242. package/src/utils/malloyString.spec.ts +24 -0
  243. package/src/utils/malloyString.ts +12 -0
  244. package/src/utils/parsing.spec.ts +26 -19
  245. package/src/utils/parsing.ts +11 -6
  246. package/src/utils/queryClient.ts +17 -0
  247. package/test/README.md +141 -0
  248. package/test/setup.ts +29 -0
  249. package/tsconfig.json +12 -1
  250. package/tsconfig.spec.json +22 -0
  251. package/vite.config.ts +3 -0
  252. package/dist/ServerProvider-lOQXDlqB.cjs.js +0 -1
  253. package/dist/ServerProvider-on-8FH5Z.es.js +0 -3060
  254. package/dist/components/Home/AddProjectDialog.d.ts +0 -1
  255. package/dist/components/Home/DeleteProjectDialog.d.ts +0 -5
  256. package/dist/components/Home/EditProjectDialog.d.ts +0 -7
  257. package/dist/components/Package/Config.d.ts +0 -5
  258. package/dist/components/Package/Databases.d.ts +0 -5
  259. package/dist/components/Package/Notebooks.d.ts +0 -6
  260. package/dist/components/Project/Project.d.ts +0 -6
  261. package/dist/components/Project/index.d.ts +0 -2
  262. package/dist/index-BOLBP6_i.cjs.js +0 -233
  263. package/src/components/Package/Config.tsx +0 -97
  264. package/src/components/Package/Connections.tsx +0 -373
  265. package/src/components/Package/Databases.tsx +0 -228
  266. package/src/components/Package/Notebooks.tsx +0 -77
  267. package/src/components/Project/AddPackageDialog.tsx +0 -159
  268. package/src/components/Project/Packages.tsx +0 -191
  269. package/src/components/Project/Project.tsx +0 -52
  270. package/src/components/Project/index.ts +0 -2
  271. /package/dist/components/{Project → Environment}/About.d.ts +0 -0
  272. /package/dist/components/{Project → Environment}/AddPackageDialog.d.ts +0 -0
  273. /package/dist/components/{Project → Environment}/ConnectionExplorer.d.ts +0 -0
  274. /package/dist/components/{Package → Environment}/Connections.d.ts +0 -0
  275. /package/dist/components/{Project → Environment}/DeletePackageDialog.d.ts +0 -0
  276. /package/dist/components/{Project → Environment}/EditPackageDialog.d.ts +0 -0
  277. /package/dist/components/{Project → Environment}/Packages.d.ts +0 -0
@@ -1,26 +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";
5
+ import { Stack, Typography } from "@mui/material";
4
6
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
- import { RawNotebook, Source } from "../../client";
6
- import {
7
- getDimensionKey,
8
- useDimensionalFilterRangeData,
9
- } from "../../hooks/useDimensionalFilterRangeData";
10
- import {
11
- FilterSelection,
12
- useDimensionFilters,
13
- } from "../../hooks/useDimensionFilters";
7
+ import { planRun } from "./runPlan";
8
+ import { RawNotebook } from "../../client";
9
+ import { GivenValue } from "../../hooks/givenValue";
10
+ import { useGivensState } from "../../hooks/useGivensState";
11
+ import { useModelGivens } from "../../hooks/useModelGivens";
14
12
  import { useQueryWithApiError } from "../../hooks/useQueryWithApiError";
15
- import { ApiErrorDisplay } from "../ApiErrorDisplay";
16
- import { DimensionFilter, RetrievalFunction } from "../filter/DimensionFilter";
17
- import {
18
- extractDimensionSpecs,
19
- parseAllSourceInfos,
20
- parseNotebookFilterAnnotation,
21
- } from "../filter/utils";
22
-
13
+ import { useSuggestOptions } from "../../hooks/useSuggestOptions";
23
14
  import { parseResourceUri } from "../../utils/formatting";
15
+ import { ApiErrorDisplay } from "../ApiErrorDisplay";
16
+ import type { NavigationClick } from "../click_helper";
17
+ import { encodeDrillValue, type DrillNavigation } from "../drill";
18
+ import { GivensPanel } from "../given";
19
+ import { givensToRequest } from "../given/paramCodec";
24
20
  import { Loading } from "../Loading";
25
21
  import { useServer } from "../ServerProvider";
26
22
  import { CleanNotebookContainer, CleanNotebookSection } from "../styles";
@@ -30,22 +26,100 @@ import { EnhancedNotebookCell } from "./types";
30
26
  // Maximum number of concurrent cell executions to avoid overwhelming the server
31
27
  const MAX_CONCURRENT = 4;
32
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
+
33
59
  interface NotebookProps {
34
60
  resourceUri: string;
35
61
  maxResultSize?: number;
36
- /** Optional retrieval function for semantic search filters */
37
- retrievalFn?: RetrievalFunction;
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
94
+ * omitted, in-notebook links fall back to plain absolute anchors, so no
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;
38
109
  }
39
110
 
40
111
  // Requires PackageProvider
41
112
  export default function Notebook({
42
113
  resourceUri,
43
114
  maxResultSize = 0,
44
- retrievalFn,
115
+ givens,
116
+ onGivensChange,
117
+ onNavigate,
118
+ onDrillNavigate,
45
119
  }: NotebookProps) {
46
120
  const { apiClients } = useServer();
47
121
  const {
48
- projectName,
122
+ environmentName,
49
123
  packageName,
50
124
  versionId,
51
125
  modelPath: notebookPath,
@@ -61,7 +135,7 @@ export default function Notebook({
61
135
  queryKey: [resourceUri],
62
136
  queryFn: async () => {
63
137
  const response = await apiClients.notebooks.getNotebook(
64
- projectName,
138
+ environmentName,
65
139
  packageName,
66
140
  notebookPath,
67
141
  versionId,
@@ -75,228 +149,263 @@ export default function Notebook({
75
149
  [],
76
150
  );
77
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);
78
158
  const [executionError, setExecutionError] = useState<Error | null>(null);
79
159
 
80
- // Parse filter configuration from notebook annotations (legacy ##(filters) approach)
81
- const filterConfig = useMemo(() => {
82
- if (!notebook) return null;
83
- return parseNotebookFilterAnnotation(notebook.annotations);
84
- }, [notebook]);
85
-
86
- // Parse all SourceInfos from notebook cells and create a map
87
- const sourceData = useMemo(() => {
88
- if (!notebook?.notebookCells) return null;
89
- return parseAllSourceInfos(notebook.notebookCells);
90
- }, [notebook]);
91
-
92
- const sourceInfoMap = useMemo(
93
- () => sourceData?.sourceInfoMap ?? new Map<string, Malloy.SourceInfo>(),
94
- [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],
95
173
  );
96
- const modelPath = sourceData?.modelPath ?? null;
97
-
98
- // Extract server-side filter definitions from notebook sources
99
- // These come from #(filter) annotations parsed by the server
100
- const serverFilters = useMemo(() => {
101
- const result = new Map<string, Source["filters"]>();
102
- if (!notebook?.sources) return result;
103
- for (const source of notebook.sources as Source[]) {
104
- if (source.name && source.filters && source.filters.length > 0) {
105
- // Exclude implicit filters from the UI
106
- const visibleFilters = source.filters.filter((f) => !f.implicit);
107
- if (visibleFilters.length > 0) {
108
- result.set(source.name, visibleFilters);
109
- }
110
- }
111
- }
112
- return result;
113
- }, [notebook]);
114
-
115
- // Determine if we're using server-driven filters (#(filter)) or legacy (##(filters))
116
- const useServerFilters = serverFilters.size > 0;
117
-
118
- // Build dimension specs from filter config and source info map
119
- // Each spec includes source and model for proper query routing
120
- const dimensionSpecs = useMemo(() => {
121
- if (useServerFilters && modelPath) {
122
- // Server-driven: build specs from #(filter) metadata
123
- const specs: import("../../hooks/useDimensionalFilterRangeData").DimensionSpec[] =
124
- [];
125
- for (const [sourceName, filters] of serverFilters) {
126
- for (const filter of filters ?? []) {
127
- if (!filter.dimension || !filter.type) continue;
128
-
129
- // Choose widget type based on the dimension's data type first,
130
- // then fall back to the annotation's comparator type
131
- type FT =
132
- import("../../hooks/useDimensionalFilterRangeData").FilterType;
133
- let filterType: FT;
134
- const dimType = filter.dimensionType;
135
- if (dimType === "boolean") {
136
- filterType = "Boolean";
137
- } else if (
138
- dimType === "date" ||
139
- dimType === "timestamp" ||
140
- dimType === "timestamptz"
141
- ) {
142
- filterType = "DateMinMax";
143
- } else if (dimType === "number") {
144
- filterType =
145
- filter.type === "equal" || filter.type === "in"
146
- ? "Star"
147
- : "MinMax";
148
- } else {
149
- const filterTypeMap: Record<string, FT> = {
150
- equal: "Star",
151
- in: "Star",
152
- like: "Star",
153
- greater_than: "MinMax",
154
- less_than: "MinMax",
155
- };
156
- filterType = filterTypeMap[filter.type] ?? "Star";
157
- }
158
174
 
159
- // Derive the match type from the #(filter) annotation type so
160
- // the UI never needs to show a match-type dropdown.
161
- type MT = import("../../hooks/useDimensionFilters").MatchType;
162
- const matchTypeMap: Record<string, MT> = {
163
- equal: "Equals",
164
- in: "Equals",
165
- like: "Contains",
166
- greater_than:
167
- filterType === "DateMinMax" ? "After" : "Greater Than",
168
- less_than:
169
- filterType === "DateMinMax" ? "Before" : "Less Than",
170
- };
171
- const defaultMatchType: MT | undefined =
172
- matchTypeMap[filter.type!];
173
-
174
- const filterLabel =
175
- filter.name !== filter.dimension ? filter.name : undefined;
176
- specs.push({
177
- source: sourceName,
178
- model: modelPath,
179
- dimensionName: filter.dimension!,
180
- filterType,
181
- label: filterLabel,
182
- filterName: filter.name ?? filter.dimension!,
183
- defaultMatchType,
184
- required: filter.required ?? false,
185
- });
186
- }
187
- }
188
- return specs;
189
- }
190
- // Legacy: use ##(filters) + #(filter) annotation approach
191
- if (!filterConfig || sourceInfoMap.size === 0 || !modelPath) return [];
192
- return extractDimensionSpecs(
193
- sourceInfoMap,
194
- filterConfig.filters,
195
- modelPath,
196
- );
197
- }, [
198
- useServerFilters,
199
- serverFilters,
200
- filterConfig,
201
- sourceInfoMap,
202
- modelPath,
203
- ]);
204
-
205
- // Initialize dimension filters hook
206
- const { filterStates, updateFilter, getActiveFilters } = useDimensionFilters(
207
- {
208
- 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()));
209
187
  },
188
+ [isSuccess, onGivensChange, declaredTypes],
210
189
  );
211
190
 
212
- // Get active filters - include filterStates in deps to ensure updates when individual items change
213
- const activeFilters = useMemo(
214
- () => getActiveFilters(),
215
- // eslint-disable-next-line react-hooks/exhaustive-deps
216
- [filterStates, getActiveFilters],
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
+ });
221
+
222
+ // A notebook's model path is the notebook itself: `suggest` queries run
223
+ // against the same model the cells do.
224
+ const {
225
+ options: givenOptions,
226
+ isLoading: givenOptionsLoading,
227
+ failed: givenOptionsFailed,
228
+ } = useSuggestOptions(
229
+ environmentName,
230
+ packageName,
231
+ notebookPath,
232
+ declaredGivens,
217
233
  );
218
234
 
219
- // Create a map of dimension key -> source name for quick lookup (used by filter UI)
220
- const _dimensionToSourceMap = useMemo(() => {
221
- const map = new Map<string, string>();
222
- for (const spec of dimensionSpecs) {
223
- const key = getDimensionKey(spec);
224
- map.set(key, spec.source);
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);
225
252
  }
226
- return map;
227
- }, [dimensionSpecs]);
228
-
229
- // Fetch filter range data when we have dimension specs.
230
- // Do NOT pass activeFilters here — the index query should return all
231
- // possible values for each dimension, not just those matching the
232
- // current selection. Otherwise selecting "FORD" would hide every other
233
- // manufacturer from the dropdown.
234
- const { data: filterValuesData } = useDimensionalFilterRangeData({
235
- project: projectName,
236
- package: packageName,
237
- dimensionSpecs,
238
- versionId,
239
- enabled: dimensionSpecs.length > 0,
240
- });
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
+ );
241
264
 
242
- /**
243
- * Convert active FilterSelections into a flat { filterName: value } map
244
- * suitable for the server's filter_params parameter.
245
- * Uses filterName from the selection (propagated from the spec) as the
246
- * API param key, falling back to dimensionName.
247
- */
248
- const buildFilterParams = useCallback(
249
- (filtersToApply: FilterSelection[]): string | undefined => {
250
- 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
+ );
251
276
 
252
- const toParamString = (v: unknown): string => {
253
- if (v instanceof Date) {
254
- return v.toISOString().slice(0, 10);
255
- }
256
- return String(v);
257
- };
258
-
259
- const params: { [key: string]: string | string[] } = {};
260
- for (const f of filtersToApply) {
261
- const paramName = f.filterName ?? f.dimensionName;
262
- const val = f.value;
263
- if (Array.isArray(val)) {
264
- params[paramName] = val.map(toParamString);
265
- } else if (val !== undefined && val !== null) {
266
- params[paramName] = toParamString(val);
267
- }
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;
287
+ }
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;
268
305
  }
269
- return Object.keys(params).length > 0
270
- ? JSON.stringify(params)
306
+ setGiven(declared, value);
307
+ },
308
+ [declaredTypes, notebookPath, resolveGiven, setGiven],
309
+ );
310
+
311
+ /**
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.
316
+ */
317
+ const buildGivens = useCallback(
318
+ (values: Map<string, GivenValue>): string | undefined => {
319
+ const request = givensToRequest(values, declaredTypes);
320
+ return Object.keys(request).length > 0
321
+ ? JSON.stringify(request)
271
322
  : undefined;
272
323
  },
273
- [],
324
+ [declaredTypes],
274
325
  );
275
326
 
276
- // Unified cell execution function
277
- // Executes all notebook cells, passing server-side filter params when available
278
- // 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
+ );
279
378
  const executeCells = useCallback(
280
- async (filtersToApply: FilterSelection[] = []) => {
379
+ async (givensToApply: Map<string, GivenValue> = new Map()) => {
281
380
  if (!isSuccess || !notebook?.notebookCells) return;
282
381
 
283
- // Initialize or reset cells
284
- setEnhancedCells((prev) => {
285
- if (prev.length === 0) {
286
- return notebook.notebookCells.map((cell) => ({ ...cell }));
287
- }
288
- return prev.map((cell) => ({
289
- ...cell,
290
- result: undefined,
291
- }));
292
- });
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 })));
293
404
 
294
405
  setIsExecuting(true);
295
406
  setExecutionError(null);
296
407
 
297
- const filterParams = useServerFilters
298
- ? buildFilterParams(filtersToApply)
299
- : undefined;
408
+ const givensParam = buildGivens(givensToApply);
300
409
 
301
410
  try {
302
411
  // Build execution tasks for code cells
@@ -313,17 +422,27 @@ export default function Notebook({
313
422
 
314
423
  const executeCell = async () => {
315
424
  try {
316
- // Use notebook cell execution API with optional filter_params
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.
317
431
  const response =
318
432
  await apiClients.notebooks.executeNotebookCell(
319
- projectName,
433
+ environmentName,
320
434
  packageName,
321
435
  notebookPath,
322
436
  cellIndex,
323
437
  versionId,
324
- filterParams,
438
+ undefined,
439
+ undefined,
440
+ givensParam,
441
+ { signal: controller.signal },
325
442
  );
326
443
 
444
+ if (runIdRef.current !== runId) return;
445
+
327
446
  const executedCell = response.data;
328
447
  const result = executedCell.result;
329
448
  const newSources =
@@ -343,10 +462,29 @@ export default function Notebook({
343
462
  return next;
344
463
  });
345
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;
346
472
  console.error(
347
473
  `Error executing cell ${cellIndex}:`,
348
474
  cellError,
349
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
+ });
350
488
  }
351
489
  };
352
490
 
@@ -370,18 +508,21 @@ export default function Notebook({
370
508
  // Wait for remaining tasks to complete
371
509
  await Promise.all(executing);
372
510
  } catch (error) {
511
+ if (controller.signal.aborted || runIdRef.current !== runId) return;
373
512
  console.error("Error executing notebook cells:", error);
374
513
  setExecutionError(error as Error);
375
514
  } finally {
376
- setIsExecuting(false);
515
+ if (runIdRef.current === runId) {
516
+ setIsExecuting(false);
517
+ inFlightRef.current = null;
518
+ }
377
519
  }
378
520
  },
379
521
  [
380
522
  isSuccess,
381
523
  notebook,
382
- useServerFilters,
383
- buildFilterParams,
384
- projectName,
524
+ buildGivens,
525
+ environmentName,
385
526
  packageName,
386
527
  notebookPath,
387
528
  versionId,
@@ -389,125 +530,109 @@ export default function Notebook({
389
530
  ],
390
531
  );
391
532
 
392
- // Execute cells when notebook is loaded (no filters initially)
393
- useEffect(() => {
394
- if (!isSuccess || !notebook?.notebookCells) return;
395
- executeCells([]);
396
- }, [isSuccess, notebook, executeCells]);
397
-
398
- // Re-execute when filters change
399
- // Track previous activeFilters to detect actual changes (not just reference changes)
400
- const prevActiveFiltersRef = 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;
401
556
 
402
557
  useEffect(() => {
403
- // Serialize activeFilters to detect actual value changes
404
- const serialized = JSON.stringify(
405
- activeFilters.map((f) => ({
406
- dim: f.dimensionName,
407
- type: f.matchType,
408
- val: f.value,
409
- val2: f.value2,
410
- })),
411
- );
412
-
413
- // Skip if no actual change or if this is the initial empty state
414
- if (serialized === prevActiveFiltersRef.current) {
415
- return;
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.
566
+ if (
567
+ lastDocumentRef.current !== undefined &&
568
+ lastDocumentRef.current !== documentKey
569
+ ) {
570
+ inFlightRef.current?.abort();
571
+ inFlightRef.current = null;
416
572
  }
417
-
418
- // Skip the initial render (when prevActiveFiltersRef is empty and filters are also empty)
419
- if (prevActiveFiltersRef.current === "" && activeFilters.length === 0) {
420
- prevActiveFiltersRef.current = serialized;
421
- return;
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
+ });
582
+
583
+ if (plan.cancelPending) {
584
+ clearTimeout(pendingRunRef.current?.timer);
585
+ pendingRunRef.current = undefined;
586
+ setRunScheduled(false);
422
587
  }
588
+ if (plan.dispatch === "none") return;
423
589
 
424
- prevActiveFiltersRef.current = serialized;
590
+ const start = () => {
591
+ pendingRunRef.current = undefined;
592
+ setRunScheduled(false);
593
+ lastRunRef.current = runKey;
594
+ void executeCells(applied);
595
+ };
425
596
 
426
- // Re-execute with current filters (or no filters if cleared)
427
- if (!isExecuting) {
428
- executeCells(activeFilters);
597
+ if (plan.dispatch === "now") {
598
+ start();
599
+ return;
429
600
  }
430
- }, [activeFilters, isExecuting, executeCells]);
431
-
432
- // Handle filter change using composite key
433
- const handleFilterChange = useCallback(
434
- (key: string) => (selection: FilterSelection | null) => {
435
- updateFilter(key, selection);
436
- },
437
- [updateFilter],
438
- );
439
-
440
- // Check if retrieval is supported
441
- const hasRetrievalFilters = dimensionSpecs.some(
442
- (spec) => spec.filterType === "Retrieval",
443
- );
444
- const _retrievalSupported = !hasRetrievalFilters || !!retrievalFn;
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
+ ]);
445
620
 
446
621
  return (
447
622
  <CleanNotebookContainer>
448
623
  <CleanNotebookSection>
449
624
  <Stack spacing={3} component="section">
450
- {/* Filter Panel */}
451
- {dimensionSpecs.length > 0 && filterValuesData && (
452
- <Paper
453
- elevation={0}
454
- sx={{
455
- p: 3,
456
- backgroundColor: "#ffffff",
457
- border: "1px solid #f0f0f0",
458
- borderRadius: 2,
459
- boxShadow: "0 1px 3px rgba(0, 0, 0, 0.04)",
460
- transition: "box-shadow 0.2s ease-in-out",
461
- "&:hover": {
462
- boxShadow: "0 2px 6px rgba(0, 0, 0, 0.08)",
463
- },
464
- }}
465
- >
466
- <Typography
467
- variant="subtitle2"
468
- sx={{
469
- fontWeight: 600,
470
- mb: 2,
471
- color: "#333",
472
- }}
473
- >
474
- Filters
475
- </Typography>
476
- <Box
477
- sx={{
478
- display: "grid",
479
- gridTemplateColumns:
480
- "repeat(auto-fill, minmax(250px, 1fr))",
481
- gap: 3,
482
- }}
483
- >
484
- {dimensionSpecs.map((spec) => {
485
- const key = getDimensionKey(spec);
486
- const values = filterValuesData.get(key) || [];
487
- const filterState = filterStates.get(key);
488
- // Skip Retrieval filters if no retrievalFn provided
489
- if (
490
- spec.filterType === "Retrieval" &&
491
- !retrievalFn
492
- ) {
493
- return null;
494
- }
495
-
496
- return (
497
- <Box key={key}>
498
- <DimensionFilter
499
- spec={spec}
500
- values={values}
501
- selection={filterState?.selection}
502
- onChange={handleFilterChange(key)}
503
- retrievalFn={retrievalFn}
504
- />
505
- </Box>
506
- );
507
- })}
508
- </Box>
509
- </Paper>
510
- )}
625
+ {/* Parameters panel: the controls for `given:` declarations */}
626
+ <GivensPanel
627
+ givens={declaredGivens}
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 }}
635
+ />
511
636
 
512
637
  {/* Loading State */}
513
638
  {!isSuccess && !isError && (
@@ -527,13 +652,24 @@ export default function Notebook({
527
652
  resourceUri={resourceUri}
528
653
  maxResultSize={maxResultSize}
529
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}
660
+ onNavigate={onNavigate}
661
+ onDrillNavigate={onDrillNavigate}
662
+ onDrillSelf={
663
+ declaredGivens.length > 0 ? onDrillSelf : undefined
664
+ }
665
+ canDrillSelf={canDrillSelf}
530
666
  />
531
667
  ))}
532
668
 
533
669
  {/* Error States */}
534
670
  {isError && error.status === 404 && (
535
- <Typography variant="body2" sx={{ color: "#666666" }}>
536
- <code>{`${projectName} > ${packageName} > ${notebookPath}`}</code>{" "}
671
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
672
+ <code>{`${environmentName} > ${packageName} > ${notebookPath}`}</code>{" "}
537
673
  not found.
538
674
  </Typography>
539
675
  )}
@@ -541,7 +677,7 @@ export default function Notebook({
541
677
  {isError && error.status !== 404 && (
542
678
  <ApiErrorDisplay
543
679
  error={error}
544
- context={`${projectName} > ${packageName} > ${notebookPath}`}
680
+ context={`${environmentName} > ${packageName} > ${notebookPath}`}
545
681
  />
546
682
  )}
547
683