@malloy-publisher/sdk 0.2.6 → 0.3.0

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 (100) hide show
  1. package/README.md +172 -204
  2. package/dist/ServerProvider-CGnLjzag.cjs.js +1 -0
  3. package/dist/{ServerProvider-ksC5Su_x.es.js → ServerProvider-DSK9rfSY.es.js} +245 -245
  4. package/dist/client/api.d.ts +13 -1
  5. package/dist/client/index.cjs.js +1 -1
  6. package/dist/client/index.es.js +1 -1
  7. package/dist/components/ApiErrorDisplay.d.ts +1 -2
  8. package/dist/components/Dashboard/Dashboard.d.ts +4 -2
  9. package/dist/components/Dashboard/promoteMeasureRow.d.ts +36 -0
  10. package/dist/components/DocumentStorage/BrowserDocumentStorage.d.ts +14 -0
  11. package/dist/components/DocumentStorage/DocumentStorage.d.ts +58 -0
  12. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +18 -0
  13. package/dist/components/DocumentStorage/index.d.ts +3 -0
  14. package/dist/components/Model/index.d.ts +0 -1
  15. package/dist/components/RenderedResult/RenderedResult.d.ts +12 -0
  16. package/dist/components/RenderedResult/ResultContainer.d.ts +7 -1
  17. package/dist/components/RenderedResult/index.d.ts +1 -0
  18. package/dist/components/RenderedResult/resultSizing.d.ts +183 -0
  19. package/dist/components/drill/index.d.ts +1 -0
  20. package/dist/components/drill/useDrillSelf.d.ts +46 -0
  21. package/dist/components/given/filterValue.d.ts +63 -0
  22. package/dist/components/given/index.d.ts +1 -0
  23. package/dist/components/given/useGivenUrlParams.d.ts +39 -0
  24. package/dist/components/index.d.ts +2 -3
  25. package/dist/components/styles.d.ts +3 -3
  26. package/dist/core-8NVBCLZh.cjs.js +148 -0
  27. package/dist/{core-xdZbLgaF.es.js → core-B8oMW4sm.es.js} +3540 -2335
  28. package/dist/hooks/index.d.ts +1 -1
  29. package/dist/hooks/useSuggestOptions.d.ts +28 -12
  30. package/dist/index.cjs.js +281 -1
  31. package/dist/index.es.js +45803 -79
  32. package/dist/sdk.css +1 -1
  33. package/dist/styles.css +0 -1
  34. package/package.json +2 -6
  35. package/src/components/ApiErrorDisplay.tsx +1 -1
  36. package/src/components/Connections/EditConnectionDialog.tsx +96 -86
  37. package/src/components/Dashboard/Dashboard.tsx +60 -95
  38. package/src/components/Dashboard/DashboardTile.tsx +25 -2
  39. package/src/components/Dashboard/promoteMeasureRow.spec.ts +137 -0
  40. package/src/components/Dashboard/promoteMeasureRow.ts +129 -0
  41. package/src/components/DocumentStorage/BrowserDocumentStorage.spec.ts +81 -0
  42. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +105 -0
  43. package/src/components/DocumentStorage/DocumentStorage.ts +73 -0
  44. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +46 -0
  45. package/src/components/DocumentStorage/index.ts +15 -0
  46. package/src/components/Environment/Connections.tsx +15 -15
  47. package/src/components/Model/ModelCell.tsx +2 -1
  48. package/src/components/Model/index.ts +0 -1
  49. package/src/components/Notebook/Notebook.tsx +10 -76
  50. package/src/components/Notebook/NotebookCell.tsx +2 -8
  51. package/src/components/RenderedResult/RenderedResult.tsx +86 -76
  52. package/src/components/RenderedResult/ResultContainer.tsx +21 -24
  53. package/src/components/RenderedResult/index.ts +15 -0
  54. package/src/components/RenderedResult/resultSizing.spec.ts +249 -0
  55. package/src/components/RenderedResult/resultSizing.ts +308 -0
  56. package/src/components/ResultsDialog.tsx +2 -1
  57. package/src/components/drill/index.ts +5 -0
  58. package/src/components/drill/useDrillSelf.spec.tsx +64 -0
  59. package/src/components/drill/useDrillSelf.ts +110 -0
  60. package/src/components/given/GivenInput.spec.tsx +196 -2
  61. package/src/components/given/GivenInput.tsx +300 -25
  62. package/src/components/given/filterValue.spec.ts +112 -0
  63. package/src/components/given/filterValue.ts +188 -0
  64. package/src/components/given/index.ts +4 -0
  65. package/src/components/given/useGivenUrlParams.spec.tsx +74 -0
  66. package/src/components/given/useGivenUrlParams.ts +87 -0
  67. package/src/components/index.ts +5 -3
  68. package/src/hooks/index.ts +0 -1
  69. package/src/hooks/useGivensState.spec.ts +158 -0
  70. package/src/hooks/useGivensState.ts +114 -23
  71. package/src/hooks/useSuggestOptions.dom.spec.ts +60 -1
  72. package/src/hooks/useSuggestOptions.ts +94 -51
  73. package/vite.config.ts +0 -1
  74. package/dist/ServerProvider-xXW1HJOJ.cjs.js +0 -1
  75. package/dist/components/AnalyzePackageButton.d.ts +0 -6
  76. package/dist/components/Workbook/BrowserWorkbookStorage.d.ts +0 -9
  77. package/dist/components/Workbook/EditableMalloyCell.d.ts +0 -11
  78. package/dist/components/Workbook/ModelPicker.d.ts +0 -11
  79. package/dist/components/Workbook/MutableCell.d.ts +0 -17
  80. package/dist/components/Workbook/Workbook.d.ts +0 -7
  81. package/dist/components/Workbook/WorkbookList.d.ts +0 -7
  82. package/dist/components/Workbook/WorkbookManager.d.ts +0 -84
  83. package/dist/components/Workbook/WorkbookStorage.d.ts +0 -17
  84. package/dist/components/Workbook/WorkbookStorageProvider.d.ts +0 -12
  85. package/dist/components/Workbook/index.d.ts +0 -7
  86. package/dist/core-RvrkY1Ss.cjs.js +0 -148
  87. package/dist/index-B3scIDRd.cjs.js +0 -356
  88. package/dist/index-Bda7HuZc.es.js +0 -66409
  89. package/dist/markdown-editor.css +0 -341
  90. package/src/components/AnalyzePackageButton.tsx +0 -319
  91. package/src/components/Workbook/BrowserWorkbookStorage.ts +0 -64
  92. package/src/components/Workbook/EditableMalloyCell.tsx +0 -49
  93. package/src/components/Workbook/ModelPicker.tsx +0 -134
  94. package/src/components/Workbook/MutableCell.tsx +0 -458
  95. package/src/components/Workbook/Workbook.tsx +0 -501
  96. package/src/components/Workbook/WorkbookList.tsx +0 -110
  97. package/src/components/Workbook/WorkbookManager.ts +0 -214
  98. package/src/components/Workbook/WorkbookStorage.ts +0 -35
  99. package/src/components/Workbook/WorkbookStorageProvider.tsx +0 -40
  100. package/src/components/Workbook/index.ts +0 -10
