@malloy-publisher/sdk 0.10.1 → 0.10.3

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 (49) hide show
  1. package/dist/{RenderedResult-vf6tu8tf.es.js → RenderedResult-B_sW7neX.es.js} +329 -266
  2. package/dist/RenderedResult-BlYdT4lz.cjs.js +179 -0
  3. package/dist/{ServerProvider-B6RLAbgV.es.js → ServerProvider-BN399NH6.es.js} +4 -4
  4. package/dist/builder/index.cjs.js +1 -1
  5. package/dist/builder/index.es.js +3 -3
  6. package/dist/client/api.d.ts +6 -6
  7. package/dist/client/index.es.js +1 -1
  8. package/dist/components/Dashboard/DashboardView.d.ts +10 -3
  9. package/dist/components/Dashboard/DownloadRowsCsv.d.ts +10 -0
  10. package/dist/components/Dashboard/RowsDialog.d.ts +63 -21
  11. package/dist/components/Dashboard/index.d.ts +2 -0
  12. package/dist/components/Dashboard/rowsCsv.d.ts +26 -0
  13. package/dist/components/RenderedResult/ResultContainer.d.ts +2 -3
  14. package/dist/components/RenderedResult/resultSizing.d.ts +2 -0
  15. package/dist/components/Report/Report.d.ts +8 -1
  16. package/dist/components/drill/drillClauses.d.ts +34 -0
  17. package/dist/components/drill/drillClickRelay.d.ts +36 -0
  18. package/dist/components/drill/resolveDrill.d.ts +29 -0
  19. package/dist/components/drill/rowsTarget.d.ts +114 -0
  20. package/dist/components/drill/useDrill.d.ts +24 -12
  21. package/dist/index.cjs.js +13 -11
  22. package/dist/index.es.js +7331 -6886
  23. package/dist/{useCompiledDocument-C995sQ3j.cjs.js → useCompiledDocument-CyPOSStA.cjs.js} +31 -31
  24. package/dist/{useCompiledDocument-CLbTFtsJ.es.js → useCompiledDocument-xJRD5DRP.es.js} +1588 -1575
  25. package/dist/utils/malloyString.d.ts +2 -1
  26. package/package.json +1 -1
  27. package/src/components/Dashboard/DashboardView.tsx +54 -28
  28. package/src/components/Dashboard/DownloadRowsCsv.tsx +152 -0
  29. package/src/components/Dashboard/RowsDialog.actions.spec.tsx +250 -0
  30. package/src/components/Dashboard/RowsDialog.drill.compile.spec.ts +672 -0
  31. package/src/components/Dashboard/RowsDialog.spec.ts +38 -11
  32. package/src/components/Dashboard/RowsDialog.tsx +194 -40
  33. package/src/components/Dashboard/index.ts +2 -0
  34. package/src/components/Dashboard/rowsCsv.spec.ts +105 -0
  35. package/src/components/Dashboard/rowsCsv.ts +107 -0
  36. package/src/components/RenderedResult/RenderedResult.tsx +44 -7
  37. package/src/components/RenderedResult/ResultContainer.tsx +2 -2
  38. package/src/components/RenderedResult/resultSizing.ts +3 -0
  39. package/src/components/Report/Report.tsx +9 -0
  40. package/src/components/drill/drillClauses.ts +201 -0
  41. package/src/components/drill/drillClickRelay.spec.ts +122 -0
  42. package/src/components/drill/drillClickRelay.ts +106 -0
  43. package/src/components/drill/resolveDrill.ts +29 -0
  44. package/src/components/drill/rowsTarget.ts +245 -0
  45. package/src/components/drill/useDrill.spec.tsx +311 -15
  46. package/src/components/drill/useDrill.tsx +206 -67
  47. package/src/components/legacy/malloynb/NotebookCell.tsx +0 -7
  48. package/src/utils/malloyString.ts +21 -2
  49. package/dist/RenderedResult-B5f4qOjp.cjs.js +0 -171
