@malloy-publisher/sdk 0.0.382-dev → 0.2.1

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 (284) 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-Cn_LhKda.cjs.js +1 -0
  5. package/dist/ServerProvider-sfabtriY.es.js +4076 -0
  6. package/dist/client/api.d.ts +3773 -1515
  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 +86 -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 +62 -0
  14. package/dist/components/Dashboard/DashboardTile.d.ts +57 -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-CqRKhtoy.cjs.js} +1 -1
  66. package/dist/{core-CjeTkq8O.es.js → core-DyU47reh.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-DRDu9kIV.es.js → index-CAkFE4Ol.es.js} +41278 -28504
  78. package/dist/index-DD4b_bt0.cjs.js +356 -0
  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 +41 -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 +132 -25
  104. package/src/components/Connections/DeleteConnectionDialog.tsx +14 -3
  105. package/src/components/Connections/EditConnectionDialog.tsx +167 -37
  106. package/src/components/Connections/common.ts +94 -3
  107. package/src/components/DOMElement/DOMElement.tsx +3 -0
  108. package/src/components/DOMElement/index.ts +3 -0
  109. package/src/components/Dashboard/Dashboard.spec.tsx +216 -0
  110. package/src/components/Dashboard/Dashboard.tsx +458 -0
  111. package/src/components/Dashboard/DashboardTile.spec.tsx +81 -0
  112. package/src/components/Dashboard/DashboardTile.tsx +199 -0
  113. package/src/components/Dashboard/index.ts +5 -0
  114. package/src/components/Dashboard/tileGridColumn.spec.ts +35 -0
  115. package/src/components/DataAppViewer/DataAppViewer.tsx +214 -0
  116. package/src/components/DataAppViewer/index.ts +4 -0
  117. package/src/components/{Project → Environment}/About.tsx +11 -4
  118. package/src/components/Environment/AddPackageDialog.tsx +202 -0
  119. package/src/components/{Project → Environment}/ConnectionExplorer.tsx +17 -14
  120. package/src/components/Environment/Connections.tsx +391 -0
  121. package/src/components/{Project → Environment}/DeletePackageDialog.tsx +8 -4
  122. package/src/components/{Project → Environment}/EditPackageDialog.tsx +21 -13
  123. package/src/components/Environment/Environment.tsx +89 -0
  124. package/src/components/Environment/Packages.tsx +206 -0
  125. package/src/components/Environment/index.ts +5 -0
  126. package/src/components/Home/{AddProjectDialog.tsx → AddEnvironmentDialog.tsx} +25 -19
  127. package/src/components/Home/{DeleteProjectDialog.tsx → DeleteEnvironmentDialog.tsx} +20 -15
  128. package/src/components/Home/{EditProjectDialog.tsx → EditEnvironmentDialog.tsx} +35 -28
  129. package/src/components/Home/Home.tsx +386 -408
  130. package/src/components/Home/index.ts +3 -0
  131. package/src/components/Loading.tsx +3 -0
  132. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +179 -0
  133. package/src/components/Materializations/CreateMaterializationDialog.tsx +112 -0
  134. package/src/components/Materializations/DeleteMaterializationDialog.tsx +109 -0
  135. package/src/components/Materializations/EnvironmentMaterializations.tsx +267 -0
  136. package/src/components/Materializations/ManifestView.tsx +87 -0
  137. package/src/components/Materializations/MaterializationDetailDialog.tsx +259 -0
  138. package/src/components/Materializations/MaterializationRunsList.tsx +256 -0
  139. package/src/components/Materializations/Materializations.tsx +355 -0
  140. package/src/components/Materializations/ScheduleCard.tsx +231 -0
  141. package/src/components/Materializations/SectionLabel.tsx +30 -0
  142. package/src/components/Materializations/SetScheduleDialog.tsx +162 -0
  143. package/src/components/Materializations/TriggerChip.tsx +44 -0
  144. package/src/components/Materializations/cron.ts +124 -0
  145. package/src/components/Materializations/index.ts +5 -0
  146. package/src/components/Materializations/utils.ts +145 -0
  147. package/src/components/Model/Model.tsx +44 -2
  148. package/src/components/Model/ModelCell.tsx +14 -5
  149. package/src/components/Model/ModelExplorer.tsx +3 -0
  150. package/src/components/Model/ModelExplorerDialog.tsx +4 -1
  151. package/src/components/Model/SourcesExplorer.tsx +9 -6
  152. package/src/components/Model/index.ts +3 -0
  153. package/src/components/Model/useModelData.ts +6 -3
  154. package/src/components/Notebook/Notebook.spec.tsx +88 -0
  155. package/src/components/Notebook/Notebook.tsx +476 -339
  156. package/src/components/Notebook/NotebookCell.tsx +264 -25
  157. package/src/components/Notebook/index.ts +3 -0
  158. package/src/components/Notebook/runPlan.spec.ts +155 -0
  159. package/src/components/Notebook/runPlan.ts +67 -0
  160. package/src/components/Notebook/types.ts +14 -0
  161. package/src/components/Package/ContentTypeIcon.spec.ts +91 -0
  162. package/src/components/Package/ContentTypeIcon.tsx +177 -0
  163. package/src/components/Package/FileTreeView.tsx +3 -0
  164. package/src/components/Package/Models.tsx +7 -4
  165. package/src/components/Package/Package.spec.tsx +113 -0
  166. package/src/components/Package/Package.tsx +692 -59
  167. package/src/components/Package/index.ts +3 -0
  168. package/src/components/QueryResult/QueryResult.tsx +17 -8
  169. package/src/components/QueryResult/index.ts +3 -0
  170. package/src/components/RenderedResult/RenderedResult.tsx +725 -67
  171. package/src/components/RenderedResult/ResultContainer.tsx +71 -2
  172. package/src/components/RenderedResult/index.ts +3 -0
  173. package/src/components/RenderedResult/renderLogs.spec.ts +58 -0
  174. package/src/components/RenderedResult/renderLogs.ts +43 -0
  175. package/src/components/ResultsDialog.tsx +13 -1
  176. package/src/components/ServerProvider.tsx +175 -51
  177. package/src/components/Workbook/BrowserWorkbookStorage.ts +3 -0
  178. package/src/components/Workbook/EditableMalloyCell.tsx +3 -0
  179. package/src/components/Workbook/ModelPicker.tsx +7 -4
  180. package/src/components/Workbook/MutableCell.tsx +10 -5
  181. package/src/components/Workbook/Workbook.tsx +8 -5
  182. package/src/components/Workbook/WorkbookList.tsx +3 -0
  183. package/src/components/Workbook/WorkbookManager.ts +3 -0
  184. package/src/components/Workbook/WorkbookStorage.ts +3 -0
  185. package/src/components/Workbook/WorkbookStorageProvider.tsx +3 -0
  186. package/src/components/Workbook/index.ts +3 -0
  187. package/src/components/click_helper.ts +17 -1
  188. package/src/components/drill/index.ts +28 -0
  189. package/src/components/drill/markDrillableCells.dom.spec.ts +313 -0
  190. package/src/components/drill/markDrillableCells.spec.ts +109 -0
  191. package/src/components/drill/markDrillableCells.ts +314 -0
  192. package/src/components/drill/resolveDrill.spec.ts +449 -0
  193. package/src/components/drill/resolveDrill.ts +375 -0
  194. package/src/components/drill/useDrill.tsx +203 -0
  195. package/src/components/filter/DimensionFilter.tsx +3 -0
  196. package/src/components/filter/index.ts +3 -0
  197. package/src/components/filter/utils.ts +16 -5
  198. package/src/components/given/GivenInput.spec.tsx +689 -0
  199. package/src/components/given/GivenInput.tsx +801 -0
  200. package/src/components/given/GivensPanel.spec.tsx +175 -0
  201. package/src/components/given/GivensPanel.tsx +195 -0
  202. package/src/components/given/filterValue.spec.ts +364 -0
  203. package/src/components/given/filterValue.ts +207 -0
  204. package/src/components/given/index.ts +9 -0
  205. package/src/components/given/paramCodec.spec.ts +857 -0
  206. package/src/components/given/paramCodec.ts +483 -0
  207. package/src/components/given/utils.spec.ts +60 -0
  208. package/src/components/given/utils.ts +79 -0
  209. package/src/components/highlighter.ts +22 -5
  210. package/src/components/index.ts +10 -2
  211. package/src/components/styles.ts +82 -33
  212. package/src/constants/docLinks.spec.ts +54 -0
  213. package/src/constants/docLinks.ts +46 -0
  214. package/src/hooks/givenValue.ts +13 -0
  215. package/src/hooks/index.ts +13 -0
  216. package/src/hooks/useDimensionFilters.ts +4 -7
  217. package/src/hooks/useDimensionFiltersFromSpec.ts +8 -5
  218. package/src/hooks/useDimensionFiltersQuery.ts +10 -13
  219. package/src/hooks/useDimensionalFilterRangeData.ts +11 -14
  220. package/src/hooks/useGivensState.spec.ts +449 -0
  221. package/src/hooks/useGivensState.ts +340 -0
  222. package/src/hooks/useModelGivens.ts +29 -0
  223. package/src/hooks/useQueryWithApiError.ts +3 -0
  224. package/src/hooks/useRawQueryData.ts +6 -3
  225. package/src/hooks/useSuggestOptions.dom.spec.ts +91 -0
  226. package/src/hooks/useSuggestOptions.spec.ts +112 -0
  227. package/src/hooks/useSuggestOptions.ts +268 -0
  228. package/src/index.ts +10 -1
  229. package/src/react-app-env.d.ts +3 -0
  230. package/src/theme/ThemeContext.tsx +86 -0
  231. package/src/theme/buildMalloyExplicitTheme.ts +61 -0
  232. package/src/theme/buildTableCssVars.spec.ts +86 -0
  233. package/src/theme/buildTableCssVars.ts +98 -0
  234. package/src/theme/buildVegaThemeOverride.spec.ts +56 -0
  235. package/src/theme/buildVegaThemeOverride.ts +47 -0
  236. package/src/theme/defaults.ts +78 -0
  237. package/src/theme/index.ts +11 -0
  238. package/src/theme/keys.ts +32 -0
  239. package/src/theme/readChartAnnotations.spec.ts +58 -0
  240. package/src/theme/readChartAnnotations.ts +69 -0
  241. package/src/theme/resolveTheme.spec.ts +160 -0
  242. package/src/theme/resolveTheme.ts +121 -0
  243. package/src/theme/types.ts +79 -0
  244. package/src/utils/dataAppEmbed.spec.ts +63 -0
  245. package/src/utils/dataAppEmbed.ts +84 -0
  246. package/src/utils/formatting.spec.ts +25 -21
  247. package/src/utils/formatting.ts +11 -7
  248. package/src/utils/malloyString.spec.ts +24 -0
  249. package/src/utils/malloyString.ts +12 -0
  250. package/src/utils/parsing.spec.ts +26 -19
  251. package/src/utils/parsing.ts +11 -6
  252. package/src/utils/queryClient.ts +17 -0
  253. package/test/README.md +185 -0
  254. package/test/serverProvider.tsx +72 -0
  255. package/test/setup.ts +29 -0
  256. package/tsconfig.json +12 -1
  257. package/tsconfig.spec.json +22 -0
  258. package/vite.config.ts +3 -0
  259. package/dist/ServerProvider-lOQXDlqB.cjs.js +0 -1
  260. package/dist/ServerProvider-on-8FH5Z.es.js +0 -3060
  261. package/dist/components/Home/AddProjectDialog.d.ts +0 -1
  262. package/dist/components/Home/DeleteProjectDialog.d.ts +0 -5
  263. package/dist/components/Home/EditProjectDialog.d.ts +0 -7
  264. package/dist/components/Package/Config.d.ts +0 -5
  265. package/dist/components/Package/Databases.d.ts +0 -5
  266. package/dist/components/Package/Notebooks.d.ts +0 -6
  267. package/dist/components/Project/Project.d.ts +0 -6
  268. package/dist/components/Project/index.d.ts +0 -2
  269. package/dist/index-BOLBP6_i.cjs.js +0 -233
  270. package/src/components/Package/Config.tsx +0 -97
  271. package/src/components/Package/Connections.tsx +0 -373
  272. package/src/components/Package/Databases.tsx +0 -228
  273. package/src/components/Package/Notebooks.tsx +0 -77
  274. package/src/components/Project/AddPackageDialog.tsx +0 -159
  275. package/src/components/Project/Packages.tsx +0 -191
  276. package/src/components/Project/Project.tsx +0 -52
  277. package/src/components/Project/index.ts +0 -2
  278. /package/dist/components/{Project → Environment}/About.d.ts +0 -0
  279. /package/dist/components/{Project → Environment}/AddPackageDialog.d.ts +0 -0
  280. /package/dist/components/{Project → Environment}/ConnectionExplorer.d.ts +0 -0
  281. /package/dist/components/{Package → Environment}/Connections.d.ts +0 -0
  282. /package/dist/components/{Project → Environment}/DeletePackageDialog.d.ts +0 -0
  283. /package/dist/components/{Project → Environment}/EditPackageDialog.d.ts +0 -0
  284. /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,264 @@ 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,
