@malloy-publisher/sdk 0.2.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +172 -204
  2. package/dist/ServerProvider-CGnLjzag.cjs.js +1 -0
  3. package/dist/{ServerProvider-ksC5Su_x.es.js → ServerProvider-DSK9rfSY.es.js} +245 -245
  4. package/dist/client/api.d.ts +13 -1
  5. package/dist/client/index.cjs.js +1 -1
  6. package/dist/client/index.es.js +1 -1
  7. package/dist/components/ApiErrorDisplay.d.ts +1 -2
  8. package/dist/components/Dashboard/Dashboard.d.ts +4 -2
  9. package/dist/components/Dashboard/promoteMeasureRow.d.ts +36 -0
  10. package/dist/components/DocumentStorage/BrowserDocumentStorage.d.ts +14 -0
  11. package/dist/components/DocumentStorage/DocumentStorage.d.ts +58 -0
  12. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +18 -0
  13. package/dist/components/DocumentStorage/index.d.ts +3 -0
  14. package/dist/components/Model/index.d.ts +0 -1
  15. package/dist/components/RenderedResult/RenderedResult.d.ts +12 -0
  16. package/dist/components/RenderedResult/ResultContainer.d.ts +7 -1
  17. package/dist/components/RenderedResult/index.d.ts +1 -0
  18. package/dist/components/RenderedResult/resultSizing.d.ts +183 -0
  19. package/dist/components/drill/index.d.ts +1 -0
  20. package/dist/components/drill/useDrillSelf.d.ts +46 -0
  21. package/dist/components/given/filterValue.d.ts +63 -0
  22. package/dist/components/given/index.d.ts +1 -0
  23. package/dist/components/given/useGivenUrlParams.d.ts +39 -0
  24. package/dist/components/index.d.ts +2 -3
  25. package/dist/components/styles.d.ts +3 -3
  26. package/dist/core-8NVBCLZh.cjs.js +148 -0
  27. package/dist/{core-xdZbLgaF.es.js → core-B8oMW4sm.es.js} +3540 -2335
  28. package/dist/hooks/index.d.ts +1 -1
  29. package/dist/hooks/useSuggestOptions.d.ts +28 -12
  30. package/dist/index.cjs.js +281 -1
  31. package/dist/index.es.js +45803 -79
  32. package/dist/sdk.css +1 -1
  33. package/dist/styles.css +0 -1
  34. package/package.json +2 -6
  35. package/src/components/ApiErrorDisplay.tsx +1 -1
  36. package/src/components/Connections/EditConnectionDialog.tsx +96 -86
  37. package/src/components/Dashboard/Dashboard.tsx +60 -95
  38. package/src/components/Dashboard/DashboardTile.tsx +25 -2
  39. package/src/components/Dashboard/promoteMeasureRow.spec.ts +137 -0
  40. package/src/components/Dashboard/promoteMeasureRow.ts +129 -0
  41. package/src/components/DocumentStorage/BrowserDocumentStorage.spec.ts +81 -0
  42. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +105 -0
  43. package/src/components/DocumentStorage/DocumentStorage.ts +73 -0
  44. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +46 -0
  45. package/src/components/DocumentStorage/index.ts +15 -0
  46. package/src/components/Environment/Connections.tsx +15 -15
  47. package/src/components/Model/ModelCell.tsx +2 -1
  48. package/src/components/Model/index.ts +0 -1
  49. package/src/components/Notebook/Notebook.tsx +10 -76
  50. package/src/components/Notebook/NotebookCell.tsx +2 -8
  51. package/src/components/RenderedResult/RenderedResult.tsx +86 -76
  52. package/src/components/RenderedResult/ResultContainer.tsx +21 -24
  53. package/src/components/RenderedResult/index.ts +15 -0
  54. package/src/components/RenderedResult/resultSizing.spec.ts +249 -0
  55. package/src/components/RenderedResult/resultSizing.ts +308 -0
  56. package/src/components/ResultsDialog.tsx +2 -1
  57. package/src/components/drill/index.ts +5 -0
  58. package/src/components/drill/useDrillSelf.spec.tsx +64 -0
  59. package/src/components/drill/useDrillSelf.ts +110 -0
  60. package/src/components/given/GivenInput.spec.tsx +196 -2
  61. package/src/components/given/GivenInput.tsx +300 -25
  62. package/src/components/given/filterValue.spec.ts +112 -0
  63. package/src/components/given/filterValue.ts +188 -0
  64. package/src/components/given/index.ts +4 -0
  65. package/src/components/given/useGivenUrlParams.spec.tsx +74 -0
  66. package/src/components/given/useGivenUrlParams.ts +87 -0
  67. package/src/components/index.ts +5 -3
  68. package/src/hooks/index.ts +0 -1
  69. package/src/hooks/useGivensState.spec.ts +158 -0
  70. package/src/hooks/useGivensState.ts +114 -23
  71. package/src/hooks/useSuggestOptions.dom.spec.ts +60 -1
  72. package/src/hooks/useSuggestOptions.ts +94 -51
  73. package/vite.config.ts +0 -1
  74. package/dist/ServerProvider-xXW1HJOJ.cjs.js +0 -1
  75. package/dist/components/AnalyzePackageButton.d.ts +0 -6
  76. package/dist/components/Workbook/BrowserWorkbookStorage.d.ts +0 -9
  77. package/dist/components/Workbook/EditableMalloyCell.d.ts +0 -11
  78. package/dist/components/Workbook/ModelPicker.d.ts +0 -11
  79. package/dist/components/Workbook/MutableCell.d.ts +0 -17
  80. package/dist/components/Workbook/Workbook.d.ts +0 -7
  81. package/dist/components/Workbook/WorkbookList.d.ts +0 -7
  82. package/dist/components/Workbook/WorkbookManager.d.ts +0 -84
  83. package/dist/components/Workbook/WorkbookStorage.d.ts +0 -17
  84. package/dist/components/Workbook/WorkbookStorageProvider.d.ts +0 -12
  85. package/dist/components/Workbook/index.d.ts +0 -7
  86. package/dist/core-RvrkY1Ss.cjs.js +0 -148
  87. package/dist/index-B3scIDRd.cjs.js +0 -356
  88. package/dist/index-Bda7HuZc.es.js +0 -66409
  89. package/dist/markdown-editor.css +0 -341
  90. package/src/components/AnalyzePackageButton.tsx +0 -319
  91. package/src/components/Workbook/BrowserWorkbookStorage.ts +0 -64
  92. package/src/components/Workbook/EditableMalloyCell.tsx +0 -49
  93. package/src/components/Workbook/ModelPicker.tsx +0 -134
  94. package/src/components/Workbook/MutableCell.tsx +0 -458
  95. package/src/components/Workbook/Workbook.tsx +0 -501
  96. package/src/components/Workbook/WorkbookList.tsx +0 -110
  97. package/src/components/Workbook/WorkbookManager.ts +0 -214
  98. package/src/components/Workbook/WorkbookStorage.ts +0 -35
  99. package/src/components/Workbook/WorkbookStorageProvider.tsx +0 -40
  100. package/src/components/Workbook/index.ts +0 -10