@@ -0,0 +1,245 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type * as Malloy from "@malloydata/malloy-interfaces";
5
+ import type { DrillClause } from "./drillClauses";
6
+ import type { DrillField, DrillTagReader } from "./resolveDrill";
7
+
8
+ /**
9
+ * What "the rows behind a value" runs, read from the result's own metadata
10
+ * rather than from the tile's text.
11
+ *
12
+ * Malloy annotates every result with what a drill needs: the source the query
13
+ * ran on (`source.name`), each nest level's filters as code (`drill_filters`:
14
+ * the view's own `where:` and any refinement's, givens included), and each
15
+ * dimension's expression as code (`drill_expression.code`: `region`,
16
+ * `d.month`, `customers.name`). So the rows behind a row are
17
+ * `run: <source> -> { where: <every filter>, <every dimension> = <value>; select: * }`,
18
+ * whatever the tile was written as: `source -> view`, a refined view, a
19
+ * named query, an inline query, a nest.
20
+ *
21
+ * `where:` and not `drill:`, measured on Malloy 0.0.435. `drill:` needs the
22
+ * view's own path for every dimension, and a refined or named query reports a
23
+ * plain source field with none (`region`, not `by_month.region`), so its rows
24
+ * could not be named that way. And a `drill:` on a joined field
25
+ * (`by_name.name`, grouped as `customers.name`) does not bring the join in,
26
+ * so its query failed with `Referenced table … not found`; the same filter as
27
+ * `where:` does (malloydata/malloy#3158). Once a Malloy release with that fix
28
+ * reaches Publisher, the join is no longer a reason; the refined query's
29
+ * missing view path still is.
30
+ *
31
+ * A field reads as having rows only when every piece is there: a source with
32
+ * no arguments, every level on the way down marked `drillable` (one stage),
33
+ * a code for every filter on the way down, and a code for every dimension of
34
+ * the row. Anything else is not clickable for rows, never a guess. Malloy's
35
+ * metadata is wrong in places that would name the wrong rows (a pipeline's
36
+ * root marked `drillable`, a joined dimension's code); Publisher's server
37
+ * corrects those before it sends a result (`drill_metadata.ts`), and stamps
38
+ * the root {@link DRILL_METADATA_CORRECTED}. A result without the stamp, from
39
+ * a server older than the correction, offers no rows.
40
+ */
41
+
42
+ /**
43
+ * The root tag Publisher's server writes on a result whose drill metadata it
44
+ * corrected. Spelled the same in the server's `drill_metadata.ts`.
45
+ */
46
+ export const DRILL_METADATA_CORRECTED = "drill_metadata_corrected";
47
+
48
+ /**
49
+ * A renderer result field, as much as the rows behind a value read: the
50
+ * drill field plus Malloy's result metadata, its place in the result, and its
51
+ * type. Its own type because the renderer declares `metadataTag` protected, so
52
+ * a renderer field does not satisfy a `DrillField` that names it; a click's
53
+ * field is read as this one ({@link asRowsField}).
54
+ */
55
+ export interface RowsField extends DrillField {
56
+ metadataTag?: DrillTagReader;
57
+ parent?: RowsField;
58
+ fields?: RowsField[];
59
+ drillStableExpression?: Malloy.Expression;
60
+ getEffectiveQueryTimezone?: () => string | undefined;
61
+ isArray?: () => boolean;
62
+ isRecord?: () => boolean;
63
+ isBasic?: () => boolean;
64
+ isString?: () => boolean;
65
+ isNumber?: () => boolean;
66
+ isBoolean?: () => boolean;
67
+ isTime?: () => boolean;
68
+ }
69
+
70
+ /** A clicked or listed renderer field, read for its rows. */
71
+ export const asRowsField = (field: DrillField) => field as RowsField;
72
+
73
+ /** One dimension of the clicked row: its expression as code, and its value. */
74
+ export interface RowsDimension {
75
+ code: string;
76
+ value: Malloy.LiteralValue;
77
+ }
78
+
79
+ /** Where the rows come from, and what narrows them. */
80
+ export interface RowsTarget {
81
+ source: string;
82
+ /** The tile's own filters, every nest level's, as code, outermost first. */
83
+ filters: string[];
84
+ /** The view or query the value was grouped in, for telemetry and the title. */
85
+ queryName?: string;
86
+ }
87
+
88
+ const call = <T>(f: (() => T) | undefined): T | undefined => {
89
+ try {
90
+ return f?.();
91
+ } catch {
92
+ return undefined;
93
+ }
94
+ };
95
+
96
+ const isDimension = (field: RowsField) =>
97
+ call(field.isBasic?.bind(field)) === true &&
98
+ call(field.wasDimension?.bind(field)) === true;
99
+
100
+ /**
101
+ * Whether a cell of this field has a value a filter can be written from. The
102
+ * renderer reports no value for any other type (a uuid, JSON, a database-native
103
+ * type), and a row missing one cannot be named.
104
+ */
105
+ const hasLiteral = (field: RowsField) =>
106
+ [field.isString, field.isNumber, field.isBoolean, field.isTime].some(
107
+ (is) => call(is?.bind(field)) === true,
108
+ );
109
+
110
+ /** A dimension's expression as Malloy code, or undefined when the result has none. */
111
+ export function dimensionCode(field: RowsField): string | undefined {
112
+ const code = field.metadataTag?.text("drill_expression", "code");
113
+ return code === undefined || code.trim() === "" ? undefined : code;
114
+ }
115
+
116
+ /** The field's ancestors, nearest first, ending at the root. */
117
+ function ancestors(field: RowsField): RowsField[] {
118
+ const out: RowsField[] = [];
119
+ for (let at = field.parent; at; at = at.parent) out.push(at);
120
+ return out;
121
+ }
122
+
123
+ /**
124
+ * The source and filters the rows behind `field`'s values run with, or
125
+ * undefined when the result does not carry them all.
126
+ */
127
+ export function rowsTargetOf(field: RowsField): RowsTarget | undefined {
128
+ const chain = ancestors(field);
129
+ const root = chain[chain.length - 1] ?? field;
130
+ const tag = root.metadataTag;
131
+ const source = tag?.text("source", "name");
132
+ // A parameterized source would need its arguments spelled; none are read.
133
+ if (
134
+ !source ||
135
+ !tag?.array ||
136
+ tag.array("source", "parameters") !== undefined ||
137
+ // Without the stamp, `drillable` and the codes are Malloy's as written,
138
+ // which name the wrong rows in places.
139
+ tag.has?.(DRILL_METADATA_CORRECTED) !== true
140
+ )
141
+ return undefined;
142
+ const filters: string[] = [];
143
+ // Outermost first, as Malloy applies them; each level's own `where:` and a
144
+ // refinement's are both here, a given (`region ~ $REGION`) included.
145
+ for (const level of [...chain].reverse()) {
146
+ if (call(level.isArray?.bind(level)) !== true) continue;
147
+ // Malloy marks a level `drillable` only when it runs one stage, and
148
+ // Publisher's server corrects the root of a longer pipeline to match:
149
+ // a later stage's dimensions are an earlier stage's outputs, which the
150
+ // source cannot be filtered by.
151
+ if (level.metadataTag?.has?.("drillable") !== true) return undefined;
152
+ for (const filter of level.metadataTag?.array?.("drill_filters") ?? []) {
153
+ const code = filter.text("code");
154
+ if (!code) return undefined;
155
+ filters.push(code);
156
+ }
157
+ }
158
+ const queryName = tag?.text("query_name");
159
+ return {
160
+ source,
161
+ filters,
162
+ ...(queryName && !queryName.startsWith("__") ? { queryName } : {}),
163
+ };
164
+ }
165
+
166
+ /**
167
+ * The dimensions of every level on the way from `field` to the root: the
168
+ * ones a row's values are given for. A level is whatever holds the fields,
169
+ * which for a table row is its repeated record (the root included).
170
+ */
171
+ export function rowDimensionsOf(field: RowsField): RowsField[] {
172
+ const seen = new Set<RowsField>();
173
+ for (const level of ancestors(field))
174
+ for (const child of level.fields ?? [])
175
+ if (isDimension(child)) seen.add(child);
176
+ return [...seen];
177
+ }
178
+
179
+ /**
180
+ * The one zone every time dimension of the row was truncated in: undefined
181
+ * when there are none or they use the default, `null` when they differ. A
182
+ * rows query has one `timezone:`, so a nest whose levels set different zones
183
+ * cannot be filtered by all of its values at once.
184
+ */
185
+ export function rowTimezone(field: RowsField): string | undefined | null {
186
+ const zones = new Set<string | undefined>(
187
+ rowDimensionsOf(field)
188
+ .filter((d) => call(d.isTime?.bind(d)) === true)
189
+ .map((d) => call(d.getEffectiveQueryTimezone?.bind(d))),
190
+ );
191
+ if (zones.size > 1) return null;
192
+ return [...zones][0];
193
+ }
194
+
195
+ /**
196
+ * Whether a click on `field` can open its rows: a dimension, with a target,
197
+ * and every dimension of its row having a code, an expression the renderer
198
+ * reports its value under, and a value a filter can spell, all in one zone.
199
+ * What the affordance asks, so a value reads as clickable exactly when the
200
+ * click can build its query: the renderer reports no row at all when any
201
+ * dimension lacks an expression, and leaves out one whose value it cannot
202
+ * write.
203
+ */
204
+ export function canShowRows(field: RowsField): boolean {
205
+ if (!isDimension(field) || dimensionCode(field) === undefined) return false;
206
+ if (rowsTargetOf(field) === undefined) return false;
207
+ if (rowTimezone(field) === null) return false;
208
+ return rowDimensionsOf(field).every(
209
+ (d) =>
210
+ dimensionCode(d) !== undefined &&
211
+ d.drillStableExpression !== undefined &&
212
+ hasLiteral(d),
213
+ );
214
+ }
215
+
216
+ /**
217
+ * The clicked row's dimensions, each as code with its value, from the
218
+ * renderer's row (`drillClauses`). Undefined unless every dimension of the row
219
+ * is there with a code: never a subset, since dropping a dimension returns
220
+ * rows that are not the row's.
221
+ */
222
+ export function rowsDimensions(
223
+ field: RowsField,
224
+ clauses: readonly DrillClause[],
225
+ ): RowsDimension[] | undefined {
226
+ const row = rowDimensionsOf(field);
227
+ const out: RowsDimension[] = [];
228
+ const seen = new Set<RowsField>();
229
+ for (const clause of clauses) {
230
+ // A level's own filter, if the renderer reported one: it is in the
231
+ // target's filters already, as code.
232
+ if ((clause as { kind?: string }).kind === "drill") continue;
233
+ const { filter } = clause;
234
+ if (filter.kind !== "literal_equality") return undefined;
235
+ const key = JSON.stringify(filter.expression);
236
+ const match = row.find(
237
+ (d) => JSON.stringify(d.drillStableExpression) === key,
238
+ );
239
+ const code = match && dimensionCode(match);
240
+ if (match === undefined || code === undefined) return undefined;
241
+ out.push({ code, value: filter.value });
242
+ seen.add(match);
243
+ }
244
+ return row.every((d) => seen.has(d)) && out.length > 0 ? out : undefined;
245
+ }
@@ -1,10 +1,45 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { act, renderHook } from "@testing-library/react";
5
- import { describe, expect, it, mock } from "bun:test";
4
+ import {
5
+ act,
6
+ cleanup,
7
+ fireEvent,
8
+ render,
9
+ screen,
10
+ } from "@testing-library/react";
11
+ import { afterEach, describe, expect, it, mock } from "bun:test";
6
12
  import type { DrillField, DrillTagReader } from "./resolveDrill";