@@ -209,7 +209,11 @@ describe("GivenInput: a control= the widget cannot honour falls through", () =>
209
209
  // rejects, and a `number` given would get a string `givensToRequest` forwards
210
210
  // verbatim for Malloy to refuse. Nothing populates `control` yet, so these
211
211
  // pin the refusal before the slice that starts populating it.
212
- const pickerCount = () => screen.queryAllByRole("combobox").length;
212
+ // Autocomplete pickers only. The time-range control's dropdown is a
213
+ // combobox too, on a `<div>`; the picker this suite is about is an `<input>`.
214
+ const pickerCount = () =>
215
+ screen.queryAllByRole("combobox").filter((el) => el.tagName === "INPUT")
216
+ .length;
213
217
 
214
218
  for (const type of ["string", "filter<string>"]) {
215
219
  it(`renders a picker for ${type}`, () => {
@@ -259,6 +263,54 @@ describe("GivenInput: a slider only claims a filter it can represent", () => {
259
263
  onChange={() => {}}
260
264
  />,
261
265
  );
266
+ // Two handles, the lower at the bound and the upper at the ceiling.
267
+ const sliders = screen.queryAllByRole("slider") as HTMLInputElement[];
268
+ expect(sliders.map((s) => s.value)).toEqual(["5", "10"]);
269
+ expect(screen.getByText("≥ 5")).toBeDefined();
270
+ });
271
+
272
+ it("renders a closed range on both handles", () => {
273
+ render(
274
+ <GivenInput
275
+ given={{
276
+ name: "n",
277
+ type: "filter<number>",
278
+ rangeMin: 0,
279
+ rangeMax: 10,
280
+ }}
281
+ value="[2 to 7]"
282
+ onChange={() => {}}
283
+ />,
284
+ );
285
+ const sliders = screen.queryAllByRole("slider") as HTMLInputElement[];
286
+ expect(sliders.map((s) => s.value)).toEqual(["2", "7"]);
287
+ expect(screen.getByText("2 to 7")).toBeDefined();
288
+ });
289
+
290
+ it("still refuses a half-open range", () => {
291
+ render(
292
+ <GivenInput
293
+ given={{
294
+ name: "n",
295
+ type: "filter<number>",
296
+ rangeMin: 0,
297
+ rangeMax: 10,
298
+ }}
299
+ value="(2 to 7]"
300
+ onChange={() => {}}
301
+ />,
302
+ );
303
+ expect(screen.queryAllByRole("slider")).toHaveLength(0);
304
+ });
305
+
306
+ it("keeps one handle for a plain number given", () => {
307
+ render(
308
+ <GivenInput
309
+ given={{ name: "n", type: "number", rangeMin: 0, rangeMax: 10 }}
310
+ value={4}
311
+ onChange={() => {}}
312
+ />,
313
+ );
262
314
  expect(screen.queryAllByRole("slider")).toHaveLength(1);
263
315
  });
264
316
 
@@ -330,6 +382,7 @@ describe("GivenInput: the whole type x control matrix", () => {
330
382
  // the property that matters most is the last assertion: no combination falls
331
383
  // through every branch and renders nothing at all.
332
384
  const widget = () => {
385
+ if (screen.queryAllByTestId("time-range").length) return "timerange";
333
386
  if (screen.queryAllByRole("combobox").length) return "picker";
334
387
  if (screen.queryAllByRole("slider").length) return "slider";
335
388
  if (screen.queryAllByRole("checkbox").length) return "checkbox";
@@ -407,9 +460,31 @@ describe("GivenInput: the whole type x control matrix", () => {
407
460
  // A filter the picker cannot represent falls through to the text box, so
408
461
  // the author's filter stays visible rather than being re-encoded.
409
462
  expect(show("filter<string>", "select", false, "-Nike")).toBe("text");
410
- // A lower-bound filter keeps the slider; a range cannot be a threshold.
463
+ // A lower bound and a closed range both fit the handles; `1 to 5` is not
464
+ // number-filter syntax at all and stays visible as written.
411
465
  expect(show("filter<number>", undefined, true, ">= 5")).toBe("slider");
466
+ expect(show("filter<number>", undefined, true, "[1 to 5]")).toBe(
467
+ "slider",
468
+ );
412
469
  expect(show("filter<number>", undefined, true, "1 to 5")).toBe("text");
470
+ // A date filter gets the time-range control for a window or a day range,
471
+ // the single day picker for one day, and the text box for the rest.
472
+ expect(show("filter<date>", undefined, false, undefined)).toBe(
473
+ "timerange",
474
+ );
475
+ expect(show("filter<date>", undefined, false, "7 days")).toBe(
476
+ "timerange",
477
+ );
478
+ expect(
479
+ show(
480
+ "filter<timestamp>",
481
+ undefined,
482
+ false,
483
+ "2024-01-01 to 2024-02-01",
484
+ ),
485
+ ).toBe("timerange");
486
+ expect(show("filter<date>", undefined, false, "2024-01-15")).toBe("text");
487
+ expect(show("filter<date>", undefined, false, "last month")).toBe("text");
413
488
  });
414
489
 
415
490
  // One test per type rather than one test for the whole matrix. The matrix is
@@ -687,3 +762,122 @@ describe("GivenInput: a date renders its UTC day, whatever zone the runner is in
687
762
  },
688
763
  );
689
764
  });
765
+
766
+ describe("GivenInput: the time-range control for a date filter", () => {
767
+ const given: Given = { name: "PERIOD", type: "filter<timestamp>" };
768
+ const dropdown = () =>
769
+ screen
770
+ .getAllByRole("combobox")
771
+ .find((el) => el.tagName !== "INPUT") as HTMLElement;
772
+
773
+ it("shows an unset given as blank, with no revert", () => {
774
+ render(
775
+ <GivenInput given={given} value={undefined} onChange={() => {}} />,
776
+ );
777
+ expect(screen.getByTestId("time-range")).toBeDefined();
778
+ expect(clearButtons()).toHaveLength(0);
779
+ expect(screen.queryAllByLabelText("From")).toHaveLength(0);
780
+ });
781
+
782
+ it("shows the preset a value spells, however it is spelled", () => {
783
+ render(<GivenInput given={given} value="30 day" onChange={() => {}} />);
784
+ expect(dropdown().textContent).toBe("Last 30 days");
785
+ expect(clearButtons()).toHaveLength(1);
786
+ });
787
+
788
+ it("commits a picked preset in Malloy's filter grammar", () => {
789
+ const onChange = mock((_next: GivenValue) => {});
790
+ render(
791
+ <GivenInput given={given} value={undefined} onChange={onChange} />,
792
+ );
793
+ fireEvent.mouseDown(dropdown());
794
+ fireEvent.click(screen.getByRole("option", { name: "Last 7 days" }));
795
+ expect(onChange).toHaveBeenCalledWith("7 days");
796
+ });
797
+
798
+ it("opens two day pickers for a custom range, committing nothing yet", () => {
799
+ const onChange = mock((_next: GivenValue) => {});
800
+ render(
801
+ <GivenInput given={given} value={undefined} onChange={onChange} />,
802
+ );
803
+ fireEvent.mouseDown(dropdown());
804
+ fireEvent.click(screen.getByRole("option", { name: "Custom range" }));
805
+ expect(screen.getByLabelText("From")).toBeDefined();
806
+ expect(screen.getByLabelText("To")).toBeDefined();
807
+ expect(onChange).not.toHaveBeenCalled();
808
+ });
809
+
810
+ it("shows a day range as the inclusive days it selects", () => {
811
+ render(
812
+ <GivenInput
813
+ given={given}
814
+ value="2024-01-01 to 2024-02-01"
815
+ onChange={() => {}}
816
+ />,
817
+ );
818
+ expect(dropdown().textContent).toBe("Custom range");
819
+ expect((screen.getByLabelText("From") as HTMLInputElement).value).toBe(
820
+ "01/01/2024",
821
+ );
822
+ expect((screen.getByLabelText("To") as HTMLInputElement).value).toBe(
823
+ "01/31/2024",
824
+ );
825
+ });
826
+
827
+ it("shows the empty filter as an override it can revert", () => {
828
+ const onChange = mock((_next: GivenValue) => {});
829
+ render(<GivenInput given={given} value="" onChange={onChange} />);
830
+ expect(dropdown().textContent).toBe("Any time");
831
+ fireEvent.click(clearButtons()[0]);
832
+ expect(onChange).toHaveBeenCalledWith(null);
833
+ });
834
+
835
+ it("leaves a filter it cannot show in the text box, as written", () => {
836
+ render(
837
+ <GivenInput given={given} value="last month" onChange={() => {}} />,
838
+ );
839
+ expect(screen.queryAllByTestId("time-range")).toHaveLength(0);
840
+ expect((screen.getByLabelText("PERIOD") as HTMLInputElement).value).toBe(
841
+ "last month",
842
+ );
843
+ });
844
+
845
+ it("keeps the single day picker for one day", () => {
846
+ render(
847
+ <GivenInput given={given} value="2024-01-15" onChange={() => {}} />,
848
+ );
849
+ expect(screen.queryAllByTestId("time-range")).toHaveLength(0);
850
+ expect(screen.getByLabelText("PERIOD")).toBeDefined();
851
+ });
852
+ });
853
+
854
+ describe("GivenInput: the range slider's commits", () => {
855
+ const given: Given = {
856
+ name: "n",
857
+ type: "filter<number>",
858
+ rangeMin: 0,
859
+ rangeMax: 10,
860
+ };
861
+ const handles = () => screen.getAllByRole("slider") as HTMLInputElement[];
862
+
863
+ it("writes a closed range when the upper handle is inside the track", () => {
864
+ const onChange = mock((_next: GivenValue) => {});
865
+ render(<GivenInput given={given} value="[2 to 7]" onChange={onChange} />);
866
+ fireEvent.change(handles()[1], { target: { value: "6" } });
867
+ expect(onChange).toHaveBeenCalledWith("[2 to 6]");
868
+ });
869
+
870
+ it("collapses to a threshold once the upper handle reaches the ceiling", () => {
871
+ const onChange = mock((_next: GivenValue) => {});
872
+ render(<GivenInput given={given} value="[2 to 7]" onChange={onChange} />);
873
+ fireEvent.change(handles()[1], { target: { value: "10" } });
874
+ expect(onChange).toHaveBeenCalledWith(">= 2");
875
+ });
876
+
877
+ it("reverts when both handles are at the ends", () => {
878
+ const onChange = mock((_next: GivenValue) => {});
879
+ render(<GivenInput given={given} value=">= 2" onChange={onChange} />);
880
+ fireEvent.change(handles()[0], { target: { value: "0" } });
881
+ expect(onChange).toHaveBeenCalledWith(null);
882
+ });
883
+ });
@@ -12,6 +12,7 @@ import {
12
12
  FormHelperText,
13
13
  IconButton,
14
14
  InputAdornment,
15
+ MenuItem,
15
16
  Slider,
16
17
  Stack,
17
18
  TextField,
@@ -22,17 +23,25 @@ import { DatePicker } from "@mui/x-date-pickers/DatePicker";
22
23
  import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
23
24
  import dayjs from "dayjs";
24
25
  import utc from "dayjs/plugin/utc";
26
+ import { type ReactNode, useEffect, useState } from "react";
25
27
  import { Given } from "../../client";
26
28
  import { paramToGiven, pickedDayToUtc } from "./paramCodec";
27
29
  import { GivenValue } from "../../hooks/givenValue";
28
30
  import {
29
31
  decodeAtLeast,
32
+ decodeBetween,
33
+ decodeDayRange,
30
34
  decodeFilterList,
35
+ decodeTimePreset,
31
36
  encodeAtLeast,
37
+ encodeBetween,
38
+ encodeDayRange,
32
39
  encodeFilterList,
40
+ encodeTimePreset,
33
41
  filterInnerType,
34
42
  isFilterType,
35
43
  isPlainFilterList,
44
+ TIME_PRESETS,
36
45
  } from "./filterValue";
37
46
  import { renderGivenDefault } from "./utils";
38
47
 
@@ -383,33 +392,48 @@ export function GivenInput({
383
392
  );
384
393
  }
385
394
 
386
- // A slider, when the declaration bounded the range. Only a lower bound is
387
- // expressible as a filter here (see `encodeAtLeast`), so this reads as
388
- // "at least", which is what a threshold control is for.
395
+ // A slider, when the declaration bounded the range. For a `filter<number>`
396
+ // it has two handles and means "between", `[lo to hi]`, the same control and
397
+ // the same spelling Malloyyo gives the same tags; with the upper handle at
398
+ // the ceiling it collapses to the lower bound alone, `>= lo`, so a threshold
399
+ // is still one drag. A plain `number` given is a single value and keeps one
400
+ // handle.
389
401
  const numericFilter =
390
402
  isFilterType(type) && filterInnerType(type) === "number";
391
403
  const { rangeMin, rangeMax } = given;
392
- // A slider can only represent `>= N`, so a `filter<number>` carrying anything
393
- // else (a range, an upper bound, a negation) falls through to the text box.
394
- // Otherwise `decodeAtLeast` returns undefined, the slider claims "Any" while a
395
- // filter is in force, and the first drag silently replaces the author's filter
396
- // with a threshold. Same principle as the picker and the date guards above.
404
+ // The handles can show a closed range or a lower bound and nothing else, so
405
+ // a `filter<number>` carrying anything else (a half-open range, an upper
406
+ // bound alone, a negation) falls through to the text box. Otherwise the
407
+ // decoders return undefined, the slider claims "Any" while a filter is in
408
+ // force, and the first drag silently replaces the author's filter. Same
409
+ // principle as the picker and the date guards above.
410
+ const atLeast =
411
+ numericFilter && typeof value === "string"
412
+ ? decodeAtLeast(value)
413
+ : undefined;
414
+ const between =
415
+ numericFilter && typeof value === "string"
416
+ ? decodeBetween(value)
417
+ : undefined;
397
418
  const sliderIsRepresentable =
398
419
  !numericFilter ||
399
420
  value === undefined ||
400
421
  value === null ||
401
422
  value === "" ||
402
- (typeof value === "string" && decodeAtLeast(value) !== undefined);
423
+ atLeast !== undefined ||
424
+ between !== undefined;
403
425
  if (
404
426
  (numericFilter || type === "number") &&
405
427
  rangeMin !== undefined &&
406
428
  rangeMax !== undefined &&
407
429
  sliderIsRepresentable
408
430
  ) {
431
+ // The filter's handles: a range as written, or a lower bound with the
432
+ // upper handle resting at the ceiling. Undefined when nothing is set.
433
+ const handles: [number, number] | undefined =
434
+ between ?? (atLeast !== undefined ? [atLeast, rangeMax] : undefined);
409
435
  const current = numericFilter
410
- ? typeof value === "string"
411
- ? decodeAtLeast(value)
412
- : undefined
436
+ ? handles?.[0]
413
437
  : typeof value === "number"
414
438
  ? value
415
439
  : undefined;
@@ -427,6 +451,14 @@ export function GivenInput({
427
451
  }
428
452
  // An unset control rests at the low end, which is the no-op threshold.
429
453
  const position = current ?? rangeMin;
454
+ // And an unset range spans the whole track, which selects everything.
455
+ const thumbs: [number, number] = handles ?? [rangeMin, rangeMax];
456
+ // A range reads as `lo to hi`, and as `≥ lo` once the upper handle is at
457
+ // the ceiling, which is also what the value on the wire says.
458
+ const rangeReadout =
459
+ thumbs[1] >= rangeMax
460
+ ? `≥ ${thumbs[0]}`
461
+ : `${thumbs[0]} to ${thumbs[1]}`;
430
462
  // `""` on a filter given is an explicit "no threshold" OVERRIDE, not an
431
463
  // absence: `paramToGiven` keeps it because the empty string is a value a
432
464
  // filter can mean, and `givensToRequest` sends it. Counting it as unset
@@ -484,7 +516,7 @@ export function GivenInput({
484
516
  : emptyFilterOverride
485
517
  ? "Any"
486
518
  : numericFilter
487
- ? `≥ ${position}`
519
+ ? rangeReadout
488
520
  : String(position)}
489
521
  </Typography>
490
522
  {isOverridden && (
@@ -508,27 +540,51 @@ export function GivenInput({
508
540
  size="small"
509
541
  min={rangeMin}
510
542
  max={rangeMax}
511
- value={position}
543
+ value={numericFilter ? thumbs : position}
544
+ // Two handles must not cross: a swapped pair would encode a
545
+ // range the decoder refuses, and the control would fall
546
+ // through to the text box mid-drag.
547
+ disableSwap={numericFilter}
512
548
  valueLabelDisplay="auto"
513
- aria-label={label}
549
+ // One name per handle, so a test or a screen reader can tell
550
+ // them apart; a single handle keeps the plain label.
551
+ aria-label={numericFilter ? undefined : label}
552
+ getAriaLabel={
553
+ numericFilter
554
+ ? (index) =>
555
+ index === 0 ? `${label} from` : `${label} to`
556
+ : undefined
557
+ }
514
558
  // MUI pads a slider vertically for a touch target, which is
515
559
  // 26px this control cannot spare; the row above already
516
560
  // gives the thumb somewhere to be.
517
561
  sx={{ py: 0, mt: 0.5 }}
518
562
  onChange={(_event, next) => {
519
- const picked = Array.isArray(next) ? next[0] : next;
520
- // Back at the floor is no threshold at all for a FILTER,
521
- // not `>= min`, so dragging left the whole way clears
522
- // rather than leaving a filter that reads as a constraint.
523
- //
563
+ if (numericFilter) {
564
+ const [lo, hi] = Array.isArray(next)
565
+ ? [next[0], next[1]]
566
+ : [next, next];
567
+ // Both handles at the ends is no filter at all, not
568
+ // `[min to max]`, so dragging the whole way out clears
569
+ // rather than leaving a filter that reads as a
570
+ // constraint. The upper handle at the ceiling alone is
571
+ // a threshold, `>= lo`, which is what it was before
572
+ // the range existed and what a URL from then holds.
573
+ if (lo <= rangeMin && hi >= rangeMax) {
574
+ onChange(null);
575
+ return;
576
+ }
577
+ onChange(
578
+ hi >= rangeMax
579
+ ? encodeAtLeast(lo)
580
+ : encodeBetween(lo, hi),
581
+ );
582
+ return;
583
+ }
524
584
  // A plain `number` given is not a threshold, so its floor
525
585
  // is an ordinary value and clearing there made the minimum
526
586
  // the one number on the scale the reader could not pick.
527
- if (numericFilter && picked <= rangeMin) {
528
- onChange(null);
529
- return;
530
- }
531
- onChange(numericFilter ? encodeAtLeast(picked) : picked);
587
+ onChange(Array.isArray(next) ? next[0] : next);
532
588
  }}
533
589
  />
534
590
  </Box>
@@ -566,6 +622,28 @@ export function GivenInput({
566
622
  const bareDate =
567
623
  typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value);
568
624
  const dateIsPickable = value === undefined || value === null || bareDate;
625
+ // A time-range control for a date-typed filter that is unset, the empty
626
+ // filter, one of the preset windows, or a range of whole days. The presets
627
+ // are Malloyyo's, so a `filter<timestamp>` given draws the same control on
628
+ // either host and a value set on one reads on the other. A bare day keeps
629
+ // the single date picker below (it is what `# drill { to=self }` hands over,
630
+ // and one day is a day, not a range); anything else the grammar can say
631
+ // falls through to the text box, as written and editable.
632
+ if (isDateFilter && !bareDate) {
633
+ const state = readTimeRange(value);
634
+ if (state !== undefined) {
635
+ return (
636
+ <TimeRangeControl
637
+ label={label}
638
+ state={state}
639
+ onChange={onChange}
640
+ helperNode={helperNode}
641
+ defaultDisplay={defaultDisplay}
642
+ />
643
+ );
644
+ }
645
+ }
646
+
569
647
  // An unrepresentable date filter falls through to the text box below, for the
570
648
  // same reason a non-list string filter does: a range like
571
649
  // `2024-01-01 to 2024-02-01` handed whole to `dayjs.utc` parses as its
@@ -799,3 +877,200 @@ function ClearAdornment({ onClear }: { onClear: () => void }) {
799
877
  </InputAdornment>
800
878
  );
801
879
  }
880
+
881
+ /** What a time-range control is showing; undefined means it cannot show it. */
882
+ type TimeRangeState =
883
+ | { kind: "unset" }
884
+ /** An explicit `""`: the empty filter, matching every row, as an override. */
885
+ | { kind: "any" }
886
+ | { kind: "preset"; key: string }
887
+ | { kind: "days"; firstDay: string; lastDay: string };
888
+
889
+ function readTimeRange(
890
+ value: GivenValue | undefined,
891
+ ): TimeRangeState | undefined {
892
+ if (value === undefined || value === null) return { kind: "unset" };
893
+ if (typeof value !== "string") return undefined;
894
+ if (value === "") return { kind: "any" };
895
+ const key = decodeTimePreset(value);
896
+ if (key !== undefined) return { kind: "preset", key };
897
+ const days = decodeDayRange(value);
898
+ if (days !== undefined) return { kind: "days", ...days };
899
+ return undefined;
900
+ }
901
+
902
+ const CUSTOM_RANGE = "__custom__";
903
+ const ANY_TIME = "__any__";
904
+
905
+ /**
906
+ * Preset windows in a dropdown, with "Custom range" opening two day pickers.
907
+ *
908
+ * The pickers are inclusive on both ends, which is how a reader thinks about
909
+ * "January 1st to January 31st"; `encodeDayRange` handles the half-open grammar
910
+ * underneath. A custom range commits only once both days are picked and in
911
+ * order: a half-filled pair sends nothing rather than a range with one
912
+ * invented end, and the value in force meanwhile is whatever it was.
913
+ *
914
+ * Custom mode is local state, because choosing "Custom range" changes what is
915
+ * on screen before it changes the value. It follows the value when the value
916
+ * moves under it (a preset arriving from the URL, a revert), keyed on the
917
+ * value's shape rather than on the object, so it does not re-run every render.
918
+ */
919
+ function TimeRangeControl({
920
+ label,
921
+ state,
922
+ onChange,
923
+ helperNode,
924
+ defaultDisplay,
925
+ }: {
926
+ label: string;
927
+ state: TimeRangeState;
928
+ onChange: (next: GivenValue) => void;
929
+ helperNode: ReactNode;
930
+ defaultDisplay: string | undefined;
931
+ }) {
932
+ const stateKey =
933
+ state.kind === "days"
934
+ ? `days:${state.firstDay}/${state.lastDay}`
935
+ : state.kind === "preset"
936
+ ? `preset:${state.key}`
937
+ : state.kind;
938
+ const [custom, setCustom] = useState(state.kind === "days");
939
+ const [draft, setDraft] = useState<{ from?: string; to?: string }>(
940
+ state.kind === "days" ? { from: state.firstDay, to: state.lastDay } : {},
941
+ );
942
+ useEffect(() => {
943
+ if (state.kind === "days") {
944
+ setCustom(true);
945
+ setDraft({ from: state.firstDay, to: state.lastDay });
946
+ } else if (state.kind !== "unset") {
947
+ // A preset or the empty filter arrived: it is what is showing now.
948
+ setCustom(false);
949
+ }
950
+ // `stateKey` stands in for `state`, whose object identity is per render.
951
+ // eslint-disable-next-line react-hooks/exhaustive-deps
952
+ }, [stateKey]);
953
+
954
+ const isOverridden = state.kind !== "unset";
955
+ const selected = custom
956
+ ? CUSTOM_RANGE
957
+ : state.kind === "preset"
958
+ ? state.key
959
+ : state.kind === "any"
960
+ ? ANY_TIME
961
+ : "";
962
+
963
+ const commitDays = (next: { from?: string; to?: string }) => {
964
+ setDraft(next);
965
+ if (
966
+ next.from &&
967
+ next.to &&
968
+ !dayjs.utc(next.to).isBefore(dayjs.utc(next.from))
969
+ ) {
970
+ onChange(encodeDayRange(next.from, next.to));
971
+ }
972
+ };
973
+
974
+ const day = (text: string | undefined) => {
975
+ const parsed = text ? dayjs.utc(text) : null;
976
+ return parsed?.isValid() ? parsed : null;
977
+ };
978
+
979
+ return (
980
+ <Stack direction="row" spacing={1} data-testid="time-range">
981
+ <TextField
982
+ select
983
+ label={label}
984
+ value={selected}
985
+ size="small"
986
+ fullWidth
987
+ // Unset shows the model's own default as the helper line, the way
988
+ // every other control does; the dropdown itself stays blank so it
989
+ // does not assert a window nobody chose.
990
+ helperText={helperNode}
991
+ slotProps={{
992
+ select: {
993
+ displayEmpty: true,
994
+ renderValue: (v) => {
995
+ if (v === CUSTOM_RANGE) return "Custom range";
996
+ if (v === ANY_TIME) return "Any time";
997
+ const preset = TIME_PRESETS.find((p) => p.key === v);
998
+ return preset
999
+ ? preset.label
1000
+ : (defaultDisplay ?? "Any time");
1001
+ },
1002
+ },
1003
+ input: {
1004
+ endAdornment: isOverridden ? (
1005
+ // Before the dropdown arrow, which MUI positions on its
1006
+ // own; the × reverts, like every × in this file.
1007
+ <IconButton
1008
+ size="small"
1009
+ aria-label="clear value"
1010
+ onClick={() => {
1011
+ setCustom(false);
1012
+ setDraft({});
1013
+ onChange(null);
1014
+ }}
1015
+ sx={{ mr: 2 }}
1016
+ >
1017
+ <ClearIcon fontSize="small" />
1018
+ </IconButton>
1019
+ ) : undefined,
1020
+ },
1021
+ }}
1022
+ onChange={(e) => {
1023
+ const key = e.target.value;
1024
+ if (key === CUSTOM_RANGE) {
1025
+ // Nothing committed yet: the pickers decide.
1026
+ setCustom(true);
1027
+ return;
1028
+ }
1029
+ setCustom(false);
1030
+ const encoded = encodeTimePreset(key);
1031
+ if (encoded !== undefined) onChange(encoded);
1032
+ }}
1033
+ >
1034
+ {/* The empty filter is showable, since a URL can carry it, but not
1035
+ offered: the gesture for "no filter" is the ×, which reverts to
1036
+ the model default rather than overriding it with everything. */}
1037
+ {state.kind === "any" && (
1038
+ <MenuItem value={ANY_TIME}>Any time</MenuItem>
1039
+ )}
1040
+ {TIME_PRESETS.map((preset) => (
1041
+ <MenuItem key={preset.key} value={preset.key}>
1042
+ {preset.label}
1043
+ </MenuItem>
1044
+ ))}
1045
+ <MenuItem value={CUSTOM_RANGE}>Custom range</MenuItem>
1046
+ </TextField>
1047
+ {custom && (
1048
+ <LocalizationProvider dateAdapter={AdapterDayjs}>
1049
+ <DatePicker
1050
+ label="From"
1051
+ value={day(draft.from)}
1052
+ onChange={(next) =>
1053
+ commitDays({
1054
+ ...draft,
1055
+ from: next ? next.format("YYYY-MM-DD") : undefined,
1056
+ })
1057
+ }
1058
+ slotProps={{ textField: { size: "small" } }}
1059
+ />
1060
+ <DatePicker
1061
+ label="To"
1062
+ value={day(draft.to)}
1063
+ minDate={day(draft.from) ?? undefined}
1064
+ onChange={(next) =>
1065
+ commitDays({
1066
+ ...draft,
1067
+ to: next ? next.format("YYYY-MM-DD") : undefined,
1068
+ })
1069
+ }
1070
+ slotProps={{ textField: { size: "small" } }}
1071
+ />
1072
+ </LocalizationProvider>
1073
+ )}
1074
+ </Stack>
1075
+ );
1076
+ }