@malloy-publisher/sdk 0.9.11 → 0.9.13

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 (74) hide show
  1. package/README.md +5 -7
  2. package/dist/{RenderedResult-Cmx8sX8d.es.js → RenderedResult-DnBtf-cI.es.js} +2 -2
  3. package/dist/{RenderedResult-BlNoIiSi.cjs.js → RenderedResult-DtQtNV0d.cjs.js} +1 -1
  4. package/dist/ServerProvider-BIFPCzTD.cjs.js +1 -0
  5. package/dist/{ServerProvider-azXLkk1q.es.js → ServerProvider-BV7IoDMR.es.js} +808 -607
  6. package/dist/builder/index.cjs.js +72 -72
  7. package/dist/builder/index.es.js +4156 -4219
  8. package/dist/builder-entry.d.ts +1 -0
  9. package/dist/client/api.d.ts +224 -1
  10. package/dist/client/index.cjs.js +1 -1
  11. package/dist/client/index.es.js +41 -37
  12. package/dist/components/Connections/common.d.ts +11 -3
  13. package/dist/components/Report/telemetry.d.ts +0 -5
  14. package/dist/components/ReportBuilder/BuilderBar.d.ts +1 -1
  15. package/dist/components/ReportBuilder/BuilderToolbar.d.ts +14 -10
  16. package/dist/components/ReportBuilder/EditorSurface.d.ts +1 -2
  17. package/dist/components/ReportBuilder/ReportBuilder.d.ts +3 -10
  18. package/dist/components/ReportBuilder/ReportEditor.d.ts +2 -9
  19. package/dist/components/ReportBuilder/SaveStatus.d.ts +16 -0
  20. package/dist/components/ReportBuilder/TileFrame.d.ts +9 -2
  21. package/dist/components/ReportBuilder/builderControls.d.ts +14 -6
  22. package/dist/components/ReportBuilder/useBuilderSession.d.ts +1 -1
  23. package/dist/components/ReportBuilder/useReportDraft.d.ts +6 -2
  24. package/dist/components/given/GivenInput.d.ts +18 -1
  25. package/dist/components/given/GivensPanel.d.ts +12 -1
  26. package/dist/components/given/useOptionSearch.d.ts +30 -0
  27. package/dist/hooks/index.d.ts +1 -1
  28. package/dist/hooks/useDocumentControls.d.ts +5 -0
  29. package/dist/hooks/useGivensState.d.ts +7 -0
  30. package/dist/hooks/useSuggestOptions.d.ts +60 -4
  31. package/dist/index.cjs.js +9 -9
  32. package/dist/index.es.js +2541 -2400
  33. package/dist/{useCompiledDocument-7j5cBjQd.es.js → useCompiledDocument-B4QF1mIl.es.js} +6912 -6759
  34. package/dist/useCompiledDocument-D0OAMejE.cjs.js +142 -0
  35. package/package.json +1 -1
  36. package/src/builder-entry.ts +1 -0
  37. package/src/components/Connections/AddConnectionDialog.tsx +34 -2
  38. package/src/components/Connections/EditConnectionDialog.tsx +45 -3
  39. package/src/components/Connections/common.spec.ts +69 -0
  40. package/src/components/Connections/common.ts +132 -0
  41. package/src/components/Environment/Connections.tsx +1 -0
  42. package/src/components/Report/ReportPage.tsx +5 -1
  43. package/src/components/Report/telemetry.ts +0 -6
  44. package/src/components/ReportBuilder/AddTileDialog.tsx +2 -2
  45. package/src/components/ReportBuilder/BuilderBar.tsx +5 -256
  46. package/src/components/ReportBuilder/BuilderHeader.tsx +9 -3
  47. package/src/components/ReportBuilder/BuilderToolbar.tsx +15 -38
  48. package/src/components/ReportBuilder/EditorSurface.tsx +0 -3
  49. package/src/components/ReportBuilder/FilterDialog.tsx +1 -1
  50. package/src/components/ReportBuilder/ReportBuilder.controls.spec.tsx +210 -24
  51. package/src/components/ReportBuilder/ReportBuilder.tsx +43 -85
  52. package/src/components/ReportBuilder/ReportEditor.package.spec.tsx +0 -36
  53. package/src/components/ReportBuilder/ReportEditor.tsx +2 -13
  54. package/src/components/ReportBuilder/SaveStatus.tsx +271 -0
  55. package/src/components/ReportBuilder/TileFrame.spec.ts +34 -0
  56. package/src/components/ReportBuilder/TileFrame.tsx +10 -3
  57. package/src/components/ReportBuilder/builderControls.ts +39 -13
  58. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  59. package/src/components/ReportBuilder/useReportDraft.ts +38 -4
  60. package/src/components/given/GivenInput.tsx +219 -104
  61. package/src/components/given/GivensPanel.spec.tsx +19 -0
  62. package/src/components/given/GivensPanel.tsx +31 -1
  63. package/src/components/given/useOptionSearch.spec.tsx +218 -0
  64. package/src/components/given/useOptionSearch.ts +100 -0
  65. package/src/hooks/index.ts +5 -1
  66. package/src/hooks/useDocumentControls.ts +12 -1
  67. package/src/hooks/useGivensState.spec.ts +54 -0
  68. package/src/hooks/useGivensState.ts +21 -1
  69. package/src/hooks/useSuggestOptions.dom.spec.ts +125 -4
  70. package/src/hooks/useSuggestOptions.spec.ts +73 -2
  71. package/src/hooks/useSuggestOptions.ts +234 -62
  72. package/dist/ServerProvider-BOgiW8MX.cjs.js +0 -1
  73. package/dist/useCompiledDocument-B21sVbb4.cjs.js +0 -141
  74. package/src/components/ReportBuilder/ReportBuilder.layoutSwitch.spec.tsx +0 -145
