@malloy-publisher/sdk 0.2.7 → 0.3.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 (221) hide show
  1. package/README.md +180 -204
  2. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +134 -0
  3. package/dist/DocumentStorageProvider-tGvodI8f.es.js +24268 -0
  4. package/dist/RenderedResult-CPi6uQWq.cjs.js +115 -0
  5. package/dist/RenderedResult-mDE-4u8S.es.js +542 -0
  6. package/dist/{ServerProvider-xXW1HJOJ.cjs.js → ServerProvider-CH71GsoL.cjs.js} +1 -1
  7. package/dist/{ServerProvider-ksC5Su_x.es.js → ServerProvider-X2Ma0HRs.es.js} +324 -359
  8. package/dist/builder/index.cjs.js +105 -0
  9. package/dist/builder/index.d.ts +2 -0
  10. package/dist/builder/index.es.js +9561 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/api.d.ts +13 -1
  13. package/dist/client/index.cjs.js +1 -1
  14. package/dist/client/index.es.js +1 -1
  15. package/dist/components/ApiErrorDisplay.d.ts +1 -2
  16. package/dist/components/Dashboard/Dashboard.d.ts +23 -16
  17. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  18. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  19. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  20. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  21. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  22. package/dist/components/Dashboard/index.d.ts +2 -0
  23. package/dist/components/Dashboard/promoteMeasureRow.d.ts +40 -0
  24. package/dist/components/Dashboard/telemetry.d.ts +43 -0
  25. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  26. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +29 -0
  27. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +112 -0
  28. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +32 -0
  29. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  30. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  31. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  32. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  33. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  34. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  35. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  36. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  37. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  38. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  39. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  40. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  41. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  42. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  43. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  44. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  45. package/dist/components/DashboardBuilder/spliceDocument.d.ts +44 -0
  46. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  47. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  48. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  49. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  50. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  51. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  52. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  53. package/dist/components/DocumentStorage/BrowserDocumentStorage.d.ts +14 -0
  54. package/dist/components/DocumentStorage/DocumentStorage.d.ts +58 -0
  55. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +25 -0
  56. package/dist/components/DocumentStorage/index.d.ts +3 -0
  57. package/dist/components/FloatingIconButton.d.ts +16 -0
  58. package/dist/components/Model/index.d.ts +0 -1
  59. package/dist/components/Prose.d.ts +46 -0
  60. package/dist/components/RenderedResult/RenderedResult.d.ts +12 -0
  61. package/dist/components/RenderedResult/ResultContainer.d.ts +7 -1
  62. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  63. package/dist/components/RenderedResult/index.d.ts +2 -0
  64. package/dist/components/RenderedResult/resultSizing.d.ts +183 -0
  65. package/dist/components/drill/index.d.ts +2 -1
  66. package/dist/components/drill/resolveDrill.d.ts +22 -0
  67. package/dist/components/drill/useDrill.d.ts +11 -2
  68. package/dist/components/drill/useDrillSelf.d.ts +46 -0
  69. package/dist/components/given/filterValue.d.ts +63 -0
  70. package/dist/components/given/index.d.ts +1 -0
  71. package/dist/components/given/useGivenUrlParams.d.ts +39 -0
  72. package/dist/components/index.d.ts +3 -3
  73. package/dist/components/styles.d.ts +3 -7
  74. package/dist/core-8NVBCLZh.cjs.js +148 -0
  75. package/dist/{core-BY7vB5gN.es.js → core-B8oMW4sm.es.js} +3540 -2335
  76. package/dist/hooks/index.d.ts +3 -1
  77. package/dist/hooks/useDocumentControls.d.ts +70 -0
  78. package/dist/hooks/useQueryResult.d.ts +40 -0
  79. package/dist/hooks/useSuggestOptions.d.ts +28 -12
  80. package/dist/index.cjs.js +34 -1
  81. package/dist/index.es.js +21487 -79
  82. package/dist/sdk.css +1 -1
  83. package/dist/styles.css +0 -1
  84. package/dist/utils/malloyLiteral.d.ts +11 -0
  85. package/package.json +25 -14
  86. package/src/builder-entry.ts +55 -0
  87. package/src/components/ApiErrorDisplay.tsx +1 -1
  88. package/src/components/Connections/EditConnectionDialog.tsx +96 -86
  89. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  90. package/src/components/Dashboard/Dashboard.tsx +184 -229
  91. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  92. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  93. package/src/components/Dashboard/DashboardTile.tsx +67 -101
  94. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  95. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  96. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  97. package/src/components/Dashboard/TileCard.tsx +120 -0
  98. package/src/components/Dashboard/index.ts +2 -0
  99. package/src/components/Dashboard/promoteMeasureRow.spec.ts +207 -0
  100. package/src/components/Dashboard/promoteMeasureRow.ts +160 -0
  101. package/src/components/Dashboard/telemetry.ts +44 -0
  102. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  103. package/src/components/DashboardBuilder/AddTileDialog.tsx +249 -0
  104. package/src/components/DashboardBuilder/BuilderToolbar.tsx +270 -0
  105. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +858 -0
  106. package/src/components/DashboardBuilder/DashboardBuilder.tsx +653 -0
  107. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +211 -0
  108. package/src/components/DashboardBuilder/DashboardEditor.tsx +493 -0
  109. package/src/components/DashboardBuilder/DiffDialog.tsx +129 -0
  110. package/src/components/DashboardBuilder/DrillDialog.tsx +281 -0
  111. package/src/components/DashboardBuilder/FilterDialog.tsx +581 -0
  112. package/src/components/DashboardBuilder/FilterStrip.tsx +125 -0
  113. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  114. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  115. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  116. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  117. package/src/components/DashboardBuilder/catalog.ts +225 -0
  118. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  119. package/src/components/DashboardBuilder/controls.ts +398 -0
  120. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  121. package/src/components/DashboardBuilder/diff.ts +93 -0
  122. package/src/components/DashboardBuilder/document.ts +209 -0
  123. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  124. package/src/components/DashboardBuilder/layout.ts +143 -0
  125. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  126. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  127. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  128. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  129. package/src/components/DashboardBuilder/preview.ts +172 -0
  130. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  131. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  132. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  133. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1108 -0
  134. package/src/components/DashboardBuilder/spliceDocument.ts +1098 -0
  135. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  136. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  137. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +255 -0
  138. package/src/components/DashboardBuilder/useDashboardEditor.ts +193 -0
  139. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  140. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  141. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  142. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  143. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  144. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  145. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  146. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  147. package/src/components/DocumentStorage/BrowserDocumentStorage.spec.ts +81 -0
  148. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +105 -0
  149. package/src/components/DocumentStorage/DocumentStorage.ts +73 -0
  150. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +58 -0
  151. package/src/components/DocumentStorage/index.ts +16 -0
  152. package/src/components/Environment/About.tsx +4 -36
  153. package/src/components/FloatingIconButton.tsx +41 -0
  154. package/src/components/Model/Model.tsx +6 -23
  155. package/src/components/Model/ModelCell.tsx +34 -72
  156. package/src/components/Model/index.ts +0 -1
  157. package/src/components/Notebook/Notebook.tsx +27 -156
  158. package/src/components/Notebook/NotebookCell.tsx +37 -191
  159. package/src/components/Prose.spec.tsx +85 -0
  160. package/src/components/Prose.tsx +179 -0
  161. package/src/components/QueryResult/QueryResult.tsx +15 -43
  162. package/src/components/RenderedResult/RenderedResult.tsx +86 -76
  163. package/src/components/RenderedResult/ResultContainer.tsx +25 -36
  164. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  165. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  166. package/src/components/RenderedResult/index.ts +16 -0
  167. package/src/components/RenderedResult/resultSizing.spec.ts +249 -0
  168. package/src/components/RenderedResult/resultSizing.ts +308 -0
  169. package/src/components/ResultsDialog.tsx +2 -1
  170. package/src/components/drill/index.ts +6 -0
  171. package/src/components/drill/resolveDrill.ts +22 -1
  172. package/src/components/drill/useDrill.spec.tsx +94 -0
  173. package/src/components/drill/useDrill.tsx +52 -12
  174. package/src/components/drill/useDrillSelf.spec.tsx +64 -0
  175. package/src/components/drill/useDrillSelf.ts +110 -0
  176. package/src/components/given/GivenInput.spec.tsx +196 -2
  177. package/src/components/given/GivenInput.tsx +300 -25
  178. package/src/components/given/GivensPanel.tsx +1 -1
  179. package/src/components/given/filterValue.spec.ts +112 -0
  180. package/src/components/given/filterValue.ts +188 -0
  181. package/src/components/given/index.ts +4 -0
  182. package/src/components/given/useGivenUrlParams.spec.tsx +74 -0
  183. package/src/components/given/useGivenUrlParams.ts +87 -0
  184. package/src/components/index.ts +11 -3
  185. package/src/components/styles.ts +0 -37
  186. package/src/hooks/index.ts +13 -1
  187. package/src/hooks/useDocumentControls.ts +170 -0
  188. package/src/hooks/useGivensState.spec.ts +158 -0
  189. package/src/hooks/useGivensState.ts +114 -23
  190. package/src/hooks/useQueryResult.ts +82 -0
  191. package/src/hooks/useSuggestOptions.dom.spec.ts +60 -1
  192. package/src/hooks/useSuggestOptions.ts +94 -51
  193. package/src/utils/malloyLiteral.spec.ts +43 -0
  194. package/src/utils/malloyLiteral.ts +76 -0
  195. package/vite.config.ts +5 -1
  196. package/dist/components/AnalyzePackageButton.d.ts +0 -6
  197. package/dist/components/Workbook/BrowserWorkbookStorage.d.ts +0 -9
  198. package/dist/components/Workbook/EditableMalloyCell.d.ts +0 -11
  199. package/dist/components/Workbook/ModelPicker.d.ts +0 -11
  200. package/dist/components/Workbook/MutableCell.d.ts +0 -17
  201. package/dist/components/Workbook/Workbook.d.ts +0 -7
  202. package/dist/components/Workbook/WorkbookList.d.ts +0 -7
  203. package/dist/components/Workbook/WorkbookManager.d.ts +0 -84
  204. package/dist/components/Workbook/WorkbookStorage.d.ts +0 -17
  205. package/dist/components/Workbook/WorkbookStorageProvider.d.ts +0 -12
  206. package/dist/components/Workbook/index.d.ts +0 -7
  207. package/dist/core-CWKmWEg2.cjs.js +0 -148
  208. package/dist/index-B0WyZAUA.es.js +0 -66412
  209. package/dist/index-kxVD1RjY.cjs.js +0 -356
  210. package/dist/markdown-editor.css +0 -341
  211. package/src/components/AnalyzePackageButton.tsx +0 -319
  212. package/src/components/Workbook/BrowserWorkbookStorage.ts +0 -64
  213. package/src/components/Workbook/EditableMalloyCell.tsx +0 -49
  214. package/src/components/Workbook/ModelPicker.tsx +0 -134
  215. package/src/components/Workbook/MutableCell.tsx +0 -458
  216. package/src/components/Workbook/Workbook.tsx +0 -501
  217. package/src/components/Workbook/WorkbookList.tsx +0 -110
  218. package/src/components/Workbook/WorkbookManager.ts +0 -214
  219. package/src/components/Workbook/WorkbookStorage.ts +0 -35
  220. package/src/components/Workbook/WorkbookStorageProvider.tsx +0 -40
  221. package/src/components/Workbook/index.ts +0 -10
