strata-react 0.1.5 → 0.1.9

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.
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
1
- import { _ as HttpError, a as useLoad, b as cn, c as ThemeProvider, d as useSystemColorScheme, f as ChoiceGroup, g as Textarea, h as NativeSelect, i as toLoad, l as colorSchemeScript, m as Input, n as createQueryClient, o as COLOR_SCHEME_STORAGE_KEY, p as Field, r as fetchJson, s as ColorSchemeChoice, t as StrataQueryProvider, u as useColorScheme, v as describeActionError, x as typeSteps, y as describeHttpError } from "./query-CmdlXVW_.js";
1
+ import { _ as HttpError, a as useLoad, b as cn, c as ThemeProvider, d as useSystemColorScheme, f as ChoiceGroup, g as Textarea, h as NativeSelect, i as toLoad, l as colorSchemeScript, m as Input, n as createQueryClient, o as COLOR_SCHEME_STORAGE_KEY, p as Field, r as fetchJson, s as ColorSchemeChoice, t as StrataQueryProvider, u as useColorScheme, v as describeActionError, x as typeSteps, y as describeHttpError } from "./query-5469ipOC.js";
2
2
  import * as React from "react";
3
3
  import { Slot } from "@radix-ui/react-slot";
4
4
  import { cva } from "class-variance-authority";
5
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
- import { ArrowDown, ArrowUp, ArrowUpDown, Check, CircleAlert, LoaderCircle, RotateCcw } from "lucide-react";
6
+ import { ArrowDown, ArrowUp, ArrowUpDown, Check, CircleAlert, LoaderCircle, RotateCcw, X } from "lucide-react";
7
7
  import { flexRender, getCoreRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
8
8
  import { useVirtualizer } from "@tanstack/react-virtual";
9
9
  import { Link, NavLink, useSearchParams } from "react-router";
10
+ import { hashKey, useInfiniteQuery } from "@tanstack/react-query";
10
11
  // src/lib/format.ts
11
12
  var NBSP = "\xA0";
12
13
  function callable(nf) {
@@ -109,6 +110,48 @@ function IconButton({ icon: Icon, label, variant = "ghost", ...props }) {
109
110
  children: /* @__PURE__ */ jsx(Icon, { "aria-hidden": true })
110
111
  });
111
112
  }
113
+ /** A small ghost action for one table row: shows `label`, and is named "`label` `subject`" so every row's action has its own name. */
114
+ function RowAction({ label, subject, icon: Icon, variant = "ghost", size = "sm", className, ...props }) {
115
+ return /* @__PURE__ */ jsxs(Button, {
116
+ variant,
117
+ size,
118
+ "aria-label": `${label} ${subject}`,
119
+ className: cn("-my-1.5", className),
120
+ ...props,
121
+ children: [Icon && /* @__PURE__ */ jsx(Icon, { "aria-hidden": true }), label]
122
+ });
123
+ }
124
+ // src/components/checkbox.tsx
125
+ /** A native checkbox and its label as one target. `label` is required; `hideLabel` keeps it as the accessible name only. */
126
+ function Checkbox({ label, hideLabel = false, detail, checked, onCheckedChange, className, disabled, ...props }) {
127
+ const ref = React.useRef(null);
128
+ React.useEffect(() => {
129
+ if (ref.current) ref.current.indeterminate = checked === "mixed";
130
+ }, [checked]);
131
+ return /* @__PURE__ */ jsxs("label", {
132
+ className: cn("inline-flex min-h-6 min-w-6 items-start gap-3", hideLabel && "items-center justify-center", disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer", className),
133
+ children: [/* @__PURE__ */ jsx("input", {
134
+ ref,
135
+ type: "checkbox",
136
+ checked: checked === true,
137
+ "aria-checked": checked === "mixed" ? "mixed" : void 0,
138
+ "aria-label": hideLabel ? label : void 0,
139
+ disabled,
140
+ onChange: (e) => onCheckedChange(e.target.checked),
141
+ className: cn("size-4.5 shrink-0 accent-primary", !hideLabel && "mt-0.5", disabled ? "cursor-not-allowed" : "cursor-pointer"),
142
+ ...props
143
+ }), !hideLabel && /* @__PURE__ */ jsxs("span", {
144
+ className: "grid",
145
+ children: [/* @__PURE__ */ jsx("span", {
146
+ className: "type-body",
147
+ children: label
148
+ }), detail && /* @__PURE__ */ jsx("span", {
149
+ className: "type-body-sm text-muted-foreground",
150
+ children: detail
151
+ })]
152
+ })]
153
+ });
154
+ }
112
155
  // src/components/async-button.tsx
113
156
  /** One button through idle, pending, done and error, with the label changing in place and its width fixed by the longest label. The outcome is announced politely, with the error's own words when `error` is given. */
114
157
  function AsyncButton({ phase, labels, error, disabled, ...props }) {
@@ -365,7 +408,31 @@ function UrlSortedTable(props) {
365
408
  sortState: useUrlSort(props.sortParam, props.initialSort)
366
409
  });
367
410
  }