@@ -0,0 +1,218 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
5
+ import {
6
+ act,
7
+ fireEvent,
8
+ render,
9
+ renderHook,
10
+ screen,
11
+ waitFor,
12
+ } from "@testing-library/react";
13
+ import { describe, expect, it, mock } from "bun:test";
14
+ import type { ReactNode } from "react";
15
+ import type { OptionPage, OptionSearch } from "../../hooks/useSuggestOptions";
16
+ import { encodeFilterList } from "./filterValue";
17
+ import { GivenInput } from "./GivenInput";
18
+ import { useOptionSearch } from "./useOptionSearch";
19
+
20
+ const withClient = () => {
21
+ const client = new QueryClient({
22
+ defaultOptions: { queries: { retry: false } },
23
+ });
24
+ function Wrapper({ children }: { children: ReactNode }) {
25
+ return (
26
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
27
+ );
28
+ }
29
+ return Wrapper;
30
+ };
31
+
32
+ /** A search whose answers the test releases, one text at a time and in any order. */
33
+ const controlledSearch = () => {
34
+ const waiting = new Map<string, (page: OptionPage) => void>();
35
+ const run = mock(
36
+ (text: string) =>
37
+ new Promise<OptionPage>((resolve) => waiting.set(text, resolve)),
38
+ );
39
+ const search: OptionSearch = { key: ["givenSuggestSearch", "MAKER"], run };
40
+ const answer = (text: string, values: string[]) =>
41
+ act(() => waiting.get(text)?.({ values, truncated: false }));
42
+ return { search, run, answer };
43
+ };
44
+
45
+ describe("useOptionSearch", () => {
46
+ it("asks nothing without a search: a list that fits filters in the browser", async () => {
47
+ const { result } = renderHook(() => useOptionSearch(undefined, "gen"), {
48
+ wrapper: withClient(),
49
+ });
50
+ await new Promise((resolve) => setTimeout(resolve, 300));
51
+ expect(result.current).toEqual({
52
+ active: false,
53
+ searching: false,
54
+ page: undefined,
55
+ failed: false,
56
+ });
57
+ });
58
+
59
+ it("waits for typing to pause, then asks once for what is typed", async () => {
60
+ const { search, run } = controlledSearch();
61
+ const { rerender } = renderHook(
62
+ ({ typed }) => useOptionSearch(search, typed),
63
+ { initialProps: { typed: "g" }, wrapper: withClient() },
64
+ );
65
+ rerender({ typed: "ge" });
66
+ rerender({ typed: "gen" });
67
+ await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
68
+ expect(run.mock.calls[0][0]).toBe("gen");
69
+ });
70
+
71
+ it("never shows an older text's answer over a newer one's, whichever lands first", async () => {
72
+ const { search, run, answer } = controlledSearch();
73
+ const { result, rerender } = renderHook(
74
+ ({ typed }) => useOptionSearch(search, typed),
75
+ { initialProps: { typed: "gen" }, wrapper: withClient() },
76
+ );
77
+ await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
78
+ rerender({ typed: "general" });
79
+ await waitFor(() => expect(run).toHaveBeenCalledTimes(2));
80
+ expect(result.current.searching).toBe(true);
81
+
82
+ // The newer answer lands first, then the older one, late.
83
+ await answer("general", ["General Motors, LLC"]);
84
+ await waitFor(() =>
85
+ expect(result.current.page?.values).toEqual(["General Motors, LLC"]),
86
+ );
87
+ await answer("gen", ["Genesis", "General Motors, LLC"]);
88
+ await new Promise((resolve) => setTimeout(resolve, 20));
89
+ expect(result.current.page?.values).toEqual(["General Motors, LLC"]);
90
+ expect(result.current.searching).toBe(false);
91
+ });
92
+
93
+ it("reuses a text's answer when the reader types back to it", async () => {
94
+ const { search, run, answer } = controlledSearch();
95
+ const { result, rerender } = renderHook(
96
+ ({ typed }) => useOptionSearch(search, typed),
97
+ { initialProps: { typed: "gen" }, wrapper: withClient() },
98
+ );
99
+ await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
100
+ await answer("gen", ["Genesis"]);
101
+ rerender({ typed: "gene" });
102
+ await waitFor(() => expect(run).toHaveBeenCalledTimes(2));
103
+ rerender({ typed: "gen" });
104
+ await waitFor(() =>
105
+ expect(result.current.page?.values).toEqual(["Genesis"]),
106
+ );
107
+ expect(run).toHaveBeenCalledTimes(2);
108
+ });
109
+ });
110
+
111
+ describe("GivenInput over a cut-off list", () => {
112
+ const MAKER = {
113
+ name: "MAKER",
114
+ type: "filter<string>",
115
+ control: "select" as const,
116
+ label: "Manufacturer",
117
+ };
118
+ // The first thousand, alphabetically: "General Motors, LLC" is not among them.
119
+ const firstThousand = Array.from(
120
+ { length: 1000 },
121
+ (_, i) => `A${String(i).padStart(4, "0")}`,
122
+ );
123
+
124
+ it("finds a value past the cutoff by searching the server, and picking it filters by it", async () => {
125
+ const run = mock(async (text: string) => ({
126
+ values: text.toLowerCase().includes("general")
127
+ ? ["General Motors, LLC"]
128
+ : [],
129
+ truncated: false,
130
+ }));
131
+ const onChange = mock((_next: unknown) => {});
132
+ const Wrapper = withClient();
133
+ render(
134
+ <Wrapper>
135
+ <GivenInput
136
+ given={MAKER}
137
+ value={undefined}
138
+ onChange={onChange}
139
+ options={firstThousand}
140
+ optionsTruncated
141
+ optionSearch={{ key: ["givenSuggestSearch", "MAKER"], run }}
142
+ />
143
+ </Wrapper>,
144
+ );
145
+ const box = screen.getByRole("combobox", { name: "Manufacturer" });
146
+ fireEvent.focus(box);
147
+ fireEvent.change(box, { target: { value: "General Motors" } });
148
+
149
+ const option = await screen.findByRole("option", {
150
+ name: "General Motors, LLC",
151
+ });
152
+ expect(run.mock.calls.at(-1)?.[0]).toBe("General Motors");
153
+ fireEvent.click(option);
154
+ // The filter that matches exactly that value, as the control row sends it.
155
+ expect(onChange).toHaveBeenCalledWith(
156
+ encodeFilterList(["General Motors, LLC"]),
157
+ );
158
+ });
159
+
160
+ it("says the list is partial before anything is typed", async () => {
161
+ const Wrapper = withClient();
162
+ render(
163
+ <Wrapper>
164
+ <GivenInput
165
+ given={MAKER}
166
+ value={undefined}
167
+ onChange={() => {}}
168
+ options={firstThousand}
169
+ optionsTruncated
170
+ optionSearch={{
171
+ key: ["givenSuggestSearch", "MAKER"],
172
+ run: async () => ({ values: [], truncated: false }),
173
+ }}
174
+ />
175
+ </Wrapper>,
176
+ );
177
+ fireEvent.mouseDown(
178
+ screen.getByRole("combobox", { name: "Manufacturer" }),
179
+ );
180
+ expect((await screen.findByRole("note")).textContent).toBe(
181
+ "Showing the first 1,000 values. Type to search them all.",
182
+ );
183
+ });
184
+
185
+ it("for a named query, filters what it has and says a value can still be typed", async () => {
186
+ render(
187
+ <GivenInput
188
+ given={MAKER}
189
+ value={undefined}
190
+ onChange={() => {}}
191
+ options={firstThousand}
192
+ optionsTruncated
193
+ />,
194
+ );
195
+ fireEvent.mouseDown(
196
+ screen.getByRole("combobox", { name: "Manufacturer" }),
197
+ );
198
+ expect((await screen.findByRole("note")).textContent).toBe(
199
+ "Showing the first 1,000 values. A value not listed can still be typed.",
200
+ );
201
+ });
202
+
203
+ it("adds no footnote to a list that is whole", async () => {
204
+ render(
205
+ <GivenInput
206
+ given={MAKER}
207
+ value={undefined}
208
+ onChange={() => {}}
209
+ options={["Ford", "General Motors, LLC"]}
210
+ />,
211
+ );
212
+ fireEvent.mouseDown(
213
+ screen.getByRole("combobox", { name: "Manufacturer" }),
214
+ );
215
+ await screen.findByRole("option", { name: "Ford" });
216
+ expect(screen.queryByRole("note")).toBeNull();
217
+ });
218
+ });
@@ -0,0 +1,100 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { QueryClientContext } from "@tanstack/react-query";
5
+ import { useContext, useEffect, useState } from "react";
6
+ import type { OptionPage, OptionSearch } from "../../hooks/useSuggestOptions";
7
+
8
+ /** How long typing has to pause before the server is asked. */
9
+ export const OPTION_SEARCH_DEBOUNCE_MS = 250;
10
+
11
+ /** How long a search's answer is reused for the same text: option lists change with the data, not the page. */
12
+ const SEARCH_STALE_MS = 5 * 60 * 1000;
13
+
14
+ export interface OptionSearchState {
15
+ /** Text is typed and the list is cut off, so what is offered comes from the server. */
16
+ active: boolean;
17
+ /** Waiting on the server for the text as it is now: still debouncing, or in flight. */
18
+ searching: boolean;
19
+ /** The server's answer for exactly the text as it is now. Undefined until it has one. */
20
+ page: OptionPage | undefined;
21
+ /** The search for the text as it is now failed. */
22
+ failed: boolean;
23
+ }
24
+
25
+ /**
26
+ * Search a cut-off option list on the server as the reader types.
27
+ *
28
+ * Without `search` (a list that was not cut off, or a named query that cannot
29
+ * be searched) this is inert and sends nothing: the picker filters the list it
30
+ * has in the browser, as before.
31
+ *
32
+ * Each search is cached under the suggest's key plus the text, in the page's
33
+ * query client, so typing back to an earlier text reuses its answer. An answer
34
+ * is shown only for the text it was asked for: one arriving after the reader
35
+ * has typed on is dropped, never shown over the newer text's.
36
+ *
37
+ * Reads the query client from context rather than requiring one: a picker
38
+ * rendered outside a provider (a test, a host without react-query) has no
39
+ * cache, and gets no server search rather than an error.
40
+ */
41
+ export function useOptionSearch(
42
+ search: OptionSearch | undefined,
43
+ typed: string,
44
+ ): OptionSearchState {
45
+ const client = useContext(QueryClientContext);
46
+ const text = typed.trim();
47
+ // Empty at first, so even the first text waits for typing to pause.
48
+ const [debounced, setDebounced] = useState("");
49
+ useEffect(() => {
50
+ const timer = setTimeout(
51
+ () => setDebounced(text),
52
+ OPTION_SEARCH_DEBOUNCE_MS,
53
+ );
54
+ return () => clearTimeout(timer);
55
+ }, [text]);
56
+
57
+ const [answer, setAnswer] = useState<{
58
+ key: string;
59
+ text: string;
60
+ page?: OptionPage;
61
+ failed?: boolean;
62
+ }>();
63
+ const keyText = search ? JSON.stringify(search.key) : undefined;
64
+ useEffect(() => {
65
+ if (!search || !client || debounced === "") return;
66
+ let current = true;
67
+ client
68
+ .fetchQuery({
69
+ queryKey: [...search.key, debounced],
70
+ queryFn: ({ signal }) => search.run(debounced, signal),
71
+ staleTime: SEARCH_STALE_MS,
72
+ })
73
+ .then((page) => {
74
+ if (current) setAnswer({ key: keyText!, text: debounced, page });
75
+ })
76
+ .catch(() => {
77
+ if (current)
78
+ setAnswer({ key: keyText!, text: debounced, failed: true });
79
+ });
80
+ // A newer text, or another suggest, makes this answer stale: it is
81
+ // dropped when it lands rather than shown over the newer one's.
82
+ return () => {
83
+ current = false;
84
+ };
85
+ // `keyText` stands for `search`, whose object identity is not the point.
86
+ // eslint-disable-next-line react-hooks/exhaustive-deps
87
+ }, [client, keyText, debounced]);
88
+
89
+ const active = search !== undefined && client !== undefined && text !== "";
90
+ // For this suggest and exactly this text: an answer for another control's
91
+ // list, or for what was typed a moment ago, is not this one's.
92
+ const answered =
93
+ answer !== undefined && answer.key === keyText && answer.text === text;
94
+ return {
95
+ active,
96
+ searching: active && !answered,
97
+ page: active && answered ? answer.page : undefined,
98
+ failed: active && answered && answer.failed === true,
99
+ };
100
+ }
@@ -42,7 +42,11 @@ export {
42
42
  type UseGivensStateOptions,
43
43
  type UseGivensStateResult,
44
44
  } from "./useGivensState";