@@ -447,3 +447,161 @@ describe("useGivensState: swapping documents", () => {
447
447
  expect(entries(result.current.applied)).toEqual({});
448
448
  });
449
449
  });
450
+
451
+ describe("useGivensState: clearing a given that has a starting value", () => {
452
+ // The limitation this hook used to document. A clear dropped the name from
453
+ // the report, the host removed it from the URL and fed that URL back in, and
454
+ // the changed `params` re-keyed the edits away: `initial` recomputed from the
455
+ // starting values and the control snapped back to what was just cleared.
456
+ it("stays cleared when the host echoes the URL back", () => {
457
+ const host = renderWithUrlHost({
458
+ autorun: true,
459
+ startingValues: { REGION: "West" },
460
+ });
461
+ expect(entries(host.current.applied)).toEqual({ REGION: "West" });
462
+
463
+ act(() => host.current.setGiven("REGION", null));
464
+ host.settle();
465
+ expect(entries(host.current.applied)).toEqual({});
466
+ expect(entries(host.current.draft)).toEqual({});
467
+ expect(host.url).toEqual({});
468
+ });
469
+
470
+ it("clears one starting value while keeping another", () => {
471
+ const host = renderWithUrlHost({
472
+ autorun: true,
473
+ startingValues: { REGION: "West", MIN_AMOUNT: "5" },
474
+ });
475
+ act(() => host.current.setGiven("REGION", null));
476
+ host.settle();
477
+ expect(entries(host.current.applied)).toEqual({ MIN_AMOUNT: 5 });
478
+ expect(host.url).toEqual({ MIN_AMOUNT: "5" });
479
+ });
480
+
481
+ it("still takes a URL the host did NOT get from us, such as a drill landing", () => {
482
+ const { result, rerender } = renderHook(
483
+ (props: { params: Record<string, string> }) =>
484
+ useGivensState({
485
+ declaredTypes: TYPES,
486
+ startingValues: { REGION: "West" },
487
+ params: props.params,
488
+ documentKey: "overview",
489
+ autorun: true,
490
+ }),
491
+ { initialProps: { params: {} } },
492
+ );
493
+ act(() => result.current.setGiven("REGION", null));
494
+ expect(entries(result.current.applied)).toEqual({});
495
+
496
+ // Not an echo: nothing this hook reported said East.
497
+ rerender({ params: { REGION: "East" } });
498
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
499
+ });
500
+
501
+ it("treats a host that keeps unrelated parameters beside ours as an echo", () => {
502
+ const { result, rerender } = renderHook(
503
+ (props: { params: Record<string, string> }) =>
504
+ useGivensState({
505
+ declaredTypes: TYPES,
506
+ startingValues: { REGION: "West" },
507
+ params: props.params,
508
+ documentKey: "overview",
509
+ autorun: true,
510
+ }),
511
+ { initialProps: { params: { tab: "sales" } } },
512
+ );
513
+ act(() => result.current.setGiven("REGION", null));
514
+ // The host writes our (empty) report but keeps its own `tab`.
515
+ rerender({ params: { tab: "sales" } });
516
+ expect(entries(result.current.applied)).toEqual({});
517
+ // And the same with the report carrying a value.
518
+ act(() => result.current.setGiven("REGION", "East"));
519
+ rerender({ params: { tab: "sales", REGION: "East" } });
520
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
521
+ });
522
+
523
+ // The regression that broke notebook clearing. A report does not reach
524
+ // `params` in the same tick, so a re-render in between (a cell finishing, the
525
+ // host's callback changing identity with its location) arrives carrying the
526
+ // URL the report has not replaced yet. Matching only the newest report read
527
+ // that stale URL as an external push: the anchor moved, the edits were
528
+ // discarded, and `initial` put the cleared value back in the control and then
529
+ // wrote it to the URL again.
530
+ it("keeps a clear across a render that still carries the pre-report URL", () => {
531
+ let url: Record<string, string> = {};
532
+ const urlWrites: Record<string, string>[] = [];
533
+ const { result, rerender } = renderHook(
534
+ (props: { params: Record<string, string> }) =>
535
+ useGivensState({
536
+ declaredTypes: TYPES,
537
+ params: props.params,
538
+ onParamsChange: (next) => {
539
+ url = next;
540
+ urlWrites.push(next);
541
+ },
542
+ documentKey: "notebook",
543
+ autorun: true,
544
+ }),
545
+ { initialProps: { params: url } },
546
+ );
547
+
548
+ act(() => result.current.setGiven("REGION", "East"));
549
+ rerender({ params: url });
550
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
551
+
552
+ act(() => result.current.setGiven("REGION", null));
553
+ expect(url).toEqual({});
554
+
555
+ // The stale render: the host has been told, but its URL has not landed.
556
+ rerender({ params: { REGION: "East" } });
557
+ expect(entries(result.current.applied)).toEqual({});
558
+
559
+ // And then the real one.
560
+ rerender({ params: url });
561
+ expect(entries(result.current.applied)).toEqual({});
562
+ expect(urlWrites.at(-1)).toEqual({});
563
+ });
564
+
565
+ // The other half: once the newer report HAS been seen, the URL it replaced is
566
+ // no longer in flight, so going back to it is a real navigation.
567
+ it("treats the previous URL as a new starting point once the report lands", () => {
568
+ let url: Record<string, string> = {};
569
+ const { result, rerender } = renderHook(
570
+ (props: { params: Record<string, string> }) =>
571
+ useGivensState({
572
+ declaredTypes: TYPES,
573
+ params: props.params,
574
+ onParamsChange: (next) => {
575
+ url = next;
576
+ },
577
+ documentKey: "notebook",
578
+ autorun: true,
579
+ }),
580
+ { initialProps: { params: url } },
581
+ );
582
+
583
+ act(() => result.current.setGiven("REGION", "East"));
584
+ rerender({ params: url });
585
+ act(() => result.current.setGiven("REGION", null));
586
+ rerender({ params: url });
587
+ expect(entries(result.current.applied)).toEqual({});
588
+
589
+ // Back button to the URL that carried East: a starting point, not an echo.
590
+ rerender({ params: { REGION: "East" } });
591
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
592
+ });
593
+
594
+ it("Reset after a clear restores the starting value and runs once", () => {
595
+ const host = renderWithUrlHost({
596
+ autorun: true,
597
+ startingValues: { REGION: "West" },
598
+ });
599
+ act(() => host.current.setGiven("REGION", null));
600
+ host.settle();
601
+ const writes = host.urlWrites.length;
602
+ act(() => host.current.reset());
603
+ host.settle();
604
+ expect(entries(host.current.applied)).toEqual({ REGION: "West" });
605
+ expect(host.urlWrites.length).toBe(writes + 1);
606
+ });
607
+ });
@@ -107,6 +107,22 @@ function stableEntries(source: Record<string, string> | undefined) {
107
107
  return Object.entries(source ?? {}).sort(([a], [b]) => (a < b ? -1 : 1));
108
108
  }
