@malloy-publisher/sdk 0.10.2 → 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 (47) hide show
  1. package/dist/{RenderedResult-BCJC0ZVj.es.js → RenderedResult-B_sW7neX.es.js} +328 -265
  2. package/dist/RenderedResult-BlYdT4lz.cjs.js +179 -0
  3. package/dist/builder/index.cjs.js +1 -1
  4. package/dist/builder/index.es.js +2 -2
  5. package/dist/client/api.d.ts +1 -1
  6. package/dist/components/Dashboard/DashboardView.d.ts +10 -3
  7. package/dist/components/Dashboard/DownloadRowsCsv.d.ts +10 -0
  8. package/dist/components/Dashboard/RowsDialog.d.ts +63 -21
  9. package/dist/components/Dashboard/index.d.ts +2 -0
  10. package/dist/components/Dashboard/rowsCsv.d.ts +26 -0
  11. package/dist/components/RenderedResult/ResultContainer.d.ts +2 -3
  12. package/dist/components/RenderedResult/resultSizing.d.ts +2 -0
  13. package/dist/components/Report/Report.d.ts +8 -1
  14. package/dist/components/drill/drillClauses.d.ts +34 -0
  15. package/dist/components/drill/drillClickRelay.d.ts +36 -0
  16. package/dist/components/drill/resolveDrill.d.ts +29 -0
  17. package/dist/components/drill/rowsTarget.d.ts +114 -0
  18. package/dist/components/drill/useDrill.d.ts +24 -12
  19. package/dist/index.cjs.js +13 -11
  20. package/dist/index.es.js +7331 -6886
  21. package/dist/{useCompiledDocument-C995sQ3j.cjs.js → useCompiledDocument-CyPOSStA.cjs.js} +31 -31
  22. package/dist/{useCompiledDocument-Citpvpnx.es.js → useCompiledDocument-xJRD5DRP.es.js} +1587 -1574
  23. package/dist/utils/malloyString.d.ts +2 -1
  24. package/package.json +1 -1
  25. package/src/components/Dashboard/DashboardView.tsx +54 -28
  26. package/src/components/Dashboard/DownloadRowsCsv.tsx +152 -0
  27. package/src/components/Dashboard/RowsDialog.actions.spec.tsx +250 -0
  28. package/src/components/Dashboard/RowsDialog.drill.compile.spec.ts +672 -0
  29. package/src/components/Dashboard/RowsDialog.spec.ts +38 -11
  30. package/src/components/Dashboard/RowsDialog.tsx +194 -40
  31. package/src/components/Dashboard/index.ts +2 -0
  32. package/src/components/Dashboard/rowsCsv.spec.ts +105 -0
  33. package/src/components/Dashboard/rowsCsv.ts +107 -0
  34. package/src/components/RenderedResult/RenderedResult.tsx +44 -7
  35. package/src/components/RenderedResult/ResultContainer.tsx +2 -2
  36. package/src/components/RenderedResult/resultSizing.ts +3 -0
  37. package/src/components/Report/Report.tsx +9 -0
  38. package/src/components/drill/drillClauses.ts +201 -0
  39. package/src/components/drill/drillClickRelay.spec.ts +122 -0
  40. package/src/components/drill/drillClickRelay.ts +106 -0
  41. package/src/components/drill/resolveDrill.ts +29 -0
  42. package/src/components/drill/rowsTarget.ts +245 -0
  43. package/src/components/drill/useDrill.spec.tsx +311 -15
  44. package/src/components/drill/useDrill.tsx +206 -67
  45. package/src/components/legacy/malloynb/NotebookCell.tsx +0 -7
  46. package/src/utils/malloyString.ts +21 -2
  47. package/dist/RenderedResult-B5f4qOjp.cjs.js +0 -171
