@malloy-publisher/sdk 0.9.12 → 0.9.14

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 (69) hide show
  1. package/README.md +5 -7
  2. package/dist/{RenderedResult-CDiXJAh9.es.js → RenderedResult-DnBtf-cI.es.js} +2 -2
  3. package/dist/{RenderedResult-De51QvsZ.cjs.js → RenderedResult-DtQtNV0d.cjs.js} +1 -1
  4. package/dist/ServerProvider-BIFPCzTD.cjs.js +1 -0
  5. package/dist/{ServerProvider-RvKSbvnL.es.js → ServerProvider-BV7IoDMR.es.js} +805 -606
  6. package/dist/builder/index.cjs.js +51 -51
  7. package/dist/builder/index.es.js +3638 -3698
  8. package/dist/builder-entry.d.ts +1 -0
  9. package/dist/client/api.d.ts +178 -0
  10. package/dist/client/index.cjs.js +1 -1
  11. package/dist/client/index.es.js +41 -37
  12. package/dist/components/Report/telemetry.d.ts +0 -5
  13. package/dist/components/ReportBuilder/BuilderBar.d.ts +1 -1
  14. package/dist/components/ReportBuilder/BuilderToolbar.d.ts +14 -10
  15. package/dist/components/ReportBuilder/EditorSurface.d.ts +8 -2
  16. package/dist/components/ReportBuilder/ReportBuilder.d.ts +3 -10
  17. package/dist/components/ReportBuilder/ReportEditor.d.ts +18 -7
  18. package/dist/components/ReportBuilder/SaveStatus.d.ts +16 -0
  19. package/dist/components/ReportBuilder/TileFrame.d.ts +9 -2
  20. package/dist/components/ReportBuilder/builderControls.d.ts +14 -6
  21. package/dist/components/ReportBuilder/useBuilderSession.d.ts +1 -1
  22. package/dist/components/ReportBuilder/useReportDraft.d.ts +6 -2
  23. package/dist/components/given/GivenInput.d.ts +18 -1
  24. package/dist/components/given/GivensPanel.d.ts +12 -1
  25. package/dist/components/given/useOptionSearch.d.ts +30 -0
  26. package/dist/hooks/index.d.ts +1 -1
  27. package/dist/hooks/useDocumentControls.d.ts +5 -0
  28. package/dist/hooks/useGivensState.d.ts +7 -0
  29. package/dist/hooks/useSuggestOptions.d.ts +60 -4
  30. package/dist/index.cjs.js +1 -1
  31. package/dist/index.es.js +5 -5
  32. package/dist/{useCompiledDocument-Bf4RSfB6.es.js → useCompiledDocument-B4QF1mIl.es.js} +6912 -6759
  33. package/dist/useCompiledDocument-D0OAMejE.cjs.js +142 -0
  34. package/package.json +1 -1
  35. package/src/builder-entry.ts +1 -0
  36. package/src/components/Report/ReportPage.tsx +5 -1
  37. package/src/components/Report/telemetry.ts +0 -6
  38. package/src/components/ReportBuilder/AddTileDialog.tsx +2 -2
  39. package/src/components/ReportBuilder/BuilderBar.tsx +5 -256
  40. package/src/components/ReportBuilder/BuilderHeader.tsx +9 -3
  41. package/src/components/ReportBuilder/BuilderToolbar.tsx +15 -38
  42. package/src/components/ReportBuilder/EditorSurface.tsx +16 -11
  43. package/src/components/ReportBuilder/FilterDialog.tsx +1 -1
  44. package/src/components/ReportBuilder/ReportBuilder.controls.spec.tsx +210 -24
  45. package/src/components/ReportBuilder/ReportBuilder.tsx +43 -85
  46. package/src/components/ReportBuilder/ReportEditor.package.spec.tsx +0 -36
  47. package/src/components/ReportBuilder/ReportEditor.queryVersion.spec.tsx +292 -0
  48. package/src/components/ReportBuilder/ReportEditor.tsx +22 -11
  49. package/src/components/ReportBuilder/SaveStatus.tsx +271 -0
  50. package/src/components/ReportBuilder/TileFrame.spec.ts +34 -0
  51. package/src/components/ReportBuilder/TileFrame.tsx +10 -3
  52. package/src/components/ReportBuilder/builderControls.ts +39 -13
  53. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  54. package/src/components/ReportBuilder/useReportDraft.ts +38 -4
  55. package/src/components/given/GivenInput.tsx +219 -104
  56. package/src/components/given/GivensPanel.spec.tsx +19 -0
  57. package/src/components/given/GivensPanel.tsx +31 -1
  58. package/src/components/given/useOptionSearch.spec.tsx +218 -0
  59. package/src/components/given/useOptionSearch.ts +100 -0
  60. package/src/hooks/index.ts +5 -1
  61. package/src/hooks/useDocumentControls.ts +12 -1
  62. package/src/hooks/useGivensState.spec.ts +54 -0
  63. package/src/hooks/useGivensState.ts +21 -1
  64. package/src/hooks/useSuggestOptions.dom.spec.ts +125 -4
  65. package/src/hooks/useSuggestOptions.spec.ts +73 -2
  66. package/src/hooks/useSuggestOptions.ts +234 -62
  67. package/dist/ServerProvider-DKrBcXL7.cjs.js +0 -1
  68. package/dist/useCompiledDocument-XsQz85Ri.cjs.js +0 -141
  69. package/src/components/ReportBuilder/ReportBuilder.layoutSwitch.spec.tsx +0 -145
