@makoai/app-sdk 2.26.0 → 2.28.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.
package/README.md CHANGED
@@ -455,6 +455,32 @@ an app's own menu that folds several filters into one dropdown on a phone.
455
455
  </DropdownMenuSubContent>
456
456
  ```
457
457
 
458
+ **Search (2.27).** `searchable` puts a search input at the top of the menu.
459
+ The order is search, All, a separator, then the values.
460
+
461
+ ```tsx
462
+ <MultiSelect searchable options={owners} value={owner} onChange={setOwner} allLabel="All owners" showOnly />
463
+ ```
464
+
465
+ - The input takes focus when the menu opens.
466
+ - Typing filters the rows by label, case-insensitive. A group whose label matches keeps all its rows.
467
+ - All and its separator hide while a query is typed. "No match" shows when no row matches (`searchEmpty`).
468
+ - The keys are shadcn Command's (cmdk). ArrowDown and ArrowUp move the highlight. Home and End jump to the ends. Enter ticks the highlighted row.
469
+ - The first row is highlighted after every keystroke, so "type a name, Enter" ticks it.
470
+ - A tick follows the All rule above, as a click does.
471
+ - The query clears when the menu closes.
472
+ - `searchPlaceholder` sets the placeholder (default "Search").
473
+ - Without `searchable` the menu is unchanged.
474
+
475
+ **Counts (2.28).** An option's `count` shows muted at the row's right edge.
476
+ It works in `MultiSelect` and `FilterItems`. Search matches the label only.
477
+ The trigger shows the label only. A number prints with thousands separators
478
+ (1,234). Put the count here, never in the label.
479
+
480
+ ```tsx
481
+ <MultiSelect searchable options={offices.map(o => ({ value: o.id, label: o.name, count: o.n }))} value={office} onChange={setOffice} allLabel="All offices" />
482
+ ```
483
+
458
484
  **Replacing an app's NestedFilterMenu: `FilterMenu`.** See "Menus" below:
459
485
  `FilterMenu` and `FilterMenuItems` from `@makoai/app-sdk/menu` take
460
486
  NestedFilterMenu's props (`label`, `options`, `selected`, `onChange`,
@@ -566,6 +592,29 @@ import { Calendar } from "@makoai/app-sdk/components/calendar";
566
592
  import { Command, CommandInput, CommandList } from "@makoai/app-sdk/components/command";
567
593
  ```
568
594
 
595
+ **Searchable single choice: `Combobox` (2.28).** shadcn's combobox recipe
596
+ (Popover + Command) on its own subpath, since it loads cmdk. A pick closes
597
+ it. Picking the picked row again clears the value to `null`. The trigger
598
+ shows `placeholder` while the value is `null`.
599
+
600
+ ```tsx
601
+ import { Combobox } from "@makoai/app-sdk/components/combobox";
602
+
603
+ <Combobox
604
+ aria-label="CSM"
605
+ placeholder="All CSMs"
606
+ searchPlaceholder="Filter CSMs..."
607
+ options={csms.map(r => ({ value: r.csm, label: r.csm, count: r.n, keywords: [r.countries] }))}
608
+ value={csm}
609
+ onChange={setCsm}
610
+ />
611
+ ```
612
+
613
+ - Search matches `label` and `keywords`. It never matches `value` or `count`.
614
+ - `count` shows muted at the row's right edge. The trigger never shows it.
615
+ - `icon` sits before the trigger text. `className` sizes the trigger (default `w-[200px]`).
616
+ - The keys are cmdk's: arrows move, Enter picks, Escape closes.
617
+
569
618
  shadcn's stock components pass refs as props, so they need React 19. On
570
619
  React 18 a ref is dropped: a Calendar's arrow keys stop moving focus. Apps
571
620
  that use them run React 19; `mako-app-lint --rules=react-version` flags any
@@ -589,6 +638,104 @@ house tokens onto Tailwind's colour names (`bg-popover`,
589
638
  optional peer set: apps that import neither `/components` nor `/menu` need
590
639
  none of it.
591
640
 