109
109
 
110
+ /**
111
+ * Same values for every DECLARED given, ignoring any other parameter a host
112
+ * carries in its URL (a tab, a view option). This is the echo test: whether the
113
+ * incoming URL says nothing about the controls that the last report did not.
114
+ */
115
+ function sameDeclaredParams(
116
+ incoming: Record<string, string>,
117
+ reported: Record<string, string>,
118
+ declaredTypes: ReadonlyMap<string, string | undefined>,
119
+ ): boolean {
120
+ for (const name of declaredTypes.keys()) {
121
+ if (incoming[name] !== reported[name]) return false;
122
+ }
123
+ return true;
124
+ }
125
+
110
126
  /** Same entries, same values: enough for state whose values are primitives. */
111
127
  function sameParams(
112
128
  a: Record<string, string>,
@@ -134,15 +150,84 @@ export function useGivensState({
134
150
  [declaredTypes, JSON.stringify(startingValues)],
135
151
  );
136
152
 
153
+ // The applied values as last reported to the host, so an incoming `params`
154
+ // can be recognised as this hook's own report coming back. Seeded on the
155
+ // first render below, once `applied` exists; null until then, so nothing on
156
+ // mount reads as an echo.
157
+ const lastReported = useRef<Record<string, string> | null>(null);
158
+
159
+ // The report BEFORE `lastReported`, kept only until the newer one is seen
160
+ // coming back.
161
+ //
162
+ // A report does not reach `params` in the same tick: the host navigates, the
163
+ // router commits, and `params` arrives a render or two later. Anything that
164
+ // re-renders this hook in between — a cell finishing, the host's callback
165
+ // changing identity with its location — sees the URL the report has not
166
+ // replaced yet. That URL is STALE, not new, and the echo test below matched
167
+ // only the newest report, so it read as an external push: the anchor moved,
168
+ // the edits were discarded, and `initial` put the value the reader had just
169
+ // cleared straight back into the control, and into the URL after it.
170
+ //
171
+ // Narrow by construction: it holds one report, only while that report is in
172
+ // flight, and is dropped the moment the newer one is observed. The cost is
173
+ // that an external push landing in that window whose values happen to equal
174
+ // the report being replaced is taken for the echo — the same values we were
175
+ // just showing, arriving in the few milliseconds before our own URL lands.
176
+ const priorReported = useRef<Record<string, string> | null>(null);
177
+
178
+ // The URL that defines the current starting point. This is `params` EXCEPT
179
+ // when `params` is our own report arriving back through the host, which is
180
+ // not a new starting point and must not be treated as one.
181
+ //
182
+ // The distinction is what lets a given with a starting value be cleared. A
183
+ // clear drops the name from the report, the host removes it from the URL and
184
+ // feeds that URL back in; read naively, that is a changed `params`, the
185
+ // edits are re-keyed away, `initial` recomputes from `startingValues` and
186
+ // still carries the value, and the control snaps back to what the reader
187
+ // just cleared. An echo is recognised by comparing the DECLARED names in
188
+ // `params` against the last report (a host may keep unrelated parameters of
189
+ // its own beside ours), and leaves the anchor where it was. Anything else, a
190
+ // drill landing on this document with new values, a Back button, a pasted
191
+ // link, moves it, and the edits are re-keyed exactly as before.
192
+ //
193
+ // A ref written during render, deliberately: the anchor is memory across
194
+ // renders, the update is idempotent, and putting it in state would cost a
195
+ // second render on every URL change for no observable difference.
196
+ //
197
+ // An echo is only an echo for the SAME document: a navigation to another
198
+ // document arrives with that document's URL, whatever the last report said,
199
+ // so the anchor follows `documentKey` unconditionally.
200
+ const anchor = useRef<{
201
+ documentKey: string | undefined;
202
+ params: Record<string, string> | undefined;
203
+ }>({ documentKey, params });
204
+ const echoes = (reported: Record<string, string> | null) =>
205
+ reported !== null &&
206
+ sameDeclaredParams(params ?? {}, reported, declaredTypes);
207
+ // The newest report has arrived, so the one it replaced is no longer in
208
+ // flight and stops counting as an echo.
209
+ if (echoes(lastReported.current)) priorReported.current = null;
210
+ if (
211
+ anchor.current.documentKey !== documentKey ||
212
+ (!sameParams(params ?? {}, anchor.current.params ?? {}) &&
213
+ !echoes(lastReported.current) &&
214
+ !echoes(priorReported.current))
215
+ ) {
216
+ anchor.current = { documentKey, params };
217
+ }
218
+ const anchorParams = anchor.current.params;
219
+ const startingValuesKey = JSON.stringify(startingValues);
220
+ const anchorParamsKey = JSON.stringify(anchorParams);
221
+
137
222
  // The URL beats the file's starting values, per the precedence above.
138
223
  const initial = useMemo(
139
224
  () =>
140
225
  paramsToGivens(
141
- { ...(startingValues ?? {}), ...(params ?? {}) },
226
+ { ...(startingValues ?? {}), ...(anchorParams ?? {}) },
142
227
  declaredTypes,
143
228
  ),
144
229
  // eslint-disable-next-line react-hooks/exhaustive-deps
145
- [declaredTypes, JSON.stringify(startingValues), JSON.stringify(params)],
230
+ [declaredTypes, startingValuesKey, anchorParamsKey],
146
231
  );
147
232
 
148
233
  // Which starting point the edits below belong to. A change means a different
@@ -167,29 +252,17 @@ export function useGivensState({
167
252
  JSON.stringify([
168
253
  documentKey ?? null,
169
254
  stableEntries(startingValues),
170
- stableEntries(params),
255
+ stableEntries(anchorParams),
171
256
  ]),
172
257
  // eslint-disable-next-line react-hooks/exhaustive-deps
173
- [documentKey, JSON.stringify(startingValues), JSON.stringify(params)],
258
+ [documentKey, startingValuesKey, anchorParamsKey],
174
259
  );
175
260
 
176
- // KNOWN LIMITATION, latent today. A given that has a starting value cannot be
177
- // cleared: `setGiven(name, null)` drops the key, the report omits it, the host
178
- // removes it from the URL, `initial` recomputes from `startingValues` and
179
- // still carries it, `initialKey` therefore changes, the edits are discarded as
180
- // stale, and the control snaps back to the value the reader just cleared.
181
- //
182
- // Not reachable yet: no server populates `startingGivens`, and deliberately
183
- // not fixed here, because the fix has to tell our OWN echo of the URL (which
184
- // must not discard edits) from an externally pushed URL such as a drill
185
- // arriving (which must), and that is the one piece of this hook the drill path
186
- // depends on and is covered by live tests. Getting it wrong breaks something
187
- // that works to fix something nothing can reach.
188
- //
189
- // The intended shape, for whoever makes it reachable: compare the incoming
190
- // `params` against `lastReported` below, treat a match as our own echo, and
191
- // keep the edits (and their key) across it. An explicit `cleared` set on
192
- // `Edits` is the alternative and needs the same echo test to survive.
261
+ // Keyed on the anchored URL rather than on `params` directly: see `anchor`
262
+ // above. That is what makes a given with a starting value clearable, since
263
+ // the host echoing the cleared URL back no longer reads as a new starting
264
+ // point. It was a documented limitation while no server populated
265
+ // `startingGivens`; dashboards and notebooks both do now.
193
266
  //
194
267
  // Only the user's edits are state; `initial` is read through, not copied in.
195
268
  //
@@ -279,10 +352,28 @@ export function useGivensState({
279
352
  () => givensToParams(applied, declaredTypes),
280
353
  [applied, declaredTypes],
281
354
  );
282
- const lastReported = useRef<Record<string, string>>(appliedParams);
355
+ if (lastReported.current === null) lastReported.current = appliedParams;
356
+ // Recorded only when the report is actually DELIVERED. A surface withholds
357
+ // the callback while it is still loading — `Notebook` passes undefined until
358
+ // the document has arrived, so that a report made in the window where it
359
+ // does not yet know which givens exist cannot tell the host to clear
360
+ // parameters belonging to the notebook then arriving — and a value recorded
361
+ // in that window is remembered as reported without the host ever hearing it.
362
+ //
363
+ // That is not merely a missed report, because the echo test above reads this
364
+ // same record: the host's URL still holds the old value, the record says the
365
+ // new one, so the next `params` fails the echo test, the anchor moves, and
366
+ // the edits are discarded as stale. Clearing a control while the cells were
367
+ // re-running put the cleared value straight back in the box.
368
+ //
369
+ // The cost is the case this guard was briefly dropped for: a host that
370
+ // writes the URL from `applied` directly without registering the callback
371
+ // never echoes, so a given with a starting value is not clearable there.
372
+ // Both Console pages register it, as does any host using `useGivenUrlParams`.
283
373
  useEffect(() => {
284
374
  if (!onParamsChange) return;
285
- if (sameParams(lastReported.current, appliedParams)) return;
375
+ if (sameParams(lastReported.current ?? {}, appliedParams)) return;
376
+ priorReported.current = lastReported.current;
286
377
  lastReported.current = appliedParams;
287
378
  onParamsChange(appliedParams);
288
379
  }, [appliedParams, onParamsChange]);
@@ -0,0 +1,82 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { QueryKey } from "@tanstack/react-query";
5
+ import { useServer } from "../components/ServerProvider";
6
+ import { CHART_RESULT_QUERY_OPTIONS } from "../utils/queryClient";
7
+ import { useQueryWithApiError } from "./useQueryWithApiError";
8
+
9
+ /**
10
+ * One query against one model, as every result surface asks for it.
11
+ *
12
+ * A dashboard tile, a model page's named query and an embedded `QueryResult`
13
+ * each ran a query through `executeQueryModel` with their own copy of the
14
+ * request, their own cache key and their own loading and error states — three
15
+ * spellings of one thing, and one of them (the model cell) had no error state
16
+ * at all. This is the request and the key; `ResultPanel` is the states.
17
+ */
18
+ export interface QueryRequestSpec {
19
+ environmentName: string;
20
+ packageName: string;
21
+ modelPath: string;
22
+ /** The package version the caller's URI named, when it named one. */
23
+ versionId?: string;
24
+ /** A named query on the model. */
25
+ queryName?: string;
26
+ /** A run expression: `run: source -> view`. */
27
+ query?: string;
28
+ sourceName?: string;
29
+ /** The applied control values this query reads, already encoded. */
30
+ givens?: Record<string, unknown>;
31
+ }
32
+
33
+ /**
34
+ * The cache key: every value the request is built from, in a fixed order, so
35
+ * the key cannot drift out of step with the request. A version that reached
36
+ * the request alone would leave two versions of one query on a single cache
37
+ * entry, each able to serve the other's result. `useQueryWithApiError` appends
38
+ * the server, so one key never spans two of them.
39
+ */
40
+ export function queryResultKey(spec: QueryRequestSpec): QueryKey {
41
+ return [
42
+ "queryResult",
43
+ spec.environmentName,
44
+ spec.packageName,
45
+ spec.versionId,
46
+ spec.modelPath,
47
+ spec.queryName,
48
+ spec.query,
49
+ spec.sourceName,
50
+ // Re-runs when the applied values change, which is the whole point of a
51
+ // control row.
52
+ JSON.stringify(spec.givens ?? {}),
53
+ ];
54
+ }
55
+
56
+ export function useQueryResult(
57
+ spec: QueryRequestSpec,
58
+ { enabled = true }: { enabled?: boolean } = {},
59
+ ) {
60
+ const { apiClients } = useServer();
61
+ return useQueryWithApiError({
62
+ queryKey: queryResultKey(spec),
63
+ queryFn: () =>
64
+ apiClients.models.executeQueryModel(
65
+ spec.environmentName,
66
+ spec.packageName,
67
+ spec.modelPath,
68
+ {
69
+ queryName: spec.queryName,
70
+ query: spec.query,
71
+ sourceName: spec.sourceName,
72
+ givens: spec.givens,
73
+ versionId: spec.versionId,
74
+ },
75
+ ),
76
+ enabled,
77
+ ...CHART_RESULT_QUERY_OPTIONS,
78
+ });
79
+ }
80
+
81
+ /** What a result surface holds while a query runs: hand it to `ResultPanel`. */
82
+ export type QueryResultState = ReturnType<typeof useQueryResult>;
@@ -53,6 +53,39 @@ const renderSuggest = (versionId?: string) =>
53
53
  { wrapper: serverWrapper },
54
54
  );
55
55
 
56
+ /** A suggest whose source is gated by TENANT; the page also filters by REGION. */
57
+ const GATED: Given[] = [
58
+ {
59
+ name: "BRAND",
60
+ control: "select",
61
+ suggest: { source: "orders", dimension: "brand", givenNames: ["TENANT"] },
62
+ },
63
+ ];
64
+ const APPLIED = {
65
+ values: new Map<string, string>([
66
+ ["TENANT", "acme"],
67
+ ["REGION", "West"],
68
+ ]),
69
+ declaredTypes: new Map<string, string>([
70
+ ["TENANT", "string"],
71
+ ["REGION", "filter<string>"],
72
+ ["BRAND", "filter<string>"],
73
+ ]),
74
+ };
75
+ const renderGated = (applied = APPLIED) =>
76
+ renderHook(
77
+ () =>
78
+ useSuggestOptions(
79
+ "env",
80
+ "pkg",
81
+ "dashboards/ops.malloy",
82
+ GATED,
83
+ undefined,
84
+ applied,
85
+ ),
86
+ { wrapper: serverWrapper },
87
+ );
88
+
56
89
  beforeEach(() => {
57
90
  clearCache();
58
91
  executeQueryModel.mockClear();
@@ -73,9 +106,10 @@ it("sends and keys nothing when no version was given", async () => {
73
106
  expect(executeQueryModel.mock.calls[0][3].versionId).toBeUndefined();
74
107
  // `useQueries` goes through the context client rather than
75
108
  // `useQueryWithApiError`, so this key carries no trailing server.
109
+ // The trailing null is the givens slot: none carried, none keyed.
76
110
  expect(cacheKeys("givenSuggest")[0]).toBe(
77
111
  '["givenSuggest","env","pkg",null,"dashboards/ops.malloy","REGION",' +
78
- 'null,"orders","region"]',
112
+ 'null,"orders","region",null]',
79
113
  );
80
114
  });
81
115
 
@@ -89,3 +123,28 @@ it("keeps two versions' option lists apart", async () => {
89
123
  await waitFor(() => expect(executeQueryModel).toHaveBeenCalledTimes(2));
90
124
  expect(new Set(cacheKeys("givenSuggest")).size).toBe(2);
91
125
  });
126
+
127
+ it("sends only the givens the suggest names, and keys on them", async () => {
128
+ renderGated();
129
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
130
+ const request = executeQueryModel.mock.calls[0][3] as { givens?: unknown };
131
+ // TENANT rides along; REGION, applied on the page, does not: the option
132
+ // list must not depend on the page's other filters.
133
+ expect(request.givens).toEqual({ TENANT: "acme" });
134
+ expect(cacheKeys("givenSuggest")[0]).toContain('{\\"TENANT\\":\\"acme\\"}');
135
+ });
136
+
137
+ it("sends no givens when the suggest names none, or the caller offers none", async () => {
138
+ renderSuggest();
139
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
140
+ expect(
141
+ (executeQueryModel.mock.calls[0][3] as { givens?: unknown }).givens,
142
+ ).toBeUndefined();
143
+ executeQueryModel.mockClear();
144
+ clearCache();
145
+ renderGated({ values: new Map(), declaredTypes: APPLIED.declaredTypes });
146
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
147
+ expect(
148
+ (executeQueryModel.mock.calls[0][3] as { givens?: unknown }).givens,
149
+ ).toBeUndefined();
150
+ });