45
- export { useSuggestOptions } from "./useSuggestOptions";
45
+ export {
46
+ type OptionPage,
47
+ type OptionSearch,
48
+ useSuggestOptions,
49
+ } from "./useSuggestOptions";
46
50
  export {
47
51
  useCompiledDocument,
48
52
  type CompiledDocumentSpec,
@@ -7,7 +7,7 @@ import type { HostGivenValue } from "./givenValue";
7
7
  import { useDrillSelf } from "../components/drill/useDrillSelf";
8
8
  import type { GivensPanelProps } from "../components/given/GivensPanel";
9
9
  import { useGivensState, type UseGivensStateResult } from "./useGivensState";
10
- import { useSuggestOptions } from "./useSuggestOptions";
10
+ import { type OptionSearch, useSuggestOptions } from "./useSuggestOptions";
11
11
 
12
12
  /**
13
13
  * Everything a document's control row needs, from what the document declares.
@@ -76,6 +76,10 @@ export interface DocumentControls extends UseGivensStateResult {
76
76
  options: Map<string, string[]>;
77
77
  optionsLoading: boolean;
78
78
  optionsFailed: ReadonlySet<string>;
79
+ /** Givens whose option list was cut off; see `useSuggestOptions`. */
80
+ optionsTruncated: ReadonlySet<string>;
81
+ /** Server search for a truncated list, per given. */
82
+ optionSearch: ReadonlyMap<string, OptionSearch>;
79
83
  /** For `useDrill`: whether a `to=self` on this given can be honoured. */
80
84
  canSelf: (given: string) => boolean;
81
85
  /** For `useDrill`: set the given to the clicked value, encoded for its type. */
@@ -136,6 +140,8 @@ export function useDocumentControls({
136
140
  options,
137
141
  isLoading: optionsLoading,
138
142
  failed: optionsFailed,
143
+ truncated: optionsTruncated,
144
+ search: optionSearch,
139
145
  } = useSuggestOptions(
140
146
  environmentName,
141
147
  packageName,
@@ -163,6 +169,8 @@ export function useDocumentControls({
163
169
  options,
164
170
  optionsLoading,
165
171
  optionsFailed,
172
+ optionsTruncated,
173
+ optionSearch,
166
174
  canSelf,
167
175
  onSelf,
168
176
  panel: {
@@ -170,9 +178,12 @@ export function useDocumentControls({
170
178
  values: state.draft,
171
179
  onChange: state.setGiven,
172
180
  onReset: state.reset,
181
+ canReset: !state.atStart,
173
182
  options,
174
183
  optionsLoading,
175
184
  optionsFailed,
185
+ optionsTruncated,
186
+ optionSearch,
176
187
  // Absent means autorun; only an explicit `false` batches behind Apply.
177
188
  apply: autorun
178
189
  ? undefined
@@ -290,6 +290,60 @@ describe("useGivensState: Reset", () => {
290
290
  });
291
291
  });
292
292
 
293
+ describe("useGivensState: atStart, whether Reset would change anything", () => {
294
+ it("is true on a document's own starting value, so Reset is not offered for it", () => {
295
+ // Was: Reset was offered whenever a value was set, so a report saving
296
+ // REGION="West" showed Reset beside West, and pressing it set West.
297
+ const host = renderWithUrlHost({
298
+ autorun: true,
299
+ startingValues: { REGION: "West" },
300
+ });
301
+ expect(entries(host.current.applied)).toEqual({ REGION: "West" });
302
+ expect(host.current.atStart).toBe(true);
303
+ });
304
+
305
+ it("is false once a control moves off the start, and true again after Reset", () => {
306
+ const host = renderWithUrlHost({
307
+ autorun: true,
308
+ startingValues: { REGION: "West" },
309
+ });
310
+ act(() => host.current.setGiven("REGION", "Northeast"));
311
+ host.settle();
312
+ expect(host.current.atStart).toBe(false);
313
+
314
+ act(() => host.current.reset());
315
+ host.settle();
316
+ expect(host.current.atStart).toBe(true);
317
+ });
318
+
319
+ it("is false when a cleared starting value leaves the control empty", () => {
320
+ const host = renderWithUrlHost({
321
+ autorun: true,
322
+ startingValues: { REGION: "West" },
323
+ });
324
+ act(() => host.current.setGiven("REGION", null));
325
+ host.settle();
326
+ expect(host.current.atStart).toBe(false);
327
+ });
328
+
329
+ it("is false for a value a link carries over the start", () => {
330
+ const host = renderWithUrlHost({
331
+ autorun: true,
332
+ startingValues: { REGION: "West" },
333
+ initialUrl: { REGION: "Northeast" },
334
+ });
335
+ expect(host.current.atStart).toBe(false);
336
+ });
337
+
338
+ it("is false while a change waits on Apply, since Reset would drop it", () => {
339
+ const host = renderWithUrlHost({ autorun: false });
340
+ expect(host.current.atStart).toBe(true);
341
+ act(() => host.current.setGiven("REGION", "Northeast"));
342
+ host.settle();
343
+ expect(host.current.atStart).toBe(false);
344
+ });
345
+ });
346
+
293
347
  describe("useGivensState: settling", () => {
294
348
  it("stops reporting once the host echoes the values back", () => {
295
349
  // The hook reports applied values out for the host to put in the URL,
@@ -67,6 +67,13 @@ export interface UseGivensStateResult {
67
67
  apply: () => void;
68
68
  /** Whether the draft differs from what is applied. */
69
69
  pending: boolean;
70
+ /**
71
+ * Whether the controls, shown and applied, are already where Reset would
72
+ * put them. A surface offers Reset only when this is false: a report that
73
+ * saves a starting value showed Reset beside it, and pressing it set the
74
+ * controls to what they already were, so the button looked broken.
75
+ */
76
+ atStart: boolean;
70
77
  }
71
78
 
72
79
  /**
@@ -431,5 +438,18 @@ export function useGivensState({
431
438
  return false;
432
439
  }, [autorun, draft, applied]);
433
440
 
434
- return { draft, applied, setGiven, reset, apply, pending };
441
+ // Compared as the URL would carry them, so a date and its encoding, or a
442
+ // list and its spelling, count as the same value.
443
+ const atStart = useMemo(() => {
444
+ const start = givensToParams(
445
+ prune(startingPoint, declaredTypes),
446
+ declaredTypes,
447
+ );
448
+ return (
449
+ sameParams(givensToParams(draft, declaredTypes), start) &&
450
+ sameParams(appliedParams, start)
451
+ );
452
+ }, [startingPoint, draft, appliedParams, declaredTypes]);
453
+
454
+ return { draft, applied, setGiven, reset, apply, pending, atStart };
435
455
  }
@@ -8,7 +8,7 @@
8
8
  * run before the hook is imported, and a static import there would hoist above
9
9
  * it.
10
10
  */
11
- import { beforeEach, expect, it, mock } from "bun:test";
11
+ import { beforeEach, describe, expect, it, mock } from "bun:test";
12
12
  import { renderHook, waitFor } from "@testing-library/react";
13
13
  import {
14
14
  cacheKeys,
@@ -30,9 +30,8 @@ const executeQueryModel = mock(
30
30
 
31
31
  mockServerProvider({ models: { executeQueryModel } });
32
32
 
33
- const { buildSuggestQuery, useSuggestOptions } = await import(
34
- "./useSuggestOptions"
35
- );
33
+ const { buildSuggestQuery, SUGGEST_OPTION_LIMIT, useSuggestOptions } =
34
+ await import("./useSuggestOptions");
36
35
 
37
36
  const SPECS: Given[] = [
38
37
  {
@@ -187,3 +186,125 @@ it("runs a suggest as the document's definitions plus one run:, by name or by di
187
186
  "source: a is orders\n\nrun: brands",
188
187
  ]);
189
188
  });
189
+
190
+ describe("a list cut off at the limit", () => {
191
+ /** `n` distinct values for one column, `Value 0001` … in order. */
192
+ const rows = (column: string, n: number) =>
193
+ JSON.stringify(
194
+ Array.from({ length: n }, (_, i) => ({
195
+ [column]: `Value ${String(i).padStart(4, "0")}`,
196
+ })),
197
+ );
198
+ const answer = (result: string) =>
199
+ Promise.resolve({ data: { result } }) as never;
200
+ const MANUFACTURER: Given[] = [
201
+ {
202
+ name: "MAKER",
203
+ control: "select",
204
+ suggest: { source: "recalls", dimension: "manufacturer" },
205
+ },
206
+ ];
207
+ const render = (specs: Given[], preamble?: string) =>
208
+ renderHook(
209
+ () =>
210
+ useSuggestOptions(
211
+ "env",
212
+ "pkg",
213
+ "README.malloy",
214
+ specs,
215
+ undefined,
216
+ undefined,
217
+ preamble,
218
+ ),
219
+ { wrapper: serverWrapper },
220
+ );
221
+
222
+ it("is flagged, and its search finds a value past the cutoff on the server", async () => {
223
+ executeQueryModel.mockImplementation((_e, _p, _m, request) => {
224
+ const query = (request as { query?: string }).query ?? "";
225
+ return answer(
226
+ query.includes("where:")
227
+ ? JSON.stringify([{ manufacturer: "General Motors, LLC" }])
228
+ : rows("manufacturer", SUGGEST_OPTION_LIMIT + 1),
229
+ );
230
+ });
231
+ const { result } = render(MANUFACTURER);
232
+ await waitFor(() =>
233
+ expect(result.current.truncated.has("MAKER")).toBe(true),
234
+ );
235
+ // The page holds the limit, not the extra row that proved it was cut off.
236
+ expect(result.current.options.get("MAKER")).toHaveLength(
237
+ SUGGEST_OPTION_LIMIT,
238
+ );
239
+ const search = result.current.search.get("MAKER");
240
+ expect(search).toBeDefined();
241
+
242
+ const page = await search!.run("General Motors");
243
+ expect(page.values).toEqual(["General Motors, LLC"]);
244
+ const sent = (
245
+ executeQueryModel.mock.calls.at(-1)?.[3] as { query: string }
246
+ ).query;
247
+ expect(sent).toBe(
248
+ buildSuggestQuery("recalls", "manufacturer", "General Motors"),
249
+ );
250
+ expect(sent).toContain(
251
+ "where: strpos(lower(manufacturer::string), 'general motors') > 0",
252
+ );
253
+ expect(search!.key[0]).toBe("givenSuggestSearch");
254
+ executeQueryModel.mockImplementation(() => pending());
255
+ });
256
+
257
+ it("is not, when the list fits: no search, and no request past the first", async () => {
258
+ executeQueryModel.mockImplementation(() =>
259
+ answer(rows("manufacturer", 3)),
260
+ );
261
+ const { result } = render(MANUFACTURER);
262
+ await waitFor(() =>
263
+ expect(result.current.options.get("MAKER")).toHaveLength(3),
264
+ );
265
+ expect(result.current.truncated.size).toBe(0);
266
+ expect(result.current.search.size).toBe(0);
267
+ expect(executeQueryModel).toHaveBeenCalledTimes(1);
268
+ executeQueryModel.mockImplementation(() => pending());
269
+ });
270
+
271
+ it("is flagged for a named query at the server's cap, with no search to offer", async () => {
272
+ executeQueryModel.mockImplementation(() =>
273
+ answer(rows("brand", SUGGEST_OPTION_LIMIT)),
274
+ );
275
+ const { result } = render([
276
+ { name: "BRAND", control: "select", suggest: { query: "brands" } },
277
+ ]);
278
+ await waitFor(() =>
279
+ expect(result.current.truncated.has("BRAND")).toBe(true),
280
+ );
281
+ expect(result.current.search.has("BRAND")).toBe(false);
282
+ executeQueryModel.mockImplementation(() => pending());
283
+ });
284
+
285
+ it("searches a text-held document as its definitions plus the search", async () => {
286
+ executeQueryModel.mockImplementation((_e, _p, _m, request) => {
287
+ const query = (request as { query?: string }).query ?? "";
288
+ return answer(
289
+ query.includes("where:")
290
+ ? JSON.stringify([{ manufacturer: "General Motors, LLC" }])
291
+ : rows("manufacturer", SUGGEST_OPTION_LIMIT + 1),
292
+ );
293
+ });
294
+ const { result } = render(MANUFACTURER, "source: recalls is t");
295
+ await waitFor(() =>
296
+ expect(result.current.search.has("MAKER")).toBe(true),
297
+ );
298
+ await result.current.search.get("MAKER")!.run("general");
299
+ expect(
300
+ (executeQueryModel.mock.calls.at(-1)?.[3] as { query: string }).query,
301
+ ).toBe(
302
+ `source: recalls is t\n\n${buildSuggestQuery("recalls", "manufacturer", "general")}`,
303
+ );
304
+ // The definitions are part of what a search is cached under.
305
+ expect(result.current.search.get("MAKER")!.key).toContain(
306
+ "source: recalls is t",
307
+ );
308
+ executeQueryModel.mockImplementation(() => pending());
309
+ });
310
+ });