233
+ versionId,
217
234
  );
218
235
 
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);
236
+ // The declared names, indexed case-insensitively, so a drill tag resolves
237
+ // whichever way the two were spelled.
238
+ //
239
+ // Neither convention can be assumed. `# drill` defaults the given name to
240
+ // the DIMENSION's name, which is conventionally lower_snake, while givens
241
+ // are conventionally SHOUTED (both in-repo examples declare `REGION` and
242
+ // `MIN_AMOUNT`). An exact match therefore failed for the common case, and
243
+ // upper-casing the dimension name, which is what this did first, only moved
244
+ // the failure onto models that spell their givens in lower case. Folding
245
+ // case resolves both instead of picking a side.
246
+ const givenNamesByFold = useMemo(() => {
247
+ const byFold = new Map<string, string>();
248
+ for (const name of declaredTypes.keys()) {
249
+ // First declaration wins, so a model with `REGION` and `region` keeps
250
+ // the one it declared first rather than silently flipping.
251
+ if (!byFold.has(name.toLowerCase()))
252
+ byFold.set(name.toLowerCase(), name);
225
253
  }
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
- });
254
+ return byFold;
255
+ }, [declaredTypes]);
256
+
257
+ /** The declared given a drill tag's name refers to, or undefined. */
258
+ const resolveGiven = useCallback(
259
+ (given: string) =>
260
+ declaredTypes.has(given)
261
+ ? given
262
+ : givenNamesByFold.get(given.toLowerCase()),
263
+ [declaredTypes, givenNamesByFold],
264
+ );
241
265
 
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;
266
+ // `to=self` filters in place, which only works for a given this notebook
267
+ // actually declares: sending one it cannot bind would fail every cell. The
268
+ // mismatch is reported to the author rather than issued: same rule, same
269
+ // wording, as the dashboard viewer.
270
+ // Asked before a cell is painted as drillable, so the affordance matches what
271
+ // a click can actually do. The refusal below still stands as a backstop for a
272
+ // caller that does not ask.
273
+ const canDrillSelf = useCallback(
274
+ (given: string) => resolveGiven(given) !== undefined,
275
+ [resolveGiven],
276
+ );
251
277
 
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
- }
278
+ const onDrillSelf = useCallback(
279
+ (given: string, rawValue: unknown) => {
280
+ const declared = resolveGiven(given);
281
+ if (declared === undefined) {
282
+ console.warn(
283
+ `# drill { to=self } tried to set '${given}', which ` +
284
+ `'${notebookPath}' does not declare as a given. Name the ` +
285
+ `given with 'given=' on the drill tag.`,
286
+ );
287
+ return;
268
288
  }
269
- return Object.keys(params).length > 0
270
- ? JSON.stringify(params)
289
+ // Encoded against the declared type of the given being set, which is
290
+ // knowable here and is not knowable at the click. Set under the name
291
+ // the MODEL declares, not the one the tag spelled, so the value goes
292
+ // into the URL and the request under the one name the server knows.
293
+ const declaredType = declaredTypes.get(declared);
294
+ const value = encodeDrillValue(rawValue, declaredType);
295
+ if (value === undefined) {
296
+ // Say so. Returning in silence left a whole column painted as
297
+ // clickable while every click did nothing, and a `given=` pointing
298
+ // at a type the clicked value cannot become is an authoring
299
+ // mistake the author has no other way to see. The sibling refusal
300
+ // in `resolveDrill` warns for the same reason.
301
+ console.warn(
302
+ `Drill declined: ${JSON.stringify(rawValue)} cannot be a value for given "${declared}"` +
303
+ (declaredType ? ` of type ${declaredType}` : ""),
304
+ );
305
+ return;
306
+ }
307
+ setGiven(declared, value);
308
+ },
309
+ [declaredTypes, notebookPath, resolveGiven, setGiven],
310
+ );
311
+
312
+ /**
313
+ * The `givens` query param for the notebook-cell GET: the same map the
314
+ * dashboard's POST body carries, JSON-encoded because this endpoint takes it
315
+ * in the URL. Built by the shared codec so a given is encoded identically
316
+ * whichever surface runs it.
317
+ */
318
+ const buildGivens = useCallback(
319
+ (values: Map<string, GivenValue>): string | undefined => {
320
+ const request = givensToRequest(values, declaredTypes);
321
+ return Object.keys(request).length > 0
322
+ ? JSON.stringify(request)
271
323
  : undefined;
272
324
  },
273
- [],
325
+ [declaredTypes],
274
326
  );