@@ -0,0 +1,308 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * Every height decision a rendered result takes, in one module.
6
+ *
7
+ * Three things used to be tangled together and spread across four files: how
8
+ * tall a result should paint, whether it is the kind of result that has a
9
+ * height of its own at all, and which DOM node that height can be read off.
10
+ * They are separated here so the first two are pure and testable, and the third
11
+ * is the single place this package touches the renderer's DOM.
12
+ *
13
+ * The renderer exposes no size API — `MalloyViz` offers `onReady` and
14
+ * `getMetadata()` and nothing that reports a height — so a result that sizes
15
+ * itself has to be measured. What CAN come from the public metadata is whether
16
+ * it is worth measuring, from two sources, in this order:
17
+ *
18
+ * 1. The root's render plugin declares `sizingStrategy: "fill" | "fixed"`,
19
+ * which is the renderer's own answer to exactly this question. Read it
20
+ * through `getPluginsForField(getRootField().key)`.
21
+ * 2. Where no plugin claims the root — a table, a `# dashboard` grid — fall
22
+ * back to `renderAs()` and the lists below.
23
+ *
24
+ * Keying off either instead of the rendered class names is what keeps the DOM
25
+ * contact down to one bounded walk.
26
+ */
27
+
28
+ /**
29
+ * How a rendered root arrives at its height.
30
+ *
31
+ * - `content`: it has a height of its own and the container should shrink to
32
+ * it — a table, a `# dashboard` grid, a `# big_value`, a list, and the maps,
33
+ * whose height comes from their aspect ratio.
34
+ * - `container`: it fills whatever box it is handed and has no height to
35
+ * report. The plotted charts, and only those. Measuring one tells you what
36
+ * you already gave it, minus the inset it drew itself at.
37
+ */
38
+ export type ResultSizing = "content" | "container";
39
+
40
+ /**
41
+ * Roots that fill their box, named in the renderer's `renderAs()` vocabulary.
42
+ *
43
+ * That vocabulary has two sources and they do not agree, which is the trap
44
+ * here. A field rendered by a plugin reports the PLUGIN's name, and the
45
+ * renderer's default registry names the bar and line plugins `"bar"` and
46
+ * `"line"` — not `"bar_chart"` and `"line_chart"`, which are the tag spellings
47
+ * and appear nowhere in what `renderAs()` returns. Measured: a `# line_chart`
48
+ * tile reports `"line"`. The tag-derived fallback in the renderer, used when no
49
+ * plugin claims the field, collapses both to `"chart"` instead, so that name
50
+ * has to be here too.
51
+ *
52
+ * "It is a chart" is not the test — filling the box is. A bar chart reports its
53
+ * box minus an 8px inset at every size: 392 in a 400px tile, 692 in a 700px
54
+ * notebook cell. That inset is the ratchet, and it is why these are never
55
+ * measured.
56
+ *
57
+ * The maps are deliberately NOT here, which is the trap in the other direction:
58
+ * the renderer declares `# shape_map` and `# segment_map` `"fixed"`, and they
59
+ * report 365 in a 400px tile and 365 in a 700px cell — the same number, because
60
+ * their size is their own and not their box's. Grouping them with the charts
61
+ * put a map that needs 365px into 700px of cell.
62
+ *
63
+ * Every name here is checked against the plugin's declared strategy at runtime
64
+ * and agrees with it today (`bar:fill`, `line:fill`, `shape_map:fixed`); the
65
+ * strategy wins where both are available, so this list carries the roots no
66
+ * plugin claims and anything a renderer stops declaring.
67
+ */
68
+ const CONTAINER_SIZED_ROOTS: ReadonlySet<string> = new Set([
69
+ "bar",
70
+ "line",
71
+ "chart",
72
+ "scatter_chart",
73
+ ]);
74
+
75
+ /**
76
+ * Roots known to have a height of their own, in the same vocabulary.
77
+ *
78
+ * Kept as an explicit list rather than "everything that is not a chart" so a
79
+ * root this SDK has never heard of — a host's own render plugin — can be told
80
+ * apart from both and given the conservative treatment in
81
+ * {@link remeasuresAfterReady}.
82
+ */
83
+ const CONTENT_SIZED_ROOTS: ReadonlySet<string> = new Set([
84
+ "table",
85
+ "dashboard",
86
+ "shape_map",
87
+ "segment_map",
88
+ "list",
89
+ "list_detail",
90
+ "big_value",
91
+ "cell",
92
+ "link",
93
+ "image",
94
+ ]);
95
+
96
+ /**
97
+ * Which sizing rule a root follows.
98
+ *
99
+ * `strategy` is the root plugin's declared `sizingStrategy` and wins when it is
100
+ * there, because it is the renderer answering the question directly rather than
101
+ * this SDK inferring it from a name. Note it is the PLUGIN's strategy, not the
102
+ * field entry's: `renderProperties.sizingStrategy` on the root reads `"fit"` for
103
+ * every result and says nothing.
104
+ *
105
+ * Unknown, with no plugin — a renderer newer than this SDK — is treated as
106
+ * content-sized, which is the behavior every root had before this
107
+ * classification existed: measure once and use what comes back.
108
+ */
109
+ export function resultSizing(
110
+ renderAs: string | undefined,
111
+ strategy?: string | undefined,
112
+ ): ResultSizing {
113
+ if (strategy === "fill") return "container";
114
+ if (strategy === "fixed") return "content";
115
+ if (!renderAs) return "content";
116
+ return CONTAINER_SIZED_ROOTS.has(renderAs) ? "container" : "content";
117
+ }
118
+
119
+ /**
120
+ * Whether the result keeps being measured after the first height lands.
121
+ *
122
+ * It has to be, and the acute case is a table. The renderer signals `onReady`
123
+ * as soon as it knows it can paint, and for a table that is immediately — a
124
+ * chart waits for a non-zero parent size, a table does not — so a single
125
+ * measurement taken there lands before the table's virtualized grid has laid
126
+ * out, and reads a height the table never keeps. A `# big_value` row loses the
127
+ * same race more quietly: it reports the box it was handed, so the panel simply
128
+ * keeps the cap and the tile carries a band of empty space under its numbers.
129
+ *
130
+ * Re-measuring a content-sized root TERMINATES, because its height does not
131
+ * depend on the box it is in. `.malloy-table.root` is
132
+ * `height: fit-content; max-height: 100%` in the renderer's own CSS and the
133
+ * wrappers between it and the container add no padding, so shrinking the
134
+ * container to the table's content height is the exact point at which the cap
135
+ * stops binding and the next measurement reports the same number.
136
+ *
137
+ * This used to be tables only, and the reason was the one root this is NOT safe
138
+ * for: a chart draws itself inset from the box it is given, so feeding its
139
+ * height back as the new container height would ratchet the container down by
140
+ * that inset every pass and never converge. Charts are classified
141
+ * container-sized now and are never measured at all, so the hazard is out of
142
+ * the measured set and the narrow exemption it forced can go with it.
143
+ *
144
+ * A root this SDK cannot place stays on the one-shot path. A plugin that
145
+ * declares itself `"fixed"` IS placed — the renderer has said its size is its
146
+ * own — so it re-measures like any other content-sized root. Only a name we do
147
+ * not know, with no plugin behind it, falls back to one measurement, which is
148
+ * what it got before any of this existed.
149
+ */
150
+ export function remeasuresAfterReady(
151
+ renderAs: string | undefined,
152
+ strategy?: string | undefined,
153
+ ): boolean {
154
+ if (strategy === "fixed") return true;
155
+ if (strategy === "fill") return false;
156
+ return renderAs !== undefined && CONTENT_SIZED_ROOTS.has(renderAs);
157
+ }
158
+
159
+ /**
160
+ * How far below the stage the node carrying a root's content height sits.
161
+ *
162
+ * This is the one renderer-DOM assumption left in the SDK, so it is stated
163
+ * rather than inlined. The stage is our own node and is box-sized, so it is
164
+ * never the answer: measuring it would floor every result at the height the
165
+ * container already has and nothing could ever shrink. Its first child is the
166
+ * renderer's outer wrapper, also box-sized, for the same reason.
167
+ *
168
+ * Depth 2 — the wrapper's child — is the root render node, and for every root
169
+ * but one its `scrollHeight` is the content height.
170
+ *
171
+ * A `# dashboard` grid is the exception: its own wrapper is constrained, and
172
+ * the grid one level further down is what reports the height. That used to be
173
+ * spelled as a class-name check on the rendered DOM
174
+ * (`classList.contains("malloy-dashboard")`); it is keyed off `renderAs()` now,
175
+ * which is metadata the renderer publishes rather than markup it happens to
176
+ * emit.
177
+ */
178
+ export function contentNodeDepth(renderAs: string | undefined): number {
179
+ return renderAs === "dashboard" ? 3 : 2;
180
+ }
181
+
182
+ /**
183
+ * The node under `stage` that carries the result's content height: `depth`
184
+ * first children down, or null if the renderer has not built that deep yet.
185
+ *
186
+ * This is the node measured AND the node watched for changes, so the two can
187
+ * never drift apart.
188
+ *
189
+ * Null rather than the deepest node available, which is the tempting fallback
190
+ * and is actively wrong. A DOM shallower than `depth` almost always means the
191
+ * renderer is still building, and the shallow nodes are its box-sized wrappers:
192
+ * answering with one reports the height the panel already has, which reads as a
193
+ * successful measurement, stops the retry, and leaves the observer watching a
194
+ * node whose size can never change. That is a `# big_value` tile stuck at its
195
+ * 400px cap with 264px of white under its numbers. Reporting nothing instead
196
+ * leaves the panel at its first-paint height and lets the caller measure again
197
+ * when the renderer mutates the DOM into its final shape.
198
+ */
199
+ export function contentNode(
200
+ stage: HTMLElement,
201
+ depth: number,
202
+ ): HTMLElement | null {
203
+ let node: HTMLElement | null = stage.firstElementChild as HTMLElement | null;
204
+ // Depth 1 is `node` itself; walk the remainder.
205
+ for (let level = 1; level < depth && node; level++) {
206
+ node = node.firstElementChild as HTMLElement | null;
207
+ }
208
+ return node;
209
+ }
210
+
211
+ /**
212
+ * Content height of the rendered result under `stage`, or 0 if the renderer
213
+ * has not built its final shape yet. See {@link contentNode}.
214
+ *
215
+ * `scrollHeight` is the CONTENT height, so this assumes the box adds no chrome
216
+ * of its own. True today: `.malloy-table.root` has no border, and a horizontal
217
+ * scrollbar costs no layout where scrollbars overlay. A wide table clipped by a
218
+ * few pixels on a platform that draws classic scrollbars would be this
219
+ * assumption breaking, and the fix is `+ (offsetHeight - clientHeight)`.
220
+ */
221
+ export function measureContentHeight(
222
+ stage: HTMLElement,
223
+ depth: number,
224
+ ): number {
225
+ const node = contentNode(stage, depth);
226
+ if (!node) return 0;
227
+ return node.scrollHeight || node.offsetHeight || 0;
228
+ }
229
+
230
+ /**
231
+ * Per-tile cap for a dashboard's composite form. A tile is one panel among
232
+ * several, so capping them keeps the grid even instead of letting one long
233
+ * table set the height of its whole row.
234
+ */
235
+ export const TILE_MAX_HEIGHT = 400;
236
+
237
+ /**
238
+ * Cap for a notebook cell result that lays itself out: a table, mostly. Tall
239
+ * enough for a screenful of rows, after which the cell scrolls rather than the
240
+ * page turning into one long table.
241
+ */
242
+ export const NOTEBOOK_CELL_MAX_HEIGHT = 700;
243
+
244
+ /** Cap for a query result shown inside a model page's cell. */
245
+ export const MODEL_CELL_MAX_HEIGHT = 600;
246
+
247
+ /** Cap for the results dialog, which gets most of a tall viewport. */
248
+ export const RESULTS_DIALOG_MAX_HEIGHT = 800;
249
+
250
+ /**
251
+ * Height for a container-sized root whose caller set no cap.
252
+ *
253
+ * A chart has no height of its own, so with nothing to measure and no cap to
254
+ * obey, something has to choose. This is that choice, and it is the same number
255
+ * a dashboard tile gets, so an uncapped chart reads like a tall tile rather
256
+ * than a page-height band.
257
+ *
258
+ * This is what closed the stretch: the single-query dashboard form used to ask
259
+ * for a 20000px "no cap" height, which a bare `# bar_chart` painted at, measured
260
+ * back off itself, and kept — 1992px for a two-row chart against 227px for the
261
+ * same query under a `# dashboard` grid. The cap is `undefined` now and a chart
262
+ * is never measured, so neither half of that can happen.
263
+ */
264
+ export const UNCAPPED_CONTAINER_HEIGHT = 400;
265
+
266
+ /**
267
+ * Height to paint at before a content-sized result has been measured.
268
+ *
269
+ * A cap is also the first paint's height, because the measured height starts
270
+ * out equal to it. Harmless while every caller passes something viewport-sized
271
+ * (400 to 800); a caller that passes no cap needs a number that is not "as tall
272
+ * as you like".
273
+ */
274
+ export const INITIAL_RENDER_HEIGHT = 2000;
275
+
276
+ /** First-paint height, before anything is known about the result. */
277
+ export function initialResultHeight(maxHeight: number | undefined): number {
278
+ return maxHeight === undefined
279
+ ? INITIAL_RENDER_HEIGHT
280
+ : Math.min(maxHeight, INITIAL_RENDER_HEIGHT);
281
+ }
282
+
283
+ /**
284
+ * The height a result panel should paint at, given what is known so far.
285
+ *
286
+ * `maxHeight` is a CAP and `undefined` means uncapped — it is not a height
287
+ * request, which is why "no cap" is expressed by leaving it out rather than by
288
+ * passing a number big enough to mean the same thing.
289
+ */
290
+ export function resolveResultHeight({
291
+ sizing,
292
+ contentHeight,
293
+ maxHeight,
294
+ }: {
295
+ sizing: ResultSizing | undefined;
296
+ contentHeight: number | undefined;
297
+ maxHeight: number | undefined;
298
+ }): number {
299
+ if (sizing === "container") {
300
+ return maxHeight ?? UNCAPPED_CONTAINER_HEIGHT;
301
+ }
302
+ if (contentHeight === undefined || contentHeight <= 0) {
303
+ return initialResultHeight(maxHeight);
304
+ }
305
+ return maxHeight === undefined
306
+ ? contentHeight
307
+ : Math.min(maxHeight, contentHeight);
308
+ }
@@ -6,6 +6,7 @@ import { Dialog, DialogContent, DialogTitle, IconButton } from "@mui/material";
6
6
  import { LogMessage } from "../client";