@@ -0,0 +1,672 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Result } from "@malloydata/malloy";
5
+ import type * as Malloy from "@malloydata/malloy-interfaces";
6
+ import { act, fireEvent, render, screen } from "@testing-library/react";
7
+ import { createElement, Fragment } from "react";
8
+ import { afterAll, describe, expect, it, setDefaultTimeout } from "bun:test";
9
+ import {
10
+ drillClickRelay,
11
+ reportRowsWithoutFilters,
12
+ } from "../drill/drillClickRelay";
13
+ import type { DrillField, DrillRowsRequest } from "../drill/resolveDrill";
14
+ import {
15
+ useDrill,
16
+ type UseDrillOptions,
17
+ type UseDrillResult,
18
+ } from "../drill/useDrill";
19
+ import {
20
+ rowsQuery,
21
+ ROWS_REFUSAL,
22
+ rowsRequestFor,
23
+ rowsTitleParts,
24
+ } from "./RowsDialog";
25
+ import { withPreamble } from "./textSource";
26
+ import { wrapWithCorrectDrillMetadata } from "../../../../server/src/service/drill_metadata";
27
+
28
+ /**
29
+ * "Show the rows" end to end, with nothing standing in for Malloy: a tile's
30
+ * query runs on DuckDB, the real renderer draws it, every body cell is
31
+ * clicked, and the rows query each click produces is compiled and run.
32
+ *
33
+ * The oracle is the tile's own `sale_count`: the rows behind a row number
34
+ * exactly that many, so a drill that drops a dimension (too many rows), spells
35
+ * a value wrong (none), or fails to compile is caught by the same assertion.
36
+ */
37
+
38
+ setDefaultTimeout(60_000);
39
+
40
+ const MODEL = `
41
+ ##! experimental.givens
42
+ source: quarterly_sales is duckdb.sql("""
43
+ select * from (values
44
+ (DATE '2026-01-15', TIMESTAMP '2026-01-15 10:30:15', 'West', 'Ben & Jerry''s', 10.0, true),
45
+ (DATE '2026-01-15', TIMESTAMP '2026-01-15 10:30:15', 'West', 'Ben & Jerry''s', 4.0, true),
46
+ (DATE '2026-02-03', TIMESTAMP '2026-02-03 23:59:00', 'East', 'O"Brien', 20.0, false),
47
+ (DATE '2026-04-10', TIMESTAMP '2026-04-10 01:00:00', 'West', NULL, 5.0, NULL),
48
+ (DATE '2026-01-20', TIMESTAMP '2026-01-20 12:00:00', NULL, 'back\\slash', 7.0, false),
49
+ (DATE '2026-12-31', TIMESTAMP '2026-12-31 20:15:00', 'East', 'Plain', 3.5, true)
50
+ ) t(sale_date, sold_at, region, product, amount, is_online)
51
+ """) extend {
52
+ dimension: sales_quarter is sale_date.quarter
53
+ measure: total_revenue is amount.sum()
54
+ measure: sale_count is count()
55
+ }
56
+ given: REGION :: filter<string> is f''
57
+ source: sales_tiles is quarterly_sales extend {
58
+ view: quarter_region_table is {
59
+ where: region ~ $REGION
60
+ group_by: sales_quarter, region
61
+ aggregate: total_revenue, sale_count
62
+ order_by: sales_quarter, total_revenue desc
63
+ }
64
+ view: by_region is {
65
+ group_by: region
66
+ aggregate: sale_count
67
+ }
68
+ view: region_hours is {
69
+ group_by: region
70
+ aggregate: sale_count
71
+ nest: by_hour is { group_by: sold_hour is sold_at.hour; aggregate: sale_count }
72
+ }
73
+ view: truncations is {
74
+ group_by:
75
+ y is sold_at.year, q is sold_at.quarter, mo is sold_at.month,
76
+ wk is sold_at.week, d is sold_at.day, h is sold_at.hour,
77
+ mi is sold_at.minute, s is sold_at, sd is sale_date,
78
+ sd_month is sale_date.month, sd_week is sale_date.week
79
+ aggregate: sale_count
80
+ }
81
+ view: tokyo_hours is {
82
+ timezone: 'Asia/Tokyo'
83
+ group_by: tokyo_day is sold_at.day, tokyo_hour is sold_at.hour
84
+ aggregate: sale_count
85
+ }
86
+ view: products is {
87
+ group_by: product, is_online, amount
88
+ aggregate: sale_count
89
+ }
90
+ join_one: owners is duckdb.sql("""
91
+ select * from (values ('West', 'Wanda'), ('East', 'Ed')) t(region_key, owner)
92
+ """) on region = owners.region_key
93
+ view: by_owner is {
94
+ group_by: owners.owner
95
+ aggregate: sale_count
96
+ }
97
+ view: two_stage is {
98
+ group_by: region
99
+ aggregate: sale_count
100
+ } -> { select: region, sale_count }
101
+ join_one: targets is duckdb.sql("""
102
+ select * from (values
103
+ ('West', 60.0, TIMESTAMP '2025-03-01 00:00:00'),
104
+ ('East', 1.0, TIMESTAMP '2024-07-01 00:00:00')
105
+ ) t(region_key, amount, sold_at)
106
+ """) extend {
107
+ dimension: target_big is amount > 50
108
+ dimension: target_year is sold_at.year
109
+ } on region = targets.region_key
110
+ view: by_target is { group_by: targets.target_big, targets.target_year; aggregate: sale_count }
111
+ view: by_month is { group_by: sold_at.month; aggregate: sale_count }
112
+ view: by_date is { group_by: sale_date; aggregate: sale_count }
113
+ view: staged_nest is {
114
+ group_by: region
115
+ aggregate: sale_count
116
+ nest: online is { group_by: is_online; aggregate: sale_count } -> { select: is_online }
117
+ }
118
+ }
119
+ query: online_staged is sales_tiles -> {
120
+ where: is_online = true
121
+ group_by: region
122
+ aggregate: sale_count
123
+ } -> { group_by: region; aggregate: n is count() }
124
+ source: edge_cases is duckdb.sql("""
125
+ select * from (values
126
+ (9007199254740993::BIGINT, TIMESTAMP '2026-01-15 10:30:15.250', 'East', 'line one
127
+ line two', '00000000-0000-0000-0000-000000000001'::UUID),
128
+ (9007199254740992::BIGINT, TIMESTAMP '2026-01-15 10:30:15.750', 'West', 'plain', '00000000-0000-0000-0000-000000000002'::UUID),
129
+ (1::BIGINT, TIMESTAMP '2026-01-16 23:30:00', 'North', 'plain', '00000000-0000-0000-0000-000000000003'::UUID)
130
+ ) t(big_id, seen_at, region, note, uid)
131
+ """) extend {
132
+ dimension: coastal is region = 'East' or region = 'West'
133
+ measure: sale_count is count()
134
+ view: by_id is { group_by: big_id; aggregate: sale_count }
135
+ view: by_at is { group_by: seen_at; aggregate: sale_count }
136
+ view: by_coastal is { group_by: coastal; aggregate: sale_count }
137
+ view: by_note is { group_by: note; aggregate: sale_count }
138
+ view: by_uid is { group_by: uid, region; aggregate: sale_count }
139
+ view: mixed_zone is {
140
+ group_by: d is seen_at.day
141
+ aggregate: sale_count
142
+ nest: tokyo is { timezone: 'Asia/Tokyo'; group_by: h is seen_at.hour; aggregate: sale_count }
143
+ }
144
+ }
145
+ source: \`edge sales\` is edge_cases
146
+ query: online_quarters is sales_tiles -> quarter_region_table + { where: is_online = true }
147
+ query: given_regions is sales_tiles -> by_region + { where: region ~ $REGION }
148
+ `;
149
+
150
+ type Row = Record<string, unknown>;
151
+
152
+ const { SingleConnectionRuntime, API } = await import("@malloydata/malloy");
153
+ const { DuckDBConnection } = await import("@malloydata/db-duckdb");
154
+ // Past any `mock.module("@malloydata/render")` another spec in the run has
155
+ // registered: the query makes this a module of its own.
156
+ const { MalloyRenderer } = (await import(
157
+ `${Bun.resolveSync("@malloydata/render", import.meta.dir)}?real`
158
+ )) as typeof import("@malloydata/render");
159
+ const connection = new DuckDBConnection("duckdb", ":memory:");
160
+ const model = new SingleConnectionRuntime({ connection } as never).loadModel(
161
+ MODEL,
162
+ );
163
+ afterAll(() => connection.close());
164
+
165
+ /** `useDrill` mounted with its menu, as a surface renders it. */
166
+ function mountDrill(options: UseDrillOptions): {
167
+ current: UseDrillResult;
168
+ unmount: () => void;
169
+ } {
170
+ const ref = {} as { current: UseDrillResult; unmount: () => void };
171
+ function Host() {
172
+ ref.current = useDrill(options);
173
+ return createElement(Fragment, null, ref.current.drillMenu);
174
+ }
175
+ ref.unmount = render(createElement(Host)).unmount;
176
+ return ref;
177
+ }
178
+
179
+ async function run(query: string) {
180
+ return model.loadQuery(query).run();
181
+ }
182
+
183
+ /** A result as Publisher's server sends it: drill metadata corrected and stamped. */
184
+ const served = wrapWithCorrectDrillMetadata;
185
+
186
+ /**
187
+ * Every body cell of `tile` clicked, through the same relay and the same
188
+ * per-tile binding the dashboard uses (`bindingFor`), run
189
+ * after `preamble` as a text-source report runs it. Also returns the fields
190
+ * the binding marks clickable, which is what the affordance paints.
191
+ */
192
+ async function clickEveryCell(
193
+ tile: string,
194
+ preamble = "",
195
+ wrap: (result: Result) => Malloy.Result = served,
196
+ ) {
197
+ const result = await run(withPreamble(preamble, `run: ${tile}`));
198
+ const requests: DrillRowsRequest[] = [];
199
+ // Mounted with its menu: every click opens it, and the rows are what the
200
+ // reader gets by picking "Show rows" there.
201
+ const hook = mountDrill({ onRows: (request) => requests.push(request) });
202
+ const binding = hook.current.bindingFor(tile, true);
203
+ const relay = drillClickRelay(binding.onClick);
204
+ const viz = new MalloyRenderer({
205
+ onClick: relay.onClick as never,
206
+ onDrill: relay.onDrill,
207
+ // happy-dom has no layout, so a virtualized table renders no body rows.
208
+ tableConfig: { enableDrill: true, disableVirtualization: true },
209
+ }).createViz();
210
+ viz.setResult(wrap(result));
211
+ // As `RenderedResult` does for a surface with drill wired.
212
+ reportRowsWithoutFilters(viz.getMetadata()?.getRootField() as never);
213
+ const element = document.createElement("div");
214
+ document.body.appendChild(element);
215
+ viz.render(element);
216
+ await new Promise((resolve) => setTimeout(resolve, 300));
217
+ const marked = (viz.getMetadata()?.getAllFields() as unknown as DrillField[])
218
+ .filter((field) => binding.canDrill(field))
219
+ .map((field) => field.name);
220
+ const cells = Array.from(
221
+ element.querySelectorAll<HTMLElement>(".cell-content"),
222
+ );
223
+ for (const cell of cells) {
224
+ await act(async () => {
225
+ cell.click();
226
+ await Promise.resolve();
227
+ });
228
+ const showRows = screen.queryByRole("menuitem", {
229
+ name: /^Show rows \(/,
230
+ });
231
+ if (showRows) {
232
+ act(() => {
233
+ fireEvent.click(showRows);
234
+ });
235
+ }
236
+ }
237
+ hook.unmount();
238
+ viz.remove();
239
+ element.remove();
240
+ return {
241
+ rows: result.data.toObject() as Row[],
242
+ requests,
243
+ marked: [...new Set(marked)],
244
+ tile,
245
+ };
246
+ }
247
+
248
+ /**
249
+ * What each clicked row asks for, one entry per distinct row in table order:
250
+ * the rows query, or the dialog's refusal when there is none.
251
+ */
252
+ function perRow(requests: DrillRowsRequest[]) {
253
+ const seen = new Map<string, { query?: string; refusal?: string }>();
254
+ for (const request of requests) {
255
+ expect(request.drillClauses).toBeDefined();
256
+ const key = JSON.stringify(request.drillClauses);
257
+ if (seen.has(key)) continue;
258
+ const rows = rowsRequestFor(request)!;
259
+ const query = rowsQuery(rows);
260
+ seen.set(key, query ? { query } : { refusal: ROWS_REFUSAL });
261
+ }
262
+ return [...seen.values()];
263
+ }
264
+
265
+ /**
266
+ * Each row's outcome against the tile's own count: its query returns exactly
267
+ * that many rows, a row holding a null included (its filter is `is null`).
268
+ */
269
+ async function expectRowsMatch(
270
+ outcomes: { query?: string; refusal?: string }[],
271
+ counts: unknown[],
272
+ ) {
273
+ expect(outcomes).toHaveLength(counts.length);
274
+ for (const [index, outcome] of outcomes.entries()) {
275
+ expect(outcome.query).toBeDefined();
276
+ const rows = (await run(outcome.query!)).data.toObject();
277
+ expect({ query: outcome.query, count: rows.length }).toEqual({
278
+ query: outcome.query,
279
+ count: counts[index] as number,
280
+ });
281
+ }
282
+ }
283
+
284
+ /** The title's field and value pairs, without the expressions they match by. */
285
+ const titleText = (request: Parameters<typeof rowsTitleParts>[0]) =>
286
+ rowsTitleParts(request).map(({ field, label }) => ({ field, label }));
287
+
288
+ describe("the rows behind a clicked table row, run on DuckDB", () => {
289
+ it("drills a two-dimension table by both dimensions", async () => {
290
+ const { rows, requests } = await clickEveryCell(
291
+ "sales_tiles -> quarter_region_table",
292
+ );
293
+ const outcomes = perRow(requests);
294
+ // The view's own `where:` (a given) and each dimension's expression,
295
+ // the quarter as its first day.
296
+ expect(outcomes[0].query).toBe(
297
+ "run: sales_tiles -> { where: region ~ $REGION, sale_date.quarter = @2026-01-01, region = 'East'; select: *; limit: 200 }",
298
+ );
299
+ await expectRowsMatch(
300
+ outcomes,
301
+ rows.map((r) => r.sale_count),
302
+ );
303
+ // A row with a null region is the rows where it is null.
304
+ expect(outcomes.some((o) => o.query?.includes("region is null"))).toBe(
305
+ true,
306
+ );
307
+ // Two dimension cells per row, and no request from a measure or header.
308
+ expect(requests).toHaveLength(rows.length * 2);
309
+ expect(titleText(rowsRequestFor(requests[0])!)).toEqual([
310
+ { field: "sales_quarter", label: "2026-Q1" },
311
+ { field: "region", label: "East" },
312
+ ]);
313
+ });
314
+
315
+ it("still drills a one-dimension table by its one value", async () => {
316
+ const { rows, requests } = await clickEveryCell(
317
+ "sales_tiles -> by_region",
318
+ );
319
+ const outcomes = perRow(requests);
320
+ expect(outcomes[0].query).toBe(
321
+ "run: sales_tiles -> { where: region = 'West'; select: *; limit: 200 }",
322
+ );
323
+ await expectRowsMatch(
324
+ outcomes,
325
+ rows.map((r) => r.sale_count),
326
+ );
327
+ });
328
+
329
+ it("drills a nested row by its own dimension and every enclosing one", async () => {
330
+ const { rows, requests } = await clickEveryCell(
331
+ "sales_tiles -> region_hours",
332
+ );
333
+ const outcomes = perRow(requests);
334
+ // The hour from the value's own digits: the renderer's text says 00.
335
+ expect(outcomes.map((o) => o.query)).toContain(
336
+ "run: sales_tiles -> { where: region = 'East', sold_at.hour = @2026-02-03 23:00:00; select: *; limit: 200 }",
337
+ );
338
+ await expectRowsMatch(
339
+ outcomes,
340
+ rows.flatMap((r) => [
341
+ r.sale_count,
342
+ ...(r.by_hour as Row[]).map((h) => h.sale_count),
343
+ ]),
344
+ );
345
+ });
346
+
347
+ it("writes every date and timestamp truncation so its rows are found", async () => {
348
+ const { rows, requests } = await clickEveryCell(
349
+ "sales_tiles -> truncations",
350
+ );
351
+ const outcomes = perRow(requests);
352
+ expect(outcomes.map((o) => o.query)).toContain(
353
+ "run: sales_tiles -> { where: sold_at.year = @2026-01-01 00:00:00, sold_at.quarter = @2026-01-01 00:00:00, sold_at.month = @2026-01-01 00:00:00, sold_at.week = @2026-01-11 00:00:00, sold_at.day = @2026-01-15 00:00:00, sold_at.hour = @2026-01-15 10:00:00, sold_at.minute = @2026-01-15 10:30:00, sold_at = @2026-01-15 10:30:15, sale_date = @2026-01-15, sale_date.month = @2026-01-01, sale_date.week = @2026-01-11; select: *; limit: 200 }",
354
+ );
355
+ await expectRowsMatch(
356
+ outcomes,
357
+ rows.map((r) => r.sale_count),
358
+ );
359
+ const titled = requests.find((r) =>
360
+ JSON.stringify(r.drillClauses).includes("2026-01-15T10:30:15"),
361
+ )!;
362
+ expect(titleText(rowsRequestFor(titled)!)).toEqual([
363
+ { field: "y", label: "2026" },
364
+ { field: "q", label: "2026-Q1" },
365
+ { field: "mo", label: "2026-01" },
366
+ { field: "wk", label: "2026-01-11" },
367
+ { field: "d", label: "2026-01-15" },
368
+ { field: "h", label: "2026-01-15 10" },
369
+ { field: "mi", label: "2026-01-15 10:30" },
370
+ { field: "s", label: "2026-01-15 10:30:15" },
371
+ { field: "sd", label: "2026-01-15" },
372
+ { field: "sd_month", label: "2026-01" },
373
+ { field: "sd_week", label: "2026-01-11" },
374
+ ]);
375
+ });
376
+
377
+ it("drills a tile with its own timezone in that zone", async () => {
378
+ const { rows, requests } = await clickEveryCell(
379
+ "sales_tiles -> tokyo_hours",
380
+ );
381
+ const outcomes = perRow(requests);
382
+ // 2026-02-03 23:59 UTC is 08:59 the next morning in Tokyo.
383
+ expect(outcomes.map((o) => o.query)).toContain(
384
+ "run: sales_tiles -> { timezone: 'Asia/Tokyo'; where: sold_at.day = @2026-02-04 00:00:00, sold_at.hour = @2026-02-04 08:00:00; select: *; limit: 200 }",
385
+ );
386
+ await expectRowsMatch(
387
+ outcomes,
388
+ rows.map((r) => r.sale_count),
389
+ );
390
+ });
391
+
392
+ it("quotes strings, and writes numbers and booleans", async () => {
393
+ const { rows, requests } = await clickEveryCell(
394
+ "sales_tiles -> products",
395
+ );
396
+ const outcomes = perRow(requests);
397
+ const queries = outcomes.map((o) => o.query ?? "");
398
+ expect(queries).toContain(
399
+ "run: sales_tiles -> { where: product = 'Ben & Jerry\\'s', is_online = true, amount = 10; select: *; limit: 200 }",
400
+ );
401
+ expect(queries).toContain(
402
+ "run: sales_tiles -> { where: product = 'O\"Brien', is_online = false, amount = 20; select: *; limit: 200 }",
403
+ );
404
+ expect(queries).toContain(
405
+ "run: sales_tiles -> { where: product = 'back\\\\slash', is_online = false, amount = 7; select: *; limit: 200 }",
406
+ );
407
+ await expectRowsMatch(
408
+ outcomes,
409
+ rows.map((r) => r.sale_count),
410
+ );
411
+ });
412
+ });
413
+
414
+ /** Every row's query, one per line, for a shape asserted in any row. */
415
+ const queriesOf = (outcomes: { query?: string }[]) =>
416
+ outcomes.map((o) => o.query ?? "").join("\n");
417
+
418
+ /** One request per distinct row, each run against the tile's own count. */
419
+ async function expectEveryRowMatches(tile: string, preamble = "") {
420
+ const { rows, requests, marked } = await clickEveryCell(tile, preamble);
421
+ const outcomes = perRow(requests).map((o) =>
422
+ o.query ? { query: withPreamble(preamble, o.query) } : o,
423
+ );
424
+ await expectRowsMatch(
425
+ outcomes,
426
+ rows.map((r) => r.sale_count),
427
+ );
428
+ return { outcomes, marked };
429
+ }
430
+
431
+ describe("which tile shapes open the rows behind a value", () => {
432
+ it("a refined tile, its refinement's filter included", async () => {
433
+ const { outcomes, marked } = await expectEveryRowMatches(
434
+ "sales_tiles -> by_region + { where: is_online = true }",
435
+ );
436
+ expect(marked).toEqual(["region"]);
437
+ expect(queriesOf(outcomes)).toContain(
438
+ "where: is_online = true, region = ",
439
+ );
440
+ });
441
+
442
+ it("a tile naming a query, as the report builder writes a filtered tile", async () => {
443
+ const { outcomes } = await expectEveryRowMatches("online_quarters");
444
+ // The view's own filter (a given), then the query's refinement.
445
+ expect(queriesOf(outcomes)).toContain(
446
+ "where: region ~ $REGION, is_online = true, sale_date.quarter = ",
447
+ );
448
+ });
449
+
450
+ it("a tile naming a query whose filter reads a given", async () => {
451
+ const { outcomes } = await expectEveryRowMatches("given_regions");
452
+ expect(queriesOf(outcomes)).toContain(
453
+ "where: region ~ $REGION, region = ",
454
+ );
455
+ });
456
+
457
+ it("an inline tile", async () => {
458
+ await expectEveryRowMatches(
459
+ "sales_tiles -> { group_by: region; aggregate: sale_count }",
460
+ );
461
+ });
462
+
463
+ it("a view grouped by a joined field (malloydata/malloy#3158)", async () => {
464
+ const { outcomes } = await expectEveryRowMatches(
465
+ "sales_tiles -> by_owner",
466
+ );
467
+ expect(outcomes.map((o) => o.query)).toContain(
468
+ "run: sales_tiles -> { where: owners.owner = 'Wanda'; select: *; limit: 200 }",
469
+ );
470
+ });
471
+
472
+ it("a text-source report's tile, its definitions sent ahead of the rows query", async () => {
473
+ const preamble = `source: doc_tiles is sales_tiles extend {
474
+ view: by_product is { where: amount > 4; group_by: product; aggregate: sale_count }
475
+ }`;
476
+ const { outcomes, marked } = await expectEveryRowMatches(
477
+ "doc_tiles -> by_product",
478
+ preamble,
479
+ );
480
+ expect(marked).toEqual(["product"]);
481
+ expect(queriesOf(outcomes)).toContain(
482
+ "run: doc_tiles -> { where: amount > 4, product = ",
483
+ );
484
+ });
485
+
486
+ it("marks nothing for rows on a view of more than one stage", async () => {
487
+ // Its later stage's dimensions are earlier outputs the source cannot be
488
+ // filtered by, so a rows query would fail rather than answer.
489
+ const { requests, marked } = await clickEveryCell(
490
+ "sales_tiles -> two_stage",
491
+ );
492
+ expect(marked).toEqual([]);
493
+ expect(requests).toEqual([]);
494
+ });
495
+
496
+ it("marks nothing for rows on an inline pipeline of more than one stage", async () => {
497
+ // Its first stage's `where:` is not in the result's filters, so a rows
498
+ // query would drop it.
499
+ const { requests, marked } = await clickEveryCell(
500
+ "sales_tiles -> { where: is_online = true; group_by: region; aggregate: sale_count } -> { group_by: region; aggregate: n is count() }",
501
+ );
502
+ expect(marked).toEqual([]);
503
+ expect(requests).toEqual([]);
504
+ });
505
+
506
+ it("marks nothing for rows on a named query of more than one stage", async () => {
507
+ const { requests, marked } = await clickEveryCell("online_staged");
508
+ expect(marked).toEqual([]);
509
+ expect(requests).toEqual([]);
510
+ });
511
+
512
+ it("marks the outer rows of a view whose nest runs two stages, and not the nest's", async () => {
513
+ const { rows, requests, marked } = await clickEveryCell(
514
+ "sales_tiles -> staged_nest",
515
+ );
516
+ expect(marked).toEqual(["region"]);
517
+ await expectRowsMatch(
518
+ perRow(requests),
519
+ rows.map((r) => r.sale_count),
520
+ );
521
+ });
522
+
523
+ it("drills a computed dimension declared in a joined source by its joined name", async () => {
524
+ // Its code is `amount > 50`, which the root source would read as its
525
+ // own `amount`; the server writes `targets.target_big` instead.
526
+ const { outcomes, marked } = await expectEveryRowMatches(
527
+ "sales_tiles -> by_target",
528
+ );
529
+ expect(marked).toEqual(["target_big", "target_year"]);
530
+ expect(queriesOf(outcomes)).toContain(
531
+ "where: targets.target_big = true, targets.target_year = @2025-01-01 00:00:00;",
532
+ );
533
+ });
534
+
535
+ it("drills an unnamed truncation where the result still says which it was", async () => {
536
+ const own = await expectEveryRowMatches(
537
+ "sales_tiles -> { group_by: sold_at.month; aggregate: sale_count }",
538
+ );
539
+ expect(queriesOf(own.outcomes)).toContain(
540
+ "where: sold_at.month = @2026-01-01 00:00:00;",
541
+ );
542
+ const joined = await expectEveryRowMatches(
543
+ "sales_tiles -> { group_by: targets.sold_at.year; aggregate: sale_count }",
544
+ );
545
+ expect(queriesOf(joined.outcomes)).toContain(
546
+ "where: targets.sold_at.year = @2025-01-01 00:00:00;",
547
+ );
548
+ });
549
+
550
+ it("marks nothing for an unnamed truncation in a view, whose truncation the result has lost", async () => {
551
+ const { requests, marked } = await clickEveryCell(
552
+ "sales_tiles -> by_month",
553
+ );
554
+ expect(marked).toEqual([]);
555
+ expect(requests).toEqual([]);
556
+ });
557
+
558
+ it("still drills a plain date column grouped in a view", async () => {
559
+ const { marked } = await expectEveryRowMatches("sales_tiles -> by_date");
560
+ expect(marked).toEqual(["sale_date"]);
561
+ });
562
+
563
+ it("marks nothing for a result from a server that did not correct its metadata", async () => {
564
+ // An older Publisher sends Malloy's metadata as written, with no stamp.
565
+ const { marked } = await clickEveryCell(
566
+ "sales_tiles -> by_region",
567
+ "",
568
+ API.util.wrapResult,
569
+ );
570
+ expect(marked).toEqual([]);
571
+ expect((await clickEveryCell("sales_tiles -> by_region")).marked).toEqual(
572
+ ["region"],
573
+ );
574
+ });
575
+
576
+ it("marks nothing for rows when the host turns rows off for the tile", async () => {
577
+ const result = await run("run: sales_tiles -> by_region");
578
+ const requests: DrillRowsRequest[] = [];
579
+ const hook = mountDrill({ onRows: (request) => requests.push(request) });
580
+ const binding = hook.current.bindingFor(
581
+ "sales_tiles -> by_region",
582
+ false,
583
+ );
584
+ const viz = new MalloyRenderer({}).createViz();
585
+ viz.setResult(served(result));
586
+ const element = document.createElement("div");
587
+ document.body.appendChild(element);
588
+ viz.render(element);
589
+ await new Promise((resolve) => setTimeout(resolve, 300));
590
+ const fields = viz
591
+ .getMetadata()!
592
+ .getAllFields() as unknown as DrillField[];
593
+ expect(fields.filter((field) => binding.canDrill(field))).toEqual([]);
594
+ binding.onClick({
595
+ field: fields.find((f) => f.name === "region")!,
596
+ value: "West",
597
+ });
598
+ await Promise.resolve();
599
+ expect(screen.queryAllByRole("menuitem")).toEqual([]);
600
+ expect(requests).toEqual([]);
601
+ hook.unmount();
602
+ viz.remove();
603
+ element.remove();
604
+ });
605
+ });
606
+
607
+ describe("values and shapes a rows query must spell exactly", () => {
608
+ it("writes a bigint id with its own digits, not a rounded number", async () => {
609
+ const { outcomes } = await expectEveryRowMatches("edge_cases -> by_id");
610
+ expect(queriesOf(outcomes)).toContain("big_id = 9007199254740993;");
611
+ expect(queriesOf(outcomes)).toContain("big_id = 9007199254740992;");
612
+ });
613
+
614
+ it("writes a raw timestamp to its fraction of a second", async () => {
615
+ const { outcomes } = await expectEveryRowMatches("edge_cases -> by_at");
616
+ expect(queriesOf(outcomes)).toContain(
617
+ "seen_at = @2026-01-15 10:30:15.25;",
618
+ );
619
+ expect(queriesOf(outcomes)).toContain(
620
+ "seen_at = @2026-01-15 10:30:15.75;",
621
+ );
622
+ });
623
+
624
+ it("parenthesizes a dimension whose code is an expression", async () => {
625
+ const { outcomes } = await expectEveryRowMatches(
626
+ "edge_cases -> by_coastal",
627
+ );
628
+ expect(queriesOf(outcomes)).toContain(
629
+ "where: (region = 'East' or region = 'West') = false;",
630
+ );
631
+ });
632
+
633
+ it("escapes a line break inside a string value", async () => {
634
+ const { outcomes } = await expectEveryRowMatches("edge_cases -> by_note");
635
+ expect(queriesOf(outcomes)).toContain("note = 'line one\\nline two';");
636
+ });
637
+
638
+ it("back-quotes a source name that cannot stand bare", async () => {
639
+ const { outcomes } = await expectEveryRowMatches("`edge sales` -> by_id");
640
+ expect(queriesOf(outcomes)).toContain("run: `edge sales` -> {");
641
+ });
642
+
643
+ it("marks no column of a row holding a value a filter cannot spell", async () => {
644
+ // The renderer reports no value for a uuid, so no row can be named.
645
+ const { requests, marked } = await clickEveryCell("edge_cases -> by_uid");
646
+ expect(marked).toEqual([]);
647
+ expect(requests).toEqual([]);
648
+ });
649
+
650
+ it("marks no column of a row the renderer reports no clauses for", async () => {
651
+ // An inline expression has no stable expression, so the renderer
652
+ // gives up on the whole row: its cells must not read as clickable.
653
+ const { requests, marked } = await clickEveryCell(
654
+ "sales_tiles -> { group_by: big_amt is amount > 6, region; aggregate: sale_count }",
655
+ );
656
+ expect(marked).toEqual([]);
657
+ expect(requests).toEqual([]);
658
+ });
659
+
660
+ it("marks a nested value only when its row's times share one zone", async () => {
661
+ const { rows, requests, marked } = await clickEveryCell(
662
+ "edge_cases -> mixed_zone",
663
+ );
664
+ // The outer day is in UTC and the nested hour in Tokyo: one rows query
665
+ // has one zone, so the nested row is not offered.
666
+ expect(marked).toEqual(["d"]);
667
+ await expectRowsMatch(
668
+ perRow(requests),
669
+ rows.map((r) => r.sale_count),
670
+ );
671
+ });
672
+ });