275
327
 
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
328
+ /**
329
+ * Run every code cell with one set of given values, up to
330
+ * {@link MAX_CONCURRENT} at a time.
331
+ *
332
+ * Each run takes a number from `runIdRef`, and a run that is no longer the
333
+ * current one drops its results on the floor. Cells resolve independently
334
+ * and out of order, so without that a slow cell from the previous values
335
+ * would land after the new run's and leave a stale number on screen under a
336
+ * control row claiming otherwise.
337
+ */
338
+ const runIdRef = useRef(0);
339
+ const inFlightRef = useRef<AbortController | null>(null);
340
+ const lastRunRef = useRef<string | null>(null);
341
+ /** The run waiting out {@link GIVEN_SETTLE_MS}, so a re-render does not restart its clock. */
342
+ const pendingRunRef = useRef<
343
+ { key: string; timer: ReturnType<typeof setTimeout> } | undefined
344
+ >(undefined);
345
+
346
+ // Cancel whatever is in flight when this component goes away, so navigating
347
+ // off a twelve-cell notebook does not leave twelve requests to complete and be
348
+ // thrown away.
349
+ //
350
+ // Its OWN effect, with an empty dependency list, and that is the whole point:
351
+ // as the run effect's cleanup this ran on every dependency change instead. The
352
+ // host echoes each reported parameter back, which gives `applied` a new
353
+ // identity with identical content, so the cleanup fired and aborted the run
354
+ // the control change had just started, while the run effect's `runKey` guard
355
+ // saw an unchanged key and refused to start a replacement. Every cell was left
356
+ // blank, with no result, no error and no spinner, until a reload. Measured on
357
+ // `governed-analytics/orders.malloynb`: 4 rendered results before a control
358
+ // change, 0 after.
359
+ useEffect(
360
+ () => () => {
361
+ inFlightRef.current?.abort();
362
+ // Forget which run was last started, so a component that comes back
363
+ // runs again instead of trusting a key whose run was just cancelled.
364
+ // The case it is reasoned from, and NOT one I could reproduce: React's
365
+ // StrictMode mounts, cleans up, and mounts again in development, and
366
+ // refs survive that. A first mount that already had the notebook
367
+ // cached would start a run, this cleanup would abort it, and the
368
+ // second mount would see an unchanged `runKey` and decline to start a
369
+ // replacement. I could not get a browser into that state, so treat the
370
+ // reset as belt-and-braces rather than a measured fix. It is right on
371
+ // its own terms either way: a key that says "this run happened" must
372
+ // not outlive the run being cancelled.
373
+ lastRunRef.current = null;
374
+ clearTimeout(pendingRunRef.current?.timer);
375
+ pendingRunRef.current = undefined;
376
+ },
377
+ [],
378
+ );
279
379
  const executeCells = useCallback(
280
- async (filtersToApply: FilterSelection[] = []) => {
380
+ async (givensToApply: Map<string, GivenValue> = new Map()) => {
281
381
  if (!isSuccess || !notebook?.notebookCells) return;
282
382
 
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
- });
383
+ const runId = ++runIdRef.current;
384
+
385
+ // Cancel the run this one supersedes rather than just ignoring its
386
+ // results. Discarding results alone keeps the requests in flight, so
387
+ // three quick control changes on a twelve-cell notebook put three full
388
+ // runs on the server and use the answers from one. `origin/main`
389
+ // refused to start a second run at all, which was the wrong trade,
390
+ // it dropped the newest values, but it did bound the load, and
391
+ // nothing replaced that bound.
392
+ inFlightRef.current?.abort();
393
+ const controller = new AbortController();
394
+ inFlightRef.current = controller;
395
+
396
+ // Rebuilt from the notebook being run, never carried over from the
397
+ // previous render's cells. Reusing them kept the OLD document's
398
+ // `text` and `type` while the new document's results were written in
399
+ // on top, so navigating between two notebooks rendered one's prose
400
+ // with the other's charts, and a shorter second notebook left the
401
+ // first one's trailing cells on screen. Nothing worth preserving
402
+ // survived that branch anyway: `result` and `error` were cleared, and
403
+ // `newSources` is re-derived from the raw cell below.
404
+ setEnhancedCells(notebook.notebookCells.map((cell) => ({ ...cell })));
293
405
 
294
406
  setIsExecuting(true);
295
407
  setExecutionError(null);
296
408
 
297
- const filterParams = useServerFilters
298
- ? buildFilterParams(filtersToApply)
299
- : undefined;
409
+ const givensParam = buildGivens(givensToApply);
300
410
 
301
411
  try {
302
412
  // Build execution tasks for code cells
@@ -313,17 +423,27 @@ export default function Notebook({
313
423
 
314
424
  const executeCell = async () => {
315
425
  try {
316
- // Use notebook cell execution API with optional filter_params
426
+ // `filterParams` and `bypassFilters` go over as undefined:
427
+ // the `#(filter)` panel this component used to render is
428
+ // gone, replaced by `given:`. The server still enforces a
429
+ // `required` filter, so a model that has one now fails
430
+ // here: visibly, via `error` below, rather than as the
431
+ // blank cell it used to be. See RELEASE_NOTES.
317
432
  const response =
318
433
  await apiClients.notebooks.executeNotebookCell(
319
- projectName,
434
+ environmentName,
320
435
  packageName,
321
436
  notebookPath,
322
437
  cellIndex,
323
438
  versionId,
324
- filterParams,
439
+ undefined,
440
+ undefined,
441
+ givensParam,
442
+ { signal: controller.signal },
325
443
  );
326
444
 
445
+ if (runIdRef.current !== runId) return;
446
+
327
447
  const executedCell = response.data;
328
448
  const result = executedCell.result;
329
449
  const newSources =
@@ -343,10 +463,29 @@ export default function Notebook({
343
463
  return next;
344
464
  });
345
465
  } catch (cellError) {
466
+ // A superseded or cancelled run is not a failure to
467
+ // report; its cells are about to be re-run.
468
+ if (
469
+ controller.signal.aborted ||
470
+ runIdRef.current !== runId
471
+ )
472
+ return;
346
473
  console.error(
347
474
  `Error executing cell ${cellIndex}:`,
348
475
  cellError,
349
476
  );
477
+ const message = cellErrorMessage(cellError);
478
+ setEnhancedCells((prev) => {
479
+ const next = [...prev];
480
+ if (!next[cellIndex]) {
481
+ next[cellIndex] = { ...rawCell };
482
+ }
483
+ next[cellIndex] = {
484
+ ...next[cellIndex],
485
+ error: message,
486
+ };
487
+ return next;
488
+ });
350
489
  }
351
490
  };
352
491
 
@@ -370,18 +509,21 @@ export default function Notebook({
370
509
  // Wait for remaining tasks to complete
371
510
  await Promise.all(executing);
372
511
  } catch (error) {
512
+ if (controller.signal.aborted || runIdRef.current !== runId) return;
373
513
  console.error("Error executing notebook cells:", error);
374
514
  setExecutionError(error as Error);
375
515
  } finally {
376
- setIsExecuting(false);
516
+ if (runIdRef.current === runId) {
517
+ setIsExecuting(false);
518
+ inFlightRef.current = null;
519
+ }
377
520
  }
378
521
  },
379
522
  [
380
523
  isSuccess,
381
524
  notebook,
382
- useServerFilters,
383
- buildFilterParams,
384
- projectName,
525
+ buildGivens,
526
+ environmentName,
385
527
  packageName,
386
528
  notebookPath,
387
529
  versionId,
@@ -389,125 +531,109 @@ export default function Notebook({
389
531
  ],
390
532
  );
391
533
 
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>("");
534
+ // Run the cells on load, and again whenever the applied parameters change.
535
+ // Applied, not draft: under `## autorun=false` the cells wait for Apply.
536
+ //
537
+ // One effect covers both, keyed on exactly what would go over the wire plus
538
+ // which notebook it is. Keying on the encoded givens means a change that
539
+ // encodes identically does not re-run, and a link carrying parameters runs
540
+ // once with them rather than running bare and running again when they land.
541
+ // A run already in flight is superseded rather than waited on, which the
542
+ // generation guard in `executeCells` makes safe.
543
+ //
544
+ // The notebook's own identity is part of that key. Its content can change
545
+ // under an open tab: a package reload, and react-query hands over a new
546
+ // object only when the content actually differs, so identity is exactly the
547
+ // "has this document changed" signal. Keying on `resourceUri` alone silently
548
+ // dropped that: a reloaded notebook kept rendering the previous run's
549
+ // results forever, because the URI and the givens were unchanged.
550
+ const notebookGenRef = useRef(0);
551
+ const seenNotebookRef = useRef<RawNotebook | undefined>(undefined);
552
+ if (seenNotebookRef.current !== notebook) {
553
+ seenNotebookRef.current = notebook;
554
+ notebookGenRef.current += 1;
555
+ }
556
+ const notebookGen = notebookGenRef.current;
401
557
 
402
558
  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;
559
+ const documentKey = `${resourceUri}|${notebookGen}`;
560
+ const runKey = `${documentKey}|${buildGivens(applied) ?? ""}`;
561
+
562
+ // Abandon the previous notebook's requests when the document changes.
563
+ // The abort-on-unmount effect does not cover this: navigating from one
564
+ // notebook to another REUSES this component, so nothing unmounts and a
565
+ // twelve-cell notebook left twelve requests running against a document
566
+ // the reader had already left.
567
+ if (
568
+ lastDocumentRef.current !== undefined &&
569
+ lastDocumentRef.current !== documentKey
570
+ ) {
571
+ inFlightRef.current?.abort();
572
+ inFlightRef.current = null;
416
573
  }
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;
574
+ lastDocumentRef.current = documentKey;
575
+
576
+ const plan = planRun({
577
+ ready: isSuccess && !!notebook?.notebookCells,
578
+ lastRunKey: lastRunRef.current,
579
+ pendingKey: pendingRunRef.current?.key,
580
+ runKey,
581
+ documentKey,
582
+ });
583
+
584
+ if (plan.cancelPending) {
585
+ clearTimeout(pendingRunRef.current?.timer);
586
+ pendingRunRef.current = undefined;
587
+ setRunScheduled(false);
422
588
  }
589
+ if (plan.dispatch === "none") return;
423
590
 
424
- prevActiveFiltersRef.current = serialized;
591
+ const start = () => {
592
+ pendingRunRef.current = undefined;
593
+ setRunScheduled(false);
594
+ lastRunRef.current = runKey;
595
+ void executeCells(applied);
596
+ };
425
597
 
426
- // Re-execute with current filters (or no filters if cleared)
427
- if (!isExecuting) {
428
- executeCells(activeFilters);
598
+ if (plan.dispatch === "now") {
599
+ start();
600
+ return;
429
601
  }
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;
602
+ // Flagged while the settle timer runs, so the cells say a run is coming.
603
+ // Without it the window was invisible: `isExecuting` is false until the
604
+ // timer fires, so a changed control sat above the PREVIOUS values with
605
+ // nothing on screen to say they were stale, and a reader who kept typing
606
+ // kept extending the window.
607
+ setRunScheduled(true);
608
+ pendingRunRef.current = {
609
+ key: runKey,
610
+ timer: setTimeout(start, GIVEN_SETTLE_MS),
611
+ };
612
+ }, [
613
+ isSuccess,
614
+ notebook,
615
+ notebookGen,
616
+ resourceUri,
617
+ applied,
618
+ buildGivens,
619
+ executeCells,
620
+ ]);
445
621
 
446
622
  return (
447
623
  <CleanNotebookContainer>
448
624
  <CleanNotebookSection>
449
625
  <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
- )}
626
+ {/* Parameters panel: the controls for `given:` declarations */}
627
+ <GivensPanel
628
+ givens={declaredGivens}
629
+ values={draft}
630
+ onChange={setGiven}
631
+ onReset={reset}
632
+ options={givenOptions}
633
+ optionsLoading={givenOptionsLoading}
634
+ optionsFailed={givenOptionsFailed}
635
+ apply={autorun ? undefined : { onApply: apply, pending }}
636
+ />
511
637
 
512
638
  {/* Loading State */}
513
639
  {!isSuccess && !isError && (
@@ -527,13 +653,24 @@ export default function Notebook({
527
653
  resourceUri={resourceUri}
528
654
  maxResultSize={maxResultSize}
529
655
  isExecuting={isExecuting}
656
+ // Distinct from `isExecuting`: the cell's spinner is
657
+ // gated on `!cell.result`, so feeding this through it
658
+ // showed nothing on a re-run, which is the only case
659
+ // the settle window has to signal.
660
+ pendingRerun={runScheduled}
661
+ onNavigate={onNavigate}
662
+ onDrillNavigate={onDrillNavigate}
663
+ onDrillSelf={
664
+ declaredGivens.length > 0 ? onDrillSelf : undefined
665
+ }
666
+ canDrillSelf={canDrillSelf}
530
667
  />
531
668
  ))}
532
669
 
533
670
  {/* Error States */}
534
671
  {isError && error.status === 404 && (
535
- <Typography variant="body2" sx={{ color: "#666666" }}>
536
- <code>{`${projectName} > ${packageName} > ${notebookPath}`}</code>{" "}
672
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
673
+ <code>{`${environmentName} > ${packageName} > ${notebookPath}`}</code>{" "}
537
674
  not found.
538
675
  </Typography>
539
676
  )}
@@ -541,7 +678,7 @@ export default function Notebook({
541
678
  {isError && error.status !== 404 && (
542
679
  <ApiErrorDisplay
543
680
  error={error}
544
- context={`${projectName} > ${packageName} > ${notebookPath}`}
681
+ context={`${environmentName} > ${packageName} > ${notebookPath}`}
545
682
  />
546
683
  )}
547
684