@malloy-publisher/sdk 0.0.248 → 0.0.249

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +32 -17
  2. package/dist/ServerProvider-CcfeBpt3.cjs.js +1 -0
  3. package/dist/{ServerProvider-BxEh3nFI.es.js → ServerProvider-EqBlMMqx.es.js} +1056 -905
  4. package/dist/client/api.d.ts +297 -6
  5. package/dist/client/index.cjs.js +1 -1
  6. package/dist/client/index.es.js +74 -70
  7. package/dist/components/Dashboard/Dashboard.d.ts +49 -0
  8. package/dist/components/Dashboard/DashboardTile.d.ts +48 -0
  9. package/dist/components/Dashboard/index.d.ts +2 -0
  10. package/dist/components/Notebook/Notebook.d.ts +46 -8
  11. package/dist/components/Notebook/NotebookCell.d.ts +37 -3
  12. package/dist/components/Notebook/runPlan.d.ts +29 -0
  13. package/dist/components/Notebook/types.d.ts +10 -0
  14. package/dist/components/Package/ContentTypeIcon.d.ts +17 -1
  15. package/dist/components/Package/Package.d.ts +1 -4
  16. package/dist/components/RenderedResult/RenderedResult.d.ts +7 -1
  17. package/dist/components/RenderedResult/ResultContainer.d.ts +3 -1
  18. package/dist/components/ResultsDialog.d.ts +4 -1
  19. package/dist/components/ServerProvider.d.ts +2 -1
  20. package/dist/components/click_helper.d.ts +10 -1
  21. package/dist/components/drill/index.d.ts +3 -0
  22. package/dist/components/drill/markDrillableCells.d.ts +55 -0
  23. package/dist/components/drill/resolveDrill.d.ts +159 -0
  24. package/dist/components/drill/useDrill.d.ts +63 -0
  25. package/dist/components/given/GivenInput.d.ts +27 -3
  26. package/dist/components/given/GivensPanel.d.ts +36 -7
  27. package/dist/components/given/filterValue.d.ts +117 -0
  28. package/dist/components/given/index.d.ts +1 -1
  29. package/dist/components/given/paramCodec.d.ts +60 -0
  30. package/dist/components/index.d.ts +4 -1
  31. package/dist/components/styles.d.ts +23 -0
  32. package/dist/constants/docLinks.d.ts +6 -0
  33. package/dist/{core-BuvlzSIX.es.js → core-DFBwNhvb.es.js} +1 -1
  34. package/dist/{core-C86Rb7tJ.cjs.js → core-DZk7z7ko.cjs.js} +1 -1
  35. package/dist/hooks/givenValue.d.ts +10 -0
  36. package/dist/hooks/index.d.ts +3 -1
  37. package/dist/hooks/useGivensState.d.ts +64 -0
  38. package/dist/hooks/useSuggestOptions.d.ts +78 -0
  39. package/dist/{index-BdtAZ5k6.es.js → index-CLcRrkxd.es.js} +41221 -39894
  40. package/dist/index-CWQXhe0D.cjs.js +338 -0
  41. package/dist/index.cjs.js +1 -1
  42. package/dist/index.es.js +77 -62
  43. package/dist/theme/types.d.ts +9 -0
  44. package/package.json +3 -1
  45. package/src/components/Connections/AddConnectionDialog.tsx +10 -1
  46. package/src/components/Dashboard/Dashboard.tsx +395 -0
  47. package/src/components/Dashboard/DashboardTile.tsx +150 -0
  48. package/src/components/Dashboard/index.ts +2 -0
  49. package/src/components/Home/Home.tsx +114 -23
  50. package/src/components/Notebook/Notebook.tsx +444 -390
  51. package/src/components/Notebook/NotebookCell.tsx +117 -3
  52. package/src/components/Notebook/runPlan.spec.ts +152 -0
  53. package/src/components/Notebook/runPlan.ts +64 -0
  54. package/src/components/Notebook/types.ts +11 -0
  55. package/src/components/Package/ContentTypeIcon.spec.ts +88 -0
  56. package/src/components/Package/ContentTypeIcon.tsx +77 -6
  57. package/src/components/Package/Package.tsx +148 -38
  58. package/src/components/RenderedResult/RenderedResult.tsx +309 -19
  59. package/src/components/RenderedResult/ResultContainer.tsx +28 -1
  60. package/src/components/ResultsDialog.tsx +5 -0
  61. package/src/components/ServerProvider.tsx +2 -0
  62. package/src/components/click_helper.ts +14 -1
  63. package/src/components/drill/index.ts +25 -0
  64. package/src/components/drill/markDrillableCells.dom.spec.ts +310 -0
  65. package/src/components/drill/markDrillableCells.spec.ts +106 -0
  66. package/src/components/drill/markDrillableCells.ts +311 -0
  67. package/src/components/drill/resolveDrill.spec.ts +446 -0
  68. package/src/components/drill/resolveDrill.ts +372 -0
  69. package/src/components/drill/useDrill.tsx +200 -0
  70. package/src/components/given/GivenInput.spec.tsx +495 -15
  71. package/src/components/given/GivenInput.tsx +562 -30
  72. package/src/components/given/GivensPanel.spec.tsx +172 -0
  73. package/src/components/given/GivensPanel.tsx +139 -32
  74. package/src/components/given/filterValue.spec.ts +361 -0
  75. package/src/components/given/filterValue.ts +204 -0
  76. package/src/components/given/index.ts +5 -1
  77. package/src/components/given/paramCodec.spec.ts +854 -0
  78. package/src/components/given/paramCodec.ts +480 -0
  79. package/src/components/index.ts +4 -1
  80. package/src/components/styles.ts +27 -3
  81. package/src/constants/docLinks.spec.ts +51 -0
  82. package/src/constants/docLinks.ts +26 -0
  83. package/src/hooks/givenValue.ts +10 -0
  84. package/src/hooks/index.ts +6 -4
  85. package/src/hooks/useGivensState.spec.ts +446 -0
  86. package/src/hooks/useGivensState.ts +337 -0
  87. package/src/hooks/useSuggestOptions.spec.ts +109 -0
  88. package/src/hooks/useSuggestOptions.ts +260 -0
  89. package/src/theme/buildTableCssVars.ts +4 -0
  90. package/src/theme/resolveTheme.spec.ts +13 -0
  91. package/src/theme/resolveTheme.ts +3 -0
  92. package/src/theme/types.ts +9 -0
  93. package/test/README.md +16 -10
  94. package/dist/ServerProvider-Dg5S1qBU.cjs.js +0 -1
  95. package/dist/hooks/useGivensForm.d.ts +0 -35
  96. package/dist/index-MES4MGpQ.cjs.js +0 -309
  97. package/src/hooks/useGivensForm.spec.ts +0 -99
  98. package/src/hooks/useGivensForm.ts +0 -107