368
- function Table({ caption, columns, rows, rowKey, sortState: [sort, setSort], virtualizeFrom = 100, maxHeight = 480, className }) {
411
+ function useSelectAll(rows, rowKey, selection) {
412
+ return React.useMemo(() => {
413
+ if (!selection) return void 0;
414
+ const keys = rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey);
415
+ const chosen = keys.filter((k) => selection.selected.has(k)).length;
416
+ const checked = chosen === 0 ? false : chosen === keys.length ? true : "mixed";
417
+ const toggle = () => {
418
+ const next = new Set(selection.selected);
419
+ if (checked === false) keys.forEach((k) => next.add(k));
420
+ else keys.forEach((k) => next.delete(k));
421
+ selection.onChange(next);
422
+ };
423
+ return {
424
+ checked,
425
+ toggle,
426
+ disabled: keys.length === 0
427
+ };
428
+ }, [
429
+ rows,
430
+ rowKey,
431
+ selection
432
+ ]);
433
+ }
434
+ function Table({ caption, columns, rows, rowKey, sortState: [sort, setSort], virtualizeFrom = 100, maxHeight = 480, selection, className }) {
435
+ const selectAll = useSelectAll(rows, rowKey, selection);
369
436
  const defs = React.useMemo(() => columns.map((c) => ({
370
437
  id: c.key,
371
438
  accessorFn: (row) => row,
@@ -376,6 +443,7 @@ function Table({ caption, columns, rows, rowKey, sortState: [sort, setSort], vir
376
443
  meta: {
377
444
  numeric: c.numeric,
378
445
  truncate: c.truncate,
446
+ hideHeader: c.hideHeader,
379
447
  className: c.className
380
448
  }
381
449
  })), [columns]);
@@ -389,7 +457,8 @@ function Table({ caption, columns, rows, rowKey, sortState: [sort, setSort], vir
389
457
  state: { sorting },
390
458
  getRowId: (row) => rowKey(row),
391
459
  getCoreRowModel: getCoreRowModel(),
392
- getSortedRowModel: getSortedRowModel()
460
+ getSortedRowModel: getSortedRowModel(),
461
+ autoResetAll: false
393
462
  });
394
463
  const toggle = (key) => setSort({
395
464
  key,
@@ -417,7 +486,7 @@ function Table({ caption, columns, rows, rowKey, sortState: [sort, setSort], vir
417
486
  role: "region",
418
487
  "aria-label": caption,
419
488
  tabIndex: 0,
420
- className: cn("min-w-0 overflow-x-auto", virtual && "overflow-y-auto", className),
489
+ className: cn("relative min-w-0 overflow-x-auto", virtual && "overflow-y-auto", className),
421
490
  style: virtual ? { maxHeight } : void 0,
422
491
  children: /* @__PURE__ */ jsxs("table", {
423
492
  className: "w-full border-collapse type-body-sm",
@@ -429,11 +498,26 @@ function Table({ caption, columns, rows, rowKey, sortState: [sort, setSort], vir
429
498
  }),
430
499
  /* @__PURE__ */ jsx("thead", {
431
500
  className: cn(virtual && "sticky top-0 z-10 bg-background"),
432
- children: table.getHeaderGroups().map((group) => /* @__PURE__ */ jsx("tr", { children: group.headers.map((header) => {
501
+ children: table.getHeaderGroups().map((group) => /* @__PURE__ */ jsxs("tr", { children: [selectAll && /* @__PURE__ */ jsx("th", {
502
+ scope: "col",
503
+ className: "w-8 py-2 pr-2 text-left align-bottom",
504
+ children: /* @__PURE__ */ jsx(Checkbox, {
505
+ className: "-my-1",
506
+ label: "Select all shown",
507
+ hideLabel: true,
508
+ checked: selectAll.checked,
509
+ disabled: selectAll.disabled,
510
+ onCheckedChange: selectAll.toggle
511
+ })
512
+ }), group.headers.map((header) => {
433
513
  const meta = header.column.columnDef.meta;
434
514
  const active = sort?.key === header.id && header.column.getCanSort() ? sort.dir : void 0;
435
515
  const Icon = active === "ascending" ? ArrowUp : active === "descending" ? ArrowDown : ArrowUpDown;
436
- const label = flexRender(header.column.columnDef.header, header.getContext());
516
+ const rendered = flexRender(header.column.columnDef.header, header.getContext());
517
+ const label = meta?.hideHeader ? /* @__PURE__ */ jsx("span", {
518
+ className: "sr-only",
519
+ children: rendered
520
+ }) : rendered;
437
521
  return /* @__PURE__ */ jsx("th", {
438
522
  scope: "col",
439
523
  "aria-sort": active,
@@ -448,24 +532,42 @@ function Table({ caption, columns, rows, rowKey, sortState: [sort, setSort], vir
448
532
  })]
449
533
  }) : label
450
534
  }, header.id);
451
- }) }, group.id))
535
+ })] }, group.id))
452
536
  }),
453
537
  /* @__PURE__ */ jsxs("tbody", { children: [
454
538
  padTop > 0 && /* @__PURE__ */ jsx("tr", {
455
539
  "aria-hidden": true,
456
540
  style: { height: padTop }
457
541
  }),
458
- visible.map((row, i) => /* @__PURE__ */ jsx("tr", {
459
- className: "border-t border-border",
460
- "aria-rowindex": virtual ? (items[i]?.index ?? 0) + 2 : void 0,
461
- children: row.getVisibleCells().map((cell) => {
462
- const meta = cell.column.columnDef.meta;
463
- return /* @__PURE__ */ jsx("td", {
464
- className: cn("py-2.5 pr-4 align-middle last:pr-0", meta?.numeric && "text-right tabular-nums", meta?.truncate && "max-w-48 truncate", meta?.className),
465
- children: flexRender(cell.column.columnDef.cell, cell.getContext())
466
- }, cell.id);
467
- })
468
- }, row.id)),
542
+ visible.map((row, i) => {
543
+ const chosen = selection?.selected.has(row.id) ?? false;
544
+ return /* @__PURE__ */ jsxs("tr", {
545
+ className: cn("border-t border-border", chosen && "bg-surface-sunken"),
546
+ "aria-rowindex": virtual ? (items[i]?.index ?? 0) + 2 : void 0,
547
+ children: [selection && /* @__PURE__ */ jsx("td", {
548
+ className: "w-8 py-2.5 pr-2 align-middle",
549
+ children: /* @__PURE__ */ jsx(Checkbox, {
550
+ className: "-my-0.5",
551
+ label: `Select ${selection.rowLabel(row.original)}`,
552
+ hideLabel: true,
553
+ checked: chosen,
554
+ disabled: !(selection.isSelectable?.(row.original) ?? true),
555
+ onCheckedChange: (on) => {
556
+ const next = new Set(selection.selected);
557
+ if (on) next.add(row.id);
558
+ else next.delete(row.id);
559
+ selection.onChange(next);
560
+ }
561
+ })
562
+ }), row.getVisibleCells().map((cell) => {
563
+ const meta = cell.column.columnDef.meta;
564
+ return /* @__PURE__ */ jsx("td", {
565
+ className: cn("py-2.5 pr-4 align-middle last:pr-0", meta?.numeric && "text-right tabular-nums", meta?.truncate && "max-w-48 truncate", meta?.className),
566
+ children: flexRender(cell.column.columnDef.cell, cell.getContext())
567
+ }, cell.id);
568
+ })]
569
+ }, row.id);
570
+ }),
469
571
  padBottom > 0 && /* @__PURE__ */ jsx("tr", {
470
572
  "aria-hidden": true,
471
573
  style: { height: padBottom }
@@ -489,9 +591,55 @@ function TableSkeleton({ rows = 4, columns = 5 }) {
489
591
  }, r))]
490
592
  });
491
593
  }
594
+ // src/components/selection.tsx
595
+ /** Chosen row keys, pruned to the rows that exist, and the calls that change them. Spread into `DataTable`'s `selection` with a `rowLabel`. */
596
+ function useSelection(rows, rowKey, initial = []) {
597
+ const [raw, setRaw] = React.useState(() => new Set(initial));
598
+ const selected = React.useMemo(() => {
599
+ const present = new Set(rows.map(rowKey));
600
+ return new Set([...raw].filter((k) => present.has(k)));
601
+ }, [raw, rows]);
602
+ const selectedRows = React.useMemo(() => rows.filter((r) => selected.has(rowKey(r))), [rows, selected]);
603
+ React.useEffect(() => {
604
+ if (selected.size !== raw.size) setRaw(selected);
605
+ }, [selected, raw]);
606
+ const onChange = React.useCallback((next) => setRaw(next), []);
607
+ const clear = React.useCallback(() => setRaw(/* @__PURE__ */ new Set()), []);
608
+ return {
609
+ selected,
610
+ selectedRows,
611
+ count: selected.size,
612
+ onChange,
613
+ clear
614
+ };
615
+ }
616
+ /** The bar for a selection: a polite live count ("2 bookings selected"), the bulk actions, and Clear selection. Renders only the live region while nothing is chosen. */
617
+ function BulkBar({ count, noun, onClear, children, format: format$1 = format, className }) {
618
+ const [one, many] = typeof noun === "string" ? [noun, `${noun}s`] : noun;
619
+ const label = `${format$1.count(count, one, many)} selected`;
620
+ return /* @__PURE__ */ jsxs("div", {
621
+ className: cn(count > 0 && "flex flex-wrap items-center gap-x-4 gap-y-2 rounded-surface bg-surface-sunken py-1.5 pr-1.5 pl-3", className),
622
+ children: [/* @__PURE__ */ jsx("p", {
623
+ "aria-live": "polite",
624
+ className: count > 0 ? "type-label tabular-nums" : "sr-only",
625
+ children: count > 0 ? label : `No ${many} selected`
626
+ }), count > 0 && /* @__PURE__ */ jsxs("div", {
627
+ role: "group",
628
+ "aria-label": `Actions for the selected ${many}`,
629
+ className: "flex flex-1 flex-wrap items-center gap-2",
630
+ children: [children, /* @__PURE__ */ jsxs(Button, {
631
+ size: "sm",
632
+ variant: "ghost",
633
+ className: "ml-auto",
634
+ onClick: onClear,
635
+ children: [/* @__PURE__ */ jsx(X, { "aria-hidden": true }), "Clear selection"]
636
+ })]
637
+ })]
638
+ });
639
+ }
492
640
  // src/components/virtual-list.tsx
493
641
  /** A list that renders only its visible rows (TanStack Virtual) from `virtualizeFrom` items, keeping list semantics for screen readers. */
494
- function VirtualList({ label, items, itemKey, children, estimateSize = 48, height = 480, virtualizeFrom = 100, className }) {
642
+ function VirtualList({ label, items, itemKey, children, estimateSize = 48, height = 480, virtualizeFrom = 100, bounded = false, footer, className }) {
495
643
  const scroller = React.useRef(null);
496
644
  const virtual = items.length >= virtualizeFrom;
497
645
  const virtualizer = useVirtualizer({
@@ -504,22 +652,28 @@ function VirtualList({ label, items, itemKey, children, estimateSize = 48, heigh
504
652
  height
505
653
  }
506
654
  });
507
- if (!virtual) return /* @__PURE__ */ jsx("ul", {
655
+ const plain = () => /* @__PURE__ */ jsx("ul", {
508
656
  "aria-label": label,
509
- className: cn("grid min-w-0", className),
657
+ className: cn("grid min-w-0", !bounded && !footer && className),
510
658
  children: items.map((item, i) => /* @__PURE__ */ jsx("li", {
659
+ "data-index": i,
511
660
  className: "border-t border-border first:border-t-0",
512
661
  children: children(item, i)
513
662
  }, itemKey(item)))
514
663
  });
515
- return /* @__PURE__ */ jsx("div", {
664
+ if (!virtual && !bounded) return footer ? /* @__PURE__ */ jsxs("div", {
665
+ className: cn("min-w-0", className),
666
+ children: [plain(), footer]
667
+ }) : plain();
668
+ return /* @__PURE__ */ jsxs("div", {
516
669
  ref: scroller,
517
670
  role: "region",
518
671
  "aria-label": label,
519
672
  tabIndex: 0,
673
+ "data-strata-scroll": "",
520
674
  className: cn("min-w-0 overflow-y-auto", className),
521
- style: { height },
522
- children: /* @__PURE__ */ jsx("ul", {
675
+ style: virtual ? { height } : { maxHeight: height },
676
+ children: [virtual ? /* @__PURE__ */ jsx("ul", {
523
677
  "aria-label": label,
524
678
  className: "relative w-full",
525
679
  style: { height: virtualizer.getTotalSize() },
@@ -535,9 +689,150 @@ function VirtualList({ label, items, itemKey, children, estimateSize = 48, heigh
535
689
  children: children(item, v.index)
536
690
  }, itemKey(item));
537
691
  })
692
+ }) : plain(), footer]
693
+ });
694
+ }
695
+ // src/components/infinite-list.tsx
696
+ /** A cursor-paged list for `useInfiniteLoad`: DataView's first-page states, virtual rows, and a next-page row that loads on approach, shows a skeleton, or says why it failed with Try again. */
697
+ function InfiniteList({ state, label, children, skeleton, empty, moreLabel, moreSkeleton = skeleton, end, rootMargin = "400px", keepAtLeast = 0, estimateSize, height = 480, virtualizeFrom, className }) {
698
+ const { more, itemKey } = state;
699
+ const held = state.status === "ready" ? state.data.length : 0;
700
+ const box = React.useRef(null);
701
+ const near = useNearEnd(state.status === "ready" && more.hasMore, rootMargin);
702
+ const { hasMore, loadingMore, error, loadMore } = more;
703
+ React.useEffect(() => {
704
+ if (state.status !== "ready" || !hasMore || loadingMore || error) return;
705
+ if (near.inView || held < keepAtLeast) loadMore();
706
+ }, [
707
+ state.status,
708
+ hasMore,
709
+ loadingMore,
710
+ error,
711
+ near.inView,
712
+ held,
713
+ keepAtLeast,
714
+ loadMore
715
+ ]);
716
+ const focusFrom = React.useRef(null);
717
+ const loadByHand = () => {
718
+ focusFrom.current = held;
719
+ loadMore();
720
+ };
721
+ React.useEffect(() => {
722
+ const from = focusFrom.current;
723
+ if (from === null || loadingMore) return;
724
+ if (held > from) {
725
+ const row = box.current?.querySelector(`li[data-index="${from}"]`);
726
+ if (row) {
727
+ row.tabIndex = -1;
728
+ row.focus();
729
+ }
730
+ focusFrom.current = null;
731
+ } else if (error || !hasMore) focusFrom.current = null;
732
+ }, [
733
+ held,
734
+ loadingMore,
735
+ error,
736
+ hasMore
737
+ ]);
738
+ const footer = /* @__PURE__ */ jsxs("div", { children: [
739
+ hasMore && !error && /* @__PURE__ */ jsx("div", {
740
+ ref: near.ref,
741
+ "aria-hidden": true,
742
+ className: "h-px"
743
+ }),
744
+ loadingMore ? /* @__PURE__ */ jsx("div", {
745
+ "aria-hidden": true,
746
+ className: "border-t border-border",
747
+ children: moreSkeleton
748
+ }) : error ? /* @__PURE__ */ jsxs("div", {
749
+ role: "alert",
750
+ className: "flex flex-wrap items-start gap-3 border-t border-border bg-danger-subtle px-3 py-2 text-danger",
751
+ children: [
752
+ /* @__PURE__ */ jsx(CircleAlert, {
753
+ "aria-hidden": true,
754
+ className: "mt-0.5 size-4 shrink-0"
755
+ }),
756
+ /* @__PURE__ */ jsx("p", {
757
+ className: "min-w-0 flex-1 type-body-sm",
758
+ children: error
759
+ }),
760
+ /* @__PURE__ */ jsxs(Button, {
761
+ size: "sm",
762
+ onClick: loadByHand,
763
+ children: [/* @__PURE__ */ jsx(RotateCcw, { "aria-hidden": true }), "Try again"]
764
+ })
765
+ ]
766
+ }) : hasMore ? /* @__PURE__ */ jsx("div", {
767
+ className: "border-t border-border py-3",
768
+ children: /* @__PURE__ */ jsx(Button, {
769
+ size: "sm",
770
+ onClick: loadByHand,
771
+ children: moreLabel
772
+ })
773
+ }) : end && /* @__PURE__ */ jsx("div", {
774
+ className: "border-t border-border py-3 type-body-sm text-muted-foreground",
775
+ children: end
776
+ }),
777
+ /* @__PURE__ */ jsx("p", {
778
+ role: "status",
779
+ className: "sr-only",
780
+ children: loadingMore ? "Loading more" : ""
781
+ })
782
+ ] });
783
+ return /* @__PURE__ */ jsx(DataView, {
784
+ state,
785
+ isEmpty: (items) => items.length === 0 && !hasMore,
786
+ skeleton,
787
+ empty,
788
+ className,
789
+ children: (items) => /* @__PURE__ */ jsx("div", {
790
+ ref: box,
791
+ "aria-busy": loadingMore || void 0,
792
+ children: /* @__PURE__ */ jsx(VirtualList, {
793
+ label,
794
+ items,
795
+ itemKey,
796
+ estimateSize,
797
+ height,
798
+ virtualizeFrom,
799
+ bounded: true,
800
+ footer,
801
+ children
802
+ })
538
803
  })
539
804
  });
540
805
  }
806
+ /**
807
+ * Watches a sentinel element and reports whether it is within `rootMargin` of its scroll region
808
+ * (the nearest `[data-strata-scroll]` ancestor, else the viewport). A callback ref, so it follows
809
+ * the sentinel as it mounts and unmounts.
810
+ */
811
+ function useNearEnd(active, rootMargin) {
812
+ const [inView, setInView] = React.useState(false);
813
+ const [el, setEl] = React.useState(null);
814
+ React.useEffect(() => {
815
+ if (!active || !el || typeof IntersectionObserver === "undefined") {
816
+ setInView(false);
817
+ return;
818
+ }
819
+ const root = el.parentElement?.closest("[data-strata-scroll]") ?? null;
820
+ const observer = new IntersectionObserver((entries) => setInView(entries[entries.length - 1].isIntersecting), {
821
+ root,
822
+ rootMargin
823
+ });
824
+ observer.observe(el);
825
+ return () => observer.disconnect();
826
+ }, [
827
+ active,
828
+ el,
829
+ rootMargin
830
+ ]);
831
+ return {
832
+ ref: setEl,
833
+ inView
834
+ };
835
+ }
541
836
  // src/components/line-chart.tsx
542
837
  function useWidth() {
543
838
  const ref = React.useRef(null);
@@ -552,35 +847,86 @@ function useWidth() {
552
847
  }, []);
553
848
  return [ref, width];
554
849
  }
555
- /** Four gridline steps of a size people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ), ending above the max. */
556
- function niceMax(max) {
557
- if (!(max > 0)) return 4;
558
- const raw = max / 4;
850
+ /** The smallest step of a size people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ) at least `raw`. */
851
+ function niceStep(raw) {
559
852
  const mag = 10 ** Math.floor(Math.log10(raw));
560
- return ([
853
+ return [
561
854
  1,
562
855
  2,
563
856
  2.5,
564
857
  4,
565
858
  5,
566
859
  10
567
- ].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag) * 4;
860
+ ].map((m) => m * mag).find((s) => s >= raw * (1 - 1e-9)) ?? 10 * mag;
861
+ }
862
+ /**
863
+ * The y-axis: four equal gridline steps covering every value. With no pins the steps are a size
864
+ * people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ), from zero or a round number below the lowest
865
+ * reading. A pinned end is used as given unless a value lies beyond it.
866
+ */
867
+ function yScale(values, pin = {}) {
868
+ const finite = values.filter(Number.isFinite);
869
+ const dMin = finite.length ? Math.min(...finite) : 0;
870
+ const dMax = finite.length ? Math.max(...finite) : 0;
871
+ const pinMin = pin.min !== void 0 && dMin >= pin.min ? pin.min : void 0;
872
+ const pinMax = pin.max !== void 0 && dMax <= pin.max ? pin.max : void 0;
873
+ let lo = pinMin ?? Math.min(0, dMin);
874
+ if (pinMax !== void 0 && pinMin === void 0 && !(pinMax > lo)) lo = pinMax - (Math.abs(pinMax) || 4);
875
+ let min;
876
+ let max;
877
+ if (pinMax !== void 0) {
878
+ max = pinMax;
879
+ min = pinMin ?? (lo < 0 ? Math.floor(lo / niceStep((max - lo) / 4)) * niceStep((max - lo) / 4) : 0);
880
+ } else {
881
+ const hi = Math.max(dMax, pin.max ?? -Infinity);
882
+ let step = hi > lo ? niceStep((hi - lo) / 4) : 1;
883
+ let base = pinMin ?? Math.floor(lo / step) * step;
884
+ while (base + 4 * step < hi) {
885
+ step = niceStep(step * 1.01);
886
+ base = pinMin ?? Math.floor(lo / step) * step;
887
+ }
888
+ min = base;
889
+ max = base + 4 * step;
890
+ }
891
+ if (!(max > min)) max = min + 4;
892
+ return {
893
+ min,
894
+ max,
895
+ ticks: [
896
+ 0,
897
+ 1,
898
+ 2,
899
+ 3,
900
+ 4
901
+ ].map((i) => min + (max - min) * i / 4)
902
+ };
903
+ }
904
+ /** Roughly how wide a 12px caption label is, in px. jsdom cannot measure text, so the chart estimates. */
905
+ var labelWidth = (text) => text.length * 7;
906
+ /**
907
+ * The x ticks that fit at this width: every k-th tick, the smallest k for which neighbouring labels
908
+ * leave a gap, so the spacing stays even. `scale` maps an x value to a pixel.
909
+ */
910
+ function fitTicks(ticks, scale, widthOf, gap = 12) {
911
+ if (ticks.length < 3) return ticks;
912
+ const sorted = [...ticks].sort((a, b) => a - b);
913
+ for (let k = 1; k < sorted.length; k++) {
914
+ const kept = sorted.filter((_, i) => i % k === 0);
915
+ if (kept.every((t, i) => i === 0 || scale(t) - scale(kept[i - 1]) >= (widthOf(t) + widthOf(kept[i - 1])) / 2 + gap)) return kept;
916
+ }
917
+ return sorted.slice(0, 1);
568
918
  }
569
919
  /** One measured series, drawn in real pixels, with the peak and current readings labelled on the chart and every reading in a screen-reader table. Optional plan, threshold band and `colourScale`. */
570
- function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, formatX, formatY, xTicks, colour = "var(--chart-1)", colourScale, colourScaleLabel, height = 280, className }) {
920
+ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, formatX, formatY, xTicks, yMin, yMax, colour = "var(--chart-1)", colourScale, colourScaleLabel, height = 280, className }) {
571
921
  const [ref, width] = useWidth();
572
922
  const gradientId = `heat-${React.useId().replace(/[^\w-]/g, "")}`;
573
923
  const all = [...series, ...planned ?? []];
574
924
  const xMin = Math.min(...all.map((p) => p.x));
575
925
  const xMax = Math.max(...all.map((p) => p.x));
576
- const yMax = niceMax(Math.max(...all.map((p) => p.y)));
577
- const yTicks = [
578
- 0,
579
- .25,
580
- .5,
581
- .75,
582
- 1
583
- ].map((f) => f * yMax);
926
+ const y = yScale(all.map((p) => p.y), {
927
+ min: yMin,
928
+ max: yMax
929
+ });
584
930
  const pad = {
585
931
  top: 16,
586
932
  right: 16,
@@ -590,7 +936,13 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
590
936
  const w = Math.max(0, width - pad.left - pad.right);
591
937
  const h = height - pad.top - pad.bottom;
592
938
  const sx = (x) => pad.left + (x - xMin) / (xMax - xMin || 1) * w;
593
- const sy = (y) => pad.top + h - y / yMax * h;
939
+ const sy = (v) => pad.top + h - (v - y.min) / (y.max - y.min) * h;
940
+ const xLabelWidth = (t) => labelWidth(formatX(t));
941
+ const xLabelAt = (t) => {
942
+ const half = xLabelWidth(t) / 2;
943
+ return Math.min(Math.max(sx(t), half), Math.max(half, width - half));
944
+ };
945
+ const shownXTicks = fitTicks(xTicks, xLabelAt, xLabelWidth);
594
946
  const path = (pts) => pts.map((p, i) => `${i ? "L" : "M"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join("");
595
947
  const last = series[series.length - 1];
596
948
  const peak = series.reduce((a, b) => b.y > a.y ? b : a, series[0]);
@@ -616,26 +968,26 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
616
968
  gradientUnits: "userSpaceOnUse",
617
969
  x1: 0,
618
970
  x2: 0,
619
- y1: sy(0),
620
- y2: sy(yMax),
971
+ y1: sy(y.min),
972
+ y2: sy(y.max),
621
973
  children: stops.map((s) => /* @__PURE__ */ jsx("stop", {
622
- offset: Math.min(1, Math.max(0, s.at / yMax)),
974
+ offset: Math.min(1, Math.max(0, (s.at - y.min) / (y.max - y.min))),
623
975
  stopColor: s.colour
624
976
  }, s.at))
625
977
  }) }),
626
- band && /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("rect", {
978
+ band && band.below > y.min && /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("rect", {
627
979
  x: pad.left,
628
- y: sy(band.below),
980
+ y: sy(Math.min(band.below, y.max)),
629
981
  width: w,
630
- height: sy(0) - sy(band.below),
982
+ height: sy(y.min) - sy(Math.min(band.below, y.max)),
631
983
  fill: "var(--success-subtle)"
632
984
  }), /* @__PURE__ */ jsx("text", {
633
985
  x: pad.left + 8,
634
- y: sy(band.below) + 16,
986
+ y: sy(Math.min(band.below, y.max)) + 16,
635
987
  className: "fill-success type-caption",
636
988
  children: band.label
637
989
  })] }),
638
- yTicks.map((t) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
990
+ y.ticks.map((t) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
639
991
  x1: pad.left,
640
992
  x2: pad.left + w,
641
993
  y1: sy(t),
@@ -650,8 +1002,8 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
650
1002
  className: "fill-muted-foreground type-caption tabular-nums",
651
1003
  children: formatY(t)
652
1004
  })] }, t)),
653
- xTicks.map((t) => /* @__PURE__ */ jsx("text", {
654
- x: sx(t),
1005
+ shownXTicks.map((t) => /* @__PURE__ */ jsx("text", {
1006
+ x: xLabelAt(t),
655
1007
  y: height - 8,
656
1008
  textAnchor: "middle",
657
1009
  className: "fill-muted-foreground type-caption tabular-nums",
@@ -810,56 +1162,167 @@ function PageHeader({ title, scope, actions, finding, as: Heading = "h1" }) {
810
1162
  });
811
1163
  }
812
1164
  // src/components/undo.tsx
813
- /** Schedules a reversible removal to commit after `windowMs` unless undone. A second removal, or unmounting, commits the pending one. */
814
- function useUndoable(windowMs = 8e3) {
1165
+ /**
1166
+ * Schedules a reversible removal to commit after a window unless undone, and owns which items
1167
+ * are out of view meanwhile.
1168
+ *
1169
+ * Only one removal is pending at a time: scheduling a second commits the first immediately.
1170
+ * Unmounting inside the window commits the pending removal (leaving is not Undo), so a navigation
1171
+ * or a test that unmounts still sends the commit's request: await `flush()` before a dependent
1172
+ * action, and in tests let MSW answer the request or flush before unmounting.
1173
+ */
1174
+ function useUndoable(options = {}) {
1175
+ const { windowMs = 8e3, describeError = describeActionError } = typeof options === "number" ? { windowMs: options } : options;
815
1176
  const [pending, setPending] = React.useState(null);
1177
+ const [failed, setFailed] = React.useState(null);
1178
+ const [removed, setRemoved] = React.useState(() => /* @__PURE__ */ new Set());
816
1179
  const current = React.useRef(null);
817
1180
  const timer = React.useRef(void 0);
818
- const set = React.useCallback((p) => {
819
- current.current = p;
820
- setPending(p);
1181
+ const mounted = React.useRef(true);
1182
+ const inFlight = React.useRef(/* @__PURE__ */ new Set());
1183
+ const describe = React.useRef(describeError);
1184
+ describe.current = describeError;
1185
+ const hide = React.useCallback((p, out) => {
1186
+ const ids = p.ids ?? [p.id];
1187
+ setRemoved((s) => {
1188
+ if (ids.every((id) => s.has(id) === out)) return s;
1189
+ const n = new Set(s);
1190
+ for (const id of ids) if (out) n.add(id);
1191
+ else n.delete(id);
1192
+ return n;
1193
+ });
821
1194
  }, []);
822
- const schedule = React.useCallback((next) => {
1195
+ const attempt = React.useCallback((p) => {
1196
+ let result;
1197
+ try {
1198
+ result = p.commit();
1199
+ } catch (error) {
1200
+ result = Promise.reject(error);
1201
+ }
1202
+ const done = Promise.resolve(result).then(() => void 0, (error) => {
1203
+ if (mounted.current) {
1204
+ hide(p, false);
1205
+ setFailed({
1206
+ removal: p,
1207
+ message: describe.current(error)
1208
+ });
1209
+ }
1210
+ p.onError?.(error);
1211
+ throw error;
1212
+ });
1213
+ inFlight.current.add(done);
1214
+ const settle = () => void inFlight.current.delete(done);
1215
+ done.then(settle, settle);
1216
+ return done;
1217
+ }, [hide]);
1218
+ const take = React.useCallback(() => {
823
1219
  window.clearTimeout(timer.current);
824
- current.current?.commit();
825
- set(next);
826
- timer.current = window.setTimeout(() => {
827
- current.current?.commit();
828
- set(null);
829
- }, windowMs);
830
- }, [set, windowMs]);
1220
+ const p = current.current;
1221
+ if (!p) return null;
1222
+ current.current = null;
1223
+ if (mounted.current) setPending(null);
1224
+ return {
1225
+ removal: p,
1226
+ done: attempt(p)
1227
+ };
1228
+ }, [attempt]);
1229
+ const commitDetached = React.useCallback(() => {
1230
+ const t = take();
1231
+ t?.done.catch((error) => {
1232
+ if (!mounted.current && !t.removal.onError) throw error;
1233
+ });
1234
+ }, [take]);
1235
+ const schedule = React.useCallback((next) => {
1236
+ commitDetached();
1237
+ setFailed(null);
1238
+ hide(next, true);
1239
+ current.current = next;
1240
+ setPending(next);
1241
+ timer.current = window.setTimeout(commitDetached, windowMs);
1242
+ }, [
1243
+ commitDetached,
1244
+ hide,
1245
+ windowMs
1246
+ ]);
831
1247
  const undo = React.useCallback(() => {
832
1248
  window.clearTimeout(timer.current);
833
- set(null);
834
- }, [set]);
835
- React.useEffect(() => () => {
836
- window.clearTimeout(timer.current);
837
- current.current?.commit();
1249
+ const p = current.current;
838
1250
  current.current = null;
839
- }, []);
1251
+ setPending(null);
1252
+ if (p) hide(p, false);
1253
+ }, [hide]);
1254
+ const flush = React.useCallback(async () => {
1255
+ take();
1256
+ const failure = (await Promise.allSettled([...inFlight.current])).find((r) => r.status === "rejected");
1257
+ if (failure) throw failure.reason;
1258
+ }, [take]);
1259
+ const retry = React.useCallback(() => {
1260
+ if (!failed) return Promise.resolve();
1261
+ setFailed(null);
1262
+ hide(failed.removal, true);
1263
+ return attempt(failed.removal);
1264
+ }, [
1265
+ attempt,
1266
+ failed,
1267
+ hide
1268
+ ]);
1269
+ const dismiss = React.useCallback(() => setFailed(null), []);
1270
+ const isRemoved = React.useCallback((id) => removed.has(id), [removed]);
1271
+ React.useEffect(() => {
1272
+ mounted.current = true;
1273
+ return () => {
1274
+ mounted.current = false;
1275
+ commitDetached();
1276
+ };
1277
+ }, [commitDetached]);
840
1278
  return {
841
1279
  pending,
1280
+ failed,
1281
+ isRemoved,
842
1282
  schedule,
843
- undo
1283
+ undo,
1284
+ flush,
1285
+ retry,
1286
+ dismiss
844
1287
  };
845
1288
  }
846
- /** The polite live region that shows a pending removal with an Undo button. */
847
- function UndoBar({ pending, onUndo, inline = false }) {
1289
+ /** The polite live region that shows a pending removal with Undo, or a failed one with Try again. Pass it the whole `useUndoable()` result. */
1290
+ function UndoBar({ undoable, inline = false }) {
1291
+ const { pending, failed, undo, retry, dismiss } = undoable;
1292
+ const ghost = "text-background hover:bg-neutral-11";
848
1293
  return /* @__PURE__ */ jsx("div", {
849
1294
  "aria-live": "polite",
850
1295
  className: inline ? "flex" : "pointer-events-none fixed inset-x-0 bottom-4 z-50 flex justify-center px-4",
851
- children: pending && /* @__PURE__ */ jsxs("div", {
1296
+ children: (pending || failed) && /* @__PURE__ */ jsx("div", {
852
1297
  className: "pointer-events-auto flex max-w-lg items-center gap-4 rounded-overlay bg-foreground py-2 pr-2 pl-4 text-background shadow-overlay",
853
- children: [/* @__PURE__ */ jsx("p", {
1298
+ children: pending ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", {
854
1299
  className: "min-w-0 type-body-sm",
855
1300
  children: pending.message
856
1301
  }), /* @__PURE__ */ jsx(Button, {
857
1302
  size: "sm",
858
1303
  variant: "ghost",
859
- className: "text-background hover:bg-neutral-11",
860
- onClick: onUndo,
1304
+ className: ghost,
1305
+ onClick: undo,
861
1306
  children: "Undo"
862
- })]
1307
+ })] }) : failed && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", {
1308
+ className: "min-w-0 type-body-sm",
1309
+ children: failed.message ? `${failed.removal.failure} ${failed.message}` : failed.removal.failure
1310
+ }), /* @__PURE__ */ jsxs("div", {
1311
+ className: "flex shrink-0 gap-1",
1312
+ children: [/* @__PURE__ */ jsx(Button, {
1313
+ size: "sm",
1314
+ variant: "ghost",
1315
+ className: ghost,
1316
+ onClick: () => void retry().catch(() => void 0),
1317
+ children: "Try again"
1318
+ }), /* @__PURE__ */ jsx(Button, {
1319
+ size: "sm",
1320
+ variant: "ghost",
1321
+ className: ghost,
1322
+ onClick: dismiss,
1323
+ children: "Dismiss"
1324
+ })]
1325
+ })] })
863
1326
  })
864
1327
  });
865
1328
  }
@@ -1037,6 +1500,321 @@ function Tabs({ param, items, label, children, className }) {
1037
1500
  })]
1038
1501
  });
1039
1502
  }
1040
- export { AppShell, AsyncButton, Breadcrumb, Button, COLOR_SCHEME_STORAGE_KEY, ChoiceGroup, ColorSchemeChoice, DataTable, DataView, Done, EmptyState, Field, HttpError, IconButton, Input, LineChart, Metric, MetricStrip, NBSP, NativeSelect, PageHeader, SideNav, Skeleton, Status, StrataQueryProvider, TableSkeleton, Tabs, Textarea, ThemeProvider, UndoBar, VirtualList, buttonVariants, cn, colorSchemeScript, createFormat, createQueryClient, describeActionError, describeHttpError, fetchJson, format, parseSort, serialiseSort, toLoad, typeSteps, useAsyncAction, useColorScheme, useLoad, useSystemColorScheme, useUndoable };
1503
+ // src/components/hotkeys.tsx
1504
+ var TEXT_INPUTS_EXEMPT = /* @__PURE__ */ new Set([
1505
+ "checkbox",
1506
+ "radio",
1507
+ "button",
1508
+ "submit",
1509
+ "reset",
1510
+ "range",
1511
+ "color",
1512
+ "file"
1513
+ ]);
1514
+ /** True when a key pressed on this element is the person typing, so single-key shortcuts must leave it alone. */
1515
+ function isTypingTarget(target) {
1516
+ if (!(target instanceof HTMLElement)) return false;
1517
+ if (target.isContentEditable || target.closest("[contenteditable=''],[contenteditable='true']")) return true;
1518
+ if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;
1519
+ if (target instanceof HTMLInputElement) return !TEXT_INPUTS_EXEMPT.has(target.type);
1520
+ return false;
1521
+ }
1522
+ function toShortcuts(input) {
1523
+ return Array.isArray(input) ? input : Object.entries(input).map(([key, run]) => ({
1524
+ keys: [key],
1525
+ label: key,
1526
+ run
1527
+ }));
1528
+ }
1529
+ /**
1530
+ * Binds single-key shortcuts on the window, ignoring keys typed into fields, chords with Ctrl, Meta
1531
+ * or Alt, IME composition and (unless `repeat`) held keys. Pass the same list to `KeysLegend`.
1532
+ */
1533
+ function useHotkeys(shortcuts, { enabled = true } = {}) {
1534
+ const latest = React.useRef([]);
1535
+ latest.current = toShortcuts(shortcuts);
1536
+ React.useEffect(() => {
1537
+ if (!enabled) return;
1538
+ const onKeyDown = (e) => {
1539
+ if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey) return;
1540
+ if (isTypingTarget(e.target)) return;
1541
+ const hit = latest.current.find((s) => !s.disabled && s.keys.includes(e.key));
1542
+ if (!hit || e.repeat && !hit.repeat) return;
1543
+ e.preventDefault();
1544
+ hit.run();
1545
+ };
1546
+ window.addEventListener("keydown", onKeyDown);
1547
+ return () => window.removeEventListener("keydown", onKeyDown);
1548
+ }, [enabled]);
1549
+ }
1550
+ var KEY_NAMES = {
1551
+ ArrowDown: "↓",
1552
+ ArrowUp: "↑",
1553
+ ArrowLeft: "←",
1554
+ ArrowRight: "→",
1555
+ Escape: "Esc",
1556
+ Enter: "Enter",
1557
+ Backspace: "Backspace",
1558
+ Delete: "Delete",
1559
+ " ": "Space"
1560
+ };
1561
+ /** A quiet legend of the screen's shortcuts, from the same list `useHotkeys` binds. Hidden on touch screens. */
1562
+ function KeysLegend({ shortcuts, label = "Keyboard shortcuts", className }) {
1563
+ return /* @__PURE__ */ jsx("dl", {
1564
+ "aria-label": label,
1565
+ className: cn("flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden", className),
1566
+ children: shortcuts.map((s) => /* @__PURE__ */ jsxs("div", {
1567
+ className: cn("flex items-center gap-1.5", s.disabled && "opacity-50"),
1568
+ children: [/* @__PURE__ */ jsx("dt", {
1569
+ className: "flex items-center gap-1",
1570
+ children: s.keys.map((k, i) => /* @__PURE__ */ jsxs(React.Fragment, { children: [i > 0 && /* @__PURE__ */ jsx("span", {
1571
+ className: "sr-only",
1572
+ children: " or "
1573
+ }), /* @__PURE__ */ jsx("kbd", {
1574
+ className: "min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground",
1575
+ children: KEY_NAMES[k] ?? k
1576
+ })] }, k))
1577
+ }), /* @__PURE__ */ jsx("dd", { children: s.label })]
1578
+ }, s.keys.join(" ")))
1579
+ });
1580
+ }
1581
+ // src/components/active-list.tsx
1582
+ /** Tracks the active item in a list worked through from the keyboard: moving, roving focus, and moving on when the active item is removed. */
1583
+ function useActiveItem(items, getKey, { initial, noun } = {}) {
1584
+ const [chosen, setChosen] = React.useState(initial ?? null);
1585
+ const lastIndex = React.useRef(0);
1586
+ const elements = React.useRef(/* @__PURE__ */ new Map());
1587
+ const navigated = React.useRef(false);
1588
+ const focusWithin = React.useRef(false);
1589
+ const keys = items.map(getKey);
1590
+ let index = chosen === null ? -1 : keys.indexOf(chosen);
1591
+ if (index === -1 && keys.length > 0) index = Math.min(lastIndex.current, keys.length - 1);
1592
+ const activeKey = index >= 0 ? keys[index] : null;
1593
+ const prevActive = React.useRef(activeKey);
1594
+ React.useLayoutEffect(() => {
1595
+ if (index >= 0) lastIndex.current = index;
1596
+ const gone = prevActive.current;
1597
+ prevActive.current = activeKey;
1598
+ if (gone !== null && gone !== chosen && !keys.includes(gone)) setChosen(gone);
1599
+ });
1600
+ React.useLayoutEffect(() => {
1601
+ const el = activeKey === null ? void 0 : elements.current.get(activeKey);
1602
+ const focused = document.activeElement;
1603
+ const lost = focusWithin.current && (focused === null || focused === document.body);
1604
+ const elsewhereInList = focused !== null && !el?.contains(focused) && [...elements.current.values()].some((item) => item.contains(focused));
1605
+ if (el && (navigated.current || lost || elsewhereInList)) {
1606
+ el.focus({ preventScroll: true });
1607
+ el.scrollIntoView?.({ block: "nearest" });
1608
+ }
1609
+ navigated.current = false;
1610
+ }, [activeKey]);
1611
+ const moveTo = (i) => {
1612
+ if (keys.length === 0) return;
1613
+ const to = Math.max(0, Math.min(keys.length - 1, i));
1614
+ navigated.current = true;
1615
+ if (to === index) {
1616
+ const el = elements.current.get(keys[to]);
1617
+ el?.focus({ preventScroll: true });
1618
+ el?.scrollIntoView?.({ block: "nearest" });
1619
+ navigated.current = false;
1620
+ }
1621
+ setChosen(keys[to]);
1622
+ };
1623
+ const next = () => moveTo(index + 1);
1624
+ const prev = () => moveTo(index - 1);
1625
+ const first = () => moveTo(0);
1626
+ const last = () => moveTo(keys.length - 1);
1627
+ const setActive = (key) => {
1628
+ const i = keys.indexOf(key);
1629
+ if (i >= 0) moveTo(i);
1630
+ };
1631
+ const name = noun ? ` ${noun}` : "";
1632
+ const shortcuts = [{
1633
+ keys: ["j"],
1634
+ label: `Next${name}`,
1635
+ run: next,
1636
+ repeat: true,
1637
+ disabled: keys.length === 0
1638
+ }, {
1639
+ keys: ["k"],
1640
+ label: `Previous${name}`,
1641
+ run: prev,
1642
+ repeat: true,
1643
+ disabled: keys.length === 0
1644
+ }];
1645
+ const itemProps = (key) => ({
1646
+ ref: (el) => {
1647
+ if (el) elements.current.set(key, el);
1648
+ else elements.current.delete(key);
1649
+ },
1650
+ tabIndex: key === activeKey ? 0 : -1,
1651
+ "aria-current": key === activeKey ? "true" : void 0,
1652
+ "data-active": key === activeKey ? "" : void 0,
1653
+ onFocus: () => {
1654
+ focusWithin.current = true;
1655
+ if (key !== activeKey) setChosen(key);
1656
+ },
1657
+ onBlur: (e) => {
1658
+ const to = e.relatedTarget;
1659
+ if (to instanceof Node && ![...elements.current.values()].some((el) => el.contains(to))) focusWithin.current = false;
1660
+ }
1661
+ });
1662
+ return {
1663
+ items,
1664
+ getKey,
1665
+ activeKey,
1666
+ activeItem: index >= 0 ? items[index] : null,
1667
+ index,
1668
+ next,
1669
+ prev,
1670
+ first,
1671
+ last,
1672
+ setActive,
1673
+ shortcuts,
1674
+ itemProps
1675
+ };
1676
+ }
1677
+ /** A keyboard-worked queue: the active item is a roving tab stop with aria-current, and the arrow keys, Home and End move it. */
1678
+ function ActiveList({ label, active, empty, children, className }) {
1679
+ if (active.items.length === 0) return /* @__PURE__ */ jsx(Fragment, { children: empty });
1680
+ const onKeyDown = (e) => {
1681
+ if (e.ctrlKey || e.metaKey || e.altKey || isTypingTarget(e.target)) return;
1682
+ const move = e.key === "ArrowDown" ? active.next : e.key === "ArrowUp" ? active.prev : e.key === "Home" ? active.first : e.key === "End" ? active.last : void 0;
1683
+ if (!move) return;
1684
+ e.preventDefault();
1685
+ move();
1686
+ };
1687
+ return /* @__PURE__ */ jsx("ul", {
1688
+ "aria-label": label,
1689
+ onKeyDown,
1690
+ className: cn("grid gap-px", className),
1691
+ children: active.items.map((item) => {
1692
+ const key = active.getKey(item);
1693
+ const isActive = key === active.activeKey;
1694
+ return /* @__PURE__ */ jsx("li", {
1695
+ ...active.itemProps(key),
1696
+ className: cn("rounded-control border-l-2 px-3 py-2 -outline-offset-2", isActive ? "border-foreground bg-accent text-accent-foreground" : "border-transparent"),
1697
+ children: children(item, { active: isActive })
1698
+ }, key);
1699
+ })
1700
+ });
1701
+ }
1702
+ // src/query/infinite.ts
1703
+ /** `useInfiniteQuery` for cursor-paged data, returned as an `InfiniteLoad<T>` for `InfiniteList` (or `DataView`). */
1704
+ function useInfiniteLoad({ queryKey, queryFn, items, itemKey, hasMore, cursorAfter = itemKey, isRemoved, describeError = describeHttpError, enabled, staleTime }) {
1705
+ const queryHash = hashKey(queryKey);
1706
+ const [stored, setStored] = React.useState(() => ({
1707
+ query: queryHash,
1708
+ keys: /* @__PURE__ */ new Set()
1709
+ }));
1710
+ const dismissed = stored.query === queryHash ? stored.keys : none;
1711
+ const hidden = React.useCallback((key) => dismissed.has(key) || (isRemoved?.(key) ?? false), [dismissed, isRemoved]);
1712
+ const latest = React.useRef({
1713
+ hidden,
1714
+ items,
1715
+ itemKey,
1716
+ hasMore,
1717
+ cursorAfter
1718
+ });
1719
+ latest.current = {
1720
+ hidden,
1721
+ items,
1722
+ itemKey,
1723
+ hasMore,
1724
+ cursorAfter
1725
+ };
1726
+ const query = useInfiniteQuery({
1727
+ queryKey,
1728
+ queryFn: ({ pageParam, signal }) => queryFn({
1729
+ cursor: pageParam.cursor,
1730
+ signal
1731
+ }),
1732
+ initialPageParam: { cursor: void 0 },
1733
+ getNextPageParam: (lastPage, pages) => {
1734
+ const l = latest.current;
1735
+ if (!l.hasMore(lastPage)) return null;
1736
+ const after = nextAfter(pages, l.items, l.itemKey, l.hidden);
1737
+ return { cursor: after === void 0 ? void 0 : l.cursorAfter(after) };
1738
+ },
1739
+ enabled,
1740
+ staleTime
1741
+ });
1742
+ const pages = query.data?.pages;
1743
+ const list = React.useMemo(() => pages ? merge(pages, latest.current.items, latest.current.itemKey, hidden).held : void 0, [pages, hidden]);
1744
+ const { hasNextPage, isFetchingNextPage, fetchNextPage, refetch } = query;
1745
+ const loadMore = React.useCallback(() => {
1746
+ if (hasNextPage && !isFetchingNextPage) fetchNextPage();
1747
+ }, [
1748
+ hasNextPage,
1749
+ isFetchingNextPage,
1750
+ fetchNextPage
1751
+ ]);
1752
+ const change = React.useCallback((edit) => setStored((s) => {
1753
+ const keys = new Set(s.query === queryHash ? s.keys : none);
1754
+ edit(keys);
1755
+ return {
1756
+ query: queryHash,
1757
+ keys
1758
+ };
1759
+ }), [queryHash]);
1760
+ const dismiss = React.useCallback((key) => change((keys) => keys.add(key)), [change]);
1761
+ const restore = React.useCallback((key) => change((keys) => keys.delete(key)), [change]);
1762
+ const extra = {
1763
+ more: {
1764
+ hasMore: Boolean(hasNextPage),
1765
+ loadingMore: isFetchingNextPage,
1766
+ error: query.isFetchNextPageError ? describeError(query.error) : void 0,
1767
+ loadMore
1768
+ },
1769
+ itemKey,
1770
+ dismiss,
1771
+ restore
1772
+ };
1773
+ if (list) return {
1774
+ status: "ready",
1775
+ data: list,
1776
+ ...extra
1777
+ };
1778
+ if (query.status === "error") return {
1779
+ status: "error",
1780
+ message: describeError(query.error),
1781
+ retry: () => void refetch(),
1782
+ ...extra
1783
+ };
1784
+ return {
1785
+ status: "loading",
1786
+ ...extra
1787
+ };
1788
+ }
1789
+ var none = /* @__PURE__ */ new Set();
1790
+ /** Every page's items, in order, once each by key: the ones held (not dismissed) and the last one seen. */
1791
+ function merge(pages, items, itemKey, hidden) {
1792
+ const seen = /* @__PURE__ */ new Set();
1793
+ const held = [];
1794
+ let last;
1795
+ let lastPageAddedAny = false;
1796
+ pages.forEach((page, p) => {
1797
+ for (const item of items(page)) {
1798
+ const key = itemKey(item);
1799
+ if (seen.has(key)) continue;
1800
+ seen.add(key);
1801
+ last = item;
1802
+ if (p === pages.length - 1) lastPageAddedAny = true;
1803
+ if (!hidden(key)) held.push(item);
1804
+ }
1805
+ });
1806
+ return {
1807
+ held,
1808
+ last,
1809
+ lastPageAddedAny
1810
+ };
1811
+ }
1812
+ /** The item the next page goes after: the last held, or the last seen when nothing is held or the last page brought nothing new. */
1813
+ function nextAfter(pages, items, itemKey, hidden) {
1814
+ const { held, last, lastPageAddedAny } = merge(pages, items, itemKey, hidden);
1815
+ if (held.length === 0 || pages.length > 1 && !lastPageAddedAny) return last;
1816
+ return held[held.length - 1];
1817
+ }
1818
+ export { ActiveList, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorSchemeChoice, DataTable, DataView, Done, EmptyState, Field, HttpError, IconButton, InfiniteList, Input, KeysLegend, LineChart, Metric, MetricStrip, NBSP, NativeSelect, PageHeader, RowAction, SideNav, Skeleton, Status, StrataQueryProvider, TableSkeleton, Tabs, Textarea, ThemeProvider, UndoBar, VirtualList, buttonVariants, cn, colorSchemeScript, createFormat, createQueryClient, describeActionError, describeHttpError, fetchJson, format, isTypingTarget, parseSort, serialiseSort, toLoad, typeSteps, useActiveItem, useAsyncAction, useColorScheme, useHotkeys, useInfiniteLoad, useLoad, useSelection, useSystemColorScheme, useUndoable };
1041
1819
 
1042
1820
  //# sourceMappingURL=index.js.map