@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
@@ -2,6 +2,7 @@
2
2
  * Escape a value for use inside a single-quoted Malloy string literal.
3
3
  *
4
4
  * Backslashes are escaped first, then quotes: doing it the other way round
5
- * would re-escape the backslash that the quote escape introduced.
5
+ * would re-escape the backslash that the quote escape introduced. A raw line
6
+ * break ends the literal, so control characters are written as escapes too.
6
7
  */
7
8
  export declare function escapeMalloyString(value: string): string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@malloy-publisher/sdk",
3
3
  "description": "Malloy Publisher SDK",
4
- "version": "0.10.2",
4
+ "version": "0.10.3",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",
@@ -9,7 +9,6 @@ import { useDocumentControls } from "../../hooks/useDocumentControls";
9
9
  import {
10
10
  useDrill,
11
11
  type DrillBinding,
12
- type DrillClickPayload,
13
12
  type DrillNavigation,
14
13
  type DrillRowsRequest,
15
14
  } from "../drill";
@@ -32,11 +31,18 @@ import {
32
31
  tileHeightPx,
33
32
  } from "./DashboardGrid";
34
33
  import { DashboardTile } from "./DashboardTile";
35
- import { RowsDialog, stepsOf, type RowsRequest } from "./RowsDialog";
34
+ import {
35
+ RowsDialog,
36
+ type RowsActions,
37
+ rowsRequestFor,
38
+ type RowsRequest,
39
+ } from "./RowsDialog";
36
40
  import { useReportEvents } from "../Report/telemetry";
37
41
  import type { TileChrome } from "./TileCard";
38
42
  import { tileIgnoredFilterLabels } from "./TileFilterTag";
39
43
  import { layoutRules } from "../Report/layoutRules";