@@ -0,0 +1,372 @@
1
+ /**
2
+ * Resolving a renderer click into a `# drill` intent.
3
+ *
4
+ * `# drill { to=[…] given=… }` is written on a source *dimension*, and Malloy
5
+ * carries a dimension's annotations through to the query result's output field.
6
+ * So everything a click needs is already on the clicked field, and drill needs
7
+ * no endpoint of its own: the same resolution works for a dashboard tile and a
8
+ * notebook cell, which is the "one drill implementation" the design asks for.
9
+ *
10
+ * That propagation is the premise the whole design rests on, and NOTHING IN THIS
11
+ * PR pins it: the specs here drive a hand-built tag stub, deliberately, because
12
+ * what they test is the grammar. It is pinned against the real compiler by
13
+ * `packages/server/src/service/drill_probe.spec.ts`, which arrives with the
14
+ * dashboard slice of this split rather than here. If a Malloy upgrade stopped
15
+ * propagating dimension annotations, drill would go quiet everywhere at once and
16
+ * this slice's tests would all still pass.
17
+ *
18
+ * This module answers only *what* was asked for, which dashboards, seeding
19
+ * which given to which value. Navigating is the host's job.
20
+ */
21
+
22
+ import {
23
+ encodeFilterList,
24
+ filterInnerType,
25
+ isFilterType,
26
+ } from "../given/filterValue";
27
+
28
+ /**
29
+ * The parsed-tag surface this module reads, structurally typed.
30
+ *
31
+ * The renderer hands over an already-parsed `Tag` from `@malloydata/malloy-tag`,
32
+ * so naming the shape rather than importing the class keeps that package a
33
+ * render-time detail: SDK consumers can bundle without it, the same allowance
34
+ * `RenderedResult` makes for its theme annotations.
35
+ */
36
+ export interface DrillTagReader {
37
+ tag(...at: string[]): DrillTagReader | undefined;
38
+ text(...at: string[]): string | undefined;
39
+ textArray(...at: string[]): string[] | undefined;
40
+ }
41
+
42
+ /** The clicked field, as much of it as drill reads. */
43
+ export interface DrillField {
44
+ name: string;
45
+ tag?: DrillTagReader;
46
+ /**
47
+ * Whether the field was grouped rather than aggregated. Only dimensions
48
+ * drill: a measure's cell has no dimension value to seed a filter with even
49
+ * when the tag reaches it, so filtering by one would filter by something
50
+ * other than what was clicked. Optional because the renderer's click payload
51
+ * and its field metadata are the two callers and only one is guaranteed to
52
+ * carry the method; absent, the field is taken at its word.
53
+ */
54
+ wasDimension?: () => boolean;
55
+ }
56
+
57
+ /**
58
+ * A click from `@malloydata/render`'s `onClick`, narrowed to what drill needs.
59
+ * Mirrors its `MalloyClickEventPayload` without importing it, since the renderer
60
+ * is a lazily-imported dependency here.
61
+ */
62
+ export interface DrillClickPayload {
63
+ field?: DrillField;
64
+ value?: unknown;
65
+ isHeader?: boolean;
66
+ /**
67
+ * The originating click, which the host needs for two things a resolved
68
+ * intent cannot express, where to anchor a menu of destinations, and whether
69
+ * a modifier was held (cmd/ctrl to open in a new tab).
70
+ */
71
+ event?: MouseEvent;
72
+ }
73
+
74
+ /** The literal `to=self`: filter the current view instead of leaving it. */
75
+ export const DRILL_SELF = "self";
76
+
77
+ /**
78
+ * The `to=` destinations a field's `# drill` declares, empty when it declares
79
+ * none or the field cannot drill.
80
+ *
81
+ * Read separately from {@link resolveDrill} because two callers need it: the
82
+ * click, which also needs the clicked value, and the *affordance*, which runs
83
+ * over the result's field metadata before any click to decide which columns read
84
+ * as clickable. Sharing this is what keeps the two honest: a cell that looks
85
+ * clickable is one whose click resolves, because both answers come from here.
86
+ */
87
+ export function drillDestinations(field: DrillField | undefined): string[] {
88
+ if (!field) return [];
89
+ // `wasDimension` is only consulted when the field answers; see DrillField.
90
+ if (field.wasDimension && !field.wasDimension()) return [];
91
+ const drill = field.tag?.tag("drill");
92
+ if (!drill) return [];
93
+ // Malloyyo accepts a lone destination unbracketed (`to=overview`) as well as
94
+ // the list form. The server grows the same leniency in `readDrillTag`
95
+ // (`service/dashboard.ts`) with the dashboard slice of this split; it is not
96
+ // in the tree yet, so keep the two in step when it lands.
97
+ return (
98
+ drill.textArray("to") ?? [drill.text("to")].filter(isNonEmpty)
99
+ ).filter(isNonEmpty);
100
+ }
101
+
102
+ /**
103
+ * A destination slug as a menu label: `category_detail` → `Category detail`.
104
+ *
105
+ * Ported from Malloyyo so the same drill reads the same way in both, rather than
106
+ * naming the file on one and a sentence on the other.
107
+ */
108
+ export function humanizeSlug(slug: string): string {
109
+ const words = slug.replace(/[-_]+/g, " ").trim();
110
+ return words.charAt(0).toUpperCase() + words.slice(1);
111
+ }
112
+
113
+ /**
114
+ * The given a `# drill` on this field would set: `given=` when the tag names
115
+ * one, otherwise the dimension name exactly as the model spells it.
116
+ *
117
+ * Shared with the affordance for the same reason `drillDestinations` is: a cell
118
+ * reads as clickable exactly when clicking it would do something, and deciding
119
+ * "would it" needs the given's name before any click happens.
120
+ */
121
+ export function drillGivenName(field: DrillField): string {
122
+ // The field name verbatim, NOT upper-cased. Given names are stored as the
123
+ // model spells them, so upper-casing meant a `to=self` on a lowercase-named
124
+ // dimension resolved to a given that does not exist and the click was
125
+ // dropped in silence. An upper-case convention is common enough that it hid
126
+ // this: `given: REGION` worked, `given: region` did not.
127
+ //
128
+ // How the name is then MATCHED is the caller's business, and Notebook folds
129
+ // case before looking it up, so a tag naming `region` still finds a declared
130
+ // `REGION`. That is a courtesy at the lookup, not a licence to re-spell the
131
+ // name here: the value has to be set under the name the model declares.
132
+ return field.tag?.tag("drill")?.text("given") ?? field.name;
133
+ }
134
+
135
+ /** Where a `# drill` click wants to go, for the host to route however it routes. */
136
+ export interface DrillNavigation {
137
+ /** The destination dashboard's slug. */
138
+ dashboard: string;
139
+ /**
140
+ * Control values to open it with: the clicked value seeded into the drill's
141
+ * given. Only the seeded given: the source view's other filters are not
142
+ * carried over, since the destination need not bind them.
143
+ */
144
+ givens: Record<string, string>;
145
+ }
146
+
147
+ /** What a click asked for, once the tag on the clicked field is read. */
148
+ export interface DrillIntent {
149
+ /** Destinations in declared order: dashboard slugs and/or {@link DRILL_SELF}. */
150
+ to: string[];
151
+ /** The given to seed: the dimension name as spelled, unless `given=` says otherwise. */
152
+ given: string;
153
+ /**
154
+ * The clicked value as Malloy filter syntax, ready to send to a `filter<…>`
155
+ * given. This is the right encoding for a cross-dashboard drill, whose
156
+ * destination declares its own givens and is conventionally `filter<…>`.
157
+ */
158
+ value: string;
159
+ /**
160
+ * The same value before any encoding.
161
+ *
162
+ * Carried because the filter encoding above is only correct for a
163
+ * `filter<…>` target, and a click cannot know what it is aiming at: the
164
+ * destination may be another dashboard entirely. A host that *does* know,
165
+ * `to=self`, where the target given is one of its own: re-encodes from this
166
+ * with {@link encodeDrillValue}. Without it, drilling into a plain `string`
167
+ * given seeded it with backslash-escaped filter syntax and matched nothing.
168
+ */
169
+ rawValue: unknown;
170
+ /** The clicked value as it read on screen, for labelling the destination menu. */
171
+ label: string;
172
+ }
173
+
174
+ /**
175
+ * The clicked cell's value as filter syntax, or undefined when it cannot be
176
+ * expressed as one.
177
+ *
178
+ * Encoded from the value's own type rather than the given's, which a click does
179
+ * not know (a notebook cell has no control row to consult). Refusing the cases
180
+ * it cannot encode is deliberate: a drill that filtered by something other than
181
+ * the cell the user clicked would be worse than one that does nothing.
182
+ */
183
+ export function drillValueToFilter(value: unknown): string | undefined {
184
+ if (typeof value === "string") {
185
+ // Refused when it ENCODES to nothing, not when it IS the empty string.
186
+ // `encodeFilterList` drops any value with no non-whitespace character,
187
+ // and the empty filter matches every row, so a drill producing one would
188
+ // silently widen instead of narrowing. Testing the input against `""`
189
+ // duplicated the encoder's rule and then fell out of step with it the
190
+ // moment that rule grew to cover whitespace: clicking a blank-looking
191
+ // cell (a space, a tab, an NBSP, all ordinary in pasted data) handed back
192
+ // the whole dataset dressed up as a drilled view. Asking the encoder is
193
+ // the one form of this that cannot drift again.
194
+ const encoded = encodeFilterList([value]);
195
+ return encoded === "" ? undefined : encoded;
196
+ }
197
+ if (typeof value === "boolean") return String(value);
198
+ if (typeof value === "number") {
199
+ // A bare number reads as equality. NaN/Infinity have no filter spelling.
200
+ return Number.isFinite(value) ? String(value) : undefined;
201
+ }
202
+ if (value instanceof Date) {
203
+ // Malloy's date filter literal. Deliberately day-granularity: seeding a
204
+ // timestamp to the millisecond would filter to a single row nobody asked
205
+ // for, and for a `date` column the clicked cell was a truncated date in
206
+ // the first place.
207
+ //
208
+ // KNOWN LIMITATION for a TIMESTAMP column feeding a `filter<…>` given.
209
+ // This truncates on the UTC day, and the renderer prints a timestamp in
210
+ // the query timezone, so the two disagree whenever that zone crosses
211
+ // midnight away from UTC: an instant of `2024-03-06T04:00:00Z` shows as
212
+ // `2024-03-05 20:00` under US-Pacific and seeds `2024-03-06`, the day
213
+ // AFTER the one on screen. Plain `date`/`timestamp` givens route around
214
+ // this entirely (`encodeDrillValue` hands them the Date and lets
215
+ // `givensToRequest` spell it per type); only the filter-typed targets
216
+ // land here, because a filter's value must be text.
217
+ //
218
+ // Not fixed rather than fixed wrongly: the correct day is the one the
219
+ // CELL displayed, which needs the query timezone, and that is not on the
220
+ // click payload or anywhere else this function can see. Guessing the
221
+ // browser's zone would be a second wrong answer that happens to be right
222
+ // more often, which is harder to diagnose than a consistent one.
223
+ const iso = value.toISOString();
224
+ return iso.slice(0, iso.indexOf("T"));
225
+ }
226
+ // null included: "the rows with no value" is expressible in Malloy, but
227
+ // clicking an empty cell is far more likely a misclick than that request.
228
+ return undefined;
229
+ }
230
+
231
+ /** How the clicked value read on screen, for a menu label. */
232
+ function drillValueLabel(value: unknown): string {
233
+ if (value instanceof Date) return drillValueToFilter(value) ?? "";
234
+ return String(value);
235
+ }
236
+
237
+ /**
238
+ * Read the `# drill` intent off a renderer click, or undefined when the click
239
+ * was not on a drillable value.
240
+ *
241
+ * Silent on anything untagged, which is most clicks: this runs on every click
242
+ * the renderer reports, so "not a drill" is the ordinary answer, not a fault.
243
+ */
244
+ export function resolveDrill(
245
+ payload: DrillClickPayload | undefined,
246
+ ): DrillIntent | undefined {
247
+ // A column header names the field rather than carrying a value, so there is
248
+ // nothing to seed even though the tag is on the field the header belongs to.
249
+ if (!payload || payload.isHeader) return undefined;
250
+
251
+ const field = payload.field;
252
+ if (!field) return undefined;
253
+
254
+ const to = drillDestinations(field);
255
+ if (to.length === 0) return undefined;
256
+
257
+ const value = drillValueToFilter(payload.value);
258
+ if (value === undefined) return undefined;
259
+
260
+ return {
261
+ to,
262
+ given: drillGivenName(field),
263
+ value,
264
+ rawValue: payload.value,
265
+ label: drillValueLabel(payload.value),
266
+ };
267
+ }
268
+
269
+ function isNonEmpty(value: string | undefined): value is string {
270
+ return typeof value === "string" && value !== "";
271
+ }
272
+
273
+ /**
274
+ * A clicked value encoded for a given whose declared type is known.
275
+ *
276
+ * `filter<…>` takes filter syntax, so the value is escaped into a one-value
277
+ * filter list. Every other type takes the value itself: a plain `string` given
278
+ * seeded with `Ben\ &\ Jerry` would match nothing, because the escaping is
279
+ * meaningful only to the filter parser.
280
+ *
281
+ * Undefined when the value has no spelling for that type, which the caller
282
+ * should treat the way it treats an unresolvable drill: do nothing.
283
+ */
284
+ export function encodeDrillValue(
285
+ rawValue: unknown,
286
+ targetType: string | undefined,
287
+ ): string | number | boolean | Date | undefined {
288
+ if (targetType !== undefined && !isFilterType(targetType)) {
289
+ // Returned in the given's OWN type, not stringified. `givensToRequest`
290
+ // converts only `Date`, so a string sent for a `number` or `boolean` given
291
+ // travels as a string and Malloy refuses the query.
292
+ if (targetType === "number") {
293
+ // Only a number, or a string that spells one. `Number()` accepts far
294
+ // more than that and every extra it accepts is a wrong filter rather
295
+ // than a refused one: a clicked Date became its epoch milliseconds
296
+ // (1709646300000 for 2024-03-05) and a null cell became 0, so the
297
+ // notebook re-ran filtered to a value nobody clicked and returned
298
+ // nothing, with no error to explain it.
299
+ if (typeof rawValue === "number") {
300
+ return Number.isFinite(rawValue) ? rawValue : undefined;
301
+ }
302
+ if (typeof rawValue !== "string" || rawValue.trim() === "") {
303
+ return undefined;
304
+ }
305
+ const parsed = Number(rawValue);
306
+ return Number.isFinite(parsed) ? parsed : undefined;
307
+ }
308
+ if (
309
+ targetType === "date" ||
310
+ targetType === "timestamp" ||
311
+ targetType === "timestamptz"
312
+ ) {
313
+ // The Date itself, so `givensToRequest` can spell it per type. Falling
314
+ // through to `drillValueToFilter` truncated it to `YYYY-MM-DD` first,
315
+ // which is the right spelling for a `date` given and drops the time of
316
+ // day for a `timestamp` one: the drill then filtered to midnight
317
+ // rather than to the instant in the cell.
318
+ return rawValue instanceof Date ? rawValue : undefined;
319
+ }
320
+ if (targetType === "boolean") {
321
+ if (typeof rawValue === "boolean") return rawValue;
322
+ if (rawValue === "true") return true;
323
+ if (rawValue === "false") return false;
324
+ return undefined;
325
+ }
326
+ // A blank cell is refused here too, for the same reason as in
327
+ // `drillValueToFilter`: on a plain given it is a real but almost certainly
328
+ // unintended value, and clicking a blank cell is far more likely a
329
+ // misclick. Whitespace counts as blank, which is what makes that reason
330
+ // and this test agree: refusing only `""` left a space, a tab or an NBSP
331
+ // drilling to a value that matches essentially nothing, so the reader got
332
+ // an empty notebook rather than the click being declined.
333
+ if (typeof rawValue === "string")
334
+ return rawValue.trim() === "" ? undefined : rawValue;
335
+ if (typeof rawValue === "number") {
336
+ return Number.isFinite(rawValue) ? String(rawValue) : undefined;
337
+ }
338
+ if (typeof rawValue === "boolean") return String(rawValue);
339
+ }
340
+ // A `filter<string>` target takes the STRING grammar, so a bare number is
341
+ // not safe there: `-5` parses as `{operator:"=", values:["5"], not:true}`,
342
+ // a NEGATION, so drilling a negative cell filtered to every row EXCEPT the
343
+ // one clicked, silently. `drillValueToFilter`'s number branch is right for a
344
+ // `filter<number>`, whose grammar reads `-5` as the value. The spec already
345
+ // knew the two grammars disagree here and pinned only the number one.
346
+ if (
347
+ filterInnerType(targetType) === "string" &&
348
+ typeof rawValue === "number"
349
+ ) {
350
+ return Number.isFinite(rawValue)
351
+ ? encodeFilterList([String(rawValue)])
352
+ : undefined;
353
+ }
354
+ // A `filter<number>` takes the NUMBER grammar, so a string belongs to it only
355
+ // if it spells a number. Falling through emitted STRING filter syntax for it:
356
+ // a click on a text cell seeded `filter<number>` with `West`, a boolean with
357
+ // `true`, and a Date with a `YYYY-MM-DD` day, each of which that grammar
358
+ // refuses, so the server failed EVERY cell and the reader got an error
359
+ // notebook rather than a declined click. The non-filter `number` branch above
360
+ // already refuses exactly these; this is the same rule for the filter arm,
361
+ // which is where the two copies had drifted.
362
+ if (filterInnerType(targetType) === "number") {
363
+ if (typeof rawValue === "number") {
364
+ return Number.isFinite(rawValue) ? String(rawValue) : undefined;
365
+ }
366
+ if (typeof rawValue !== "string" || rawValue.trim() === "") {
367
+ return undefined;
368
+ }
369
+ return Number.isFinite(Number(rawValue)) ? rawValue.trim() : undefined;
370
+ }
371
+ return drillValueToFilter(rawValue);
372
+ }
@@ -0,0 +1,200 @@
1
+ import { ListSubheader, Menu, MenuItem } from "@mui/material";
2
+ import { useCallback, useMemo, useState, type ReactNode } from "react";
3
+ import type { DrillField } from "./resolveDrill";
4
+ import {
5
+ DRILL_SELF,
6
+ drillDestinations,
7
+ drillGivenName,
8
+ humanizeSlug,
9
+ resolveDrill,
10
+ type DrillClickPayload,
11
+ type DrillIntent,
12
+ type DrillNavigation,
13
+ } from "./resolveDrill";
14
+
15
+ export interface UseDrillOptions {
16
+ /**
17
+ * Open another dashboard, seeded with the clicked value. Omitted on a surface
18
+ * that cannot navigate, which makes those destinations inert rather than
19
+ * dead-ended.
20
+ */
21
+ onNavigate?: (target: DrillNavigation, event?: MouseEvent) => void;
22
+ /**
23
+ * Apply the clicked value to this surface's own control row (`to=self`).
24
+ * Omitted on a surface that has none, such as a notebook cell.
25
+ */
26
+ onSelf?: (given: string, rawValue: unknown) => void;
27
+ /**
28
+ * Whether a `to=self` drill onto this given can actually be honoured: for a
29
+ * notebook, whether it declares that given at all.
30
+ *
31
+ * Without it the affordance says yes to every self-drill and the click is
32
+ * refused afterwards with a console warning, which is the dead link this
33
+ * module exists to avoid. Absent means "any self-drill is fine", the right
34
+ * default for a surface that binds whatever it is handed.
35
+ */
36
+ canSelf?: (given: string) => boolean;
37
+ /**
38
+ * What `to=self` is called in the menu. A notebook filtering itself is not
39
+ * "this dashboard", and the drill tag: written on a shared model dimension,
40
+ * cannot know which document the reader is in, so the surface names itself.
41
+ */
42
+ selfLabel?: string;
43
+ }
44
+
45
+ /**
46
+ * What a surface hands to its result renderer to become drillable: the click
47
+ * handler, and the predicate that decides which cells say so.
48
+ *
49
+ * One object because the two must agree. Passing only the handler is what
50
+ * produced the original asymmetry: clicks worked, but nothing looked clickable.
51
+ */
52
+ export interface DrillBinding {
53
+ /**
54
+ * Every cell click. Most carry no `# drill` and mean nothing, so this
55
+ * tolerates being called constantly.
56
+ */
57
+ onClick: (payload: DrillClickPayload) => void;
58
+ /** Whether this field's cells should read as clickable. */
59
+ canDrill: (field: DrillField) => boolean;
60
+ }
61
+
62
+ export interface UseDrillResult {
63
+ /** Hand to `ResultContainer`'s (or `RenderedResult`'s) `drill` prop. */
64
+ drill: DrillBinding;
65
+ /** Render anywhere in the subtree: the menu a multi-destination drill opens. */
66
+ drillMenu: ReactNode;
67
+ }
68
+
69
+ interface DrillMenuState {
70
+ intent: DrillIntent;
71
+ destinations: string[];
72
+ event?: MouseEvent;
73
+ top: number;
74
+ left: number;
75
+ }
76
+
77
+ /**
78
+ * Click-to-drill for any surface that renders a Malloy result.
79
+ *
80
+ * Shared between the dashboard viewer and notebook cells on purpose: `# drill`
81
+ * is declared on a model *dimension*, so it fires wherever that dimension is
82
+ * grouped, and a notebook can therefore drill into a dashboard with no notebook-
83
+ * specific code. What differs between surfaces is only what they can do about it,
84
+ * which is what the two callbacks express.
85
+ */
86
+ export function useDrill({
87
+ onNavigate,
88
+ onSelf,
89
+ selfLabel = "Filter this view",
90
+ canSelf,
91
+ }: UseDrillOptions): UseDrillResult {
92
+ // A cell inside the renderer's own DOM is the anchor, and this component
93
+ // holds no ref to it, so the menu is positioned from the click coordinates.
94
+ const [menu, setMenu] = useState<DrillMenuState | null>(null);
95
+
96
+ // What this surface can actually do about a destination. Applied to the click
97
+ // and to the affordance from one place, so a cell reads as clickable exactly
98
+ // when clicking it would do something.
99
+ const honorable = useCallback(
100
+ (destinations: string[], given: string) =>
101
+ destinations.filter((destination) =>
102
+ destination === DRILL_SELF
103
+ ? onSelf !== undefined && (canSelf?.(given) ?? true)
104
+ : onNavigate !== undefined,
105
+ ),
106
+ [onNavigate, onSelf, canSelf],
107
+ );
108
+
109
+ const go = useCallback(
110
+ (intent: DrillIntent, destination: string, event?: MouseEvent) => {
111
+ if (destination === DRILL_SELF) {
112
+ // The raw value, not `intent.value`: only this surface knows the
113
+ // declared type of its own given, so only it can encode correctly.
114
+ onSelf?.(intent.given, intent.rawValue);
115
+ return;
116
+ }
117
+ onNavigate?.(
118
+ {
119
+ dashboard: destination,
120
+ givens: { [intent.given]: intent.value },
121
+ },
122
+ event,
123
+ );
124
+ },
125
+ [onNavigate, onSelf],
126
+ );
127
+
128
+ const onClick = useCallback(
129
+ (payload: DrillClickPayload) => {
130
+ // Runs on every cell click, so "not a drill" is the ordinary answer.
131
+ const intent = resolveDrill(payload);
132
+ if (!intent) return;
133
+
134
+ // Offer only what this surface can actually do, so a menu never lists a
135
+ // destination that would be a no-op when picked.
136
+ const destinations = honorable(intent.to, intent.given);
137
+ if (destinations.length === 0) return;
138
+ if (destinations.length === 1) {
139
+ go(intent, destinations[0], payload.event);
140
+ return;
141
+ }
142
+ setMenu({
143
+ intent,
144
+ destinations,
145
+ event: payload.event,
146
+ top: payload.event?.clientY ?? 0,
147
+ left: payload.event?.clientX ?? 0,
148
+ });
149
+ },
150
+ [go, honorable],
151
+ );
152
+
153
+ const canDrill = useCallback(
154
+ (field: DrillField) =>
155
+ honorable(drillDestinations(field), drillGivenName(field)).length > 0,
156
+ [honorable],
157
+ );
158
+
159
+ const drill = useMemo<DrillBinding>(
160
+ () => ({ onClick, canDrill }),
161
+ [onClick, canDrill],
162
+ );
163
+
164
+ const close = useCallback(() => setMenu(null), []);
165
+
166
+ return {
167
+ drill,
168
+ drillMenu: (
169
+ <Menu
170
+ open={menu !== null}
171
+ onClose={close}
172
+ anchorReference="anchorPosition"
173
+ anchorPosition={{ top: menu?.top ?? 0, left: menu?.left ?? 0 }}
174
+ >
175
+ <ListSubheader sx={{ lineHeight: "32px" }}>
176
+ {menu ? `${menu.intent.label} →` : ""}
177
+ </ListSubheader>
178
+ {/* Deduplicated: `# drill { to=[overview, overview] }` is a typo
179
+ rather than a request for two identical rows, and React keys
180
+ these by destination, so the duplicate warned as well as
181
+ rendered twice. */}
182
+ {Array.from(new Set(menu?.destinations ?? [])).map(
183
+ (destination) => (
184
+ <MenuItem
185
+ key={destination}
186
+ onClick={() => {
187
+ close();
188
+ if (menu) go(menu.intent, destination, menu.event);
189
+ }}
190
+ >
191
+ {destination === DRILL_SELF
192
+ ? selfLabel
193
+ : humanizeSlug(destination)}
194
+ </MenuItem>
195
+ ),
196
+ )}
197
+ </Menu>
198
+ ),
199
+ };
200
+ }