641
+ ### Date filters: `PeriodPicker` (2.27)
642
+
643
+ A date filter reads **‹ Nov 2026 ›**. The arrows step one period. The middle
644
+ opens a picker with the units, the recent periods and a Custom range. The
645
+ period in progress is tinted and says "in progress": its numbers are not
646
+ final.
647
+
648
+ ```tsx
649
+ import { PeriodPicker, clipToday, periodOf, todayIso, type Period } from "@makoai/app-sdk/components";
650
+
651
+ const [period, setPeriod] = useState<Period>(periodOf("month", todayIso()));
652
+ <PeriodPicker value={period} onChange={setPeriod}
653
+ units={["week", "month", "quarter", "year"]} min="2024-01-01" label="Hires" />
654
+
655
+ const { from, to } = clipToday(period); // the month in progress stops at today
656
+ ```
657
+
658
+ - `units` defaults to month, quarter and year. The picker lists 12 weeks,
659
+ 12 months, 8 quarters or 4 years.
660
+ - `custom` is `"month"` (whole months, the default), `"day"` (any days) or
661
+ `false`. The arrows move a custom range by its own length.
662
+ - ‹ stops at `min`, the first day with data. › stops at today, or at `max`
663
+ (next month's end for a capacity plan).
664
+ - `periodOf(unit, day)`, `shift(period, k)`, `isCurrent(period)`,
665
+ `clipToday(period)` and `periodLabel(period)` are the helpers. Dates are
666
+ "YYYY-MM-DD" UTC day keys, both ends inclusive. Weeks start on Monday.
667
+ - The menu is the stock `Popover`. Focus moves into it on open and back to
668
+ the middle on Escape.
669
+
670
+ ### The page filter bar (2.27)
671
+
672
+ `FilterBar` puts the page-wide filters in one row under the tabs. Each control
673
+ gets a small-caps label over it. `FilterSep` draws the hairline between two
674
+ groups. Reset sits at the end and stays disabled while every filter is at its
675
+ default. The row wraps on a narrow window. At 768px and under the fields fold
676
+ behind one Filters chip that counts the active filters. The chip opens a
677
+ bottom sheet with Done.
678
+
679
+ A tab adds its own fields with `TabFilters`. They render into the same bar,
680
+ after the page's. `useResettable(id, dirty, reset)` tells Reset and the chip
681
+ about a tab's filter. Wrap the page in `FilterProvider`.
682
+
683
+ ```tsx
684
+ import {
685
+ FilterBar, FilterField, FilterProvider, FilterSep, TabFilters, useResettable,
686
+ Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
687
+ } from "@makoai/app-sdk/components";
688
+
689
+ function RoleTab() {
690
+ const [role, setRole] = useState("bdr");
691
+ useResettable("role", role !== "bdr", () => setRole("bdr"));
692
+ return (
693
+ <TabFilters>
694
+ <FilterSep />
695
+ <FilterField label="Role" hint="The role at hire">
696
+ <Select value={role} onValueChange={setRole}>
697
+ <SelectTrigger aria-label="Role" className="w-[210px]"><SelectValue /></SelectTrigger>
698
+ <SelectContent>{ROLES.map(r => <SelectItem key={r.value} value={r.value}>{r.label}</SelectItem>)}</SelectContent>
699
+ </Select>
700
+ </FilterField>
701
+ </TabFilters>
702
+ );
703
+ }
704
+
705
+ <FilterProvider>
706
+ <FilterBar dirty={market !== "ALL"} onReset={() => setMarket("ALL")}>
707
+ <FilterField label="Market">{/* Select, FilterMenu or MultiSelect */}</FilterField>
708
+ </FilterBar>
709
+ {tab === "role" && <RoleTab />}
710
+ </FilterProvider>
711
+ ```
712
+
713
+ The bar holds any control: `Select`, `FilterMenu`, `MultiSelect`. In the
714
+ phone sheet each control takes the full width. The sheet sits at z-index 50,
715
+ so the Radix popovers of `/components` and `/menu` open above it. Escape
716
+ closes an open popover first and the sheet on the next press.
717
+
718
+ ### Country colours: `COUNTRY_COLORS`, `COUNTRY_ORDER` (2.27)
719
+
720
+ A market has one colour in every app. Keys are lowercase codes.
721
+
722
+ ```ts
723
+ import { COUNTRY_COLORS, COUNTRY_ORDER } from "@makoai/app-sdk";
724
+
725
+ COUNTRY_COLORS.ch; // "#dc2626"; `all` is "#475569", the all-markets line
726
+ COUNTRY_ORDER; // ["ch", "fr", "es", "it", "pl", "pt"]
727
+ rows.sort((a, b) => COUNTRY_ORDER.indexOf(a.country) - COUNTRY_ORDER.indexOf(b.country));
728
+ ```
729
+
730
+ CH red, FR blue, IT green, ES amber, PT teal, PL rose. Other series in a
731
+ country chart take `--chart-1…5`. Both objects are frozen.
732
+
733
+ 2.28 adds the 6 lead-only markets of dbt seed `markets` (valuation funnel
734
+ only, no agents): DE violet, AT lime, CZ ochre, NL orange, BE fuchsia, GB navy
735
+ (realadvisor.co.uk). `COUNTRY_ORDER` keeps the 6 site markets. The lead-only
736
+ markets follow them in the map's key order, so an app that lists markets from
737
+ data sorts by `COUNTRY_ORDER`, then by key order of `COUNTRY_COLORS`.
738
+
592
739
  ### Times and dates (2.21)
593
740
 
594
741
  DuckDB runs in UTC, and that stays. Display code decides the zone.
@@ -624,6 +771,15 @@ Run it in an app folder (or pass several). It exits 1 on a finding;
624
771
  anything inside a `<>` fragment: a chart loses its reference lines. The
625
772
  fix is `"pnpm": { "overrides": { "react-is": "^19.1.10" } }`.
626
773
 
774
+ - `distinct-sum` (2.27, warning): a binding column that is a distinct count
775
+ (`COUNT(DISTINCT …)`, `uniq…`, `APPROX_COUNT_DISTINCT`) summed in `src/`
776
+ (`SUM(col)` in DuckDB SQL, or a JS `reduce`/`sum`/`pivot` next to it). One
777
+ person in several groups counts once per group: visibility-dashboard's unique
778
+ users read 13% high in Spain (19 Nov 2026). Return the total at the shown
779
+ grain from the binding (`GROUP BY GROUPING SETS`), or mark a deliberate sum
780
+ ("user-days") with `// mako-lint-ignore distinct-sum` and the reason.
781
+ Warnings print and never fail the run.
782
+
627
783
  `--rules=react-version` runs only the named rules (2.24).
628
784
 
629
785
  ### Chart tooltips: `TableTooltip` (2.10+, every series from 2.15)
@@ -683,6 +839,29 @@ const SEGMENTS = [ // bottom-up, as stacked; drives the bars, the legend AND the
683
839
  - On a chart with an HTML overlay (a donut's centre label), lift the tooltip:
684
840
  `<Tooltip wrapperStyle={{ zIndex: 20 }} … />`.
685
841
 
842
+ **Stacks: an absent segment is a zero, plus its share.** A stacked bar's
843
+ bucket often has no row for a segment (no 3xx requests that hour). That is a
844
+ zero, not missing data. `absentAsZero: true` turns a null or absent key into a
845
+ muted "0". NaN stays a "–" (a mean the bucket cannot compute). `share: true`
846
+ adds `share` to each row: its value over the sum of the non-missing values,
847
+ null when the value is missing or the sum is 0. `colWidth` on `TableTooltip`
848
+ sets the value columns' minimum width (`"9ch"`, or px as a number). Both
849
+ options are off by default, and with them off the rows are the same as before.
850
+
851
+ ```tsx
852
+ content={tableTooltip((d) => {
853
+ const rows = tooltipSeriesRows(d, STACKS, { stacked: true, absentAsZero: true, share: true });
854
+ const total = rows.reduce((a, r) => a + (r.value ?? 0), 0);
855
+ return {
856
+ title: d.hour,
857
+ columns: ["Requests", "% of total"],
858
+ colWidth: "9ch",
859
+ rows: rows.map((r) => ({ ...r, cells: [tooltipCell(r.value, fmtInt), tooltipCell(r.share, fmtPct, { percent: true })] })),
860
+ total: { label: "Total", cells: [tooltipCell(total, fmtInt), total > 0 ? "100%" : tooltipCell(0, fmtPct, { percent: true })] },
861
+ };
862
+ })}
863
+ ```
864
+
686
865
  **Opt-out.** Before 2.15, `tooltipSeriesRows` dropped zero and missing values
687
866
  and sorted line charts highest value first. A caller that truly needs that
688
867
  passes `{ hideEmpty: true, byValue: true }`. `hideEmpty` drops zero and
@@ -767,6 +946,47 @@ const COLUMNS: DataTableColumn<Customer>[] = [
767
946
  focused row); clicks on links and buttons inside a cell stay theirs.
768
947
  `rowLabel(row)` names a clickable row for screen readers. `rowKey` defaults
769
948
  to `row.id`.
949
+ - **Row tints.** `rowClassName(row)` adds a class to a body row. Set
950
+ `--mk-dt-row-bg` in that class and every cell paints it, the pinned first
951
+ column included. Pick an opaque colour so scrolled cells stay behind the
952
+ pin. Without `rowClassName` rows get no class.
953
+
954
+ ```tsx
955
+ // app.css: .deal-lost { --mk-dt-row-bg: color-mix(in srgb, var(--negative) 12%, var(--card)); }
956
+ <DataTable rows={deals} columns={COLUMNS} rowClassName={d => (d.status === "lost" ? "deal-lost" : undefined)} />
957
+ ```
958
+ - **Labels.** `labels` translates every string the table writes itself: the
959
+ footer, the empty state, the page-size select, the « ‹ › » aria-labels, the
960
+ sort hint and the export button. Pass any subset. Missing keys keep the
961
+ English defaults in `DATA_TABLE_LABELS`. Text with numbers is a function
962
+ that gets raw numbers, so format them in your locale. `noun` still names the
963
+ rows, and an `empty` prop wins over `labels.empty`.
964
+
965
+ ```tsx
966
+ const fr = (n: number) => n.toLocaleString("fr-FR");
967
+ const FR: Partial<DataTableLabels> = {
968
+ range: (from, to, total, noun) => `${fr(from)}–${fr(to)} sur ${fr(total)} ${noun}`,
969
+ none: noun => `Aucun ${noun.replace(/s$/, "")}`,
970
+ empty: "Aucune ligne pour ces filtres.",
971
+ page: (page, pageCount) => `Page ${page} sur ${pageCount}`,
972
+ perPage: size => `${size} par page`,
973
+ rowsPerPage: "Lignes par page",
974
+ first: "Première page",
975
+ previous: "Page précédente",
976
+ next: "Page suivante",
977
+ last: "Dernière page",
978
+ sortHint: label => `${label} · cliquer pour trier`,
979
+ exportCsv: "Exporter en CSV",
980
+ exportTitle: "Exporter toutes les lignes, dans l'ordre du tri",
981
+ exportFailed: "Le navigateur a bloqué le téléchargement. Ouvrez l'app dans un nouvel onglet.",
982
+ };
983
+
984
+ <DataTable rows={list} columns={COLUMNS} noun="clients" labels={FR} />
985
+ // footer: 51–100 sur 1 234 clients · 50 par page · « ‹ Page 2 sur 25 › »
986
+ ```
987
+
988
+ The English `range` bolds the two numbers. A custom `range` may return JSX
989
+ to do the same.
770
990
  - **CSV.** `exportFilename` adds an "Export CSV" button that downloads every
771
991
  row on every page, as sorted. Mako's app frames allow downloads. Numbers
772
992
  export as is. Text starting with `=`, `+`, `-`, `@`, tab or CR gets a
@@ -774,8 +994,60 @@ const COLUMNS: DataTableColumn<Customer>[] = [
774
994
  midnight exports as `YYYY-MM-DD`, any other Date as a UTC ISO timestamp. For
775
995
  your own button: `saveCsv(filename, toCsv(rows, columns))` returns
776
996
  `"downloaded"` or `"failed"`.
997
+ - **Column groups.** Give columns a `group` and the header gets a second row
998
+ on top. Each group's label spans its adjacent columns. Ungrouped columns
999
+ (the pinned name) span both rows. A line runs down the left of each section.
1000
+ `groups` sets a label and a class per group id; a group not listed shows its
1001
+ id. Sorting, the sticky header and the pinned column work as before. With
1002
+ no `group` on any column the header is one row, as before.
1003
+
1004
+ ```tsx
1005
+ const COLUMNS = [
1006
+ { id: "country", label: "Country", value: r => r.country, sticky: true },
1007
+ { id: "calls", label: "Calls", num: true, value: r => r.calls, group: "activity" },
1008
+ { id: "demos", label: "Demos", num: true, value: r => r.demos, group: "activity" },
1009
+ { id: "cash", label: "Cash", num: true, value: r => r.cash, group: "money" },
1010
+ ];
1011
+ <DataTable rows={rows} columns={COLUMNS}
1012
+ groups={[{ id: "activity", label: "Activity" }, { id: "money", label: "Money", className: "tone-positive" }]} />
1013
+ ```
1014
+ - **Wrapped headers.** `wrapHeaders` lets a header label take 2 lines before
1015
+ it ellipsizes. The sort icon stays beside it. Use it for long or translated
1016
+ labels in narrow columns.
1017
+ - **Header info.** A column's `info` adds an "i" button after its header
1018
+ label. A click opens a popover with the label and this content. The button
1019
+ sits outside the sort button, so it never sorts. Focus moves into the
1020
+ popover. Escape closes it and returns focus to the "i".
1021
+ - **Expandable rows.** `renderExpanded(row)` puts a chevron in each row's
1022
+ first cell. The chevron opens a full-width detail row under its record.
1023
+ Enter or Space on a focused chevron toggles it too. `canExpand(row)` limits
1024
+ which rows get one. The pager, the sort and the CSV count records only. The
1025
+ open rows are uncontrolled (`defaultExpanded`) or controlled (`expanded` +
1026
+ `onExpandedChange`). The state is `{ [rowKey]: true }`, or `true` for every
1027
+ row: TanStack Table's `ExpandedState`. `labels.expand(row)` and
1028
+ `labels.collapse(row)` name the chevron for screen readers.
1029
+
1030
+ ```tsx
1031
+ <DataTable rows={records} columns={COLUMNS} rowKey={r => r.item_id}
1032
+ renderExpanded={r => <RecordFacts row={r} />}
1033
+ canExpand={r => r.detail != null}
1034
+ labels={{ expand: r => `Show details for ${r.item_label}`, collapse: r => `Hide details for ${r.item_label}` }} />
1035
+ ```
1036
+ - **Total row.** `totalRow` pins a bold row to the bottom of the scroll box,
1037
+ under a rule. Pass a row object or a function of the filtered `rows`. Each
1038
+ column renders it with its own `value` and `render`. The pinned first
1039
+ column holds in it. It never sorts or pages. It stays out of the CSV unless
1040
+ `exportTotalRow`. `onTotalRowClick(row)` makes it clickable for a
1041
+ drill-down. A `render` can return a button per cell, as on any row.
1042
+
1043
+ ```tsx
1044
+ <DataTable rows={reps} columns={COLUMNS}
1045
+ totalRow={rs => ({ name: "Total", demos: sum(rs, "demos"), cash: sum(rs, "cash") })}
1046
+ onTotalRowClick={() => openDrill(null)} />
1047
+ ```
777
1048
  - Pure helpers for custom tables: `sortRows`, `compareValues`, `nextSort`,
778
- `pageSlice`, `pageToSync`, `toCsv`, `csvCell`, `csvDate`, `csvToTsv`.
1049
+ `pageSlice`, `pageToSync`, `toCsv`, `csvCell`, `csvDate`, `csvToTsv`,
1050
+ `columnLayout`, `columnGroupRuns`.
779
1051
 
780
1052
  `ui.css` is plain CSS (no Tailwind needed; it coexists with Tailwind) and
781
1053
  every kit class is prefixed `mk-`. It also sets the house base: Inter 14px on
@@ -0,0 +1,137 @@
1
+ "use client"
2
+
3
+ // Combobox (2.28): shadcn's combobox recipe (ui.shadcn.com/docs/components/combobox)
4
+ // as shipped: Popover + Command, a Button trigger, a Check on the picked row,
5
+ // a pick closes the popover and picking the picked row again clears it.
6
+ // The recipe is a demo, so its hard-coded list, labels and width become props.
7
+ // Mako thin props (2.28): `count` per option (muted, right-aligned, never
8
+ // searched, never in the trigger), `keywords` per option, `icon` in the trigger.
9
+ // Search matches the label and keywords only, never the value or the count.
10
+
11
+ import * as React from "react"
12
+ import { CheckIcon, ChevronsUpDownIcon } from "lucide-react"
13
+ import { defaultFilter } from "cmdk"
14
+ import { cn } from "../menu/utils"
15
+ import { Button } from "./button"
16
+ import {
17
+ Command,
18
+ CommandEmpty,
19
+ CommandGroup,
20
+ CommandInput,
21
+ CommandItem,
22
+ CommandList,
23
+ } from "./command"
24
+ import { Popover, PopoverContent, PopoverTrigger } from "./popover"
25
+
26
+ export type ComboboxOption<V extends string = string> = {
27
+ value: V
28
+ label: string
29
+ /** Mako thin prop (2.28): a number shown muted at the row's right edge. */
30
+ count?: number | string
31
+ /** Mako thin prop (2.28): extra words the search matches. */
32
+ keywords?: string[]
33
+ }
34
+
35
+ const formatCount = (n: number | string) =>
36
+ typeof n === "number" ? n.toLocaleString("en-US") : n
37
+
38
+ // The item's value is the option value (unique); its keywords hold the label
39
+ // first, so the search scores the label and keywords and never the value.
40
+ const filterByLabel = (_value: string, search: string, keywords?: string[]) =>
41
+ defaultFilter(keywords?.[0] ?? "", search, keywords?.slice(1))
42
+
43
+ function Combobox<V extends string = string>({
44
+ options,
45
+ value,
46
+ onChange,
47
+ placeholder = "Select...",
48
+ searchPlaceholder = "Search...",
49
+ emptyText = "No results found.",
50
+ icon,
51
+ disabled,
52
+ className,
53
+ contentClassName,
54
+ "aria-label": ariaLabel,
55
+ }: {
56
+ options: ReadonlyArray<V | ComboboxOption<V>>
57
+ value: V | null
58
+ onChange: (value: V | null) => void
59
+ placeholder?: string
60
+ searchPlaceholder?: string
61
+ emptyText?: React.ReactNode
62
+ icon?: React.ReactNode
63
+ disabled?: boolean
64
+ className?: string
65
+ contentClassName?: string
66
+ "aria-label"?: string
67
+ }) {
68
+ const [open, setOpen] = React.useState(false)
69
+ const items = options.map((o) =>
70
+ typeof o === "string" ? { value: o, label: o } : o
71
+ ) as ComboboxOption<V>[]
72
+ const picked = items.find((o) => o.value === value)
73
+ const text = picked?.label ?? value ?? placeholder
74
+
75
+ return (
76
+ <Popover open={open} onOpenChange={setOpen}>
77
+ <PopoverTrigger asChild>
78
+ <Button
79
+ data-slot="combobox-trigger"
80
+ variant="outline"
81
+ role="combobox"
82
+ aria-expanded={open}
83
+ aria-label={ariaLabel}
84
+ disabled={disabled}
85
+ title={text}
86
+ className={cn("w-[200px] justify-between", className)}
87
+ >
88
+ {icon}
89
+ <span className="min-w-0 flex-1 truncate text-left">{text}</span>
90
+ <ChevronsUpDownIcon className="opacity-50" />
91
+ </Button>
92
+ </PopoverTrigger>
93
+ <PopoverContent
94
+ className={cn("w-(--radix-popover-trigger-width) min-w-[200px] p-0", contentClassName)}
95
+ align="start"
96
+ >
97
+ <Command filter={filterByLabel}>
98
+ <CommandInput placeholder={searchPlaceholder} className="h-9" />
99
+ <CommandList>
100
+ <CommandEmpty>{emptyText}</CommandEmpty>
101
+ <CommandGroup>
102
+ {items.map((o) => (
103
+ <CommandItem
104
+ key={o.value}
105
+ value={o.value}
106
+ keywords={[o.label, ...(o.keywords ?? [])]}
107
+ onSelect={() => {
108
+ onChange(o.value === value ? null : o.value)
109
+ setOpen(false)
110
+ }}
111
+ >
112
+ <span className="min-w-0 flex-1 truncate">{o.label}</span>
113
+ {o.count != null && (
114
+ <span
115
+ data-slot="combobox-count"
116
+ className="text-xs text-muted-foreground tabular-nums"
117
+ >
118
+ {formatCount(o.count)}
119
+ </span>
120
+ )}
121
+ <CheckIcon
122
+ className={cn(
123
+ "ml-auto",
124
+ value === o.value ? "opacity-100" : "opacity-0"
125
+ )}
126
+ />
127
+ </CommandItem>
128
+ ))}
129
+ </CommandGroup>
130
+ </CommandList>
131
+ </Command>
132
+ </PopoverContent>
133
+ </Popover>
134
+ )
135
+ }
136
+
137
+ export { Combobox }
@@ -0,0 +1,218 @@
1
+ "use client"
2
+
3
+ // The page's filter bar (one row under the tabs): a small-caps label above each
4
+ // control, groups split by a hairline, Reset at the end. Each tab adds its own
5
+ // fields with <TabFilters>; they render into the bar, next to the global ones.
6
+ // Phones (768px and under): the fields fold behind one "Filters" chip that
7
+ // opens a bottom sheet with Done.
8
+ //
9
+ // A house component, not a shadcn one (2.27): ported 1:1 from the workspace's
10
+ // apps/attrition-por-cohorte/src/ui/FilterBar.tsx and its .fb CSS, written as
11
+ // Tailwind classes on the house tokens. The bar and the sheet are one element
12
+ // (CSS restyles it), so the tab fields portalled into its slot stay mounted on
13
+ // every width. Two changes from the reference: the sheet sits at z-50 (scrim
14
+ // z-49), so the SDK's Radix popovers (z-50, portalled after it) open above it;
15
+ // and Escape leaves the sheet open when a popover inside it took the key.
16
+ import * as React from "react"
17
+ import { createPortal } from "react-dom"
18
+ import { cn } from "../menu/utils"
19
+
20
+ type Entry = { dirty: boolean; reset: () => void }
21
+ type Ctx = {
22
+ slot: HTMLElement | null
23
+ setSlot: (el: HTMLElement | null) => void
24
+ entries: Record<string, Entry>
25
+ register: (id: string, e: Entry | null) => void
26
+ }
27
+ const FilterCtx = React.createContext<Ctx>({ slot: null, setSlot: () => {}, entries: {}, register: () => {} })
28
+
29
+ /** Wraps the page: the bar and every tab that adds fields to it. */
30
+ function FilterProvider({ children }: { children: React.ReactNode }) {
31
+ const [slot, setSlot] = React.useState<HTMLElement | null>(null)
32
+ const [entries, setEntries] = React.useState<Record<string, Entry>>({})
33
+ const register = React.useCallback((id: string, e: Entry | null) => {
34
+ setEntries(prev => {
35
+ if (e == null) {
36
+ if (!(id in prev)) return prev
37
+ const { [id]: _, ...rest } = prev
38
+ return rest
39
+ }
40
+ if (prev[id]?.dirty === e.dirty && prev[id]?.reset === e.reset) return prev
41
+ return { ...prev, [id]: e }
42
+ })
43
+ }, [])
44
+ const ctx = React.useMemo(() => ({ slot, setSlot, entries, register }), [slot, entries, register])
45
+ return <FilterCtx.Provider value={ctx}>{children}</FilterCtx.Provider>
46
+ }
47
+
48
+ /** The bar. `dirty`/`onReset` cover the page-wide fields; tabs register theirs with useResettable. */
49
+ function FilterBar({
50
+ children,
51
+ dirty,
52
+ onReset,
53
+ className,
54
+ }: {
55
+ children: React.ReactNode
56
+ dirty: boolean
57
+ onReset: () => void
58
+ className?: string
59
+ }) {
60
+ const { setSlot, entries } = React.useContext(FilterCtx)
61
+ const active = (dirty ? 1 : 0) + Object.values(entries).filter(e => e.dirty).length
62
+ const [sheet, setSheet] = React.useState(false)
63
+ React.useEffect(() => {
64
+ if (!sheet) return
65
+ // A Radix popover in the sheet marks the Escape it handled: only it closes.
66
+ const key = (e: KeyboardEvent) => {
67
+ if (e.key === "Escape" && !e.defaultPrevented) setSheet(false)
68
+ }
69
+ window.addEventListener("keydown", key)
70
+ return () => window.removeEventListener("keydown", key)
71
+ }, [sheet])
72
+ const reset = () => {
73
+ onReset()
74
+ Object.values(entries).forEach(e => e.reset())
75
+ }
76
+
77
+ return (
78
+ <>
79
+ <div data-slot="filter-chipbar" className="hidden max-[769px]:flex">
80
+ <button
81
+ type="button"
82
+ data-slot="filter-chip"
83
+ aria-expanded={sheet}
84
+ onClick={() => setSheet(!sheet)}
85
+ className="inline-flex h-[34px] items-center gap-2 rounded-[8px] border border-border bg-card px-3 text-sm font-medium shadow-[0_1px_2px_rgb(0_0_0/.05)]"
86
+ >
87
+ Filters{" "}
88
+ {active > 0 && (
89
+ <span
90
+ data-slot="filter-count"
91
+ className="inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-brand px-[5px] text-[11px] font-semibold text-white"
92
+ >
93
+ {active}
94
+ </span>
95
+ )}
96
+ <svg width="12" height="12" viewBox="0 0 24 24" aria-hidden>
97
+ <path d="m6 9 6 6 6-6" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
98
+ </svg>
99
+ </button>
100
+ </div>
101
+ {sheet && (
102
+ <div
103
+ data-slot="filter-scrim"
104
+ className="hidden max-[769px]:fixed max-[769px]:inset-0 max-[769px]:z-49 max-[769px]:block max-[769px]:bg-black/40"
105
+ onClick={() => setSheet(false)}
106
+ />
107
+ )}
108
+ <div
109
+ data-slot="filter-bar"
110
+ data-open={sheet || undefined}
111
+ role="group"
112
+ aria-label="Filters"
113
+ className={cn(
114
+ "group/fb flex flex-wrap items-end gap-x-3 gap-y-2.5",
115
+ sheet
116
+ ? "max-[769px]:fixed max-[769px]:inset-x-0 max-[769px]:bottom-0 max-[769px]:z-50 max-[769px]:max-h-[85dvh] max-[769px]:flex-col max-[769px]:items-stretch max-[769px]:gap-3.5 max-[769px]:overflow-auto max-[769px]:rounded-t-2xl max-[769px]:border-t max-[769px]:border-border max-[769px]:bg-background max-[769px]:px-4 max-[769px]:pt-1 max-[769px]:pb-[calc(16px+env(safe-area-inset-bottom,0px))] max-[769px]:shadow-[0_-12px_32px_rgb(0_0_0/.2)]"
117
+ : "max-[769px]:hidden",
118
+ className
119
+ )}
120
+ >
121
+ <div
122
+ data-slot="filter-sheet-head"
123
+ className="hidden items-center justify-between border-b border-border pt-3 pb-2 font-semibold max-[769px]:group-data-[open]/fb:flex"
124
+ >
125
+ <span>Filters</span>
126
+ <button
127
+ type="button"
128
+ data-slot="filter-done"
129
+ onClick={() => setSheet(false)}
130
+ className="h-8 rounded-[8px] border-0 bg-brand px-4 font-semibold text-white"
131
+ >
132
+ Done
133
+ </button>
134
+ </div>
135
+ {children}
136
+ <div ref={setSlot} data-slot="filter-slot" className="contents" />
137
+ <button
138
+ type="button"
139
+ data-slot="filter-reset"
140
+ disabled={active === 0}
141
+ onClick={reset}
142
+ title="Back to the default filters"
143
+ className="inline-flex h-[34px] items-center gap-1.5 self-end rounded-[8px] border border-border bg-card px-3 text-sm font-medium text-foreground enabled:hover:bg-accent disabled:cursor-default disabled:bg-transparent disabled:text-muted-foreground disabled:opacity-60 max-[769px]:self-start"
144
+ >
145
+ <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden>
146
+ <path d="M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
147
+ </svg>
148
+ Reset
149
+ </button>
150
+ </div>
151
+ </>
152
+ )
153
+ }
154
+
155
+ /** A tab's own fields, rendered into the page's filter bar. */
156
+ function TabFilters({ children }: { children: React.ReactNode }) {
157
+ const { slot } = React.useContext(FilterCtx)
158
+ return slot ? createPortal(children, slot) : null
159
+ }
160
+
161
+ /** Lets Reset (and the Filters badge) know about a tab's filter. */
162
+ function useResettable(id: string, dirty: boolean, reset: () => void) {
163
+ const { register } = React.useContext(FilterCtx)
164
+ const keep = React.useRef(reset)
165
+ keep.current = reset
166
+ const stable = React.useCallback(() => keep.current(), [])
167
+ React.useEffect(() => {
168
+ register(id, { dirty, reset: stable })
169
+ }, [id, dirty, stable, register])
170
+ React.useEffect(() => () => register(id, null), [id, register])
171
+ }
172
+
173
+ /** A small-caps label over its control. `hint` shows as the label's title, with an ⓘ. */
174
+ function FilterField({
175
+ label,
176
+ hint,
177
+ children,
178
+ className,
179
+ }: {
180
+ label: string
181
+ hint?: string
182
+ children: React.ReactNode
183
+ className?: string
184
+ }) {
185
+ return (
186
+ <div
187
+ data-slot="filter-field"
188
+ className={cn("flex min-w-0 flex-col gap-1.5 max-[769px]:group-data-[open]/fb:*:w-full!", className)}
189
+ >
190
+ <span
191
+ data-slot="filter-label"
192
+ title={hint}
193
+ className="inline-flex items-center gap-1 text-[11px] font-semibold tracking-[.06em] whitespace-nowrap text-muted-foreground uppercase"
194
+ >
195
+ {label}
196
+ {hint && (
197
+ <span aria-hidden className="cursor-help text-xs tracking-normal">
198
+ ⓘ
199
+ </span>
200
+ )}
201
+ </span>
202
+ {children}
203
+ </div>
204
+ )
205
+ }
206
+
207
+ /** The hairline between two groups of fields. */
208
+ function FilterSep() {
209
+ return (
210
+ <span
211
+ data-slot="filter-sep"
212
+ aria-hidden
213
+ className="mx-1 h-[34px] w-px self-end bg-border max-[769px]:group-data-[open]/fb:hidden"
214
+ />
215
+ )
216
+ }
217
+
218
+ export { FilterBar, FilterField, FilterProvider, FilterSep, TabFilters, useResettable }