7
- import { useDrill } from "./useDrill";
13
+ import { DRILL_METADATA_CORRECTED } from "./rowsTarget";
14
+ import {
15
+ useDrill,
16
+ type UseDrillOptions,
17
+ type UseDrillResult,
18
+ } from "./useDrill";
19
+
20
+ afterEach(cleanup);
21
+
22
+ /**
23
+ * The hook mounted with its menu, as a surface renders it: the menu is what
24
+ * every click opens, so a test reads and picks its items the way a reader does.
25
+ */
26
+ function mountDrill(options: UseDrillOptions): { current: UseDrillResult } {
27
+ const ref = {} as { current: UseDrillResult };
28
+ function Host() {
29
+ ref.current = useDrill(options);
30
+ return <>{ref.current.drillMenu}</>;
31
+ }
32
+ render(<Host />);
33
+ return ref;
34
+ }
35
+
36
+ const menuItems = () =>
37
+ screen.queryAllByRole("menuitem").map((item) => item.textContent);
38
+
39
+ const pick = (name: string) =>
40
+ act(() => {
41
+ fireEvent.click(screen.getByRole("menuitem", { name }));
42
+ });
8
43
 
9
44
  const tag = (drill?: { to: string[]; given?: string }): DrillTagReader => ({
10
45
  tag: (...at: string[]) =>
@@ -22,66 +57,175 @@ const dimension = (
22
57
  name: string,
23
58
  drill?: { to: string[]; given?: string },
24
59
  ): DrillField => ({ name, tag: tag(drill), wasDimension: () => true });
60
+ /**
61
+ * A grouped field as the renderer's metadata reports it: its expression as
62
+ * code, under a root that names its source. What a rows query is built from.
63
+ */
64
+ const reported = (name: string, code: string): DrillField => {
65
+ const root = {
66
+ name: "root",
67
+ isArray: () => true,
68
+ metadataTag: {
69
+ text: (...at: string[]) =>
70
+ at.join(".") === "source.name"
71
+ ? "overview"
72
+ : at[0] === "query_name"
73
+ ? "by_cat"
74
+ : undefined,
75
+ array: () => undefined,
76
+ has: (...at: string[]) =>
77
+ ["drillable", DRILL_METADATA_CORRECTED].includes(at.join(".")),
78
+ },
79
+ fields: [] as unknown[],
80
+ };
81
+ const field = {
82
+ name,
83
+ tag: tag(),
84
+ parent: root,
85
+ isBasic: () => true,
86
+ isString: () => true,
87
+ wasDimension: () => true,
88
+ drillStableExpression: { kind: "field_reference", name },
89
+ metadataTag: {
90
+ text: (...at: string[]) =>
91
+ at.join(".") === "drill_expression.code" ? code : undefined,
92
+ array: () => undefined,
93
+ },
94
+ };
95
+ root.fields.push(field);
96
+ return field;
97
+ };
25
98
  const measure = (name: string): DrillField => ({
26
99
  name,
27
100
  tag: tag(),
28
101
  wasDimension: () => false,
29
102
  });
30
103
 
31
- describe("useDrill: the rows behind a value", () => {
32
- it("opens the rows for a grouped value that has no drill, and marks it clickable", () => {
104
+ describe("useDrill: every drillable click opens a menu that says what it does", () => {
105
+ it("offers Show rows alone for a grouped value with no drill, and opens the rows only when picked", () => {
33
106
  const onRows = mock(() => {});
34
- const { result } = renderHook(() => useDrill({ onRows }));
35
- expect(result.current.drill.canDrill(dimension("cat"))).toBe(true);
107
+ const result = mountDrill({ onRows });
108
+ const cat = reported("cat", "products.category");
109
+ expect(result.current.drill.canDrill(cat)).toBe(true);
36
110
  expect(result.current.drill.canDrill(measure("revenue"))).toBe(false);
37
111
  act(() =>
38
112
  result.current.drill.onClick({
39
- field: dimension("cat"),
113
+ field: cat,
40
114
  value: "Jeans",
41
115
  context: "overview -> by_cat",
42
116
  }),
43
117
  );
118
+ expect(onRows).not.toHaveBeenCalled();
119
+ expect(menuItems()).toEqual(["Show rows (cat: Jeans)"]);
120
+ pick("Show rows (cat: Jeans)");
44
121
  expect(onRows).toHaveBeenCalledWith({
45
122
  field: "cat",
46
123
  rawValue: "Jeans",
47
124
  label: "Jeans",
125
+ target: { source: "overview", filters: [], queryName: "by_cat" },
126
+ code: "products.category",
48
127
  context: "overview -> by_cat",
49
128
  });
129
+ expect(menuItems()).toEqual([]);
130
+ });
131
+
132
+ it("marks no dimension the result names no rows for, and opens no menu for it", () => {
133
+ const onRows = mock(() => {});
134
+ const result = mountDrill({ onRows });
135
+ // No source or code in its metadata: nothing to build a query from.
136
+ expect(result.current.drill.canDrill(dimension("cat"))).toBe(false);
137
+ act(() =>
138
+ result.current.drill.onClick({
139
+ field: dimension("cat"),
140
+ value: "Jeans",
141
+ }),
142
+ );
143
+ expect(menuItems()).toEqual([]);
144
+ expect(onRows).not.toHaveBeenCalled();
50
145
  });
51
146
 
52
147
  it("does nothing for a header, a measure, or an empty cell", () => {
53
148
  const onRows = mock(() => {});
54
- const { result } = renderHook(() => useDrill({ onRows }));
149
+ const result = mountDrill({ onRows });
55
150
  act(() => {
56
151
  result.current.drill.onClick({
57
- field: dimension("cat"),
152
+ field: reported("cat", "products.category"),
58
153
  value: "Jeans",
59
154
  isHeader: true,
60
155
  });
61
156
  result.current.drill.onClick({ field: measure("revenue"), value: 3 });
62
157
  result.current.drill.onClick({ field: dimension("cat"), value: null });
63
158
  });
159
+ expect(menuItems()).toEqual([]);
64
160
  expect(onRows).not.toHaveBeenCalled();
65
161
  });
66
162
 
67
- it("leaves a drilled value to its drill: one destination still navigates at once", () => {
163
+ it("offers a to=self drill and the rows side by side, filter first", () => {
68
164
  const onRows = mock(() => {});
69
165
  const onSelf = mock(() => {});
70
- const { result } = renderHook(() => useDrill({ onRows, onSelf }));
166
+ const result = mountDrill({
167
+ onRows,
168
+ onSelf,
169
+ });
170
+ const cat = {
171
+ ...reported("cat", "products.category"),
172
+ tag: tag({ to: ["self"], given: "CATEGORY" }),
173
+ } as DrillField;
71
174
  act(() =>
72
175
  result.current.drill.onClick({
73
- field: dimension("cat", { to: ["self"], given: "CATEGORY" }),
176
+ field: cat,
74
177
  value: "Jeans",
75
178
  context: "overview -> by_cat",
76
179
  }),
77
180
  );
181
+ expect(onSelf).not.toHaveBeenCalled();
182
+ expect(menuItems()).toEqual([
183
+ "Filter to cat: Jeans",
184
+ "Show rows (cat: Jeans)",
185
+ ]);
186
+ pick("Filter to cat: Jeans");
78
187
  expect(onSelf).toHaveBeenCalledWith("CATEGORY", "Jeans");
79
188
  expect(onRows).not.toHaveBeenCalled();
80
189
  });
81
190
 
82
- it("still navigates straight away when rows are not on offer", () => {
191
+ it("lists every report a drill names, self first, and opens the one picked", () => {
83
192
  const onSelf = mock(() => {});
84
- const { result } = renderHook(() => useDrill({ onSelf }));
193
+ const onNavigate = mock(() => {});
194
+ const result = mountDrill({ onSelf, onNavigate });
195
+ act(() =>
196
+ result.current.drill.onClick({
197
+ field: dimension("cat", {
198
+ to: [
199
+ "category-detail",
200
+ "self",
201
+ "brand_review",
202
+ "category-detail",
203
+ ],
204
+ given: "CATEGORY",
205
+ }),
206
+ value: "Jeans",
207
+ }),
208
+ );
209
+ expect(menuItems()).toEqual([
210
+ "Filter to cat: Jeans",
211
+ "Open Category detail (cat: Jeans)",
212
+ "Open Brand review (cat: Jeans)",
213
+ ]);
214
+ pick("Open Brand review (cat: Jeans)");
215
+ expect(onNavigate).toHaveBeenCalledWith(
216
+ {
217
+ path: "brand_review",
218
+ dashboard: "brand_review",
219
+ givens: { CATEGORY: "Jeans" },
220
+ },
221
+ undefined,
222
+ );
223
+ expect(onSelf).not.toHaveBeenCalled();
224
+ });
225
+
226
+ it("still says what one tag action does when rows are not on offer", () => {
227
+ const onSelf = mock(() => {});
228
+ const result = mountDrill({ onSelf });
85
229
  expect(result.current.drill.canDrill(dimension("cat"))).toBe(false);
86
230
  act(() =>
87
231
  result.current.drill.onClick({
@@ -89,6 +233,158 @@ describe("useDrill: the rows behind a value", () => {
89
233
  value: "Jeans",
90
234
  }),
91
235
  );
236
+ expect(onSelf).not.toHaveBeenCalled();
237
+ expect(menuItems()).toEqual(["Filter to cat: Jeans"]);
238
+ pick("Filter to cat: Jeans");
92
239
  expect(onSelf).toHaveBeenCalledWith("CATEGORY", "Jeans");
93
240
  });
241
+
242
+ it("moves focus into the menu, and Escape closes it without acting", async () => {
243
+ const onRows = mock(() => {});
244
+ const result = mountDrill({ onRows });
245
+ act(() =>
246
+ result.current.drill.onClick({
247
+ field: reported("cat", "products.category"),
248
+ value: "Jeans",
249
+ }),
250
+ );
251
+ await act(async () => {
252
+ await new Promise((resolve) => setTimeout(resolve, 0));
253
+ });
254
+ const first = screen.getByRole("menuitem", {
255
+ name: "Show rows (cat: Jeans)",
256
+ });
257
+ expect(document.activeElement).toBe(first);
258
+ act(() => {
259
+ fireEvent.keyDown(first, { key: "Escape" });
260
+ });
261
+ await act(async () => {
262
+ await new Promise((resolve) => setTimeout(resolve, 300));
263
+ });
264
+ expect(menuItems()).toEqual([]);
265
+ expect(onRows).not.toHaveBeenCalled();
266
+ });
267
+
268
+ it("names every value of the row the rows are filtered on, and holds nothing but actions", () => {
269
+ const onRows = mock(() => {});
270
+ const onSelf = mock(() => {});
271
+ const result = mountDrill({
272
+ onRows,
273
+ onSelf,
274
+ });
275
+ // A two-dimension row: the click is on `region`, the row also has `month`.
276
+ const root = {
277
+ name: "root",
278
+ isArray: () => true,
279
+ metadataTag: {
280
+ text: (...at: string[]) =>
281
+ at.join(".") === "source.name" ? "orders" : undefined,
282
+ array: () => undefined,
283
+ has: (...at: string[]) =>
284
+ ["drillable", DRILL_METADATA_CORRECTED].includes(at.join(".")),
285
+ },
286
+ fields: [] as unknown[],
287
+ };
288
+ const rowField = (
289
+ name: string,
290
+ drill?: { to: string[]; given?: string },
291
+ ) => {
292
+ const field = {
293
+ name,
294
+ tag: tag(drill),
295
+ parent: root,
296
+ isBasic: () => true,
297
+ isString: () => true,
298
+ wasDimension: () => true,
299
+ drillStableExpression: { kind: "field_reference", name },
300
+ metadataTag: {
301
+ text: (...at: string[]) =>
302
+ at.join(".") === "drill_expression.code" ? name : undefined,
303
+ array: () => undefined,
304
+ },
305
+ };
306
+ root.fields.push(field);
307
+ return field as unknown as DrillField;
308
+ };
309
+ // Named as its column header reads: a `# label`, else the field name.
310
+ const region = {
311
+ ...(rowField("region", { to: ["self"], given: "REGION" }) as object),
312
+ getLabel: () => "Region",
313
+ } as unknown as DrillField;
314
+ root.fields[0] = region;
315
+ rowField("status");
316
+ const clause = (name: string, value: string) => ({
317
+ filter: {
318
+ kind: "literal_equality" as const,
319
+ expression: { kind: "field_reference" as const, name },
320
+ value: { kind: "string_literal" as const, string_value: value },
321
+ },
322
+ });
323
+ act(() =>
324
+ result.current.drill.onClick({
325
+ field: region,
326
+ value: "West",
327
+ drillClauses: [
328
+ clause("region", "West"),
329
+ clause("status", "Shipped"),
330
+ ],
331
+ }),
332
+ );
333
+ expect(menuItems()).toEqual([
334
+ "Filter to Region: West",
335
+ "Show rows (Region: West, status: Shipped)",
336
+ ]);
337
+ // No header or divider: every child of the menu list is an action.
338
+ const list = screen.getByRole("menu");
339
+ expect(
340
+ Array.from(list.children).every(
341
+ (child) => child.getAttribute("role") === "menuitem",
342
+ ),
343
+ ).toBe(true);
344
+ const rows = screen.getByRole("menuitem", {
345
+ name: "Show rows (Region: West, status: Shipped)",
346
+ });
347
+ expect(rows.getAttribute("title")).toBe(
348
+ "Show rows (Region: West, status: Shipped)",
349
+ );
350
+ });
351
+
352
+ it("names a destination report by its title, and by its file name when it has none", () => {
353
+ const onNavigate = mock(() => {});
354
+ const result = mountDrill({
355
+ onNavigate,
356
+ destinationTitle: (destination) =>
357
+ destination === "regions/deep_dive"
358
+ ? "Regional deep dive"
359
+ : undefined,
360
+ });
361
+ act(() =>
362
+ result.current.drill.onClick({
363
+ field: {
364
+ ...dimension("region", {
365
+ to: ["regions/deep_dive", "brand_review"],
366
+ given: "REGION",
367
+ }),
368
+ getLabel: () => "Region",
369
+ } as DrillField,
370
+ value: "East",
371
+ }),
372
+ );
373
+ expect(menuItems()).toEqual([
374
+ "Open Regional deep dive (Region: East)",
375
+ "Open Brand review (Region: East)",
376
+ ]);
377
+ });
378
+
379
+ it("leaves out a destination this surface cannot honour", () => {
380
+ const onSelf = mock(() => {});
381
+ const result = mountDrill({ onSelf, canSelf: () => false });
382
+ const field = dimension("cat", {
383
+ to: ["self", "detail"],
384
+ given: "CATEGORY",
385
+ });
386
+ expect(result.current.drill.canDrill(field)).toBe(false);
387
+ act(() => result.current.drill.onClick({ field, value: "Jeans" }));
388
+ expect(menuItems()).toEqual([]);
389
+ });
94
390
  });