7
7
  import type { DrillBinding } from "./drill";
8
8
  import ResultContainer from "./RenderedResult/ResultContainer";
9
+ import { RESULTS_DIALOG_MAX_HEIGHT } from "./RenderedResult/resultSizing";
9
10
 
10
11
  interface ResultsDialogProps {
11
12
  open: boolean;
@@ -60,7 +61,7 @@ export default function ResultsDialog({
60
61
  >
61
62
  <ResultContainer
62
63
  result={result}
63
- maxHeight={800}
64
+ maxHeight={RESULTS_DIALOG_MAX_HEIGHT}
64
65
  maxResultSize={1000000}
65
66
  renderLogs={renderLogs}
66
67
  drill={drill}
@@ -26,3 +26,8 @@ export {
26
26
  type UseDrillOptions,
27
27
  type UseDrillResult,
28
28
  } from "./useDrill";
29
+ export {
30
+ useDrillSelf,
31
+ type UseDrillSelfOptions,
32
+ type UseDrillSelfResult,
33
+ } from "./useDrillSelf";
@@ -0,0 +1,64 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { afterEach, describe, expect, it, mock, spyOn } from "bun:test";
5
+ import { renderHook } from "@testing-library/react";
6
+ import type { GivenValue } from "../../hooks/givenValue";
7
+ import { useDrillSelf } from "./useDrillSelf";
8
+
9
+ const TYPES = new Map<string, string | undefined>([
10
+ ["REGION", "filter<string>"],
11
+ ["MIN_AMOUNT", "number"],
12
+ ]);
13
+
14
+ function hook(setGiven = mock((_n: string, _v: GivenValue) => {})) {
15
+ const view = renderHook(() =>
16
+ useDrillSelf({
17
+ declaredTypes: TYPES,
18
+ setGiven,
19
+ documentName: "overview",
20
+ }),
21
+ );
22
+ return { ...view.result.current, setGiven };
23
+ }
24
+
25
+ describe("useDrillSelf", () => {
26
+ let warn: ReturnType<typeof spyOn> | undefined;
27
+ afterEach(() => warn?.mockRestore());
28
+
29
+ it("resolves a tag's name as declared, or by folding case", () => {
30
+ const { resolveGiven, canSelf } = hook();
31
+ expect(resolveGiven("REGION")).toBe("REGION");
32
+ expect(resolveGiven("region")).toBe("REGION");
33
+ expect(resolveGiven("Min_Amount")).toBe("MIN_AMOUNT");
34
+ expect(resolveGiven("STATE")).toBeUndefined();
35
+ expect(canSelf("region")).toBe(true);
36
+ expect(canSelf("STATE")).toBe(false);
37
+ });
38
+
39
+ it("sets the given under the DECLARED name, encoded for its type", () => {
40
+ const { onSelf, setGiven } = hook();
41
+ onSelf("region", "West");
42
+ expect(setGiven).toHaveBeenCalledWith("REGION", "West");
43
+ onSelf("min_amount", 42);
44
+ expect(setGiven).toHaveBeenLastCalledWith("MIN_AMOUNT", 42);
45
+ });
46
+
47
+ it("declines, aloud, a name the document does not declare", () => {
48
+ warn = spyOn(console, "warn").mockImplementation(() => {});
49
+ const { onSelf, setGiven } = hook();
50
+ onSelf("STATE", "CA");
51
+ expect(setGiven).not.toHaveBeenCalled();
52
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("'overview'"));
53
+ });
54
+
55
+ it("declines, aloud, a value the given's type cannot hold", () => {
56
+ warn = spyOn(console, "warn").mockImplementation(() => {});
57
+ const { onSelf, setGiven } = hook();
58
+ onSelf("MIN_AMOUNT", "not a number");
59
+ expect(setGiven).not.toHaveBeenCalled();
60
+ expect(warn).toHaveBeenCalledWith(
61
+ expect.stringContaining("Drill declined"),
62
+ );
63
+ });
64
+ });
@@ -0,0 +1,110 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useCallback, useMemo } from "react";
5
+ import type { GivenValue } from "../../hooks/givenValue";
6
+ import { encodeDrillValue } from "./resolveDrill";
7
+
8
+ export interface UseDrillSelfOptions {
9
+ /** Declared type per given name: what this document can set. */
10
+ declaredTypes: ReadonlyMap<string, string | undefined>;
11
+ /** The control row's setter, from `useGivensState`. */
12
+ setGiven: (name: string, value: GivenValue) => void;
13
+ /**
14
+ * How the document names itself in the warning for a tag that names a given
15
+ * it does not declare: a dashboard's slug, a notebook's path.
16
+ */
17
+ documentName: string;
18
+ }
19
+
20
+ export interface UseDrillSelfResult {
21
+ /** The declared given a drill tag's name refers to, or undefined. */
22
+ resolveGiven: (given: string) => string | undefined;
23
+ /** For `useDrill`: whether a `to=self` on this given can be honoured. */
24
+ canSelf: (given: string) => boolean;
25
+ /** For `useDrill`: set the given to the clicked value, encoded for its type. */
26
+ onSelf: (given: string, rawValue: unknown) => void;
27
+ }
28
+
29
+ /**
30
+ * The `# drill { to=self }` half of a document's drill wiring: which of its
31
+ * givens a tag can set, and setting one from a clicked cell.
32
+ *
33
+ * Shared by the dashboard and the notebook so one tag behaves identically on
34
+ * both surfaces, which used to be two copies of this code with the same
35
+ * warning string in each. Three rules live here:
36
+ *
37
+ * - **Names fold case.** `# drill` with no `given=` falls back to the
38
+ * DIMENSION's spelling, conventionally lower_snake, while givens are
39
+ * conventionally SHOUTED; neither convention can be assumed, so a tag naming
40
+ * `region` finds a declared `REGION` and vice versa. First declaration wins
41
+ * when a model declares both spellings.
42
+ * - **The value is encoded against the DECLARED type**, which is knowable here
43
+ * and is not knowable at the click: `useDrill` hands over the raw cell value
44
+ * for exactly this reason. Passing it straight to `setGiven` skipped the
45
+ * encoder, so a clicked date reached a `number` given as epoch milliseconds
46
+ * and a filter value went unescaped. It is set under the name the MODEL
47
+ * declares, so it reaches the URL and the request under the one name the
48
+ * server knows.
49
+ * - **A refusal is said aloud.** `canSelf` checks only that the name resolves,
50
+ * so a `given=` naming a type the clicked value cannot become still paints a
51
+ * whole column clickable and would then drop every click in silence. Both
52
+ * refusals warn, because each is an authoring mistake with no other symptom.
53
+ */
54
+ export function useDrillSelf({
55
+ declaredTypes,
56
+ setGiven,
57
+ documentName,
58
+ }: UseDrillSelfOptions): UseDrillSelfResult {
59
+ const givenNamesByFold = useMemo(() => {
60
+ const byFold = new Map<string, string>();
61
+ for (const name of declaredTypes.keys()) {
62
+ if (!byFold.has(name.toLowerCase()))
63
+ byFold.set(name.toLowerCase(), name);
64
+ }
65
+ return byFold;
66
+ }, [declaredTypes]);
67
+
68
+ const resolveGiven = useCallback(
69
+ (given: string) =>
70
+ declaredTypes.has(given)
71
+ ? given
72
+ : givenNamesByFold.get(given.toLowerCase()),
73
+ [declaredTypes, givenNamesByFold],
74
+ );
75
+
76
+ // Asked before a cell is painted as drillable, so the affordance matches
77
+ // what a click can do: sending a given the document cannot bind would fail
78
+ // every query on the page.
79
+ const canSelf = useCallback(
80
+ (given: string) => resolveGiven(given) !== undefined,
81
+ [resolveGiven],
82
+ );
83
+
84
+ const onSelf = useCallback(
85
+ (given: string, rawValue: unknown) => {
86
+ const declared = resolveGiven(given);
87
+ if (declared === undefined) {
88
+ console.warn(
89
+ `# drill { to=self } tried to set '${given}', which ` +
90
+ `'${documentName}' does not declare as a given. Name the ` +
91
+ `given with 'given=' on the drill tag.`,
92
+ );
93
+ return;
94
+ }
95
+ const declaredType = declaredTypes.get(declared);
96
+ const value = encodeDrillValue(rawValue, declaredType);
97
+ if (value === undefined) {
98
+ console.warn(
99
+ `Drill declined: ${JSON.stringify(rawValue)} cannot be a value for given "${declared}"` +
100
+ (declaredType ? ` of type ${declaredType}` : ""),
101
+ );
102
+ return;
103
+ }
104
+ setGiven(declared, value);
105
+ },
106
+ [declaredTypes, documentName, resolveGiven, setGiven],
107
+ );
108
+
109
+ return { resolveGiven, canSelf, onSelf };
110
+ }