@@ -478,8 +478,12 @@ export const selectionSx = (
478
478
  selected: boolean;
479
479
  flash?: boolean;
480
480
  bare?: boolean;
481
- /** How far a bare ring stands off its prose. Only content outside the grid may go wider than the grid's own. */
482
- ringOffset?: number;
481
+ /**
482
+ * How far a bare ring stands off its prose: one distance, or one across
483
+ * and one above and below. Only content outside the grid may go wider
484
+ * than the grid's own.
485
+ */
486
+ ringOffset?: number | { x: number; y: number };
483
487
  },
484
488
  ): SystemStyleObject<Theme> => {
485
489
  const ui = theme.ui;
@@ -504,7 +508,10 @@ export const selectionSx = (
504
508
  "&::before": {
505
509
  content: '""',
506
510
  position: "absolute",
507
- inset: `${-ringOffset}px`,
511
+ inset:
512
+ typeof ringOffset === "number"
513
+ ? `${-ringOffset}px`
514
+ : `${-ringOffset.y}px ${-ringOffset.x}px`,
508
515
  borderRadius: 1,
509
516
  border: `2px solid ${ring}`,
510
517
  ...(halo && { boxShadow: halo }),
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { useEffect, useMemo, useRef } from "react";
5
- import type { ReportLayout } from "../Package/documentLocation";
5
+ import type { RestoredDraft } from "./useReportDraft";
6
6
 
7
7
  /**
8
8
  * The builder's page-level controls, as state and actions rather than as a
@@ -25,11 +25,6 @@ export interface BuilderControls {
25
25
  undo: () => void;
26
26
  canRedo: boolean;
27
27
  redo: () => void;
28
- /** The layout and its switch. Absent when the layout cannot be changed here. */
29
- layout?: {
30
- value: ReportLayout;
31
- set: (layout: ReportLayout) => void;
32
- };
33
28
  /** What can be added to the page. A missing entry is not offered. */
34
29
  add: {
35
30
  /** Open the picker of views for a query tile. */
@@ -53,6 +48,19 @@ export interface BuilderControls {
53
48
  draftKeptAt?: number;
54
49
  /** Put the report back to the file's, as one undoable edit, and drop the draft. Absent with nothing to discard. */
55
50
  discard?: () => void;
51
+ /**
52
+ * Edits kept in this browser that the builder found on opening. Not
53
+ * `pending`: they were put back, which is news for the save status (the
54
+ * SDK's says when they are from in its menu) until `dismissRestored`, or
55
+ * the next edit. `pending`: the report changed since they were kept, so
56
+ * they are offered, not applied; the page asks the author to choose, and
57
+ * `restore` and `discard` are the two answers.
58
+ */
59
+ restored?: RestoredDraft;
60
+ /** Apply an offered (stale) draft, replacing the current version. Present while `restored.pending`. */
61
+ restore?: () => void;
62
+ /** The author has seen the restored edits: `restored` goes. Present while `restored` is, and not pending. */
63
+ dismissRestored?: () => void;
56
64
  }
57
65
 
58
66
  /** What a host passes to take over the builder's page-level controls. */
@@ -81,14 +89,14 @@ export function useReportControls(
81
89
  save: () => latest.current.save?.(),
82
90
  undo: () => latest.current.undo(),
83
91
  redo: () => latest.current.redo(),
84
- setLayout: (layout: ReportLayout) =>
85
- latest.current.layout?.set(layout),
86
92
  addTile: () => latest.current.add.tile?.(),
87
93
  addText: () => latest.current.add.text?.(),
88
94
  addFilter: () => latest.current.add.filter?.(),
89
95
  exit: () => latest.current.exit?.(),
90
96
  done: () => latest.current.done?.(),
91
97
  discard: () => latest.current.discard?.(),
98
+ restore: () => latest.current.restore?.(),
99
+ dismissRestored: () => latest.current.dismissRestored?.(),
92
100
  }),
93
101
  [],
94
102
  );
@@ -101,7 +109,6 @@ export function useReportControls(
101
109
  add: { filterUnavailable },
102
110
  } = controls;
103
111
  const hasSave = controls.save !== undefined;
104
- const layout = controls.layout?.value;
105
112
  const hasTile = controls.add.tile !== undefined;
106
113
  const hasText = controls.add.text !== undefined;
107
114
  const hasFilter = controls.add.filter !== undefined;
@@ -109,6 +116,11 @@ export function useReportControls(
109
116
  const hasDone = controls.done !== undefined;
110
117
  const hasDiscard = controls.discard !== undefined;
111
118
  const { draftKeptAt } = controls;
119
+ const restoredAt = controls.restored?.savedAt;
120
+ const restoredStale = controls.restored?.stale ?? false;
121
+ const restoredPending = controls.restored?.pending ?? false;
122
+ const hasRestore = controls.restore !== undefined;
123
+ const hasDismissRestored = controls.dismissRestored !== undefined;
112
124
 
113
125
  const shown = useMemo<BuilderControls>(
114
126
  () => ({
@@ -119,9 +131,6 @@ export function useReportControls(
119
131
  undo: actions.undo,
120
132
  canRedo,
121
133
  redo: actions.redo,
122
- ...(layout !== undefined
123
- ? { layout: { value: layout, set: actions.setLayout } }
124
- : {}),
125
134
  add: {
126
135
  ...(hasTile ? { tile: actions.addTile } : {}),
127
136
  ...(hasText ? { text: actions.addText } : {}),
@@ -132,6 +141,19 @@ export function useReportControls(
132
141
  ...(hasDone ? { done: actions.done } : {}),
133
142
  ...(draftKeptAt !== undefined ? { draftKeptAt } : {}),
134
143
  ...(hasDiscard ? { discard: actions.discard } : {}),
144
+ ...(restoredAt !== undefined
145
+ ? {
146
+ restored: {
147
+ savedAt: restoredAt,
148
+ stale: restoredStale,
149
+ pending: restoredPending,
150
+ },
151
+ }
152
+ : {}),
153
+ ...(hasRestore ? { restore: actions.restore } : {}),
154
+ ...(hasDismissRestored
155
+ ? { dismissRestored: actions.dismissRestored }
156
+ : {}),
135
157
  }),
136
158
  [
137
159
  actions,
@@ -140,7 +162,6 @@ export function useReportControls(
140
162
  hasSave,
141
163
  canUndo,
142
164
  canRedo,
143
- layout,
144
165
  hasTile,
145
166
  hasText,
146
167
  hasFilter,
@@ -149,6 +170,11 @@ export function useReportControls(
149
170
  hasDone,
150
171
  draftKeptAt,
151
172
  hasDiscard,
173
+ restoredAt,
174
+ restoredStale,
175
+ restoredPending,
176
+ hasRestore,
177
+ hasDismissRestored,
152
178
  ],
153
179
  );
154
180
 
@@ -125,7 +125,7 @@ source: a is one extend {
125
125
  const suggest = back.localGivens?.[0].suggest;
126
126
  expect(suggest).toEqual({ source: "a", dimension: "products.category" });
127
127
  expect(buildSuggestQuery(suggest!.source!, suggest!.dimension)).toBe(
128
- `run: a -> {\n group_by: products.category\n order_by: category asc\n limit: ${SUGGEST_OPTION_LIMIT}\n}`,
128
+ `run: a -> {\n group_by: products.category\n order_by: category asc\n limit: ${SUGGEST_OPTION_LIMIT + 1}\n}`,
129
129
  );
130
130
  });
131
131
  });
@@ -36,7 +36,11 @@ interface StoredDraft {
36
36
  savedAt: number;
37
37
  }
38
38
 
39
- /** What the builder found on opening, for the notice that says so. */
39
+ /**
40
+ * What the builder found on opening. A draft put back is said in the save
41
+ * status (its menu names when the edits are from) until the author has seen it
42
+ * or edits again; a stale one is a choice the page asks for.
43
+ */
40
44
  export interface RestoredDraft {
41
45
  savedAt: number;
42
46
  /**
@@ -187,7 +191,7 @@ export function useReportDraft(
187
191
  ): {
188
192
  /** When unsaved edits were last kept in this browser; undefined when none are. */
189
193
  keptAt: number | undefined;
190
- /** The draft the builder opened with, until the notice is dismissed. */
194
+ /** The draft the builder opened with: until it is seen, or edited over; a stale one until the author chooses. */
191
195
  restored: RestoredDraft | undefined;
192
196
  dismissRestored: () => void;
193
197
  /** Put the document back to the file's, as one undoable edit; the draft goes with the edits. */
@@ -205,6 +209,12 @@ export function useReportDraft(
205
209
  // A stale draft waiting on the author: kept as it is, not overwritten or
206
210
  // removed by the clean document the builder opened on.
207
211
  const offered = useRef<StoredDraft | undefined>(undefined);
212
+ // The document a draft was put back as, until the next edit: that edit
213
+ // ends the "restored" news, since the draft is now just the edits.
214
+ const restoredAs = useRef<string | undefined>(undefined);
215
+ // Set until the put-back document has rendered: the pass in between still
216
+ // sees the document from before, which is not an edit.
217
+ const restoring = useRef(false);
208
218
  const base = textFingerprint(opened);
209
219
  const editorRef = useRef(editor);
210
220
  editorRef.current = editor;
@@ -227,6 +237,8 @@ export function useReportDraft(
227
237
  return;
228
238
  }
229
239
  current.update((document) => replaceContents(document, draft.document));
240
+ restoredAs.current = JSON.stringify(draft.document);
241
+ restoring.current = true;
230
242
  setRestored({ savedAt: draft.savedAt, stale: false, pending: false });
231
243
  // Only on opening: the key and the file it opened on are fixed for a mount.
232
244
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -239,7 +251,21 @@ export function useReportDraft(
239
251
  // The offered draft stands until the author chooses; an edit before
240
252
  // they do is a choice too, and replaces it.
241
253
  if (offered.current && !dirty) return;
242
- offered.current = undefined;
254
+ if (offered.current) {
255
+ // Edited over instead of chosen: the edits are the choice, and the
256
+ // offer goes, so nothing goes on asking about a draft no longer kept.
257
+ offered.current = undefined;
258
+ setRestored(undefined);
259
+ }
260
+ if (restoredAs.current !== undefined) {
261
+ const now = JSON.stringify(document);
262
+ if (restoring.current) {
263
+ if (now === restoredAs.current) restoring.current = false;
264
+ } else if (now !== restoredAs.current) {
265
+ restoredAs.current = undefined;
266
+ setRestored(undefined);
267
+ }
268
+ }
243
269
  if (!dirty) {
244
270
  remove(key);
245
271
  setKeptAt(undefined);
@@ -264,10 +290,17 @@ export function useReportDraft(
264
290
  editorRef.current.update((document) =>
265
291
  replaceContents(document, draft.document),
266
292
  );
293
+ restoredAs.current = JSON.stringify(draft.document);
294
+ restoring.current = true;
267
295
  setRestored((was) => was && { ...was, pending: false });
268
296
  }, []);
269
297
 
270
- const dismissRestored = useCallback(() => setRestored(undefined), []);
298
+ const dismissRestored = useCallback(() => {
299
+ // A stale draft is a choice still to make, not news to dismiss.
300
+ if (offered.current) return;
301
+ restoredAs.current = undefined;
302
+ setRestored(undefined);
303
+ }, []);
271
304
  const discard = useCallback(() => {
272
305
  if (offered.current && key !== undefined) {
273
306
  // An offered draft was never applied: dropping it is all there is.
@@ -278,6 +311,7 @@ export function useReportDraft(
278
311
  }
279
312
  const current = editorRef.current;
280
313
  current.update((document) => replaceContents(document, current.saved));
314
+ restoredAs.current = undefined;
281
315
  setRestored(undefined);
282
316
  }, [key]);
283
317
 
@@ -13,6 +13,8 @@ import {
13
13
  IconButton,
14
14
  InputAdornment,
15
15
  MenuItem,
16
+ Paper,
17
+ type PaperProps,
16
18
  Slider,
17
19
  Stack,
18
20
  TextField,
@@ -25,10 +27,23 @@ import { DatePicker } from "@mui/x-date-pickers/DatePicker";
25
27
  import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
26
28
  import dayjs from "dayjs";
27
29
  import utc from "dayjs/plugin/utc";
28
- import { type FocusEvent, type ReactNode, useEffect, useState } from "react";
30
+ import {
31
+ createContext,
32
+ type FocusEvent,
33
+ type ReactNode,
34
+ useContext,
35
+ useEffect,
36
+ useState,
37
+ } from "react";
29
38
  import { Given } from "../../client";
30
39
  import { paramToGiven, pickedDayToUtc } from "./paramCodec";
31
40
  import { GivenValue } from "../../hooks/givenValue";
41
+ import {
42
+ type OptionSearch,
43
+ SUGGEST_OPTION_LIMIT,
44
+ SUGGEST_SEARCH_LIMIT,
45
+ } from "../../hooks/useSuggestOptions";
46
+ import { type OptionSearchState, useOptionSearch } from "./useOptionSearch";
32
47
  import {
33
48
  decodeAtLeast,
34
49
  decodeBetween,
@@ -87,6 +102,16 @@ export interface GivenInputProps {
87
102
  * Free text still works, so the control degrades rather than locking up.
88
103
  */
89
104
  optionsFailed?: boolean;
105
+ /**
106
+ * The option list was cut off: more values exist than `options` holds. The
107
+ * dropdown says so, since a value missing from it may still be in the data.
108
+ */
109
+ optionsTruncated?: boolean;
110
+ /**
111
+ * Search the whole dimension on the server as the reader types, for a list
112
+ * that was cut off. Absent, typing filters `options` in the browser.
113
+ */
114
+ optionSearch?: OptionSearch;
90
115
  }
91
116
 
92
117
  /**
@@ -147,6 +172,8 @@ export function GivenInput({
147
172
  options,
148
173
  optionsLoading,
149
174
  optionsFailed,
175
+ optionsTruncated,
176
+ optionSearch,
150
177
  }: GivenInputProps) {
151
178
  const label = given.label ?? given.name ?? "";
152
179
  const { theme: publisherTheme } = usePublisherTheme();
@@ -255,6 +282,15 @@ export function GivenInput({
255
282
  ? [value]
256
283
  : [];
257
284
 
285
+ // What the reader is typing into the picker, for a server search of a list
286
+ // that was cut off. Called for every given, as hooks must be; inert unless
287
+ // the picker below renders with a search to run.
288
+ const [typed, setTyped] = useState("");
289
+ const search = useOptionSearch(
290
+ pickerControl ? optionSearch : undefined,
291
+ typed,
292
+ );
293
+
258
294
  if (
259
295
  pickerControl &&
260
296
  pickableType &&
@@ -305,113 +341,133 @@ export function GivenInput({
305
341
  onChange(filtered ? (encoded as string) : next[0]);
306
342
  };
307
343
 
344
+ const hint = optionHint(search, optionsTruncated, optionSearch);
308
345
  return (
309
- <Autocomplete
310
- multiple={multiple}
311
- // Picking one value out of several should not put the list away;
312
- // MUI closes on select by default, which makes "and also Aurora"
313
- // cost a second click to reopen.
314
- disableCloseOnSelect={multiple}
315
- // Free text keeps the control from being a cage: the suggest query
316
- // returns the common values, not necessarily every legal one.
317
- freeSolo
318
- // MUI hides the dropdown arrow whenever `freeSolo` is set, which
319
- // left a control that HAS a list of values looking exactly like a
320
- // plain text box: nothing on it said the list existed, so the only
321
- // way to find the options was to guess that clicking would reveal
322
- // them. Reported independently by a reader as "the controls render
323
- // as text boxes rather than dropdowns"; the options were being
324
- // fetched and offered correctly the whole time, and only the
325
- // affordance was missing. Same principle as `markDrillableCells`:
326
- // something you can act on has to look like it.
327
- forcePopupIcon
328
- // Keeps text the reader typed but did not pick from the list. A
329
- // `freeSolo` Autocomplete without this discards it on blur, so a
330
- // value that is legal but absent from `suggest` could be typed and
331
- // then silently vanish.
332
- //
333
- // Single-pick only. On blur MUI's `autoSelect` also picks the
334
- // HIGHLIGHTED option while the list is open, and a multi-pick
335
- // keeps its list open after a pick with that option still
336
- // highlighted, so clicking away picked it a second time, which in
337
- // a multi-pick takes it back out: choose Aurora, click the page,
338
- // and the filter was gone. A multi-pick keeps typed text itself,
339
- // in the input's blur below.
340
- autoSelect={!multiple}
341
- options={options ?? []}
342
- loading={optionsLoading}
343
- noOptionsText={
344
- optionsFailed ? "Options unavailable" : "No matching values"
345
- }
346
- value={multiple ? selected : (selected[0] ?? null)}
347
- onChange={(_event, next) =>
348
- commit(
349
- next === null
350
- ? []
351
- : Array.isArray(next)
352
- ? (next as string[])
353
- : [next as string],
354
- )
355
- }
356
- renderInput={(params) => (
357
- <TextField
358
- {...params}
359
- label={label}
360
- size="small"
361
- // The model's own default when it has one, as a ghost, the
362
- // way every other unset control shows it. A hardcoded "All"
363
- // told the reader nothing would be filtered while the query
364
- // was about to run on the declared default.
365
- //
366
- // Except when an explicit `""` is in force. That is the EMPTY
367
- // filter, so the default is precisely what is NOT running,
368
- // and showing it as a ghost made the control assert one
369
- // filter while the query used another.
370
- placeholder={
371
- selected.length !== 0
372
- ? undefined
373
- : value === ""
374
- ? "All"
375
- : (defaultDisplay ?? "All")
376
- }
377
- error={optionsFailed}
378
- helperText={
379
- optionsFailed ? (
380
- <>
381
- Could not load the options for this control. Type a
382
- value to filter anyway.
383
- {helperNode ? <br /> : null}
384
- {helperNode}
385
- </>
386
- ) : (
387
- helperNode
388
- )
389
- }
390
- slotProps={{
391
- input: {
392
- ...params.InputProps,
393
- endAdornment: (
346
+ <OptionHint.Provider value={hint}>
347
+ <Autocomplete
348
+ multiple={multiple}
349
+ // Picking one value out of several should not put the list away;
350
+ // MUI closes on select by default, which makes "and also Aurora"
351
+ // cost a second click to reopen.
352
+ disableCloseOnSelect={multiple}
353
+ // Free text keeps the control from being a cage: the suggest query
354
+ // returns the common values, not necessarily every legal one.
355
+ freeSolo
356
+ // MUI hides the dropdown arrow whenever `freeSolo` is set, which
357
+ // left a control that HAS a list of values looking exactly like a
358
+ // plain text box: nothing on it said the list existed, so the only
359
+ // way to find the options was to guess that clicking would reveal
360
+ // them. Reported independently by a reader as "the controls render
361
+ // as text boxes rather than dropdowns"; the options were being
362
+ // fetched and offered correctly the whole time, and only the
363
+ // affordance was missing. Same principle as `markDrillableCells`:
364
+ // something you can act on has to look like it.
365
+ forcePopupIcon
366
+ // Keeps text the reader typed but did not pick from the list. A
367
+ // `freeSolo` Autocomplete without this discards it on blur, so a
368
+ // value that is legal but absent from `suggest` could be typed and
369
+ // then silently vanish.
370
+ //
371
+ // Single-pick only. On blur MUI's `autoSelect` also picks the
372
+ // HIGHLIGHTED option while the list is open, and a multi-pick
373
+ // keeps its list open after a pick with that option still
374
+ // highlighted, so clicking away picked it a second time, which in
375
+ // a multi-pick takes it back out: choose Aurora, click the page,
376
+ // and the filter was gone. A multi-pick keeps typed text itself,
377
+ // in the input's blur below.
378
+ autoSelect={!multiple}
379
+ // The server's matches once it has answered for exactly what is
380
+ // typed; until then the list in hand, filtered here as usual.
381
+ options={search.page?.values ?? options ?? []}
382
+ // Already matched on the server, case and all: filtering them
383
+ // again here could only hide a match.
384
+ {...(search.page
385
+ ? { filterOptions: (found: string[]) => found }
386
+ : {})}
387
+ onInputChange={(_event, text, reason) =>
388
+ // Only typing searches. MUI also sets the text on a pick and
389
+ // on a reset to the value, and searching for the value just
390
+ // picked would replace the list with that one value.
391
+ setTyped(reason === "input" ? text : "")
392
+ }
393
+ loading={optionsLoading || search.searching}
394
+ loadingText={search.searching ? "Searching…" : "Loading…"}
395
+ noOptionsText={
396
+ optionsFailed ? "Options unavailable" : "No matching values"
397
+ }
398
+ slots={{ paper: HintPaper }}
399
+ value={multiple ? selected : (selected[0] ?? null)}
400
+ onChange={(_event, next) =>
401
+ commit(
402
+ next === null
403
+ ? []
404
+ : Array.isArray(next)
405
+ ? (next as string[])
406
+ : [next as string],
407
+ )
408
+ }
409
+ renderInput={(params) => (
410
+ <TextField
411
+ {...params}
412
+ label={label}
413
+ size="small"
414
+ // The model's own default when it has one, as a ghost, the
415
+ // way every other unset control shows it. A hardcoded "All"
416
+ // told the reader nothing would be filtered while the query
417
+ // was about to run on the declared default.
418
+ //
419
+ // Except when an explicit `""` is in force. That is the EMPTY
420
+ // filter, so the default is precisely what is NOT running,
421
+ // and showing it as a ghost made the control assert one
422
+ // filter while the query used another.
423
+ placeholder={
424
+ selected.length !== 0
425
+ ? undefined
426
+ : value === ""
427
+ ? "All"
428
+ : (defaultDisplay ?? "All")
429
+ }
430
+ error={optionsFailed}
431
+ helperText={
432
+ optionsFailed ? (
394
433
  <>
395
- {optionsLoading && <CircularProgress size={16} />}
396
- {params.InputProps.endAdornment}
434
+ Could not load the options for this control. Type
435
+ a value to filter anyway.
436
+ {helperNode ? <br /> : null}
437
+ {helperNode}
397
438
  </>
398
- ),
399
- },
400
- htmlInput: {
401
- ...params.inputProps,
402
- onBlur: (event: FocusEvent<HTMLInputElement>) => {
403
- params.inputProps.onBlur?.(event);
404
- if (!multiple) return;
405
- const typed = event.target.value.trim();
406
- if (typed !== "" && !selected.includes(typed))
407
- commit([...selected, typed]);
439
+ ) : (
440
+ helperNode
441
+ )
442
+ }
443
+ slotProps={{
444
+ input: {
445
+ ...params.InputProps,
446
+ endAdornment: (
447
+ <>
448
+ {optionsLoading && (
449
+ <CircularProgress size={16} />
450
+ )}
451
+ {params.InputProps.endAdornment}
452
+ </>
453
+ ),
408
454
  },
409
- },
410
- }}
411
- />
412
- )}
413
- fullWidth
414
- />
455
+ htmlInput: {
456
+ ...params.inputProps,
457
+ onBlur: (event: FocusEvent<HTMLInputElement>) => {
458
+ params.inputProps.onBlur?.(event);
459
+ if (!multiple) return;
460
+ const typed = event.target.value.trim();
461
+ if (typed !== "" && !selected.includes(typed))
462
+ commit([...selected, typed]);
463
+ },
464
+ },
465
+ }}
466
+ />
467
+ )}
468
+ fullWidth
469
+ />
470
+ </OptionHint.Provider>
415
471
  );
416
472
  }
417
473
 
@@ -1222,3 +1278,62 @@ function TimeRangeControl({
1222
1278
  </Stack>
1223
1279
  );
1224
1280
  }
1281
+
1282
+ /** The line under a picker's options that says the list is partial, or being searched. */
1283
+ const OptionHint = createContext<string | undefined>(undefined);
1284
+
1285
+ /**
1286
+ * The picker's dropdown, with a line under its options when there is
1287
+ * something to say about them. Read from context rather than props: MUI
1288
+ * renders the slot itself and passes it only its own props.
1289
+ */
1290
+ function HintPaper({ children, ...props }: PaperProps) {
1291
+ const hint = useContext(OptionHint);
1292
+ return (
1293
+ <Paper {...props}>
1294
+ {children}
1295
+ {hint && (
1296
+ <Box
1297
+ role="note"
1298
+ sx={{
1299
+ px: 2,
1300
+ py: 1,
1301
+ borderTop: 1,
1302
+ borderColor: "divider",
1303
+ color: "text.secondary",
1304
+ typography: "caption",
1305
+ }}
1306
+ >
1307
+ {hint}
1308
+ </Box>
1309
+ )}
1310
+ </Paper>
1311
+ );
1312
+ }
1313
+
1314
+ const count = (n: number) => n.toLocaleString("en-US");
1315
+
1316
+ /**
1317
+ * What the dropdown says about its options, if anything. Only a cut-off list
1318
+ * has something to say: a whole list needs no footnote.
1319
+ */
1320
+ export function optionHint(
1321
+ search: OptionSearchState,
1322
+ truncated: boolean | undefined,
1323
+ searchable: OptionSearch | undefined,
1324
+ ): string | undefined {
1325
+ if (search.active) {
1326
+ if (search.searching) return "Searching all values…";
1327
+ if (search.failed)
1328
+ return `Could not search all values. Showing matches in the first ${count(SUGGEST_OPTION_LIMIT)}.`;
1329
+ if (search.page?.truncated)
1330
+ return `Showing the first ${count(SUGGEST_SEARCH_LIMIT)} matches. Keep typing to narrow them.`;
1331
+ return undefined;
1332
+ }
1333
+ if (!truncated) return undefined;
1334
+ // A named suggest query cannot be searched on the server, so the list in
1335
+ // hand is all there is to filter; a value past it can still be typed in.
1336
+ return searchable
1337
+ ? `Showing the first ${count(SUGGEST_OPTION_LIMIT)} values. Type to search them all.`
1338
+ : `Showing the first ${count(SUGGEST_OPTION_LIMIT)} values. A value not listed can still be typed.`;
1339
+ }
@@ -180,4 +180,23 @@ describe("layout and title", () => {
180
180
  fireEvent.click(screen.getByRole("button", { name: "Reset" }));
181
181
  expect(reset).toBe(1);
182
182
  });
183
+
184
+ it("offers no Reset when the values are already where it would put them", () => {
185
+ // A value the document starts with is set, but Reset would change
186
+ // nothing: offered anyway, it was a button that did nothing.
187
+ render(
188
+ <GivensPanel
189
+ {...props}
190
+ layout="bar"
191
+ values={new Map([["BRAND", "Nike"]])}
192
+ canReset={false}
193
+ />,
194
+ );
195
+ expect(screen.queryByRole("button", { name: "Reset" })).toBeNull();
196
+ });
197
+
198
+ it("offers Reset when the values have moved off the start, even to empty", () => {
199
+ render(<GivensPanel {...props} layout="bar" canReset />);
200
+ expect(screen.getByRole("button", { name: "Reset" })).toBeDefined();
201
+ });
183
202
  });