44
+ import { resolveDrillTarget } from "../Package/documentLocation";
45
+ import { useReportListing } from "../Package/useDocumentLocation";
40
46
  import {
41
47
  ReportHeader,
42
48
  ReportPage,
@@ -82,8 +88,8 @@ export interface DashboardViewProps {
82
88
  controlsLayout?: GivensLayout;
83
89
  /**
84
90
  * Text-source mode: the document's definitions (see `documentPreamble`),
85
- * sent ahead of each tile's `run:` so every query runs as the viewer's own
86
- * text. Rows, which reopens a tile by name, is off in this mode.
91
+ * sent ahead of each tile's `run:`, and of a rows query, so every query
92
+ * runs as the viewer's own text.
87
93
  */
88
94
  preamble?: string;
89
95
  /** Text-source mode: the model the text runs on top of, in place of `manifest.path`. */
@@ -108,6 +114,12 @@ export interface DashboardViewProps {
108
114
  * end of the title's line, where the builder's toolbar sits.
109
115
  */
110
116
  actions?: ReactNode;
117
+ /**
118
+ * The host's actions for the rows behind a clicked value (a download),
119
+ * drawn in the rows dialog's title row. Omitted, the dialog offers its own
120
+ * Download CSV; return `null` for none.
121
+ */
122
+ rowsActions?: RowsActions;
111
123
  }
112
124
 
113
125
  /**
@@ -134,6 +146,7 @@ export function DashboardView({
134
146
  literalReads,
135
147
  onLinkNavigate,
136
148
  actions,
149
+ rowsActions,
137
150
  }: DashboardViewProps) {
138
151
  // Where a relative link in the report's prose resolves from, and how the
139
152
  // host navigates to it. Only a host with a router gets its links resolved:
@@ -220,18 +233,12 @@ export function DashboardView({
220
233
  );
221
234
  }, [manifest, givens, declaredTypes]);
222
235
 
223
- // The rows behind a clicked value: the way past a number. Composite tiles
224
- // only: each names its source, which is what the rows are of.
236
+ // The rows behind a clicked value: the way past a number. What they are
237
+ // rows of, and filtered by, comes from the clicked result's own metadata.
225
238
  const [rows, setRows] = useState<RowsRequest | undefined>(undefined);
226
239
  const onRows = useCallback((request: DrillRowsRequest) => {
227
- const steps = stepsOf(request.context);
228
- if (steps === undefined) return;
229
- setRows({
230
- ...steps,
231
- field: request.field,
232
- rawValue: request.rawValue,
233
- label: request.label,
234
- });
240
+ const next = rowsRequestFor(request);
241
+ if (next !== undefined) setRows(next);
235
242
  }, []);
236
243
 
237
244
  // The whole applied row and any gate givens: a source's own `where:` may read any of it, and a
@@ -245,22 +252,39 @@ export function DashboardView({
245
252
  [applied, declaredTypes, tileHostGivens],
246
253
  );
247
254
 
248
- const { drill, drillMenu } = useDrill({
255
+ // A `to=` entry names its report by title. The listing is the one drill
256
+ // navigation resolves against, so it is usually cached already; read only
257
+ // when a click can navigate.
258
+ const { reports } = useReportListing(
259
+ environmentName,
260
+ packageName,
261
+ versionId,
262
+ onNavigate !== undefined,
263
+ );
264
+ const destinationTitle = useCallback(
265
+ (destination: string) => {
266
+ const target = resolveDrillTarget(destination, reports);
267
+ if (target.kind !== "path") return undefined;
268
+ const path = target.report.path;
269
+ return (
270
+ reports.find((report) => report.path === path)?.title || undefined
271
+ );
272
+ },
273
+ [reports],
274
+ );
275
+ const { bindingFor, drillMenu } = useDrill({
249
276
  onNavigate,
250
277
  onSelf,
251
278
  canSelf,
252
- selfLabel: "Filter this report",
253
- ...(preamble === undefined ? { onRows } : {}),
279
+ onRows,
280
+ destinationTitle,
254
281
  });
255
- // Each tile's clicks carry the tile they came from, so the rows behind a
256
- // value know which source to run against.
282
+ // Each tile's clicks carry the tile they came from. A restricted tile
283
+ // never ran, so it offers no rows.
257
284
  const drillFor = useCallback(
258
- (tile: string): DrillBinding => ({
259
- canDrill: drill.canDrill,
260
- onClick: (payload: DrillClickPayload) =>
261
- drill.onClick({ ...payload, context: tile }),
262
- }),
263
- [drill],
285
+ (tile: string, restricted: boolean | undefined): DrillBinding =>
286
+ bindingFor(tile, restricted !== true),
287
+ [bindingFor],
264
288
  );
265
289
 
266
290
  // The layout decides the arrangement only, as it does in the builder.
@@ -391,7 +415,7 @@ export function DashboardView({
391
415
  tableMaxHeight={tableMaxHeight}
392
416
  fixedHeight={tile.rowspan !== undefined || placed}
393
417
  maxResultSize={maxResultSize}
394
- drill={drillFor(tile.query)}
418
+ drill={drillFor(tile.query, tile.restricted)}
395
419
  ignoredFilters={tileIgnoredFilterLabels(
396
420
  tile.givenNames &&
397
421
  (tile.query && literalReads?.[tile.query]
@@ -429,14 +453,16 @@ export function DashboardView({
429
453
  packageName={packageName}
430
454
  {...(versionId === undefined ? {} : { versionId })}
431
455
  modelPath={modelPath}
456
+ {...(preamble === undefined ? {} : { preamble })}
432
457
  givens={rowsGivens}
458
+ {...(rowsActions === undefined ? {} : { actions: rowsActions })}
433
459
  onClose={() => setRows(undefined)}
434
460
  onDone={(ok, durationMs) => {
435
461
  if (rows)
436
462
  events.emit({
437
463
  type: "report.rows_shown",
438
- source: rows.source,
439
- view: rows.view,
464
+ source: rows.target.source,
465
+ view: rows.target.queryName ?? "",
440
466
  field: rows.field,
441
467
  ok,
442
468
  durationMs,
@@ -0,0 +1,152 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import DownloadIcon from "@mui/icons-material/Download";
5
+ import { Box, Button, Tooltip, Typography } from "@mui/material";
6
+ import type * as Malloy from "@malloydata/malloy-interfaces";
7
+ import { useEffect, useRef, useState } from "react";
8
+ import { useServer } from "../ServerProvider";
9
+ import type { RowsActionsContext } from "./RowsDialog";
10
+ import { resultRecords, resultToCsv, serverCappedAt } from "./rowsCsv";
11
+ import { withPreamble } from "./textSource";
12
+
13
+ const DEFAULT_TIP =
14
+ "Download the rows behind this value as CSV, up to the server's row limit";
15
+
16
+ /**
17
+ * How long a saved file's object URL outlives the click. Revoking it at once
18
+ * can cancel the save in Firefox and Safari; FileSaver.js waits 40 seconds.
19
+ * The timer deliberately outlives the dialog: revoking on close would cancel
20
+ * a save the reader started just before closing it.
21
+ */
22
+ const REVOKE_AFTER_MS = 40_000;
23
+
24
+ /** Hands `text` to the browser as a file named `fileName`. */
25
+ function saveFile(text: string, fileName: string) {
26
+ const url = URL.createObjectURL(
27
+ new Blob([text], { type: "text/csv;charset=utf-8" }),
28
+ );
29
+ const link = document.createElement("a");
30
+ link.href = url;
31
+ link.download = fileName;
32
+ document.body.appendChild(link);
33
+ link.click();
34
+ link.remove();
35
+ setTimeout(() => URL.revokeObjectURL(url), REVOKE_AFTER_MS);
36
+ }
37
+
38
+ /** The server's own message for a failed request, else the error's. */
39
+ function failureMessage(error: unknown): string {
40
+ const response = (error as { response?: { data?: { message?: unknown } } })
41
+ ?.response;
42
+ const message = response?.data?.message;
43
+ if (typeof message === "string" && message !== "") return message;
44
+ return error instanceof Error && error.message !== ""
45
+ ? error.message
46
+ : "The request failed.";
47
+ }
48
+
49
+ /**
50
+ * The rows dialog's own download, for a host that passes no `rowsActions`:
51
+ * runs the rows query with no row limit through the same query endpoint the
52
+ * dialog uses, and saves the result as CSV. The server's own row cap still
53
+ * applies; when the file reached it, the file name and the tooltip say so.
54
+ * A failure is written beside the button, where a keyboard user reaches it,
55
+ * with the server's message. Closing the dialog cancels a download in flight.
56
+ */
57
+ export function DownloadRowsCsv({
58
+ query,
59
+ preamble,
60
+ environmentName,
61
+ packageName,
62
+ modelPath,
63
+ versionId,
64
+ givens,
65
+ fileName,
66
+ }: RowsActionsContext) {
67
+ const { apiClients } = useServer();
68
+ const [busy, setBusy] = useState(false);
69
+ const [tip, setTip] = useState(DEFAULT_TIP);
70
+ const [failure, setFailure] = useState<string | undefined>(undefined);
71
+ const inFlight = useRef<AbortController | undefined>(undefined);
72
+ useEffect(() => () => inFlight.current?.abort(), []);
73
+
74
+ const download = async () => {
75
+ inFlight.current?.abort();
76
+ const controller = new AbortController();
77
+ inFlight.current = controller;
78
+ setBusy(true);
79
+ setFailure(undefined);
80
+ try {
81
+ const response = await apiClients.models.executeQueryModel(
82
+ environmentName,
83
+ packageName,
84
+ modelPath,
85
+ {
86
+ query:
87
+ preamble === undefined
88
+ ? query
89
+ : withPreamble(preamble, query),
90
+ givens,
91
+ versionId,
92
+ },
93
+ undefined,
94
+ { signal: controller.signal },
95
+ );
96
+ if (controller.signal.aborted) return;
97
+ const body = response.data;
98
+ const result = JSON.parse(body.result ?? "{}") as Malloy.Result;
99
+ const capped = serverCappedAt(
100
+ resultRecords(result).length,
101
+ body.queryRowLimit,
102
+ body.queryRowLimitSource,
103
+ );
104
+ setTip(
105
+ capped === undefined
106
+ ? DEFAULT_TIP
107
+ : `First ${capped} rows: the server's row limit, so there may be more`,
108
+ );
109
+ saveFile(
110
+ resultToCsv(result),
111
+ capped === undefined
112
+ ? `${fileName}.csv`
113
+ : `${fileName}_first_${capped}_rows_server_limit.csv`,
114
+ );
115
+ } catch (error) {
116
+ if (controller.signal.aborted) return;
117
+ setFailure(`Download failed: ${failureMessage(error)}`);
118
+ } finally {
119
+ if (inFlight.current === controller) {
120
+ inFlight.current = undefined;
121
+ setBusy(false);
122
+ }
123
+ }
124
+ };
125
+
126
+ return (
127
+ <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
128
+ {failure && (
129
+ <Typography
130
+ role="alert"
131
+ variant="caption"
132
+ color="error"
133
+ sx={{ maxWidth: 320 }}
134
+ >
135
+ {failure}
136
+ </Typography>
137
+ )}
138
+ <Tooltip title={tip}>
139
+ <span>
140
+ <Button
141
+ size="small"
142
+ startIcon={<DownloadIcon fontSize="small" />}
143
+ onClick={() => void download()}
144
+ disabled={busy}
145
+ >
146
+ Download CSV
147
+ </Button>
148
+ </span>
149
+ </Tooltip>
150
+ </Box>
151
+ );
152
+ }
@@ -0,0 +1,250 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * The rows dialog's actions: what a host's `rowsActions` is handed, and the
6
+ * dialog's own Download CSV when a host passes none.
7
+ */
8
+ import { afterEach, beforeEach, expect, it, mock } from "bun:test";
9
+ import {
10
+ act,
11
+ cleanup,
12
+ fireEvent,
13
+ render,
14
+ screen,
15
+ waitFor,
16
+ } from "@testing-library/react";
17
+ import {
18
+ clearCache,
19
+ mockServerProvider,
20
+ pending,
21
+ serverWrapper,
22
+ } from "../../../test/serverProvider";
23
+ import type { RowsActionsContext, RowsRequest } from "./RowsDialog";
24
+
25
+ const executeQueryModel = mock(
26
+ (
27
+ _environmentName: string,
28
+ _packageName: string,
29
+ _modelPath: string,
30
+ _request: {
31
+ query?: string;
32
+ givens?: Record<string, unknown>;
33
+ versionId?: string;
34
+ },
35
+ _includeHidden?: boolean,
36
+ _options?: { signal?: AbortSignal },
37
+ ): Promise<unknown> => pending(),
38
+ );
39
+
40
+ mockServerProvider({ models: { executeQueryModel } });
41
+
42
+ const { RowsDialog, rowsQuery } = await import("./RowsDialog");
43
+ const { withPreamble } = await import("./textSource");
44
+
45
+ const request: RowsRequest = {
46
+ target: { source: "orders", filters: ["region ~ $REGION"] },
47
+ field: "status",
48
+ rawValue: "Complete",
49
+ label: "Complete",
50
+ dimensions: [
51
+ {
52
+ code: "status",
53
+ value: { kind: "string_literal", string_value: "Complete" },
54
+ },
55
+ ],
56
+ drillClauses: [
57
+ {
58
+ filter: {
59
+ kind: "literal_equality",
60
+ expression: { kind: "field_reference", name: "status" },
61
+ value: { kind: "string_literal", string_value: "Complete" },
62
+ },
63
+ },
64
+ ],
65
+ };
66
+
67
+ const givens = { REGION: "West" };
68
+
69
+ beforeEach(() => {
70
+ clearCache();
71
+ executeQueryModel.mockClear();
72
+ });
73
+ afterEach(cleanup);
74
+
75
+ function mount(extra: {
76
+ preamble?: string;
77
+ actions?: (context: RowsActionsContext) => null;
78
+ }) {
79
+ render(
80
+ <RowsDialog
81
+ request={request}
82
+ environmentName="env"
83
+ packageName="pkg"
84
+ versionId="v3"
85
+ modelPath="report.malloy"
86
+ givens={givens}
87
+ onClose={() => {}}
88
+ {...extra}
89
+ />,
90
+ { wrapper: serverWrapper },
91
+ );
92
+ }
93
+
94
+ it("hands a host the rows query with no limit, and the givens the dialog sends", async () => {
95
+ const seen: RowsActionsContext[] = [];
96
+ mount({
97
+ actions: (context) => {
98
+ seen.push(context);
99
+ return null;
100
+ },
101
+ });
102
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
103
+ const context = seen.at(-1)!;
104
+ expect(context.query).toBe(rowsQuery(request, null)!);
105
+ expect(context.query).not.toContain("limit:");
106
+ expect(context.preamble).toBeUndefined();
107
+ const sent = executeQueryModel.mock.calls[0][3];
108
+ // The host's query is the dialog's own, less its limit.
109
+ expect(sent.query).toBe(rowsQuery(request)!);
110
+ expect(context.givens).toEqual(sent.givens!);
111
+ expect(context).toMatchObject({
112
+ environmentName: "env",
113
+ packageName: "pkg",
114
+ modelPath: "report.malloy",
115
+ versionId: "v3",
116
+ fileName: "orders_rows_Complete",
117
+ });
118
+ // A host action replaces the dialog's own download.
119
+ expect(screen.queryByRole("button", { name: /Download CSV/ })).toBeNull();
120
+ });
121
+
122
+ it("hands a host the preamble in text-source mode, apart from the query", async () => {
123
+ const seen: RowsActionsContext[] = [];
124
+ const preamble = "source: orders_tiles is orders extend {}";
125
+ mount({
126
+ preamble,
127
+ actions: (context) => {
128
+ seen.push(context);
129
+ return null;
130
+ },
131
+ });
132
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
133
+ const context = seen.at(-1)!;
134
+ expect(context.preamble).toBe(preamble);
135
+ expect(context.query).toBe(rowsQuery(request, null)!);
136
+ expect(executeQueryModel.mock.calls[0][3].query).toBe(
137
+ withPreamble(preamble, rowsQuery(request)!),
138
+ );
139
+ });
140
+
141
+ it("downloads every row as CSV by default, and says when the server's cap cut it short", async () => {
142
+ const saved: { text: string; name: string }[] = [];
143
+ const blobs = new Map<string, Blob>();
144
+ const originalCreate = URL.createObjectURL;
145
+ const originalRevoke = URL.revokeObjectURL;
146
+ URL.createObjectURL = (blob: Blob) => {
147
+ const url = `blob:${blobs.size}`;
148
+ blobs.set(url, blob);
149
+ return url;
150
+ };
151
+ URL.revokeObjectURL = () => {};
152
+ const originalClick = HTMLAnchorElement.prototype.click;
153
+ HTMLAnchorElement.prototype.click = function (this: HTMLAnchorElement) {
154
+ const blob = blobs.get(this.href)!;
155
+ void blob
156
+ .text()
157
+ .then((text) => saved.push({ text, name: this.download }));
158
+ };
159
+ try {
160
+ mount({});
161
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
162
+ const rows = Array.from({ length: 3 }, () => ({
163
+ kind: "record_cell",
164
+ record_value: [{ kind: "string_cell", string_value: "Complete" }],
165
+ }));
166
+ executeQueryModel.mockImplementationOnce(async () => ({
167
+ data: {
168
+ result: JSON.stringify({
169
+ connection_name: "duckdb",
170
+ schema: {
171
+ fields: [
172
+ {
173
+ kind: "dimension",
174
+ name: "status",
175
+ type: { kind: "string_type" },
176
+ },
177
+ ],
178
+ },
179
+ data: { kind: "array_cell", array_value: rows },
180
+ }),
181
+ queryRowLimit: 3,
182
+ queryRowLimitSource: "server_default",
183
+ },
184
+ }));
185
+ await act(async () => {
186
+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/ }));
187
+ });
188
+ await waitFor(() => expect(saved.length).toBe(1));
189
+ const download = executeQueryModel.mock.calls.at(-1)![3];
190
+ expect(download.query).toBe(rowsQuery(request, null)!);
191
+ expect(download.givens).toEqual(givens);
192
+ expect(download.versionId).toBe("v3");
193
+ expect(saved[0].name).toBe(
194
+ "orders_rows_Complete_first_3_rows_server_limit.csv",
195
+ );
196
+ expect(saved[0].text).toBe(
197
+ "\uFEFFstatus\r\nComplete\r\nComplete\r\nComplete\r\n",
198
+ );
199
+ fireEvent.mouseOver(screen.getByRole("button", { name: /Download CSV/ }));
200
+ expect(
201
+ await screen.findByText(
202
+ "First 3 rows: the server's row limit, so there may be more",
203
+ ),
204
+ ).toBeTruthy();
205
+ } finally {
206
+ URL.createObjectURL = originalCreate;
207
+ URL.revokeObjectURL = originalRevoke;
208
+ HTMLAnchorElement.prototype.click = originalClick;
209
+ }
210
+ });
211
+
212
+ it("says why a download failed, with the server's message, where a keyboard user reaches it", async () => {
213
+ mount({});
214
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
215
+ executeQueryModel.mockImplementationOnce(async () => {
216
+ throw Object.assign(new Error("Request failed with status code 413"), {
217
+ response: {
218
+ data: { message: "The result is over the 1000-row cap." },
219
+ },
220
+ });
221
+ });
222
+ await act(async () => {
223
+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/ }));
224
+ });
225
+ expect((await screen.findByRole("alert")).textContent).toBe(
226
+ "Download failed: The result is over the 1000-row cap.",
227
+ );
228
+ });
229
+
230
+ it("cancels a download in flight when the dialog closes", async () => {
231
+ const { unmount } = render(
232
+ <RowsDialog
233
+ request={request}
234
+ environmentName="env"
235
+ packageName="pkg"
236
+ modelPath="report.malloy"
237
+ givens={givens}
238
+ onClose={() => {}}
239
+ />,
240
+ { wrapper: serverWrapper },
241
+ );
242
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
243
+ await act(async () => {
244
+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/ }));
245
+ });
246
+ const options = executeQueryModel.mock.calls.at(-1)![5];
247
+ expect(options?.signal?.aborted).toBe(false);
248
+ unmount();
249
+ expect(options?.signal?.aborted).toBe(true);
250
+ });