Documentation menu
Getting Started
Components
Primitives
- Agent Thinking
- Alert
- Alert Dialog
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Checkbox
- Command
- Command Palette
- Context Menu
- Data Table
- Dialog
- Dropdown Menu
- Empty
- Field
- Glow Cloud
- Input
- Label
- Medication Schedule
- Period Tabs
- Popover
- Rainbow Button
- Scroll Area
- Select
- Selectable Card
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner
- Spinner
- Switch
- Table
- Tabs
- Tag
- Textarea
- Timeline
- Tooltip
- Use Count Up
Charts and metrics
Patterns
- Confirm Button
- Date Picker
- Embedded
- Empty State
- Entity Drawer
- Error Boundary
- Field Row
- File Dropzone
- Form Dialog
- Kv
- List Editor
- List Page
- Live Time
- Mini Table
- Money
- Note Field
- Note Text
- Page Card
- Page Header
- Page Tabs
- Page Toolbar
- Person Cell
- Picture Field
- Print Card
- Range Switcher
- Row Actions
- Search Input
- Search Select
- Selected Box
- Signature Pad
- Status Badge
- Sub Nav Layout
- Suggest Input
- Tab Icons
- Table Footer
- Theme Accent Picker
- Time Picker
- View All Link
Dashboard cards
Advanced
Device frames
Website widgets
Website screens
Website panels
Advanced
Filters
Filter chips and an advanced filter builder with operators, dates and saved queries.
import { Filters } from "@/registry/vcare/ui/filters/filters"
import type { FilterField } from "@/registry/vcare/ui/filters/filters-types"
const fields: FilterField[] = [
{ id: "status", label: "Status", type: "select", options: [{ value: "paid", label: "Paid" }, { value: "due", label: "Due" }, { value: "void", label: "Void" }] },
{ id: "department", label: "Department", type: "multiselect", options: ["General medicine", "Lab", "Pharmacy", "Physiotherapy"].map((d) => ({ value: d, label: d })) },
{ id: "amount", label: "Amount", type: "number" },
{ id: "patient", label: "Patient", type: "text" },
{ id: "insured", label: "Insured", type: "boolean" },
]
export default function FiltersDemo() {
return (
<div className="w-full">
<Filters fields={fields} />
</div>
)
}Installation
npx shadcn@latest add @vcare/filtersOr install directly from the URL: https://ui.vcarehms.com/r/filters.json
- Install the dependencies:
npm i class-variance-authority date-fns lucide-react - Add the registry items it uses: button, button-group, cascader, dropdown-menu, input, popover, tooltip, utils.
- Copy these 14 files into your project and change the
@/registry/vcare/…imports to your own paths.
components/ui/filters/filters-advanced.tsx
import * as React from 'react';
import { FilterFieldPicker } from '@/registry/vcare/ui/filters/filters-builder';
import {
FilterMoveToMenuItems,
FilterOperatorPopover,
FilterRuleMenuItems,
FilterValuePopover,
useFilterRuleDisplay,
} from '@/registry/vcare/ui/filters/filters-chip';
import {
filterControlSizes,
filterReadOnlyProps,
FilterReorderProvider,
isFilterLocked,
useFilterActions,
useFilterChipAutoOpen,
useFilterChipFocused,
useFilterFocusEmpty,
useFilterFocusStore,
useFilterRender,
useFilterReorderable,
useFilterRowPending,
useFilterRowStateStore,
useFilterSegmentFocus,
useFilterState,
type FilterActionsContextValue,
} from '@/registry/vcare/ui/filters/filters-context';
import { FILTER_ROW_SELECTOR, useFilterRowDrag } from '@/registry/vcare/ui/filters/filters-dnd';
import { filterIssueLabel } from '@/registry/vcare/ui/filters/filters-i18n';
import {
FILTER_FIELD_PICKER_CLASS,
FILTER_MENU_CLASS,
FILTER_MENU_LABEL_CLASS,
filterCombinatorSlot,
getFilterField,
isFilterFieldPickable,
joinFilterPath,
} from '@/registry/vcare/ui/filters/filters-lib';
import { getFilterArity, getFilterOperator, operatorTakesValue } from '@/registry/vcare/ui/filters/filters-operators';
import { collectFilterIssues, createFilterRule, isFilterRule } from '@/registry/vcare/ui/filters/filters-query';
import type {
FilterCombinator,
FilterEmptyStateContext,
FilterField,
FilterGroupNode,
FilterIssue,
FilterNode,
FilterOperator,
FilterQuery,
FilterRule,
} from '@/registry/vcare/ui/filters/filters-types';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/registry/vcare/ui/dropdown-menu';
import { Input } from '@/registry/vcare/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/registry/vcare/ui/popover';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/registry/vcare/ui/tooltip';
import {
RefreshCwIcon,
CircleAlertIcon,
GripVerticalIcon,
ChevronDownIcon,
EllipsisVerticalIcon,
XIcon,
PlusIcon,
CopyIcon,
UngroupIcon,
Trash2Icon,
ListFilterIcon,
FolderPlusIcon,
} from 'lucide-react';
/* -------------------------------------------------------------------------- */
/* Columns */
/* -------------------------------------------------------------------------- */
const CONTENT_COLUMNS = ['combinator', 'field', 'operator', 'value'] as const;
const ACTION_COLUMNS = ['drag', 'menu', 'add', 'remove'] as const;
/** Every column a row may draw, in two bands. Navigation is by COLUMN NAME and
* never position: the BANDS keep ArrowDown off a group's footer button. */
type FilterColumn = (typeof CONTENT_COLUMNS)[number] | (typeof ACTION_COLUMNS)[number];
/** The nearest column in `band` that `available` has; backward wins a tie. */
function nearestColumn(band: readonly FilterColumn[], from: FilterColumn, available: Map<string | null, HTMLElement>): HTMLElement | undefined {
const at = band.indexOf(from);
if (at === -1) return undefined;
for (let step = 0; step < band.length; step++) {
const before = step === 0 ? undefined : available.get(band[at - step] ?? '');
if (before) return before;
const after = available.get(band[at + step] ?? '');
if (after) return after;
}
return undefined;
}
/** Marks a focusable cell control, read by the keyboard walker. Not
* `data-slot`: a cell control is handed to a Base UI trigger through `render`,
* which stamps its own, so a slot here would be two owners on one attribute. */
const CELL_ATTRIBUTE = 'data-filter-cell';
/** Marks a cell the user TYPES into: the builder claims the arrows, Home, End
* and Delete, and each means something else in a text box. */
const CELL_INPUT_ATTRIBUTE = 'data-filter-cell-input';
const ROW_SELECTOR = FILTER_ROW_SELECTOR;
/** Hands every row's handle its pointer wiring: only the panel, which owns the
* body element, can measure a drop. */
const FilterDragContext = React.createContext<ReturnType<typeof useFilterRowDrag> | null>(null);
/** What each node is missing, by id. An empty map by default, so a row mounted
* outside the shipped panel gets "nothing is wrong" instead of a throw. */
const FilterIssueContext = React.createContext<ReadonlyMap<string, FilterIssue>>(new Map());
function cellProps(column: FilterColumn, active: FilterColumn | null) {
return {
'data-filter-cell': column,
// ONE tab stop for the whole builder; the arrows move within it.
tabIndex: active === column ? 0 : -1,
};
}
/** What an INVALID cell wears: `aria-invalid` to announce it, `data-invalid`
* to style it, `aria-description` for the sentence. */
function issueProps(issue: FilterIssue | undefined, column: FilterIssue['column'], message: string) {
if (!issue || issue.column !== column) return null;
return {
'aria-invalid': true,
'data-invalid': '',
'aria-description': message,
// NO `title`: the hint icon carries the sentence in a real tooltip, and a
// native one would clobber the truncation `title` beside it.
} as const;
}
/** Sera's uppercase and wide tracking cost about a third of a cell, so where
* every other style drew "migration" sera drew "MIGRATI...". */
const SERA_TEXT_CLASS = '';
const CELL_CLASS = cn(
'w-full min-w-0 justify-between gap-1.5 font-normal',
// `>svg` is the caret and only the caret: a field's own type icon sits in a
// nested span, where it keeps full strength because it is content.
'[&>svg]:text-muted-foreground',
// WHAT A CELL GIVES UP FIRST: padding, icon and caret cost about 44px before
// a character is drawn, and the name is what nothing else can reconstruct.
// Container queries and not a viewport breakpoint: the question is how wide
// THIS cell is, and one panel holds a 300px cell and a 40px one.
'@max-[7rem]/cell:gap-0 @max-[7rem]/cell:[&>svg]:hidden',
'@max-[5rem]/cell:[&_span>svg]:hidden',
SERA_TEXT_CLASS,
);
/** What an invalid cell looks like. A ring, not a border: a border changes the
* box, so a cell turning invalid would nudge every cell beside it. */
const CELL_INVALID_CLASS = 'data-invalid:ring-destructive/40 data-invalid:ring-1';
/** Width of the leading combinator column. The 58.72px pill put this track at
* 4rem and it does not shrink now the pill has: it is sized for the longest of
* the three things in it, "Where", 51.44px in every style. */
const COMBINATOR_CLASS = cn(
'w-16 shrink-0 items-center justify-center',
// 6px of its own on TOP of the band's `gap-1.5`: this column is the
// sentence's connective, not a fourth control butted against the attribute.
'me-1.5',
);
/** The two static words in that column, CENTRED because the pill's own
* `justify-center` centres its word. `w-full`, or `truncate` has no box. */
const COMBINATOR_TEXT_CLASS = cn('text-muted-foreground w-full truncate px-1 text-center text-sm', SERA_TEXT_CLASS);
/** A row is TWO BANDS. The trailing pair of every row at every depth shares one
* vertical axis - 0.00px of spread from 1104px to 240px, eight styles, depth
* three - and only because the content band may shrink to nothing. */
const ROW_BAND_CLASS = 'flex min-w-0 items-center gap-1.5';
const CONTENT_BAND_CLASS = 'flex min-w-0 flex-1 items-center gap-1.5';
/** FLEX and not a block: a `Button` is `inline-flex`, so a block wrapper builds
* a line box as tall as its font's strut - 28px buttons in 28.141px wrappers. */
const CELL_BOX_CLASS = '@container/cell flex min-w-0 shrink grow-0';
/** THE DEFAULT WIDTH OF EACH CONTENT CELL. An INLINE FALLBACK and not a
* declaration on the panel: declared, the panel would beat anything an ANCESTOR
* set, which is where a consumer sets it in popover mode. So all four work:
*
* <Filters variant="advanced" className="[--filter-field-width:14rem]" />
* <FiltersAdvancedPanel className="[--filter-operator-width:7rem]" />
* <Card className="[--filter-value-width:16rem]"><Filters … /></Card>
* [data-slot="filters-advanced"] { --filter-field-width: 14rem } */
const FIELD_CELL_CLASS = 'basis-[var(--filter-field-width,11rem)]';
const OPERATOR_CELL_CLASS = 'basis-[var(--filter-operator-width,9rem)]';
const VALUE_CELL_CLASS = 'basis-[var(--filter-value-width,12rem)]';
/** The trailing band. `pe-1` is on the BAND and not the gutter, since a group
* card is `pe-0`; the footer and `DROP_SLOT_INDICATOR` restate the same four. */
const ACTION_BAND_CLASS = cn('text-muted-foreground flex shrink-0 items-center gap-0.5 pe-1');
/** What the grip and the kebab wear while open. TWO ATTRIBUTES, because Radix
* sets `data-state="open"` and Base UI `data-popup-open`, so one selector alone
* would be dead in one twin, silently, in a byte-locked file. */
const ACTION_CONTROL_CLASS = cn(
'hover:inset-ring hover:inset-ring-border',
// Base UI.
'data-popup-open:inset-ring data-popup-open:inset-ring-border',
// Radix.
'data-[state=open]:inset-ring data-[state=open]:inset-ring-border',
);
/** The gap between sibling rows, one third of one measurement:
* `FILTER_ROW_SEAM_PX` is HALF of it and the footer's `-mt-*` cancels it. */
const FILTER_ROW_GAP_CLASS = 'gap-3';
const FILTER_ROW_GAP_CANCEL_CLASS = '-mt-3';
const FILTER_ROW_HALF_GAP_CLASS = {
// The slot names the BOUNDARY between two rows, which is the middle of the
// gap: 6px of it less HALF the rule's own 2px, so its CENTRE lands there.
before: 'data-[drop-edge=before]:after:mb-[5px]',
after: 'data-[drop-edge=after]:after:mt-[5px]',
} as const;
/** POPOVER: the popover content is `p-0`, so this IS the popup's own inner
* padding. INLINE there is no popup, and a panel that pads itself as well is a
* second inset the page did not ask for. */
const PANEL_PAD_VAR = '--filter-panel-pad';
const PANEL_PAD_POPOVER = '0.75rem';
const PANEL_PAD_INLINE = '0px';
/** The panel's ONE horizontal rhythm: a row's trailing controls sit at the
* content edge, which IS this padding, so a footer that disagrees breaks it. */
const PANEL_GUTTER_CLASS = 'px-(--filter-panel-pad)';
const PANEL_CLASS = 'flex w-full min-w-0 flex-col gap-2 py-(--filter-panel-pad)';
/** A RING and not a border, the whole answer to the staggered trailing
* controls: a border pushes the content edge inward a pixel per level. */
const GROUP_CARD_CLASS = cn(
'bg-muted/40 min-w-0 flex-1 rounded-md',
'inset-ring inset-ring-border',
'ps-2 pe-0',
'data-invalid:inset-ring-destructive/50',
// The DESTINATION of a drop into this group, told apart from the insertion
// slot by STYLE and not size: dashed is not there yet, solid exists.
'data-drop-into:bg-muted/60',
'data-drop-into:outline-1 data-drop-into:outline-solid',
'data-drop-into:outline-border data-drop-into:-outline-offset-2',
);
/** THE CONTAINER a row measures its own room against, on the panel body and on
* every group's list, so a row asks how wide the list it is IN is. */
const TRACK_CONTAINER_CLASS = '@container/track';
/** When a group stops putting its combinator BESIDE the card. A DEPTH budget
* was wrong both ways: at 380px the depth-three row painted zero pixels of
* field, operator and value and fanned the kebab column out by up to 119px.
* 26rem is what a row MEASURES: 134px of fixed cost plus about 200px of cells. */
const GROUP_COMBINATOR_WRAP_CLASS = '@max-[26rem]/track:w-full';
/** The combinator itself, once its wrapper has a whole line. Pinned to the
* same 4rem the gutter track is, so it is the same control at every width. */
const GROUP_COMBINATOR_WRAPPED_CLASS = '@max-[26rem]/track:w-16';
/** How a row shows where a dragged node would land. `data-drop-edge` is an
* insertion BETWEEN rows, drawn here; `data-drop-into` is painted on the CARD,
* so "inside this group" and "after this group" are not one picture. */
const DROP_SLOT_INDICATOR = cn(
// The SOURCE in flight, faded rather than hidden. THREE FIFTHS is a contrast
// measurement: at 35 under a `blur-[1px]` the text composited to #a9a9a9,
// 2.35:1 on the light panel, under even the 3:1 line for a non-text mark.
'relative rounded-md',
'data-dragging:opacity-60',
// THE INSERTION LINE lives in the gap rather than overlaying a real row.
// `end-1` and not `end-0`: four pixels of `pe-1` are the kebab column.
'data-drop-edge:after:absolute',
'data-drop-edge:after:start-0 data-drop-edge:after:end-1',
'data-drop-edge:after:h-0.5 data-drop-edge:after:rounded-full',
'data-drop-edge:after:bg-primary',
'data-drop-edge:after:z-10',
'data-[drop-edge=before]:after:bottom-full',
FILTER_ROW_HALF_GAP_CLASS.before,
'data-[drop-edge=after]:after:top-full',
FILTER_ROW_HALF_GAP_CLASS.after,
);
/** What a CONDITION row draws, which is what a group's row draws: the slot and
* nothing else. It used to add a faint dashed outline of its own, a second
* dashed rectangle a few pixels from the first saying what it already said. */
const DROP_INDICATOR = DROP_SLOT_INDICATOR;
/** How the footer says "append to the top level": the same RULE the rows draw.
* `data-drop-into` and not `data-drop-edge`, because an explicit zone is a
* DESTINATION. Both ends restate the padding VARIABLE, since `inset` resolves
* against the PADDING box and `inset-x-0` overran every rule above it. */
const FOOTER_DROP_CLASS = cn(
'data-drop-into:after:absolute',
'data-drop-into:after:start-(--filter-panel-pad)',
'data-drop-into:after:end-[calc(var(--filter-panel-pad)+4px)]',
'data-drop-into:after:top-0 data-drop-into:after:h-0.5',
'data-drop-into:after:rounded-full data-drop-into:after:bg-primary',
);
/** The cells a row owns ITSELF: a group's row contains its children's rows, so
* a bare `querySelectorAll` would let ArrowRight walk into the first of them. */
function ownCells(row: HTMLElement): HTMLElement[] {
return Array.from(row.querySelectorAll<HTMLElement>(`[${CELL_ATTRIBUTE}]`)).filter((cell) => cell.closest<HTMLElement>(ROW_SELECTOR) === row);
}
/* -------------------------------------------------------------------------- */
/* Shared cells */
/* -------------------------------------------------------------------------- */
interface RowPosition {
index: number;
parentId: string;
combinator: FilterCombinator;
depth: number;
}
/** The leading and/or slot: one group is joined by ONE operator, and mixing is
* what a nested group is FOR. */
function CombinatorCell({
index,
parentId,
combinator,
active,
onFocus,
className,
}: {
index: number;
parentId: string;
combinator: FilterCombinator;
active: FilterColumn | null;
onFocus: (column: FilterColumn) => () => void;
className?: string;
}) {
const actions = useFilterActions();
const sizes = filterControlSizes(actions);
const slot = filterCombinatorSlot(index);
const word = combinator === 'and' ? actions.labels.and : actions.labels.or;
if (slot === 'where') {
return <span className={cn(COMBINATOR_TEXT_CLASS, className)}>{actions.labels.where}</span>;
}
if (slot === 'echo') {
return <span className={cn(COMBINATOR_TEXT_CLASS, className)}>{word}</span>;
}
const name = actions.labels.combinatorLabel(word);
return (
<Button
variant="outline"
size={sizes.button}
/* The WORD is in the name: the track is fixed, so a locale whose
word overflows draws "a...". */
aria-label={name}
title={name}
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
className={cn('group/combinator relative w-full min-w-0 justify-center px-1.5 font-normal', SERA_TEXT_CLASS, className)}
{...cellProps('combinator', active)}
onFocus={onFocus('combinator')}
onClick={() => actions.toggleCombinator(parentId)}
>
<span className="truncate">{word}</span>
{/* ABSOLUTELY POSITIONED, so the word still centres at 0.00px. */}
<span
aria-hidden="true"
className={cn(
'pointer-events-none absolute end-1 opacity-0 transition-opacity',
'group-hover/combinator:opacity-60',
'group-focus-visible/combinator:opacity-60',
'[&_svg]:size-3',
)}
>
<RefreshCwIcon />
</span>
</Button>
);
}
/** Whether dragging this node could change the tree at all; the grip is drawn
* only when it could. Every destination outside the footer zone lives inside
* some row and the drop layer discards any inside the dragged one, so the sole
* child of the root is the one case with nowhere to go. A pure function of the
* QUERY, deliberately blind to `disabled` and `readOnly`: a locked bar keeps
* its grip, because "you may not move this" and "there is nowhere to move it"
* are different sentences. */
function canFilterNodeMove(query: FilterQuery<unknown>, position: { parentId: string }) {
if (position.parentId !== query.id) return true;
return query.rules.length > 1;
}
/** The error, as a QUIET mark the pointer can ask about: ONE per ROW, and
* `aria-hidden`, since the cell carries it as `aria-description`. */
function RowIssueHint({ message, className }: { message: string; className?: string }) {
if (!message) return null;
return (
<TooltipProvider delay={200}>
<Tooltip>
<TooltipTrigger
render={
<span
data-slot="filter-row-issue"
/* Focusable so a keyboard user can summon it, but OUT of the
tab order: the sentence is already on the invalid cell. */
tabIndex={-1}
aria-hidden="true"
className={cn('text-destructive flex shrink-0 items-center justify-center [&_svg]:size-3.5', className)}
>
<CircleAlertIcon />
</span>
}
/>
<TooltipContent side="top">{message}</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
/** The drag handle: what ARMS the gesture, since arming the row would turn
* every text selection into a drag, and the only thing a screen reader can be
* told about, which is why Alt+arrow hangs off it. */
function RowHandle({ nodeId, active, onFocus }: { nodeId: string; active: FilterColumn | null; onFocus: (column: FilterColumn) => () => void }) {
const actions = useFilterActions();
const sizes = filterControlSizes(actions);
const dragProps = React.useContext(FilterDragContext);
const locked = isFilterLocked(actions);
return (
<Button
variant="ghost"
size={sizes.icon}
aria-label={actions.labels.reorder}
/* The activation is the DRAG, which no click performs, so without these
a screen reader finds a "Reorder" button that appears broken. */
aria-keyshortcuts="Alt+ArrowUp Alt+ArrowDown"
aria-description={actions.labels.reorderHint}
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
/* `touch-none`, or a finger on the handle becomes a page scroll the
gesture then fights. Muted at rest, never hidden. */
className={cn('focus-visible:text-foreground cursor-grab touch-none', 'active:cursor-grabbing', ACTION_CONTROL_CLASS)}
{...cellProps('drag', active)}
onFocus={onFocus('drag')}
/* Not armed at all while locked; the engine refuses it again. */
{...(locked ? null : dragProps?.(nodeId))}
>
<GripVerticalIcon />
</Button>
);
}
/** Which cell of a row owns the builder's single tab stop. An operator change
* can take the value column out from under the focus pointing at it. */
function useActiveColumn(nodeId: string, columns: FilterColumn[], isFirstRow: boolean): FilterColumn | null {
const focused = useFilterChipFocused(nodeId);
const segment = useFilterSegmentFocus(nodeId);
const noFocus = useFilterFocusEmpty();
if (focused) {
return segment && columns.includes(segment as FilterColumn) ? (segment as FilterColumn) : columns[0];
}
return noFocus && isFirstRow ? columns[0] : null;
}
function useFilterIssue(nodeId: string): FilterIssue | undefined {
return React.useContext(FilterIssueContext).get(nodeId);
}
/* -------------------------------------------------------------------------- */
/* Inline free text */
/* -------------------------------------------------------------------------- */
/** Whether a value is FREE TEXT, and therefore typed in the row itself. The
* CHIP row keeps its popover for every value, deliberately, which is why this
* lives here and not in the shared display hook. NUMBER is in: empty clears,
* and anything unparseable snaps back to the last committed number. */
function usesInlineTextEditor<V, O>(field: FilterField<V, O>, operator: FilterOperator | undefined, hasCustomDisplay: boolean): boolean {
if (field.editor) return false;
if (field.options || field.loadOptions) return false;
if (field.renderValue || field.valueText || hasCustomDisplay) return false;
const type = field.type ?? 'text';
if (type !== 'text' && type !== 'number') return false;
return getFilterArity(operator) === 'one';
}
/** The value cell as a real text box. COMMIT IS BLUR AND ENTER: per keystroke
* makes the ROOT the source of truth for every character, and debouncing only
* adds a window where the cell and the query disagree with no event. */
function FilterInlineValueCell<V, O>({
rule,
field,
issue,
issueText,
active,
onFocus,
}: {
rule: FilterRule<V>;
field: FilterField<V, O>;
issue: FilterIssue | undefined;
issueText: string;
active: FilterColumn | null;
onFocus: (column: FilterColumn) => () => void;
}) {
const actions = useFilterActions<V, O>();
const focusStore = useFilterFocusStore();
const locked = isFilterLocked(actions);
const numeric = (field.type ?? 'text') === 'number';
// The handoff the value POPOVER honours, answered by taking the caret.
const autoOpen = useFilterChipAutoOpen(rule.id) === 'value';
const inputRef = React.useRef<HTMLInputElement>(null);
const committed = rule.value === undefined || rule.value === null ? '' : String(rule.value);
const [draft, setDraft] = React.useState(committed);
// STATE and not a ref: the sync below runs during render.
const [seed, setSeed] = React.useState(committed);
// Adjusting state during render; an effect would paint the stale text.
if (seed !== committed) {
setSeed(committed);
setDraft(committed);
}
// CONSUMED as it is honoured: a flag left standing is spent by the next row.
React.useEffect(() => {
if (!autoOpen) return;
if (!locked) {
const input = inputRef.current;
input?.focus();
// SELECTED: the condition step may have coerced a value across.
input?.select();
}
focusStore.set({ id: rule.id, segment: 'value', autoOpen: false });
}, [autoOpen, locked, focusStore, rule.id]);
const commit = () => {
if (draft === seed) return;
if (numeric) {
const text = draft.trim();
// Empty clears rather than writing 0, which silently matches rows.
if (text === '') {
actions.updateRule(rule.id, { value: undefined as V });
return;
}
const parsed = Number(text);
// Revert, do not write: a NaN compares false against every row.
if (!Number.isFinite(parsed)) {
setDraft(seed);
return;
}
actions.updateRule(rule.id, { value: parsed as V });
return;
}
actions.updateRule(rule.id, { value: draft as V });
};
return (
/* A FRAGMENT, not a wrapper: the positioning context for the error mark
is the CELL itself, which already carries the column's basis. */
<>
<Input
ref={inputRef}
aria-label={field.label}
placeholder={field.placeholder ?? actions.labels.valuePlaceholder}
/* The RIGHT KEYPAD only: `type="number"` brings spinners. */
inputMode={numeric ? 'decimal' : undefined}
value={draft}
/* `h-full` and no size class: `Input` has ONE height per style, so
at `size="sm"` it was a pixel taller in nova and two in sera. */
className={cn('h-full', issueText && 'pe-7', CELL_INVALID_CLASS)}
/* Native `readOnly`, not `disabled`: it keeps its tab stop. */
readOnly={locked}
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
{...cellProps('value', active)}
{...{ [CELL_INPUT_ATTRIBUTE]: '' }}
{...issueProps(issue, 'value', issueText)}
onFocus={onFocus('value')}
onChange={(event) => setDraft(event.target.value)}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === 'Enter' && !event.nativeEvent.isComposing) {
event.preventDefault();
commit();
return;
}
if (event.key === 'Escape') {
/* Only when there is something to revert; Escape belongs to the
surface the builder sits in. */
if (draft === seed) return;
event.preventDefault();
event.stopPropagation();
setDraft(seed);
}
}}
/>
<RowIssueHint
message={issueText}
/* `pointer-events-none`, so a click still lands in the input. */
className="pointer-events-none absolute end-2 top-1/2 -translate-y-1/2 [&>*]:pointer-events-auto"
/>
</>
);
}
/* -------------------------------------------------------------------------- */
/* Rule row */
/* -------------------------------------------------------------------------- */
export interface FilterAdvancedRowProps<V = unknown> {
rule: FilterRule<V>;
position: RowPosition;
}
function FilterAdvancedRowImpl<V, O>({ rule, position }: FilterAdvancedRowProps<V>) {
const actions = useFilterActions<V, O>();
const render = useFilterRender<V, O>();
const sizes = filterControlSizes(actions);
const focusStore = useFilterFocusStore();
const locked = isFilterLocked(actions);
const { query } = useFilterState<V>();
const field = getFilterField(actions.index, rule.path);
const operators = field ? actions.resolveOperators(field) : [];
const operator = getFilterOperator(operators, rule.operator);
const takesValue = Boolean(rule.operator) && operatorTakesValue(operator);
const inlineValue = takesValue && field ? usesInlineTextEditor(field, operator, Boolean(render.renderValue)) : false;
const issue = useFilterIssue(rule.id);
const issueText = issue ? filterIssueLabel(issue, actions.labels) : '';
const { pathText, pathLabel, pathCollapsed, operatorLabel, valueLabel, valueText, valueFullText, valueEmpty } = useFilterRuleDisplay<V, O>(
rule,
field,
operator,
);
/* ------------------------------ field cell ------------------------------ */
const fieldAutoOpen = useFilterChipAutoOpen(rule.id) === 'field';
const [pickerOpen, setPickerOpen] = React.useState(false);
// Controlled so both can REFUSE to open while locked.
const [menuOpen, setMenuOpen] = React.useState(false);
// Seeded from the rule's own level, so amending opens beside its siblings.
const [pickerPath, setPickerPath] = React.useState<string[]>(() => rule.path.slice(0, -1));
const [pickerQuery, setPickerQuery] = React.useState('');
// A new row arrives with a GUESS at its field, so the one choice not yet the
// user's own opens itself. CONSUMED as it is honoured: `pickerOpen` is a
// dependency, so a flag left standing reopened the picker in the frame it
// closed, a keyboard trap on the one row a user creates most.
React.useEffect(() => {
if (!fieldAutoOpen || pickerOpen) return;
if (!locked) setPickerOpen(true);
focusStore.set({ id: rule.id, segment: 'field', autoOpen: false });
}, [fieldAutoOpen, pickerOpen, locked, focusStore, rule.id]);
// Re-seed on each open, so a browse that was abandoned last time does not
// decide where this one starts.
React.useEffect(() => {
if (!pickerOpen) return;
setPickerPath(rule.path.slice(0, -1));
setPickerQuery('');
}, [pickerOpen, rule.path]);
/* ------------------------------- tab stop ------------------------------- */
const slot = filterCombinatorSlot(position.index);
const reorderable = useFilterReorderable();
const canMove = reorderable && canFilterNodeMove(query, position);
const rowStateStore = useFilterRowStateStore();
// Still waiting for its attribute, so neither later cell is drawn.
const pending = useFilterRowPending(rule.id);
const columns = React.useMemo(() => {
const list: FilterColumn[] = [];
if (slot === 'toggle') list.push('combinator');
list.push('field');
if (!pending) {
list.push('operator');
if (takesValue) list.push('value');
}
// The grip is only a tab stop when it is drawn.
if (canMove) list.push('drag');
list.push('menu');
return list;
}, [slot, takesValue, canMove, pending]);
const active = useActiveColumn(rule.id, columns, position.depth === 1 && position.index === 0);
const onCellFocus = React.useCallback(
(column: FilterColumn) => () => focusStore.set({ id: rule.id, segment: column, autoOpen: false }),
[focusStore, rule.id],
);
/* -------------------------------- render -------------------------------- */
if (!field) return null;
return (
<div
/* A GROUP, not a grid row: four depths of grid describes to no
assistive technology at all. */
role="group"
aria-label={actions.labels.rowLabel(`${pathText} ${operatorLabel}`, position.depth)}
data-slot="filter-row"
data-node-id={rule.id}
data-parent-id={position.parentId}
data-index={position.index}
data-depth={position.depth}
className={cn('group/row', ROW_BAND_CLASS, DROP_INDICATOR)}
>
<div className={cn(COMBINATOR_CLASS, CELL_BOX_CLASS)}>
<CombinatorCell index={position.index} parentId={position.parentId} combinator={position.combinator} active={active} onFocus={onCellFocus} />
</div>
{/* THE CONTENT BAND: sized to itself, not to a share of the row. */}
<div className={CONTENT_BAND_CLASS}>
<div className={cn(CELL_BOX_CLASS, FIELD_CELL_CLASS)}>
<Popover
open={pickerOpen}
onOpenChange={(next) => {
if (next && locked) return;
setPickerOpen(next);
}}
>
<PopoverTrigger
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
render={
<Button
variant="outline"
size={sizes.button}
/* The path is truncated on screen, so the name carries all
of it: "Primary loca... > State" identifies nothing. */
aria-label={pathText}
/* And as a `title` - unless the path is COLLAPSED, where the
ellipsis inside already carries this exact sentence. */
title={pathCollapsed ? undefined : pathText}
className={CELL_CLASS}
{...cellProps('field', active)}
onFocus={onCellFocus('field')}
>
<span className="flex min-w-0 items-center gap-1.5 truncate">
{field.icon}
<span className="truncate">{pathLabel}</span>
</span>
<ChevronDownIcon />
</Button>
}
/>
<PopoverContent align="start" className={cn(FILTER_FIELD_PICKER_CLASS, actions.fieldPickerClassName)}>
<FilterFieldPicker<V, O>
path={pickerPath}
onPathChange={setPickerPath}
query={pickerQuery}
onQueryChange={setPickerQuery}
onSelect={(path, defaultOperator) => {
setPickerOpen(false);
// BUILDING versus AMENDING, the fork of the stepped
// flow. Naming `operator` retires the field handoff.
focusStore.set({
id: rule.id,
segment: pending ? 'operator' : 'field',
autoOpen: pending,
});
// BEFORE the same-path early return, or a row minted
// on a guessed field the user then picks stays pending.
rowStateStore.resolvePending(rule.id);
// Re-picking the field it has is a dismissal.
if (joinFilterPath(path) === joinFilterPath(rule.path)) return;
// On the create path the condition stays UNSET, so the
// menu opening next has nothing selected.
actions.updateRule(rule.id, {
path,
operator: pending ? '' : (defaultOperator ?? ''),
value: undefined,
});
}}
/>
</PopoverContent>
</Popover>
</div>
{pending ? null : (
<div className={cn(CELL_BOX_CLASS, OPERATOR_CELL_CLASS)}>
<FilterOperatorPopover
rule={rule}
field={field}
trigger={
<Button
variant="outline"
size={sizes.button}
/* No `aria-label`: the label IS the name. */
title={operatorLabel}
className={cn(CELL_CLASS, CELL_INVALID_CLASS, 'text-muted-foreground')}
{...cellProps('operator', active)}
{...issueProps(issue, 'operator', issueText)}
onFocus={onCellFocus('operator')}
>
<span className="truncate">{operatorLabel}</span>
<ChevronDownIcon />
</Button>
}
/>
</div>
)}
{/* The cell stays even with no value: dropping it would shift the
trailing buttons into the value column on that row alone. It goes
ENTIRELY while the row is PENDING, the one case that argument does
not cover: a row choosing its attribute has no column count yet. */}
{pending ? null : (
<div
className={cn(
CELL_BOX_CLASS,
VALUE_CELL_CLASS,
/* The positioning context for an inline editor's error mark. */
'relative',
/* What lets an inline box match the buttons beside it: as tall as
the row, so `h-full` inside resolves to the button height. */
'self-stretch',
)}
>
{takesValue ? (
inlineValue ? (
<FilterInlineValueCell<V, O> rule={rule} field={field} issue={issue} issueText={issueText} active={active} onFocus={onCellFocus} />
) : (
<FilterValuePopover
rule={rule}
field={field}
operator={operator}
trigger={
<Button
variant="outline"
size={sizes.button}
/* The VALUE is the name, never the attribute.
Locked, it grows to the whole list. */
aria-label={locked ? valueFullText : valueText}
title={valueFullText}
className={cn(CELL_CLASS, CELL_INVALID_CLASS, 'h-full', valueEmpty && 'text-muted-foreground')}
{...cellProps('value', active)}
{...issueProps(issue, 'value', issueText)}
onFocus={onCellFocus('value')}
>
{/* FREE OUTPUT: whatever the field draws. */}
<span className="min-w-0 flex-1 truncate text-start">{valueLabel}</span>
{/* The error, INSIDE the control that failed. */}
<RowIssueHint message={issueText} />
</Button>
}
/>
)
) : null}
</div>
)}
</div>
{/* The WEIGHT is on the CLUSTER: a `ghost` button names no colour, so
the kebab took the full `--foreground`. */}
<div className={ACTION_BAND_CLASS}>
{canMove ? <RowHandle nodeId={rule.id} active={active} onFocus={onCellFocus} /> : null}
<DropdownMenu
open={menuOpen}
onOpenChange={(next) => {
if (next && locked) return;
setMenuOpen(next);
}}
>
<DropdownMenuTrigger
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
render={
<Button
variant="ghost"
size={sizes.icon}
aria-label={actions.labels.chipMenu(field.label)}
className={ACTION_CONTROL_CLASS}
{...cellProps('menu', active)}
onFocus={onCellFocus('menu')}
/>
}
>
<EllipsisVerticalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className={cn(FILTER_MENU_CLASS, actions.menuClassName)}>
{/* Grouping is HERE, not on a chip: the keyboard path to
`a AND (b OR c)`. */}
<FilterRuleMenuItems ruleId={rule.id} allowGrouping />
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
);
}
/** One rule, as a row, memoized: the query tree shares structure, so editing
* one row of twenty re-renders one. */
export const FilterAdvancedRow = React.memo(FilterAdvancedRowImpl) as typeof FilterAdvancedRowImpl;
/** A rule whose field the schema no longer has: dropping it would lose a saved
* view's data, rendering nothing would leave it filtering invisibly. */
function FilterUnknownRow<V>({ rule, position }: { rule: FilterRule<V>; position: RowPosition }) {
const actions = useFilterActions();
const sizes = filterControlSizes(actions);
return (
<div
role="group"
aria-label={actions.labels.rowLabel(rule.path.join(actions.labels.pathSeparator), position.depth)}
data-slot="filter-row"
data-node-id={rule.id}
data-parent-id={position.parentId}
data-index={position.index}
data-depth={position.depth}
data-unknown=""
/* The DROP language too: the hit test pushes every row carrying
`data-parent-id` into the surface, and this row carries one. */
className={cn(ROW_BAND_CLASS, DROP_INDICATOR)}
>
<span className="text-muted-foreground min-w-0 flex-1 truncate text-sm">{rule.path.join(actions.labels.pathSeparator)}</span>
{/* The same trailing band, so the broken row lands on the kebab column. */}
<div className={ACTION_BAND_CLASS}>
<Button
variant="ghost"
size={sizes.icon}
aria-label={actions.labels.remove}
className={ACTION_CONTROL_CLASS}
/* Outside the roving scheme: a real tab stop keeps it removable. */
data-filter-cell="remove"
/* It had no gate, so the one row whose purpose is to be removed
could be removed from a read-only bar. */
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
onClick={() => actions.removeNode(rule.id)}
>
<XIcon />
</Button>
</div>
</div>
);
}
/* -------------------------------------------------------------------------- */
/* Group */
/* -------------------------------------------------------------------------- */
/** A nested group: an indented card, its conditions, and one way to add
* another. The HEADLINE went; the pill outside already says "or". */
function FilterAdvancedGroup<V, O>({ group, position }: { group: FilterGroupNode<V>; position: RowPosition }) {
const actions = useFilterActions<V, O>();
const sizes = filterControlSizes(actions);
const focusStore = useFilterFocusStore();
const { query } = useFilterState<V>();
const issue = useFilterIssue(group.id);
const issueText = issue ? filterIssueLabel(issue, actions.labels) : '';
const reorderable = useFilterReorderable();
const canMove = reorderable && canFilterNodeMove(query, position);
const rowStateStore = useFilterRowStateStore();
const slot = filterCombinatorSlot(position.index);
const columns = React.useMemo(() => {
const list: FilterColumn[] = [];
if (slot === 'toggle') list.push('combinator');
// DOM order, which the arrow walker reads: a group's own controls are all
// in its footer now, add first and the trailing pair after it.
list.push('add');
if (canMove) list.push('drag');
list.push('menu');
return list;
}, [slot, canMove]);
const active = useActiveColumn(group.id, columns, position.depth === 1 && position.index === 0);
const onCellFocus = React.useCallback(
(column: FilterColumn) => () => focusStore.set({ id: group.id, segment: column, autoOpen: false }),
[focusStore, group.id],
);
const description = group.combinator === 'and' ? actions.labels.groupAll : actions.labels.groupAny;
const addInto = () => {
const id = addFilterRow(actions, group.id);
if (!id) return;
rowStateStore.markPending(id);
focusStore.set({ id, segment: 'field', autoOpen: true });
};
return (
<div
role="group"
aria-label={actions.labels.groupLabel(description, position.depth)}
data-slot="filter-row"
data-node-id={group.id}
data-parent-id={position.parentId}
data-index={position.index}
data-depth={position.depth}
/* `flex-wrap` is the whole of the narrow-panel fix. `items-center`
measures the flex line, so the pill centres on the card. */
className={cn('flex flex-wrap items-center gap-1.5', DROP_SLOT_INDICATOR)}
>
<div className={cn(COMBINATOR_CLASS, CELL_BOX_CLASS, GROUP_COMBINATOR_WRAP_CLASS)}>
<CombinatorCell
index={position.index}
parentId={position.parentId}
combinator={position.combinator}
active={active}
onFocus={onCellFocus}
className={GROUP_COMBINATOR_WRAPPED_CLASS}
/>
</div>
{/* The CARD lights up as the drop destination, not the header strip the
engine measured. This `data-invalid` only styles; the announcement
rides the footer's add button, which is the focusable control. */}
<div data-slot="filter-group" data-invalid={issue ? '' : undefined} className={GROUP_CARD_CLASS}>
{/* Eight pixels, because it is a DROP TARGET and a zone beats a row. */}
<div
data-slot="filter-group-header"
className="flex h-2 items-center"
/* The TOP of the card means the top of the list: index 0 PREPENDS.
It used to append, so the one place a pointer can aim to say "into
this group" put the row at the far other end of it. */
data-drop-parent={group.id}
data-drop-index={0}
/>
{/* A CONTAINER: the box every child row divides up. */}
<div className={cn(TRACK_CONTAINER_CLASS, 'flex flex-col', FILTER_ROW_GAP_CLASS)}>
{group.rules.length === 0 ? (
<p
className={cn(
/* 70% foreground, not the muted token: on the card's tint the
muted foreground measured 4.35:1 in light, under 4.5:1 AA. */
'text-foreground/70 rounded-md border border-dashed px-2 py-3',
'text-center text-xs',
'data-drop-into:border-primary/60 data-drop-into:bg-primary/5',
'data-drop-into:text-primary',
)}
data-slot="filter-group-empty"
data-drop-parent={group.id}
data-drop-index={0}
>
{actions.labels.groupPlaceholder}
</p>
) : (
group.rules.map((node, index) => (
<FilterAdvancedNode<V, O>
key={node.id}
node={node}
position={{
index,
parentId: group.id,
combinator: group.combinator,
depth: position.depth + 1,
}}
/>
))
)}
</div>
{/* `flex-nowrap`, or the group's kebab leaves the kebab column. */}
<div
data-slot="filter-group-footer"
className="text-muted-foreground flex flex-nowrap items-center gap-2 pt-2 pb-2"
data-drop-parent={group.id}
data-drop-index={group.rules.length}
>
<Button
variant="outline"
size={sizes.button}
aria-label={actions.labels.addToGroup}
className={cn(
/* `shrink` and not merely `min-w-0`: `shrink-0` is baked into
the shadcn button's own base class. */
'min-w-0 shrink font-normal',
'overflow-hidden',
CELL_INVALID_CLASS,
)}
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
{...cellProps('add', active)}
/* An EMPTY group is flagged on the control that fills it. */
{...issueProps(issue, 'group', issueText)}
onFocus={onCellFocus('add')}
onClick={addInto}
>
<PlusIcon />
{actions.labels.addCondition}
</Button>
<div className={cn('ms-auto', ACTION_BAND_CLASS)}>
{canMove ? <RowHandle nodeId={group.id} active={active} onFocus={onCellFocus} /> : null}
<FilterGroupMenu group={group} active={active} onFocus={onCellFocus} />
</div>
</div>
</div>
</div>
);
}
/** A group's kebab. A menu row affords six words, where two icons said none. */
function FilterGroupMenu<V>({
group,
active,
onFocus,
}: {
group: FilterGroupNode<V>;
active: FilterColumn | null;
onFocus: (column: FilterColumn) => () => void;
}) {
const actions = useFilterActions();
const sizes = filterControlSizes(actions);
const locked = isFilterLocked(actions);
const [open, setOpen] = React.useState(false);
return (
<DropdownMenu
open={open}
onOpenChange={(next) => {
if (next && locked) return;
setOpen(next);
}}
>
<DropdownMenuTrigger
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
render={
<Button
variant="ghost"
size={sizes.icon}
aria-label={actions.labels.groupMenu}
className={ACTION_CONTROL_CLASS}
{...cellProps('menu', active)}
onFocus={onFocus('menu')}
/>
}
>
<EllipsisVerticalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className={cn(FILTER_MENU_CLASS, actions.menuClassName)}>
<DropdownMenuItem disabled={locked} onClick={() => actions.duplicateNode(group.id)}>
<CopyIcon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.duplicate}</span>
</DropdownMenuItem>
<DropdownMenuItem disabled={locked} onClick={() => actions.unwrapGroup(group.id)}>
{/* The inverse of the row menu's layers glyph. */}
<UngroupIcon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.ungroup}</span>
</DropdownMenuItem>
<FilterMoveToMenuItems nodeId={group.id} />
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" disabled={locked} onClick={() => actions.removeNode(group.id)}>
{/* No colour: the destructive variant paints the row's svgs. */}
<Trash2Icon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.removeGroup}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
function FilterAdvancedNode<V, O>({ node, position }: { node: FilterNode<V>; position: RowPosition }) {
const actions = useFilterActions<V, O>();
if (!isFilterRule(node)) {
return <FilterAdvancedGroup<V, O> group={node} position={position} />;
}
if (!getFilterField(actions.index, node.path)) {
return <FilterUnknownRow<V> rule={node} position={position} />;
}
return <FilterAdvancedRow<V, O> rule={node} position={position} />;
}
/* -------------------------------------------------------------------------- */
/* Adding */
/* -------------------------------------------------------------------------- */
/** Appends a condition on the first attribute anyone may filter on, at any
* depth. `isFilterFieldPickable` is the picker's own rule. */
function addFilterRow<V, O>(actions: FilterActionsContextValue<V, O>, parentId?: string): string | null {
// Before `nextId` and before `addRule`: while the store points at a row that
// was never created, the whole panel drops out of the tab order.
if (isFilterLocked(actions)) return null;
const entry = actions.index.all.find((candidate) => isFilterFieldPickable(candidate.field));
if (!entry) return null;
const id = actions.nextId();
actions.addRule(
createFilterRule<V>({
id,
path: entry.path,
// Deliberately empty: the row arrives PENDING, and a seeded default
// would open the next menu with its own answer highlighted.
operator: '',
}),
parentId,
);
return id;
}
/* -------------------------------------------------------------------------- */
/* Panel */
/* -------------------------------------------------------------------------- */
/** The panel draws NO border, NO background and NO radius, and takes no
* element to be drawn as: a surface is the page's decision. */
export interface FiltersAdvancedPanelProps {
/** Which of the two boxes the panel sits in, the only thing deciding whether
* it pads itself: a popover's content is `p-0`, so this padding IS its
* inner padding, and `"inline"` is a page that owns its own. */
mode?: 'popover' | 'inline';
/** Replaces the empty state for this panel only. Wins over
* `Filters.renderEmpty`, the precedence a field has over the root's. */
renderEmpty?: (context: FilterEmptyStateContext) => React.ReactNode;
/** Whether rows can be reordered. See `FiltersProps.reorderable`. */
reorderable?: boolean;
className?: string;
}
/** The builder itself: nested groups over the query tree the chips read. A
* group is a parenthesised list joined by ONE operator, so nesting is a real
* tree: a flat model cannot represent `a AND (b OR c)` without inventing
* precedence, and invented precedence returns the wrong rows. */
export function FiltersAdvancedPanel<V, O>({ mode = 'popover', renderEmpty, reorderable = false, className }: FiltersAdvancedPanelProps) {
const actions = useFilterActions<V, O>();
const panelRender = useFilterRender<V, O>();
const sizes = filterControlSizes(actions);
const { query, ruleCount, announcement, announcementSeq } = useFilterState<V>();
const focusStore = useFilterFocusStore();
const rowStateStore = useFilterRowStateStore();
// A version counter, because the store is mutable and stable by identity.
const rowStateVersion = React.useSyncExternalStore(
rowStateStore.subscribe,
() => rowStateStore.version(),
() => 0,
);
const bodyRef = React.useRef<HTMLDivElement>(null);
const locked = isFilterLocked(actions);
/* ------------------------------ validation ------------------------------ */
/** What is unfinished, computed ONCE: an empty group is a fact about a
* group, not about any row inside it. */
const issues = React.useMemo(
() =>
collectFilterIssues(
query,
(rule) => {
const field = getFilterField(actions.index, rule.path);
if (!field) return null;
return getFilterArity(getFilterOperator(actions.resolveOperators(field), rule.operator));
},
// The same normalisation the display callbacks get.
(rule) => {
const field = getFilterField(actions.index, rule.path);
if (!field?.validate) return null;
const operator = getFilterOperator(actions.resolveOperators(field), rule.operator);
if (!operator) return null;
return field.validate({
value: rule.value,
values: rule.value === undefined || rule.value === null ? [] : Array.isArray(rule.value) ? (rule.value as unknown[]) : [rule.value],
field,
operator,
arity: getFilterArity(operator) ?? 'one',
rule,
labels: actions.labels,
});
},
),
[query, actions],
);
/** Every issue, keyed by node: what the tree IS, drawn or not. */
const issueMap = React.useMemo(() => new Map(issues.map((issue) => [issue.nodeId, issue])), [issues]);
/** The issues a row may DRAW: the ones on a value committed once. */
const visibleIssueMap = React.useMemo(() => {
const visible = new Map<string, FilterIssue>();
for (const issue of issues) {
// CUSTOM ONLY. The built-in reasons describe a row as HALF BUILT,
// so every Add filter produced a red row on the happy path.
if (issue.reason !== 'custom') continue;
if (rowStateStore.has(issue.nodeId)) visible.set(issue.nodeId, issue);
}
return visible;
}, [issues, rowStateStore, rowStateVersion]);
/** Says out loud that a VISIBLE error has appeared, which would
* otherwise happen in silence. The DRAWN issues, on a RISE only. */
const announcedIssues = React.useRef({
count: visibleIssueMap.size,
seq: announcementSeq,
});
React.useEffect(() => {
const before = announcedIssues.current;
announcedIssues.current = {
count: visibleIssueMap.size,
seq: announcementSeq,
};
if (announcementSeq !== before.seq) return;
if (visibleIssueMap.size <= before.count) return;
actions.announce(actions.labels.issueSummary(visibleIssueMap.size));
}, [visibleIssueMap, announcementSeq, actions]);
/** Sends focus to the first thing that needs it. Walked and not selected
* by id: a node id is consumer-supplied, and `CSS.escape` is not
* optional in a hand-built selector. */
const focusFirstIssue = React.useCallback(() => {
const first = issues[0];
const body = bodyRef.current;
if (!first || !body) return;
const row = Array.from(body.querySelectorAll<HTMLElement>(ROW_SELECTOR)).find((candidate) => candidate.dataset.nodeId === first.nodeId);
if (!row) return;
// A group's issue is drawn on the add button that resolves it.
const column = first.column === 'group' ? 'add' : first.column;
const target = ownCells(row).find((cell) => cell.getAttribute(CELL_ATTRIBUTE) === column);
target?.focus();
}, [issues]);
/* ---------------------------- focus recovery ---------------------------- */
/** Whether the panel, or a menu of its own, held focus a moment ago. A
* blur WITH a `relatedTarget` is focus arriving somewhere real; a blur
* with none, or none at all when the element is simply removed, is what
* this exists to repair. */
const heldFocus = React.useRef(false);
const addRowRef = React.useRef<HTMLButtonElement>(null);
/** Puts focus back after a mutation that destroyed the thing holding it:
* measured at 50, 200, 600 and 1200ms after Convert to group, Remove,
* Ungroup and Move to group, `document.activeElement` was the BODY,
* because a menu restores focus to a trigger the action unmounted. */
const restoreFocus = React.useCallback(() => {
// A handoff is mid-air and owns focus: between one step being answered
// and the next opening `document.activeElement` IS the body.
if (focusStore.getSnapshot().autoOpen) return;
if (!heldFocus.current) return;
const active = document.activeElement;
if (active && active !== document.body) return;
const rows = Array.from(bodyRef.current?.querySelectorAll<HTMLElement>(ROW_SELECTOR) ?? []);
const { id, segment } = focusStore.getSnapshot();
const row = id ? rows.find((candidate) => candidate.dataset.nodeId === id) : undefined;
const cells = row ? ownCells(row) : [];
const target =
cells.find((entry) => entry.getAttribute(CELL_ATTRIBUTE) === segment) ??
cells[0] ??
(rows[0] ? ownCells(rows[0])[0] : undefined) ??
addRowRef.current ??
undefined;
target?.focus();
}, [focusStore]);
// In the passive effect, not a frame later: React removes the control in
// the mutation phase, so a menu's restore then aims at a detached node.
React.useEffect(() => {
restoreFocus();
}, [query, announcementSeq, restoreFocus]);
/* -------------------------------- adding -------------------------------- */
const addRow = React.useCallback(() => {
const id = addFilterRow(actions);
if (!id) return;
// PENDING until the attribute is chosen, the first of three questions.
rowStateStore.markPending(id);
focusStore.set({ id, segment: 'field', autoOpen: true });
}, [actions, focusStore, rowStateStore]);
const addGroup = React.useCallback(() => {
const id = actions.addGroup();
// An empty id means it refused, and focusing a group never created
// would strand the tab stop.
if (!id) return;
// Onto the group's own chrome, not into it: it arrives empty.
focusStore.set({ id, segment: 'add', autoOpen: false });
}, [actions, focusStore]);
/* ------------------------------- keyboard ------------------------------- */
const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
const cell = (event.target as HTMLElement).closest<HTMLElement>(`[${CELL_ATTRIBUTE}]`);
// A key pressed inside an open popover belongs to that popover; its
// content is portaled out, so this is belt and braces.
//
// ArrowDown never reaches here: Base UI stops it at the menu trigger.
if (!cell || event.target !== cell) return;
const body = bodyRef.current;
const row = cell.closest<HTMLElement>(ROW_SELECTOR);
if (!body || !row) return;
/* A cell the user TYPES into keeps the keys that edit text; only the
VERTICAL keys stay. */
const editing = cell.hasAttribute(CELL_INPUT_ATTRIBUTE);
// DOM order for the two places that mean "the whole builder".
const rows = Array.from(body.querySelectorAll<HTMLElement>(ROW_SELECTOR));
const cells = ownCells(row);
const rowIndex = rows.indexOf(row);
const cellIndex = cells.indexOf(cell);
const rtl = getComputedStyle(cell).direction === 'rtl';
const forward = rtl ? 'ArrowLeft' : 'ArrowRight';
const backward = rtl ? 'ArrowRight' : 'ArrowLeft';
const focus = (target: HTMLElement | undefined) => {
if (!target) return;
event.preventDefault();
target.focus();
};
const from = cell.getAttribute(CELL_ATTRIBUTE) as FilterColumn;
const band = (CONTENT_COLUMNS as readonly FilterColumn[]).includes(from) ? CONTENT_COLUMNS : ACTION_COLUMNS;
/* The rows that draw a cell in this BAND, in cell order: by ROW it went
BACKWARDS at +212, -166, +122, -76, +38 pixels once a group's own
controls moved to its footer. */
const bandRows: HTMLElement[] = [];
const seen = new Set<HTMLElement>();
for (const entry of body.querySelectorAll<HTMLElement>(`[${CELL_ATTRIBUTE}]`)) {
const column = entry.getAttribute(CELL_ATTRIBUTE) as FilterColumn;
if (!(band as readonly FilterColumn[]).includes(column)) continue;
const owner = entry.closest<HTMLElement>(ROW_SELECTOR);
if (!owner || seen.has(owner)) continue;
seen.add(owner);
bandRows.push(owner);
}
const bandIndex = bandRows.indexOf(row);
const focusRow = (step: number) => {
const nextRow = bandRows[bandIndex + step];
if (!nextRow) return;
const cellsThere = ownCells(nextRow);
const byColumn = new Map(cellsThere.map((entry) => [entry.getAttribute(CELL_ATTRIBUTE), entry]));
// The band, then anything at all, which keeps a consumer's cell
// reachable.
focus(nearestColumn(band, from, byColumn) ?? cellsThere[0]);
};
const nodeId = row.dataset.nodeId;
if (!nodeId) return;
// Alt reorders rather than navigates, within the owning group only:
// changing depth with an arrow would make one gesture mean two things.
if (event.altKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
// Plain arrows, Home and End are deliberately NOT gated.
if (locked || !reorderable) return;
event.preventDefault();
actions.moveNode(nodeId, event.key === 'ArrowDown' ? 1 : -1);
return;
}
if (event.key === 'ArrowDown') return focusRow(1);
if (event.key === 'ArrowUp') return focusRow(-1);
if (editing) return;
if (event.key === forward) return focus(cells[cellIndex + 1]);
if (event.key === backward) return focus(cells[cellIndex - 1]);
if (event.key === 'Home') {
return focus(event.ctrlKey ? ownCells(rows[0])[0] : cells[0]);
}
if (event.key === 'End') {
const scope = event.ctrlKey ? ownCells(rows[rows.length - 1]) : cells;
return focus(scope[scope.length - 1]);
}
if (event.key === 'Backspace' || event.key === 'Delete') {
if (locked) return;
event.preventDefault();
actions.removeNode(nodeId);
// Focus the row that takes this one's place, so removing several
// does not throw focus to the body.
requestAnimationFrame(() => {
const remaining = Array.from(bodyRef.current?.querySelectorAll<HTMLElement>(ROW_SELECTOR) ?? []);
const target = remaining[Math.min(rowIndex, remaining.length - 1)];
if (target) ownCells(target)[0]?.focus();
});
}
};
/* --------------------------------- drag --------------------------------- */
/** Pointer drag, not HTML5 drag and drop: its drag image is a
* browser-owned snapshot no copy badge can be drawn on, and a nested
* drop would mean hit-testing on every `dragover`. */
const dragProps = useFilterRowDrag({
// THE PANEL, reached through the body, because the top level's append
// zone is in the FOOTER and the footer is the body's sibling.
root: () => bodyRef.current?.parentElement ?? null,
disabled: locked,
onDrop: (nodeId, drop) => {
if (drop.copy) actions.copyNodeTo(nodeId, drop.parentId, drop.index);
else actions.moveNodeTo(nodeId, drop.parentId, drop.index);
},
});
/* -------------------------------- render -------------------------------- */
const panelProps = {
// The panel's programmatic NAME. `group`, because the rows inside are
// groups too, so the tree reads as a query rather than as a landmark.
role: 'group',
'aria-label': actions.labels.advancedFilter,
// WHAT IS IN IT, on entry, for a reader who did not press the trigger.
// The read-only half rides along: `aria-readonly` is illegal here.
'aria-description': actions.readOnly
? `${actions.labels.countAnnouncement(ruleCount)} ${actions.labels.readOnly}`
: actions.labels.countAnnouncement(ruleCount),
'data-slot': 'filters-advanced',
'data-readonly': actions.readOnly || undefined,
// Capture, and on the PANEL, so portaled menus report too.
onFocusCapture: () => {
heldFocus.current = true;
},
onBlurCapture: (event: React.FocusEvent) => {
if (event.relatedTarget) heldFocus.current = false;
},
} as const;
/** The empty state, resolved once: the panel's own prop, else the root's.
* Assembled here so a replacement gets the SAME two actions the footer
* calls, focus handoff included. */
const renderEmptyState = renderEmpty ?? panelRender.renderEmpty;
const emptyState = renderEmptyState
? renderEmptyState({
labels: actions.labels,
readOnly: Boolean(actions.readOnly),
mode,
addFilter: addRow,
addGroup,
})
: null;
const body = (
<>
{/* VISIBLE, not an ARIA attribute: `aria-readonly` is illegal on every
role here, and dimmed controls owe the reader a reason. */}
{actions.readOnly ? (
<p data-slot="filters-readonly" className={cn('text-muted-foreground text-xs', PANEL_GUTTER_CLASS)}>
{actions.labels.readOnly}
</p>
) : null}
{query.rules.length > 0 ? (
<div
ref={bodyRef}
data-slot="filters-advanced-body"
/* NO `overflow-x`: nothing here is ever wider than its box. */
className={cn(TRACK_CONTAINER_CLASS, 'flex min-w-0 flex-col', FILTER_ROW_GAP_CLASS, PANEL_GUTTER_CLASS)}
onKeyDown={onKeyDown}
>
<FilterReorderProvider value={reorderable}>
<FilterDragContext.Provider value={reorderable ? dragProps : null}>
<FilterIssueContext.Provider value={visibleIssueMap}>
{query.rules.map((node, index) => (
<FilterAdvancedNode<V, O>
key={node.id}
node={node}
position={{
index,
parentId: query.id,
combinator: query.combinator,
depth: 1,
}}
/>
))}
</FilterIssueContext.Provider>
</FilterDragContext.Provider>
</FilterReorderProvider>
</div>
) : /*
THE EMPTY STATE, a real state and not a missing one: with no rules
the body renders nothing, so the panel used to open as a footer
floating in a blank popover. The HINT is withheld when the bar is
locked, since it points at two disabled buttons.
*/
// The CALLBACK's presence decides, not its result: a consumer returning
// null wants a blank panel, and `??` would hand them the default back.
renderEmptyState ? (
emptyState
) : (
<div
data-slot="filters-advanced-empty"
className={cn('flex flex-col items-center justify-center gap-1 py-8 text-center', PANEL_GUTTER_CLASS)}
>
<span
aria-hidden="true"
/* `rounded-full` is the one radius literal safe in every
style, square or round. */
className="bg-muted text-muted-foreground mb-1 flex size-9 items-center justify-center rounded-full [&_svg]:size-4"
>
<ListFilterIcon />
</span>
<p className="text-sm font-medium">{actions.labels.builderEmpty}</p>
{actions.readOnly ? null : <p className="text-muted-foreground text-xs">{actions.labels.builderEmptyHint}</p>}
</div>
)}
{/* `shrink-0` on all three: a button clips its label rather than
reflowing it, so Clear all read as "ear all filters". */}
<div
data-slot="filters-advanced-footer"
/* THE APPEND TARGET FOR THE TOP LEVEL, which every group's footer had
and the root did not: at depth the strip under the last row is a 48px
"put it here", while at the root it was 47px of `no-drop`. */
data-drop-parent={query.id}
data-drop-index={query.rules.length}
className={cn(
'relative flex flex-wrap items-center gap-2',
PANEL_GUTTER_CLASS,
/* FOUR PIXELS MORE than the gutter, which is what a row's action
band spends after its kebab. */
'pe-[calc(var(--filter-panel-pad)+4px)]',
FOOTER_DROP_CLASS,
/* The strip's BOX reaches the body's bottom edge and pads its
content back down, so the append zone TILES with the last row.
`pt-5` and not `pt-2`: the row above already grows 4px into this
strip, so at `pt-2` the toolbar read as the last filter's tail. */
query.rules.length > 0 && cn(FILTER_ROW_GAP_CANCEL_CLASS, 'pt-5'),
)}
>
<Button
/* The last resort of `restoreFocus`: the only control that exists
at every query. */
ref={addRowRef}
/* OUTLINE, and the only pair in the panel with a box: they are
what the footer is FOR. */
variant="outline"
size={sizes.button}
className="shrink-0 font-normal"
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
onClick={addRow}
>
<PlusIcon />
{actions.labels.addCondition}
</Button>
<Button
variant="outline"
size={sizes.button}
className="shrink-0 font-normal"
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
onClick={addGroup}
>
<FolderPlusIcon />
{actions.labels.addConditionGroup}
</Button>
{/* NO PANEL-LEVEL SUMMARY: a validator's no belongs on the cell. */}
{ruleCount > 0 ? (
<Button
variant="ghost"
size={sizes.button}
className="text-muted-foreground hover:text-foreground ms-auto shrink-0"
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
onClick={() => actions.clearQuery()}
>
{actions.labels.clearAll}
</Button>
) : null}
</div>
{/* The `key` is what makes a REPEATED sentence audible: `aria-live`
fires on a mutation and React writes nothing when the string is
unchanged, so three presses mutated the region once. */}
<div aria-live="polite" role="status" className="sr-only">
<span key={announcementSeq}>{announcement}</span>
</div>
</>
);
return (
<div
{...panelProps}
/* An inline style because it is a VALUE: one declaration to beat
rather than three classes in three places. */
style={
{
[PANEL_PAD_VAR]: mode === 'inline' ? PANEL_PAD_INLINE : PANEL_PAD_POPOVER,
} as React.CSSProperties
}
className={cn(PANEL_CLASS, className)}
>
{body}
</div>
);
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
export interface FiltersAdvancedProps {
/** Where the builder lives. `"popover"` hangs it off a trigger; `"inline"`
* renders the same panel with no popup, for a sidebar or a settings page. */
mode?: 'popover' | 'inline';
/** Replaces the default trigger. Ignored inline. */
trigger?: React.ReactNode;
/** Whether rows can be reordered. See `FiltersProps.reorderable`. */
reorderable?: boolean;
/** Popover placement. */
align?: 'start' | 'center' | 'end';
className?: string;
}
export function FiltersAdvanced<V, O>({ mode = 'popover', trigger, reorderable = false, align = 'start', className }: FiltersAdvancedProps) {
const actions = useFilterActions<V, O>();
const sizes = filterControlSizes(actions);
const { ruleCount } = useFilterState<V>();
const [open, setOpen] = React.useState(false);
if (mode === 'inline') {
return <FiltersAdvancedPanel<V, O> mode="inline" reorderable={reorderable} className={className} />;
}
return (
<Popover open={open} onOpenChange={setOpen}>
{/* `actions.disabled` alone, and READ ONLY DELIBERATELY DOES NOT
GATE IT: opening this panel is reading, not writing. */}
<PopoverTrigger
/* On the TRIGGER rather than the button below it, so a consumer's own
trigger wears the same state. Still `actions.disabled` alone. */
disabled={actions.disabled}
render={
trigger ? (
(trigger as React.ReactElement)
) : (
<Button
variant="outline"
size={sizes.button}
/* THE COUNT IN THE NAME, not only in the box: a consumer who
replaces `trigger` never had the badge, which is hidden. */
aria-label={ruleCount > 0 ? `${actions.labels.advancedFilter}, ${actions.labels.countAnnouncement(ruleCount)}` : undefined}
>
<ListFilterIcon />
{actions.labels.advancedFilter}
{ruleCount > 0 ? (
<span aria-hidden="true" className="bg-muted text-muted-foreground rounded-sm px-1.5 text-xs tabular-nums">
{ruleCount}
</span>
) : null}
</Button>
)
}
/>
{/* Wide enough for a nested group to keep real words at depth three;
the rows truncate rather than wrap. */}
<PopoverContent
align={align}
/* THE POPUP'S OWN NAME: it is a `role="dialog"`, and the panel's is
one level in, on its `role="group"`. */
aria-label={actions.labels.advancedFilter}
className={cn('w-[42rem] max-w-[95vw] p-0', className)}
>
{/* `mode` defaults to "popover", which keeps the panel's padding. */}
<FiltersAdvancedPanel<V, O> reorderable={reorderable} />
</PopoverContent>
</Popover>
);
}components/ui/filters/filters-builder.tsx
'use client';
import * as React from 'react';
import { Cascader, CascaderEmpty, CascaderList, CascaderPanel, CascaderStatus } from '@/registry/vcare/ui/cascader/cascader';
import { CascaderFooter } from '@/registry/vcare/ui/cascader/cascader-footer';
import { CascaderBreadcrumb, CascaderInput, CascaderNav } from '@/registry/vcare/ui/cascader/cascader-nav';
import type { CascaderActionItem, CascaderLabels, CascaderNode } from '@/registry/vcare/ui/cascader/cascader-types';
import { CascaderVirtualItems } from '@/registry/vcare/ui/cascader/cascader-virtual';
import { filterControlSizes, filterReadOnlyProps, useFilterActions, useFilterState } from '@/registry/vcare/ui/filters/filters-context';
import {
FILTER_FIELD_PICKER_CLASS,
getFilterField,
getFilterFieldCount,
joinFilterPath,
splitFilterPath,
} from '@/registry/vcare/ui/filters/filters-lib';
import { getDefaultFilterOperator } from '@/registry/vcare/ui/filters/filters-operators';
import type { FilterField } from '@/registry/vcare/ui/filters/filters-types';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/registry/vcare/ui/popover';
import { ListFilterPlusIcon } from 'lucide-react';
/**
* Projects ONLY the field tree: operators or values as nodes would force the
* wizard through a combobox that owns the arrows and `aria-activedescendant`.
*/
function toCascaderNodes<V, O>(fields: readonly FilterField<V, O>[], parentPath: string[] = []): CascaderNode<FilterField<V, O>>[] {
return fields.map((field) => {
const path = [...parentPath, field.id];
const node: CascaderNode<FilterField<V, O>> = {
value: joinFilterPath(path),
label: field.label,
icon: field.icon,
description: field.description,
keywords: field.keywords,
disabled: field.disabled,
data: field,
};
if (field.fields?.length) {
node.children = toCascaderNodes(field.fields, path);
node.count = getFilterFieldCount(field);
}
return node;
});
}
export interface FilterFieldPickerProps {
/** The level being browsed. Not the chosen field. */
path: string[];
onPathChange: (path: string[]) => void;
query: string;
onQueryChange: (query: string) => void;
/** A field was chosen, with its starting operator already resolved. */
onSelect: (path: string[], defaultOperator: string | null) => void;
/** Viewport height before the list scrolls. */
maxHeight?: number;
/** Cascader-only strings; the `FilterLabels` bridge below covers the rest. */
labels?: Partial<CascaderLabels>;
/** Pinned footer rows, OUT of the option ring so arrows never land on one. */
actions?: CascaderActionItem[];
}
/**
* Fully controlled, not draft-driven, so ONE picker serves both the create
* popover (driven by the draft reducer) and an advanced row (its own state).
*/
export function FilterFieldPicker<V, O>({
path,
onPathChange,
query,
onQueryChange,
onSelect,
maxHeight = 260,
labels: labelsProp,
actions: actionItems,
}: FilterFieldPickerProps) {
const actions = useFilterActions<V, O>();
const items = React.useMemo(() => toCascaderNodes(actions.index.roots), [actions.index]);
// Bridges `FilterLabels` onto the cascader's own key names. `labelsProp` is
// spread LAST, so a consumer override always wins.
const cascaderLabels = React.useMemo<Partial<CascaderLabels>>(
() => ({
search: actions.labels.searchFields,
back: actions.labels.back,
empty: actions.labels.empty,
pathSeparator: actions.labels.pathSeparator.trim() || '/',
itemCount: actions.labels.itemCount,
branchAffordance: actions.labels.branchAffordance,
rootLevel: actions.labels.fieldsLabel,
panelLabel: actions.labels.fieldsLabel,
resultsAnnouncement: actions.labels.resultsAnnouncement,
actionsLabel: actions.labels.actionsLabel,
...labelsProp,
}),
[actions.labels, labelsProp],
);
return (
<Cascader
inline
/* Pinned open: inline renders no popup and forces `open`, so the
single-select commit's `setOpen(false)` dismisses nothing. That avoids
the `multiple` plus `max` workaround and its `aria-multiselectable`. */
open
onOpenChange={() => {}}
items={items}
/* No `selectable` predicate: LEAVES commit, branches navigate. Honouring
a branch's opt-in made one click mean both drill and commit. */
searchScope="deep"
/* Nothing is ever selected, so the ~24px check gutter is dead space. */
indicator={false}
path={path}
onPathChange={onPathChange}
/* Controlled: the single-select arm of `commit()` never clears the query,
so an uncontrolled one would bleed into the next step. */
inputValue={query}
onInputValueChange={onQueryChange}
value=""
onValueChange={(value) => {
const nextPath = splitFilterPath(value);
const field = getFilterField(actions.index, nextPath);
if (!field) return;
onSelect(nextPath, getDefaultFilterOperator(field, actions.resolveOperators(field)));
}}
labels={cascaderLabels}
actions={actionItems}
/* Set here only: `CascaderList` takes its own `maxHeight` and that WINS,
so a second copy on the list is a divergence waiting to happen. */
maxHeight={maxHeight}
>
<CascaderPanel>
<CascaderNav>
<CascaderInput placeholder={actions.labels.searchFields} />
</CascaderNav>
<CascaderBreadcrumb />
<CascaderEmpty />
<CascaderList>
{/* WINDOWED: the picker is where scale lives and nothing here pins.
Below the threshold it renders what `CascaderItems` does. */}
<CascaderVirtualItems />
</CascaderList>
<CascaderFooter />
<CascaderStatus />
</CascaderPanel>
</Cascader>
);
}
function FieldStep<V, O>() {
const actions = useFilterActions<V, O>();
const { draft } = useFilterState<V>();
return (
<FilterFieldPicker<V, O>
path={draft?.cascaderPath ?? []}
onPathChange={(next) => actions.dispatchDraft({ type: 'setCascaderPath', path: next })}
query={draft?.query ?? ''}
onQueryChange={(query) => actions.dispatchDraft({ type: 'setQuery', query })}
onSelect={(path, defaultOperator) => actions.dispatchDraft({ type: 'selectField', path, defaultOperator })}
/>
);
}
export interface FiltersBuilderProps {
/** Replaces the default Add filter button. */
trigger?: React.ReactNode;
className?: string;
}
/**
* The Add filter popover. ONE panel, the field step: picking a field commits
* the rule and opens the operator menu on the new chip. `open` derives from the
* draft and `openCreate` is gated, so read-only and disabled shut every route.
*/
export function FiltersBuilder<V, O>({ trigger, className }: FiltersBuilderProps) {
const actions = useFilterActions<V, O>();
const sizes = filterControlSizes(actions);
const { draft, ruleCount } = useFilterState<V>();
const open = draft !== null && draft.ruleId === null;
// The HANDOFF close, the one that must not FADE: the panel is a 224px card
// dissolving over the very menu the user is now meant to read.
const committing = draft !== null && draft.ruleId === null && draft.status === 'ready';
// LATCHED, because `committing` is true for one render only, before the exit
// it suppresses begins. Adjusted during render; an effect is one frame late.
const [instantExit, setInstantExit] = React.useState(false);
if (committing && !instantExit) setInstantExit(true);
else if (open && !committing && instantExit) setInstantExit(false);
// Icon-only once chips sit beside it. Both states come off ONE size ladder,
// so they share height and radius in every style at every bar size. The
// hardcoded `icon`/`default` pair this replaced IS the `default` rung, so it
// drifted the moment the bar was `sm`.
const compact = ruleCount > 0;
// Base UI's own microtask-then-rAF ordering hands focus to the new chip, NOT
// anything this file arranges. Suppressing the close restore with
// `finalFocus` only removes the fallback that keeps focus off the BODY.
return (
<Popover
open={open}
onOpenChange={(next) => {
if (!next) actions.closeDraft();
else actions.openCreate();
}}
>
<PopoverTrigger
/* On the TRIGGER so a consumer's own `trigger` wears the state too. */
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
render={
trigger ? (
(trigger as React.ReactElement)
) : (
<Button
variant="outline"
size={compact ? sizes.icon : sizes.button}
aria-label={compact ? actions.labels.addFilter : undefined}
/* THE RESET BOUNCE: the button's base class carries
`transition-all`, so flipping the size class eased padding 0 to
`px-6` in sera over 150ms. Naming a transition REPLACES it. */
className="transition-[color,background-color,border-color,box-shadow]"
>
{/* No filter-plus glyph in phosphor or remixicon. */}
<ListFilterPlusIcon />
{compact ? null : actions.labels.addFilter}
</Button>
)
}
/>
{/* The default, then the root override, then this `className` last, so
the specific wins. */}
<PopoverContent
align="start"
className={cn(
FILTER_FIELD_PICKER_CLASS,
/* See `instantExit`. Both PROPERTIES (an `exit` animation AND a
transition each paint over the successor) and both twins (Base UI
`data-ending-style`, Radix `data-[state=closed]`); only one can
match in a given build. The string stays identical on both sides
because listing only the Base UI half left the radix twin fading
a 224px card over its successor. */
instantExit &&
cn(
'data-ending-style:animate-none data-ending-style:transition-none',
'data-[state=closed]:animate-none data-[state=closed]:transition-none',
),
actions.fieldPickerClassName,
className,
)}
>
<FieldStep<V, O> />
</PopoverContent>
</Popover>
);
}
/** Exported for custom field pickers. */
export { toCascaderNodes };components/ui/filters/filters-chip.tsx
'use client';
import * as React from 'react';
import {
filterControlSizes,
filterReadOnlyProps,
isFilterLocked,
useFilterActions,
useFilterChipAutoOpen,
useFilterChipFocused,
useFilterFocusEmpty,
useFilterFocusStore,
useFilterRender,
useFilterReorderable,
} from '@/registry/vcare/ui/filters/filters-context';
import { FilterMenu, useFilterOptions, useFilterValueResolution } from '@/registry/vcare/ui/filters/filters-editors';
import {
collapseFilterPath,
FILTER_MENU_CLASS,
FILTER_MENU_LABEL_CLASS,
formatFilterPath,
getFilterField,
getFilterFieldChain,
} from '@/registry/vcare/ui/filters/filters-lib';
import {
coerceFilterValue,
getFilterArity,
getFilterOperator,
operatorTakesValue,
visibleFilterOperators,
} from '@/registry/vcare/ui/filters/filters-operators';
import { findFilterNode, isFilterGroup } from '@/registry/vcare/ui/filters/filters-query';
import type { FilterEditorProps, FilterField, FilterGroupNode, FilterOperator, FilterRule } from '@/registry/vcare/ui/filters/filters-types';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { ButtonGroup, ButtonGroupText } from '@/registry/vcare/ui/button-group';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/registry/vcare/ui/dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '@/registry/vcare/ui/popover';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/registry/vcare/ui/tooltip';
import {
ChevronRightIcon,
CornerDownRightIcon,
CopyIcon,
ArrowLeftRightIcon,
LayersIcon,
SlidersHorizontalIcon,
Trash2Icon,
XIcon,
EllipsisVerticalIcon,
} from 'lucide-react';
/** Which part of the chip a pointer or key is aimed at. No `field`: the chip's
* attribute segment is display only, and only the builder re-picks one. */
type ChipSegment = 'operator' | 'value' | 'menu';
/** The ref half of `autoFocusProps`: a CALLBACK ref, the one shape an editor
* can spread onto any element without a cast, and a no-op here. */
const noopAutoFocusRef: React.RefCallback<HTMLElement> = () => {};
function defaultValueDisplay<V>(
value: V | undefined,
operator: FilterOperator | undefined,
resolveOption: (value: string) => { label: string } | undefined,
labels: ReturnType<typeof useFilterActions>['labels'],
// The field's own word for "no value yet", which a generic label cannot beat.
fieldPlaceholder?: string,
/** Whether the value is PICKED rather than typed: a select's search prompt
* and "enter text..." both give way to `labels.selectPlaceholder`. */
optionBacked?: boolean,
): string {
const emptyLabel = optionBacked ? labels.selectPlaceholder : (fieldPlaceholder ?? labels.valuePlaceholder);
if (value === undefined || value === null || value === '') {
return emptyLabel;
}
if (getFilterArity(operator) === 'range' && Array.isArray(value)) {
const [from, to] = value as unknown[];
return labels.valueRange(String(from ?? ''), String(to ?? ''));
}
if (Array.isArray(value)) {
const values = value as string[];
if (values.length === 0) return emptyLabel;
if (values.length === 1) {
return resolveOption(values[0])?.label ?? String(values[0]);
}
return labels.valueCount(values.length);
}
if (typeof value === 'boolean') return value ? 'True' : 'False';
return resolveOption(String(value))?.label ?? String(value);
}
/** The same display with the option's own icon in front. A status filter reads
* as its colour before its word, so dropping the swatch the picker showed
* makes the chip harder to scan than the list it came from. */
function valueWithIcon<V>(
value: V | undefined,
text: string,
resolveOption: (value: string) => { icon?: React.ReactNode } | undefined,
): React.ReactNode {
const single =
value === undefined || value === null || Array.isArray(value)
? Array.isArray(value) && value.length === 1
? String(value[0])
: null
: String(value);
const icon = single ? resolveOption(single)?.icon : null;
if (!icon) return text;
return (
<span className="flex items-center gap-1.5">
{icon}
{text}
</span>
);
}
/** The glyph between two ancestors in a nested attribute path, a chevron
* because the `pathSeparator` string read as loud as the names it parts.
* DECORATIVE: `aria-hidden`, and the plain string is still what
* `formatFilterPath` joins for the chip's accessible name and `title`. */
function FilterPathSeparator() {
return (
<ChevronRightIcon
aria-hidden="true"
data-slot="filter-path-separator"
className="text-muted-foreground mx-[3px] inline-block size-3 shrink-0 self-center align-[calc(0.3635em_-_0.375rem)]"
/>
);
}
/** The elided run of a collapsed path, with the FULL path behind it. THE
* TOOLTIP IS NOT THE ACCESSIBLE ROUTE: it is hover and focus, so the segment
* is `aria-hidden` and the whole path stays in the control's NAME. The host's
* own `title` is dropped while collapsed (`pathCollapsed`) or both fire. */
function FilterPathEllipsis({ full }: { full: string }) {
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger
render={
<span
aria-hidden="true"
data-slot="filter-path-ellipsis"
/* A path SEGMENT with no air of its own: the chevron's margin
is all that parts a name from the next, and this used to STACK
an `mx` on it. Plain inline, no `vertical-align`: `middle` sat
the dots 1.7px low and inline-block grew the run to 21.17px. */
className="text-muted-foreground shrink-0 self-center"
>
...
</span>
}
/>
<TooltipContent>{full}</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
/** Everything a rule needs in order to be READ, in either chrome. */
export interface FilterRuleDisplay {
pathText: string;
pathLabel: React.ReactNode;
/** Whether `pathLabel` shows fewer names than the path has, so the cell's
* own `title` can step aside for the ellipsis segment's tooltip. */
pathCollapsed: boolean;
operatorLabel: string;
valueLabel: React.ReactNode;
/** The same value as PLAIN TEXT, for an accessible name. Never scraped from
* the `renderValue` node: whatever text survives inside avatars and a count
* badge announces "plus one" for two people. Kept separate from
* `valueLabel`, not derived from it: a React node has no honest text to
* read back. A field whose values do not stringify supplies `valueText`
* itself, or the built-in fallback says "[object Object]" to exactly the
* audience the visible display is hiding it from. */
valueText: string;
/** The same value with any collapsed COUNT spelled out. "3 selected" cannot
* be recovered from, which is fine while the editor opens and not once
* locked, so the control carries this as `title` and, locked, as its name. */
valueFullText: string;
valueEmpty: boolean;
}
/** How one rule reads, resolved once and shared by both chromes, so a consumer
* `renderValue`, the field's own and the built-in cannot disagree. */
export function useFilterRuleDisplay<V, O>(
rule: FilterRule<V>,
field: FilterField<V, O> | undefined,
operator: FilterOperator | undefined,
): FilterRuleDisplay {
const actions = useFilterActions<V, O>();
const render = useFilterRender<V, O>();
// Lazily: a label needs no options until an editor actually opens.
const optionsState = useFilterOptions<V, O>(field, false);
const values = rule.value === undefined || rule.value === null ? [] : Array.isArray(rule.value) ? (rule.value as unknown[]) : [rule.value];
// Saved views: values the loader has never returned are resolved through the
// field's own `resolveValues`, so a restored chip reads "John Doe", not an id.
useFilterValueResolution(field, values);
const pathText = formatFilterPath(actions.index, rule.path, actions.labels.pathSeparator);
const chain = getFilterFieldChain(actions.index, rule.path);
// The CASCADER's collapser, from the actions context rather than per host, so
// a deep path reads the same on a chip and in a builder row.
const segments = collapseFilterPath(chain, {
maxSegments: actions.maxPathSegments,
collapse: actions.pathCollapse,
});
const pathCollapsed = segments.some((segment) => segment.type === 'ellipsis');
const pathLabel = chain.length
? segments.map((segment, index) => (
<React.Fragment
/* Positional, because a field id is unique among its SIBLINGS only:
"Company > Team > Company" is a legal path and its two ids collide. */
key={segment.type === 'field' ? `${index}:${segment.field.id}` : `${index}:ellipsis`}
>
{index > 0 ? <FilterPathSeparator /> : null}
{segment.type === 'field' ? <span>{segment.field.label}</span> : <FilterPathEllipsis full={pathText} />}
</React.Fragment>
))
: pathText;
const operatorLabel = operator
? rule.negated
? actions.labels.negated(operator.label)
: operator.label
: rule.operator || actions.labels.selectCondition;
const valueEmpty = rule.value === undefined || rule.value === null || rule.value === ('' as unknown as V) || values.length === 0;
if (!field) {
return {
pathText,
pathLabel,
pathCollapsed,
operatorLabel,
valueLabel: '',
valueText: '',
valueFullText: '',
valueEmpty,
};
}
const valueContext = {
value: rule.value,
values,
field,
operator: operator ?? { value: rule.operator, label: rule.operator },
// Resolved, not empty: a custom display needs the option behind each value.
options: values.map((entry) => optionsState.resolve(String(entry))).filter(Boolean) as NonNullable<ReturnType<typeof optionsState.resolve>>[],
labels: actions.labels,
};
// Computed even when a custom display replaces it: this is the string the
// accessible name is built from. `field.valueText` overrides it.
const valueText = field.valueText
? field.valueText(valueContext)
: defaultValueDisplay(
rule.value,
operator,
optionsState.resolve,
actions.labels,
field.placeholder,
// Option-backed by the FIELD, not the operator: `is any of` is
// multi-value on a plain text field too, and that one is typed into.
field.type === 'select' || field.type === 'multiselect' || Boolean(field.options?.length) || Boolean(field.loadOptions),
);
const valueLabel = render.renderValue
? render.renderValue(valueContext)
: field.renderValue
? field.renderValue(valueContext)
: valueWithIcon(rule.value, valueText, optionsState.resolve);
// The list behind the count, or the same text again. Multi-value only: a
// RANGE also stores an array but already spells both ends out ("10 to 99").
const valueFullText =
field.valueText || !Array.isArray(rule.value) || getFilterArity(operator) === 'range' || values.length < 2
? valueText
: actions.labels.valueDetail(
valueText,
values.map((entry) => optionsState.resolve(String(entry))?.label ?? String(entry)),
);
return {
pathText,
pathLabel,
pathCollapsed,
operatorLabel,
valueLabel,
valueText,
valueFullText,
valueEmpty,
};
}
interface FilterValueEditorProps<V = unknown, O = unknown> {
rule: FilterRule<V>;
field: FilterField<V, O>;
operator: FilterOperator;
/** Whether the surface holding it is showing. Gates the option service. */
open: boolean;
onClose: () => void;
}
/** The value editor - draft, option service, commit - with NO surface of its
* own, so surface and wiring can be replaced independently. The draft lives
* here, so a text filter dispatches once on commit, not once per keystroke. */
function FilterValueEditor<V, O>({ rule, field, operator, open, onClose }: FilterValueEditorProps<V, O>) {
const actions = useFilterActions<V, O>();
const [draft, setDraft] = React.useState<V | undefined>(rule.value);
React.useEffect(() => {
if (open) setDraft(rule.value);
}, [open, rule.value]);
const options = useFilterOptions<V, O>(field, open);
// A LOOKUP, not a definition: every result is a module-level built-in or the
// consumer's own component, so the editor is never remounted mid-edit.
const editor = React.useMemo(() => actions.resolveEditor(field, operator), [actions, field, operator]);
if (!editor) return null;
const editorProps: FilterEditorProps<V, O> = {
field,
operator,
value: draft,
onValueChange: (next) => setDraft(next as V),
host: 'amend',
autoFocusProps: {
ref: noopAutoFocusRef,
autoFocus: true,
},
commit: (next, commitOptions) => {
actions.updateRule(rule.id, {
value: (next === undefined ? draft : next) as V,
});
// A multi-select commits per toggle and asks to stay put; others dismiss.
if (commitOptions?.close === false) return;
onClose();
},
cancel: onClose,
// The same as cancel, honestly: `back` means something only to a `create`
// host.
back: onClose,
options,
labels: actions.labels,
};
// `createElement` rather than JSX: the component comes out of a lookup, so
// `<Editor />` trips `react-hooks/static-components`. The fragment keeps the
// props object, which carries a ref, from looking like a ref read in render.
return <>{React.createElement(editor, editorProps)}</>;
}
/** One step of the flow, released when the panel that owes it has LEFT THE
* DOM: both popovers keep portal content mounted through the exit transition,
* so this unmount IS that moment and nothing is timed. `onRelease` is used AS
* the cleanup, so an unmemoized callback fires its step early. */
function FilterStepHandoff({ onRelease }: { onRelease: () => void }) {
React.useEffect(() => onRelease, [onRelease]);
return null;
}
/** The value host: the editor in a popover anchored to the value segment, and
* BOTH routes end here. The operator popover used to draw the editor itself,
* so a handed-off panel sat a segment's width left of a second press. */
export interface FilterValuePopoverProps<V = unknown, O = unknown> {
rule: FilterRule<V>;
field: FilterField<V, O>;
operator: FilterOperator | undefined;
/** The element that opens it, WITH its own children: a chip segment must be
* a direct child of its `ButtonGroup` for the pill to fuse. */
trigger: React.ReactElement;
className?: string;
}
export function FilterValuePopover<V, O>({ rule, field, operator, trigger, className }: FilterValuePopoverProps<V, O>) {
const actions = useFilterActions<V, O>();
const focusStore = useFilterFocusStore();
const autoOpen = useFilterChipAutoOpen(rule.id) === 'value';
const [open, setOpen] = React.useState(false);
const locked = isFilterLocked(actions);
// The last step of the flow as well as the amend route; by now the condition
// menu has UNMOUNTED (see `FilterStepHandoff`). CONSUMED as it is honoured,
// or Escape closes the editor and this effect reopens it in the same frame.
// The `set` stays OUTSIDE the `locked` guard on purpose: a handoff nobody
// spends sits armed until some later chip spends it, and a chip that opened
// because a DIFFERENT chip was arrowed onto is worse than one that opened
// nothing.
React.useEffect(() => {
if (!autoOpen || open) return;
if (!locked) setOpen(true);
focusStore.set({ id: rule.id, segment: 'value', autoOpen: false });
}, [autoOpen, open, focusStore, rule.id, locked]);
// Nothing to open, but the trigger still renders so the value keeps its
// place, and it wears the bar's state: that hangs on the TRIGGER below,
// which this path never reaches, so the segment used to look live.
if (!operator || !actions.resolveEditor(field, operator)) {
return React.cloneElement(trigger as React.ReactElement<Record<string, unknown>>, {
disabled: actions.disabled,
...filterReadOnlyProps(actions),
});
}
return (
// REFUSES to open while locked rather than leaving it to the trigger: an
// `aria-disabled` control that still opens an editor is one that lied.
<Popover
open={open}
onOpenChange={(next) => {
if (next && locked) return;
setOpen(next);
}}
>
{/* The trigger IS the segment, never a wrapper. `ButtonGroup` fuses
DIRECT children only (`*:data-slot:rounded-r-none`,
`[&>[data-slot]~[data-slot]]:border-l-0`), so a nested one keeps its
own border and the chip reads as separate badges. */}
<PopoverTrigger render={trigger} disabled={actions.disabled} {...filterReadOnlyProps(actions)} />
<PopoverContent align="start" className={cn('w-auto p-0', className)}>
<FilterValueEditor<V, O>
rule={rule}
field={field}
operator={operator}
open={open}
onClose={() => {
setOpen(false);
focusStore.set({ id: rule.id, segment: 'value', autoOpen: false });
}}
/>
</PopoverContent>
</Popover>
);
}
/* A chip's ATTRIBUTE is fixed once the chip exists: no field popover here. A
new field invalidates the operator and the value, so "amending" threw both
away. The builder keeps its picker, where a row reads as a form. */
/** The condition menu, and the step after it. The list is the cascader run
* flat: the old hand-rolled one marked the keyboard HIGHLIGHT with
* `aria-selected` and had no Home, End or typeahead. It HANDS OFF to the
* value popover once its own panel has left the DOM; advancing in place
* anchored the editor to the CONDITION segment and doubled up in the row. */
export interface FilterOperatorPopoverProps<V = unknown, O = unknown> {
rule: FilterRule<V>;
field: FilterField<V, O>;
trigger: React.ReactElement;
className?: string;
}
export function FilterOperatorPopover<V, O>({ rule, field, trigger, className }: FilterOperatorPopoverProps<V, O>) {
const actions = useFilterActions<V, O>();
const focusStore = useFilterFocusStore();
const autoOpen = useFilterChipAutoOpen(rule.id) === 'operator';
const [open, setOpen] = React.useState(false);
const locked = isFilterLocked(actions);
/** Whether the close this panel is going through IS the step being handed
* on. A ref, so it survives the render that closes the popover. Every OPEN
* clears it, so an Escape or an outside press finds it already lowered and
* spends nothing; `release` leaves it standing because one twin asks again
* later: Radix reads it from `onCloseAutoFocus`, a macrotask after the
* unmount. Clearing it in `release` would break that twin only. */
const handoff = React.useRef(false);
const operators = actions.resolveOperators(field);
const operator = getFilterOperator(operators, rule.operator);
// Memoized because the array IS the menu's identity: the cascader rebuilds
// its index per `items` identity, so a fresh array rebuilds it per keystroke.
const items = React.useMemo(
() =>
visibleFilterOperators(operators).map((entry) => ({
value: entry.value,
label: entry.label,
})),
[operators],
);
// Opened by the root the moment the chip is created. CONSUMED here, or the
// handoff re-opens the menu on the frame Escape closes it. Consumed even
// while locked, for the reason on the value popover's copy.
React.useEffect(() => {
if (!autoOpen || open) return;
handoff.current = false;
if (!locked) setOpen(true);
focusStore.set({ id: rule.id, segment: 'operator', autoOpen: false });
}, [autoOpen, open, focusStore, rule.id, locked]);
const close = () => {
handoff.current = false;
setOpen(false);
focusStore.set({ id: rule.id, segment: 'operator', autoOpen: false });
};
/** The parked step, spent on the frame this panel stops existing. Memoized
* on nothing that changes, and load bearing: `FilterStepHandoff` uses this
* AS its cleanup, so a new identity mid-flow fires the step too early. */
const release = React.useCallback(() => {
if (!handoff.current) return;
focusStore.set({ id: rule.id, segment: 'value', autoOpen: true });
}, [focusStore, rule.id]);
// The chip going away takes its step with it: React destroys a deleted
// subtree top down, so this runs before the panel's own cleanup.
React.useEffect(
() => () => {
handoff.current = false;
},
[],
);
return (
<Popover
open={open}
onOpenChange={(next) => {
if (next && locked) return;
/* Escape, an outside press, a second press: none is the step being
taken, so none may spend it. RETIRED ON OPEN, not on close, and that
is a twin difference: in Radix an item choice dismisses through here
too, so retiring on close wiped the request before the unmount. */
if (next) handoff.current = false;
setOpen(next);
}}
>
<PopoverTrigger render={trigger} disabled={actions.disabled} {...filterReadOnlyProps(actions)} />
<PopoverContent
align="start"
/* Base UI restores focus to the trigger as this panel closes, which
lands on the condition segment AFTER the value editor has opened and
focused its input, so a keyboard user is dropped back a step and
cannot reach the value at all. Suppressed only while the handoff is
up; a function because Base UI resolves it at close time, which is
when the ref is accurate. Radix runs the same guard through
`onCloseAutoFocus`. */
finalFocus={() => !handoff.current}
/* `w-auto` with a FLOOR: a catalog sizes to its longest label, and a
boolean field's "is" and "is not" would read as a scrap of paper. */
className={cn('w-auto min-w-40 p-0', className)}
>
{/* INSIDE the panel deliberately: only a child of the content is
unmounted by the exit transition rather than by the close. */}
<FilterStepHandoff onRelease={release} />
<FilterMenu
items={items}
selected={rule.operator ? [rule.operator] : []}
onSelectionChange={(values) => {
const value = values[0];
/* Deselecting the committed operator is a step back rather than a
choice, so pressing the current row simply closes. */
if (value === undefined) {
close();
return;
}
const chosen = getFilterOperator(operators, value);
/* BUILDING versus AMENDING, the same fork the advanced row draws
at its field step. A rule reaches this menu with no operator
exactly once, while it is being added, and only then is the
value the step after this one. Re-picking the condition on a
rule that already has one is an edit of that one cell: it
commits and closes, and the user opens the value themselves. */
const building = !rule.operator;
actions.updateRule(rule.id, {
operator: value,
/* The value moves with the operator: "is" to "is any of" would
leave a bare string where every reader expects an array. */
value: coerceFilterValue(rule.value, getFilterOperator(operators, rule.operator), chosen) as V,
});
if (building && operatorTakesValue(chosen)) {
/* PARKED, not opened: `release` hands the row to its value
surface once this panel has unmounted. */
handoff.current = true;
setOpen(false);
return;
}
close();
}}
labels={actions.labels}
ariaLabel={field.label}
searchPlaceholder={actions.labels.searchOperators}
/* No visible search field: a CLOSED enum of six to ten labels, all
on screen. Still RENDERED, visually hidden, because it owns focus
and `aria-activedescendant`: arrows, Home, End and typeahead. */
searchable={false}
/* Taller than a value list on purpose: the operator set is CLOSED, so
all of it fits and the height buys the whole catalog. A value list
is open ended and would only push its own footer off the screen. */
maxHeight={320}
/* Deliberately unpinned: one selected operator in a short list, so
lifting it would lose the catalog's declared reading order. */
/>
</PopoverContent>
</Popover>
);
}
/** The keyboard path to a CROSS-GROUP move: Alt+Arrow reorders within the
* owning group only and Wrap creates a NEW group, so the drag layer's
* cross-group move had no keyboard parity. Numbered in document order. */
export function FilterMoveToMenuItems({ nodeId }: { nodeId: string }) {
const actions = useFilterActions();
// A menu ITEM takes the native word: both twins already make `disabled`
// roving-focusable and `aria-disabled`.
const reorderable = useFilterReorderable();
const locked = isFilterLocked(actions);
// Read at render time: the menu's content mounts when the menu opens, so
// this is the tree the user is looking at.
const query = actions.getQuery();
const found = findFilterNode(query, nodeId);
if (!found || !found.parent) return null;
const destinations: { id: string; label: string; size: number }[] = [];
if (found.parent.id !== query.id) {
destinations.push({
id: query.id,
label: actions.labels.moveToTopLevel,
size: query.rules.length,
});
}
let position = 0;
// `inside` suppresses the PUSH and not the walk, so the numbering stays
// document order rather than renumbering every group after this one. Counted
// before the exclusions for the same reason: the current parent is not
// offered but still holds its number, so the numbering is stable whichever
// row's menu is open.
const visit = (group: FilterGroupNode<unknown>, inside: boolean) => {
for (const child of group.rules) {
if (!isFilterGroup(child)) continue;
position += 1;
// Itself and everything under it: `moveFilterNodeTo` already refuses that
// move - it would detach the subtree and leave a cycle - so offering it
// would be a menu row that quietly does nothing.
const within = inside || child.id === nodeId;
if (!within && child.id !== found.parent!.id) {
destinations.push({
id: child.id,
label: actions.labels.moveToGroup(position),
size: child.rules.length,
});
}
visit(child, within);
}
};
visit(query, false);
if (destinations.length === 0) return null;
// The THIRD route into a move, gated on the same switch as the grip and
// Alt+Arrow: ungated, a builder that draws no handle still reordered here.
if (!reorderable) return null;
return (
<>
{destinations.map((destination) => (
<DropdownMenuItem key={destination.id} disabled={locked} onClick={() => actions.moveNodeTo(nodeId, destination.id, destination.size)}>
{/* A bend into the destination: movement, not duplication or nesting. */}
<CornerDownRightIcon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{destination.label}</span>
</DropdownMenuItem>
))}
</>
);
}
/** The per-rule actions, without the trigger: the chip's kebab and a builder
* row's kebab act on the same rule. `allowGrouping` is the CHROME's answer;
* "Convert to advanced filter" is the CONSUMER's, and hides itself there. */
export function FilterRuleMenuItems({
ruleId,
/** Offer "Wrap in condition group". Off for the chip row, which cannot draw
* a group; on in the builder, the only way to nest without dragging. */
allowGrouping = false,
}: {
ruleId: string;
allowGrouping?: boolean;
}) {
const actions = useFilterActions();
// Gated here as well as at the trigger, because this is EXPORTED: a consumer
// composing their own menu gets rows that say they are unavailable.
const locked = isFilterLocked(actions);
return (
/* Every row leads with an icon. `IconPlaceholder` because the source ships
under five icon sets; no size class, because each style already sizes an
unsized svg in a menu row; `aria-hidden`, the label IS the name. */
<>
<DropdownMenuItem disabled={locked} onClick={() => actions.duplicateNode(ruleId)}>
<CopyIcon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.duplicate}</span>
</DropdownMenuItem>
<DropdownMenuItem disabled={locked} onClick={() => actions.negateRule(ruleId)}>
{/* Two arrows swapping: negation flips to the declared inverse. */}
<ArrowLeftRightIcon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.negate}</span>
</DropdownMenuItem>
{allowGrouping ? (
<DropdownMenuItem disabled={locked} onClick={() => actions.wrapNodeInGroup(ruleId)}>
{/* Layers: braces read as grouping in only three of the five sets. */}
<LayersIcon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.wrapInGroup}</span>
</DropdownMenuItem>
) : null}
{allowGrouping ? <FilterMoveToMenuItems nodeId={ruleId} /> : null}
{/* OPTIONAL, and gated on both halves of "would this do anything": the
handler is the consumer's opt-in, and an already-advanced bar has
nothing to convert. NOT gated on `locked`: it changes no query, is
handed no mutator, and the shipped kebab will not open while locked. */}
{actions.convertToAdvanced && actions.variant !== 'advanced' ? (
<DropdownMenuItem onClick={() => actions.convertToAdvanced?.()}>
{/* Sliders: the one "advanced settings" glyph in all five sets. */}
<SlidersHorizontalIcon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.convertToAdvanced}</span>
</DropdownMenuItem>
) : null}
<DropdownMenuItem variant="destructive" disabled={locked} onClick={() => actions.removeNode(ruleId)}>
{/* No colour: the destructive variant already paints the row's svgs. */}
<Trash2Icon aria-hidden="true" />
<span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.remove}</span>
</DropdownMenuItem>
</>
);
}
export interface FilterChipProps<V = unknown> {
rule: FilterRule<V>;
index: number;
}
/** One filter, as a chip. Memoization means something here: the actions
* context is stable, the focus store is subscribed to a boolean and the query
* shares structure, so editing one filter of forty re-renders one chip. */
function FilterChipImpl<V, O>({ rule, index }: FilterChipProps<V>) {
const actions = useFilterActions<V, O>();
const render = useFilterRender<V, O>();
const focusStore = useFilterFocusStore();
const focused = useFilterChipFocused(rule.id);
const noFocus = useFilterFocusEmpty();
const locked = isFilterLocked(actions);
// THE CHIP'S HEIGHT, by way of the one button in it that has one:
// `ButtonGroup` is `items-stretch` and no style gives a text segment a
// height, so the kebab's rung is the pill's. The RADIUS survives because
// every style whose `icon-sm` rounds differently re-pins it in a group.
const sizes = filterControlSizes(actions);
// The kebab is CONTROLLED so it can refuse to open: every mutating row
// behind it is gated. That puts "Convert to advanced filter" out of reach
// while locked; a consumer-composed menu still draws it.
const [menuOpen, setMenuOpen] = React.useState(false);
// Exactly one chip is in the tab order at a time. Before anything has been
// focused that is the first chip, so Tab reaches the row in one press.
const isTabStop = focused || (noFocus && index === 0);
const field = getFilterField(actions.index, rule.path);
const operators = field ? actions.resolveOperators(field) : [];
const operator = getFilterOperator(operators, rule.operator);
const { pathText, pathLabel, pathCollapsed, operatorLabel, valueLabel, valueText, valueFullText, valueEmpty } = useFilterRuleDisplay<V, O>(
rule,
field,
operator,
);
if (!field) {
// A rule pointing at a field the schema no longer has. Dropping it loses a
// saved view's data; rendering nothing leaves an invisible condition still
// filtering. It carries the SAME roving wiring as a real chip: `data-slot`
// alone joined the arrow-key query with no `tabIndex` to land on.
return (
<ButtonGroup
data-slot="filter-chip"
data-unknown=""
role="group"
aria-label={actions.labels.filterLabel(rule.path.join(actions.labels.pathSeparator))}
data-focused={focused || undefined}
data-rule-id={rule.id}
data-index={index}
tabIndex={isTabStop ? 0 : -1}
onFocusCapture={() => {
if (!focused) focusStore.set({ id: rule.id, segment: null, autoOpen: false });
}}
>
<ButtonGroupText className="bg-background dark:bg-input/30 text-muted-foreground">
{rule.path.join(actions.labels.pathSeparator)}
</ButtonGroupText>
<Button
variant="outline"
size={sizes.icon}
className="bg-background dark:bg-input/30"
aria-label={actions.labels.remove}
/* It had no gate at all, so the one chip whose whole purpose is to be
removed could be removed from a bar that refuses every other edit. */
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
onClick={() => actions.removeNode(rule.id)}
>
<XIcon />
</Button>
</ButtonGroup>
);
}
if (render.renderChip) return <>{render.renderChip(rule)}</>;
const focusSegment = (segment: ChipSegment) => focusStore.set({ id: rule.id, segment, autoOpen: false });
// A rule with no condition yet, KEPT rather than removed (see
// `isFilterRuleComplete`), so it has to read as unfinished. Through WORDS:
// the dashed outline it replaces degraded to an underline under sera.
const incomplete = !rule.operator;
// The same test the value segment renders under, so the name matches the
// chip: `valueText` alone appended a placeholder to valueless conditions.
const hasValue = Boolean(rule.operator) && operatorTakesValue(operator);
// The value's spoken form in the chip's NAME: a name is not a prompt, so
// "Description contains enter text..." becomes "no value".
const valueName = valueEmpty && !field.valueText ? actions.labels.noValue : valueText;
return (
<ButtonGroup
data-slot="filter-chip"
role="group"
aria-label={actions.labels.filterLabel(
`${pathText} ${operatorLabel}${hasValue ? ` ${valueName}` : ''}`.trim() + (incomplete ? `, ${actions.labels.incomplete}` : ''),
)}
data-focused={focused || undefined}
data-incomplete={incomplete || undefined}
data-rule-id={rule.id}
tabIndex={isTabStop ? 0 : -1}
className={cn(
/* Sera is an underline style, so the boxed segments are normalised to
its bottom-border-only look or the chip reads as a mix of both. */
'',
)}
onFocusCapture={() => {
if (!focused) focusStore.set({ id: rule.id, segment: null, autoOpen: false });
}}
data-index={index}
>
{/* DISPLAY ONLY: a div, not a button, not a tab stop, no popover. The
attribute is fixed for the life of the chip. */}
<ButtonGroupText
/* Dropped while the path is collapsed: the ellipsis inside carries the
same sentence as a tooltip, and the two would stack. */
title={pathCollapsed ? undefined : pathText}
className="bg-background dark:bg-input/30 cursor-default gap-1.5"
>
{field.icon}
{/* Zero gap INSIDE the path, so the separator's own margin is the only
air around a chevron; `gap-1.5` used to stack 6px a side on it. */}
<span className="flex items-center">{pathLabel}</span>
</ButtonGroupText>
<FilterOperatorPopover
rule={rule}
field={field}
trigger={
<ButtonGroupText
render={<button type="button" />}
className={cn(
'hover:bg-accent bg-background dark:bg-input/30 cursor-default',
/* The operator is connective tissue between the field and the
value, so it reads quieter than either - unless it is still
the prompt "Select condition", the one thing to act on. */
incomplete ? 'text-foreground' : 'text-muted-foreground',
)}
onPointerDown={() => focusSegment('operator')}
>
{operatorLabel}
</ButtonGroupText>
}
/>
{/* No condition, no value: `getFilterArity(undefined)` defaults to "one",
so testing the operator alone renders a stray value segment. */}
{hasValue ? (
<FilterValuePopover
rule={rule}
field={field}
operator={operator}
trigger={
<ButtonGroupText
render={<button type="button" />}
/* Named explicitly rather than by its contents: avatars or a
"+2" badge, and "plus two" says nothing about two people. It
grows to the whole list when the editor cannot be opened,
since locked it must carry what a press no longer reveals. */
aria-label={locked ? valueFullText : valueText}
/* The pointer's route to the same thing, and only when there is
more to say than the segment already says. */
title={valueFullText === valueText ? undefined : valueFullText}
className={cn('hover:bg-accent bg-background dark:bg-input/30 cursor-default', valueEmpty && 'text-muted-foreground')}
onPointerDown={() => focusSegment('value')}
>
{valueLabel}
</ButtonGroupText>
}
/>
) : null}
<DropdownMenu
open={menuOpen}
onOpenChange={(next) => {
if (next && locked) return;
setMenuOpen(next);
}}
>
<DropdownMenuTrigger
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
render={
<Button
variant="outline"
size={sizes.icon}
/* The same surface the three text segments force. Styles whose
outline button is transparent in dark (sera, luma, rhea) left
the kebab as a notch in an otherwise filled pill. */
className="bg-background dark:bg-input/30"
aria-label={actions.labels.chipMenu(field.label)}
onPointerDown={() => focusSegment('menu')}
/>
}
>
<EllipsisVerticalIcon />
</DropdownMenuTrigger>
{/* The SAME sizing the builder's menus use, from one constant: a menu
that cuts "Convert to group" in one chrome is one defect twice. */}
<DropdownMenuContent align="end" className={cn(FILTER_MENU_CLASS, actions.menuClassName)}>
<FilterRuleMenuItems ruleId={rule.id} />
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
);
}
export const FilterChip = React.memo(FilterChipImpl) as typeof FilterChipImpl;components/ui/filters/filters-context.tsx
import * as React from 'react';
import type { FilterDraftAction } from '@/registry/vcare/ui/filters/filters-draft';
import type { FilterPathCollapse } from '@/registry/vcare/ui/filters/filters-lib';
import type {
FilterCombinator,
FilterDraft,
FilterDraftStep,
FilterEditor,
FilterEditorRegistry,
FilterEmptyStateContext,
FilterField,
FilterIndex,
FilterLabels,
FilterOperator,
FilterOption,
FilterQuery,
FilterRule,
FilterValueDisplayContext,
FilterValueType,
} from '@/registry/vcare/ui/filters/filters-types';
/** Four publishing channels, not one, so a chip never re-renders at the rate
* of the fastest: `actions` republishes on a schema, labels or config change,
* `state` on every query edit and keystroke, `render` on a `renderValue` /
* `renderChip` identity change, `focus` on every arrow key. The reorder flag
* and the row-state store further down are contexts too, but not channels the
* query is published through. */
/* -------------------------------------------------------------------------- */
/* Actions */
/* -------------------------------------------------------------------------- */
/** Stable for the life of the component, bar a config change. Every mutator
* reads a latest-props ref rather than closing over the state it needs, so a
* keystroke rebuilds no handler and no memoized chip re-renders. The two lock
* flags are published rather than kept only in that ref: a refusal that lives
* in a ref arrives one commit late. The two resolvers are the deliberate
* exception: they are read DURING render, so they memoize on the values they
* read instead of going through the ref. Every mutator is also the MUTATION
* BOUNDARY - `disabled` and `readOnly` are enforced here, not at the call
* sites that draw the buttons, so a route added next month is refused by
* construction rather than by remembering. See `isFilterLocked`. */
export interface FilterActionsContextValue<V = unknown, O = unknown> {
/** Normalized schema. Also on the state context, from the same memo. */
index: FilterIndex<V, O>;
labels: FilterLabels;
operatorCatalog: Record<FilterValueType, FilterOperator[]>;
editors: FilterEditorRegistry;
size: 'sm' | 'default';
/** The bar is off: nothing operable, and the controls leave the tab order. */
disabled: boolean;
/** Readable and navigable, but not changeable. See `isFilterLocked`. */
readOnly: boolean;
/** Which chrome is drawing, so a chip kebab can hide its convert row. */
variant: 'basic' | 'advanced';
/** Consumer classes for the menus and the field picker, merged AFTER the
* primitive's own defaults so a consumer `w-*` wins through tailwind-merge
* rather than on source order. On the context: four chromes mount the same
* menu, and a per-chrome prop is set in four places and missed in a fifth. */
menuClassName: string | undefined;
fieldPickerClassName: string | undefined;
/** Turns on the chip kebab's "Convert to advanced filter" row: present means
* offered. A callback with no boolean beside it, since only the consumer
* can switch chromes. Changes no query, so it skips the mutation boundary,
* which is safe only because it is handed no setter: a consumer's handler
* has no route to the query at all. */
convertToAdvanced: (() => void) | undefined;
/** Path shortening, published so BOTH chromes render the same path. */
pathCollapse: FilterPathCollapse;
maxPathSegments: number;
/** Operators for a field, memoized on the catalog and the schema. */
resolveOperators: (field: FilterField<V, O>) => FilterOperator[];
resolveEditor: (field: FilterField<V, O>, operator: FilterOperator | undefined) => FilterEditor<V, O> | undefined;
/** Value-to-label store shared by every `useFilterOptions` under the root. */
resolution: FilterResolutionStore;
/** Appends a rule. Defaults to the ROOT group. The parent is a parameter
* rather than always the root because a nested group's add button is the
* keyboard path into that group, and routing it through the root then
* moving it would be two edits and two announcements for one action. */
addRule: (rule: FilterRule<V>, parentId?: string) => void;
/** Appends an empty group and returns its id, so the caller can focus it.
* Returns an EMPTY STRING when the bar is disabled or read only, the one
* mutator that has to report its refusal: focusing a group that was never
* created strands the tab stop. `""` rather than `string | null` keeps the
* callers that already test the id honest without widening a published
* signature. */
addGroup: (parentId?: string, combinator?: FilterCombinator) => string;
updateRule: (id: string, updates: Partial<Omit<FilterRule<V>, 'id' | 'type'>>) => void;
/** Removes a rule OR a group, and prunes the groups that empties. Node-level
* rather than rule-level because a chip only ever removes a rule, while a
* builder row's trash and a group header's trash are the same button on two
* kinds of node. */
removeNode: (id: string) => void;
duplicateNode: (id: string) => void;
negateRule: (id: string) => void;
/** Reorders within the node's own parent. Out of range moves are no-ops. */
moveNode: (id: string, delta: number) => void;
/** Moves a node into another group, at an index. The drag-and-drop half. */
moveNodeTo: (id: string, parentId: string, index: number) => void;
/** Copies a node into another group, at an index. The Alt-drag half, apart
* from `duplicateNode` (which copies BESIDE, with no destination): the two
* composed would emit two queries for one gesture, and a controlled
* consumer would persist a tree the user never asked for. */
copyNodeTo: (id: string, parentId: string, index: number) => void;
/** Nests one node in a new group. The keyboard half of the same idea. */
wrapNodeInGroup: (id: string, combinator?: FilterCombinator) => void;
/** Dissolves a group into its parent. The inverse of `wrapNodeInGroup`. */
unwrapGroup: (groupId: string) => void;
setCombinator: (groupId: string, combinator: FilterCombinator) => void;
toggleCombinator: (groupId: string) => void;
clearQuery: () => void;
openCreate: () => void;
openAmend: (id: string, step: FilterDraftStep) => void;
closeDraft: () => void;
dispatchDraft: (action: FilterDraftAction<V>) => void;
/** Writes the bar's live region, for a change no visible surface reports: an
* editor's popover is the one place something destructive happens to rows
* the user is not on, with focus, name and text unchanged afterwards. Not a
* query write, so it skips `emit` and asks the lock nothing. */
announce: (message: string) => void;
/** Getters for event handlers, so a handler never closes over stale state. */
getQuery: () => FilterQuery<V>;
getDraft: () => FilterDraft<V> | null;
/** Fresh id from the SSR-safe factory. */
nextId: () => string;
}
/* -------------------------------------------------------------------------- */
/* The mutation lock */
/* -------------------------------------------------------------------------- */
/** `disabled` and `readOnly` are NOT two words for one state. `disabled` is
* the native attribute: not operable, out of the tab order. `readOnly` blocks
* MUTATION and preserves NAVIGATION, because a read-only bar exists so a
* keyboard or screen reader user can walk the chips and find out what the
* view is filtered by. Collapsing the two once put the native attribute on
* all thirteen advanced-builder cell controls while the roving tab stop sat
* on a disabled element, so not one row could be reached from the keyboard.
*
* So a mutating control keeps its tab stop and wears `aria-disabled` plus
* `data-readonly` (`filterReadOnlyProps`), this repo's convention for
* "present, focusable, not operable". `aria-readonly` is never used, being
* disallowed on the button, group and toolbar roles, so the BAR says it in
* prose through `labels.readOnly`. The refusal itself is enforced once, where
* all fourteen query writes pass through `emit` in `filters.tsx`. */
export function isFilterLocked(state: { disabled: boolean; readOnly: boolean }): boolean {
return state.disabled || state.readOnly;
}
/** What a MUTATING control wears while the bar is read only. `null` when the
* bar is disabled, because the native attribute already says it. A
* conditional spread, not explicit `undefined`s: `aria-disabled="false"` on
* an enabled control is noise, and `data-readonly` is a presence hook. */
export function filterReadOnlyProps(state: { disabled: boolean; readOnly: boolean }) {
if (state.disabled || !state.readOnly) return null;
return { 'aria-disabled': true, 'data-readonly': '' } as const;
}
/* -------------------------------------------------------------------------- */
/* The size ladder */
/* -------------------------------------------------------------------------- */
/** The two shadcn button sizes one filters size resolves to. Two rungs because
* shadcn ships a separate ladder for labelled and for icon-only buttons, and
* pairing them keeps a row's kebab as tall as the cell beside it. */
export interface FilterControlSizes {
/** Labelled buttons: the row cells, both triggers, the panel footer. */
button: 'sm' | 'default';
/** Icon-only buttons, and also the CHIP's height: a chip is an
* `items-stretch` `ButtonGroup` and no style gives its text segment a
* height, so the segments stretch to the kebab, the one child that has one.
* Sizing the kebab sizes the pill. */
icon: 'icon-sm' | 'icon';
}
/** ONE ladder, keyed off `size`, for every control the chrome renders, because
* the alternative already happened: five advanced-builder cells took
* `actions.size` while seven sites hardcoded `icon-sm` and three `sm`, giving
* one row three heights. Nothing here is a pixel - each value is a shadcn
* size NAME that `Button` resolves per style, since the control-height ladder
* is per style (nova 7/8, sera 9/10, mira 6/7, and so on), and the glyph size
* rides the same name, so pinning an icon size in here would fight the style
* rather than match it. Two rungs only: `lg` would make the bar taller than
* the style's own default control height (want taller, pick a taller STYLE),
* and `icon-xs` is a 20-24px square in most styles, too small for a chip's
* own label to clear. */
const FILTER_CONTROL_SIZES: Record<'sm' | 'default', FilterControlSizes> = {
sm: { button: 'sm', icon: 'icon-sm' },
default: { button: 'default', icon: 'icon' },
};
/** The pair for a bar's size, off anything with a `size`, so a
* consumer-composed chrome uses the same ladder as the shipped one. The
* fallback is for JavaScript callers: a `"lg"` TypeScript would have rejected
* must still draw buttons rather than throw on `.button`. */
export function filterControlSizes(state: { size: 'sm' | 'default' }): FilterControlSizes {
return FILTER_CONTROL_SIZES[state.size] ?? FILTER_CONTROL_SIZES.default;
}
const FilterActionsContext = React.createContext<FilterActionsContextValue | null>(null);
export function useFilterActions<V = unknown, O = unknown>(): FilterActionsContextValue<V, O> {
const context = React.useContext(FilterActionsContext);
if (!context) {
throw new Error('useFilterActions must be used inside <Filters>');
}
return context as unknown as FilterActionsContextValue<V, O>;
}
/* -------------------------------------------------------------------------- */
/* State */
/* -------------------------------------------------------------------------- */
/** Volatile by construction: typing one character into a value editor
* republishes it. Subscribe from the bar and the panel, never from a chip. */
export interface FilterStateContextValue<V = unknown> {
query: FilterQuery<V>;
draft: FilterDraft<V> | null;
ruleCount: number;
/** Live region text. Empty except immediately after an announced change. */
announcement: string;
/** How many announcements have been made, so a REPEATED one is still heard:
* `aria-live` reports a DOM mutation and React writes nothing when the
* string is unchanged, so the chrome keys the region's contents on this. A
* counter rather than a timestamp: it is compared for identity, never read
* as a value, and is stable across a rerender that a clock is not. */
announcementSeq: number;
}
const FilterStateContext = React.createContext<FilterStateContextValue | null>(null);
export function useFilterState<V = unknown>(): FilterStateContextValue<V> {
const context = React.useContext(FilterStateContext);
if (!context) {
throw new Error('useFilterState must be used inside <Filters>');
}
return context as unknown as FilterStateContextValue<V>;
}
/* -------------------------------------------------------------------------- */
/* Render */
/* -------------------------------------------------------------------------- */
/** Consumer render overrides, on their own channel. They must be
* always-current closures yet change identity on every parent render when
* written inline, so isolating them re-renders only what calls them. */
export interface FilterRenderContextValue<V = unknown, O = unknown> {
renderValue?: (context: FilterValueDisplayContext<V, O>) => React.ReactNode;
renderChip?: (rule: FilterRule<V>) => React.ReactNode;
renderEmpty?: (context: FilterEmptyStateContext) => React.ReactNode;
}
const FilterRenderContext = React.createContext<FilterRenderContextValue>({});
export function useFilterRender<V = unknown, O = unknown>(): FilterRenderContextValue<V, O> {
return React.useContext(FilterRenderContext) as FilterRenderContextValue<V, O>;
}
/* -------------------------------------------------------------------------- */
/* Focus store */
/* -------------------------------------------------------------------------- */
/** Which chip currently owns the row's single tab stop. */
export interface FilterFocus {
id: string | null;
/** Which cell inside that row, for restoring focus after an edit. A chip
* draws only `field`, `operator`, `value` and `menu`; the rest are advanced
* builder cells, where a GROUP header is a row too (its `field` is the
* combinator sentence). One union, because the chromes share the store. */
segment: 'combinator' | 'field' | 'operator' | 'value' | 'add' | 'menu' | 'ungroup' | 'remove' | 'drag' | null;
/** Open that segment's popover, not merely focus it. Picking a field commits
* the rule straight away and the chip appears with no condition yet, so the
* operator menu has to open ON THE CHIP without a second click. */
autoOpen: boolean;
}
/** An external store, deliberately NOT React state. A roving tabindex
* republishes on every arrow key, and `setState` would re-render the whole
* bar to move one outline. The SELECTOR hooks below each narrow to one value,
* so arrowing across forty chips re-renders two components. `useFilterFocus`
* is the exception: it returns the whole snapshot. */
export interface FilterFocusStore {
subscribe: (onStoreChange: () => void) => () => void;
getSnapshot: () => FilterFocus;
/** No-ops when nothing changed. */
set: (next: FilterFocus) => void;
}
const NO_FOCUS: FilterFocus = { id: null, segment: null, autoOpen: false };
export function createFilterFocusStore(): FilterFocusStore {
let snapshot: FilterFocus = NO_FOCUS;
const listeners = new Set<() => void>();
return {
subscribe(onStoreChange) {
listeners.add(onStoreChange);
return () => {
listeners.delete(onStoreChange);
};
},
// The SAME object until something actually changes, which is what
// `useSyncExternalStore` requires to avoid an infinite render loop.
getSnapshot() {
return snapshot;
},
set(next) {
if (next.id === snapshot.id && next.segment === snapshot.segment && next.autoOpen === snapshot.autoOpen) {
return;
}
snapshot = next;
for (const listener of listeners) listener();
},
};
}
/** A shared, permanently empty store, so the hook degrades to "nothing
* focused" outside a `Filters`. Nothing ever writes to it: each root creates
* and writes its own. */
const FALLBACK_FOCUS_STORE = createFilterFocusStore();
const FilterFocusContext = React.createContext<FilterFocusStore>(FALLBACK_FOCUS_STORE);
/* -------------------------------------------------------------------------- */
/* Reordering */
/* -------------------------------------------------------------------------- */
/** Whether rows may be reordered at all, published once for the subtree. Two
* files have to agree about it: the builder gates the grip and Alt+Arrow,
* while the row and group menus commit the same mutator by a third route, so
* gating only the builder left it off for a pointer and on from a menu. */
const FilterReorderContext = React.createContext(false);
export const FilterReorderProvider = FilterReorderContext.Provider;
export function useFilterReorderable(): boolean {
return React.useContext(FilterReorderContext);
}
/* -------------------------------------------------------------------------- */
/* Touched */
/* -------------------------------------------------------------------------- */
/** Which rules the user has actually edited the VALUE of, which decides WHEN
* an error may appear: "Add filter" mints a row with no value, so flagging
* every invalid row turns the builder red before the user did anything wrong.
* An issue is still COLLECTED for every rule - the footer count,
* `onQueryChange` and tree validity do not change - and only DRAWN once the
* user has committed a value. An external store for the focus store's reason,
* keyed by rule id and never pruned: a stale id costs one Set entry, and
* reconciling against the query on every commit is hot-path work. */
export interface FilterRowStateStore {
subscribe: (listener: () => void) => () => void;
/** Bumped on every write. What a memo depends on, since the Sets are mutable. */
version: () => number;
/** Whether this rule has had a value committed to it by the user. */
has: (id: string) => boolean;
mark: (id: string) => void;
/** Starts this rule over. Changing a rule's ATTRIBUTE resets its operator
* and its value, so it has to reset this too, or the row stays warned about
* a value that no longer exists on a field the user navigated away from. */
unmark: (id: string) => void;
/** Whether this rule is still being CREATED: minted by Add filter and not
* yet given an attribute. The row enters the query with a guessed field to
* keep the tree valid, so while pending the builder draws only that cell. */
isPending: (id: string) => boolean;
markPending: (id: string) => void;
/** The attribute was chosen. The rest of the row appears. */
resolvePending: (id: string) => void;
/** Forgets everything. The bar's own Clear all, and a whole-tree replace. */
reset: () => void;
}
export function createFilterRowStateStore(): FilterRowStateStore {
const touched = new Set<string>();
const pending = new Set<string>();
const listeners = new Set<() => void>();
let version = 0;
const notify = () => {
version += 1;
for (const listener of listeners) listener();
};
return {
subscribe: (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
version: () => version,
has: (id) => touched.has(id),
mark: (id) => {
if (touched.has(id)) return;
touched.add(id);
notify();
},
unmark: (id) => {
if (!touched.delete(id)) return;
notify();
},
isPending: (id) => pending.has(id),
markPending: (id) => {
if (pending.has(id)) return;
pending.add(id);
notify();
},
resolvePending: (id) => {
if (!pending.delete(id)) return;
notify();
},
reset: () => {
if (touched.size === 0 && pending.size === 0) return;
touched.clear();
pending.clear();
notify();
},
};
}
const FALLBACK_ROW_STATE_STORE = createFilterRowStateStore();
const FilterRowStateContext = React.createContext<FilterRowStateStore>(FALLBACK_ROW_STATE_STORE);
export const FilterRowStateProvider = FilterRowStateContext.Provider;
/** The store itself, for handlers that write without subscribing. */
export function useFilterRowStateStore(): FilterRowStateStore {
return React.useContext(FilterRowStateContext);
}
/** Whether THIS rule is still waiting for its attribute. */
export function useFilterRowPending(id: string): boolean {
const store = React.useContext(FilterRowStateContext);
return React.useSyncExternalStore(
store.subscribe,
() => store.isPending(id),
() => false,
);
}
/** Whether THIS rule may show an error yet. */
export function useFilterTouched(id: string): boolean {
const store = React.useContext(FilterRowStateContext);
return React.useSyncExternalStore(
store.subscribe,
() => store.has(id),
() => false,
);
}
/** The whole focus snapshot, so the caller re-renders on EVERY move anywhere
* in the row. A chip wants `useFilterChipFocused` or `useFilterSegmentFocus`
* below instead. */
export function useFilterFocus(): FilterFocus {
const store = React.useContext(FilterFocusContext);
return React.useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
}
/** The store itself, for event handlers that write without subscribing. */
export function useFilterFocusStore(): FilterFocusStore {
return React.useContext(FilterFocusContext);
}
/** The segment of THIS chip that should open itself, or null. */
export function useFilterChipAutoOpen(id: string): FilterFocus['segment'] | null {
const store = React.useContext(FilterFocusContext);
return React.useSyncExternalStore(
store.subscribe,
() => {
const snapshot = store.getSnapshot();
return snapshot.autoOpen && snapshot.id === id ? snapshot.segment : null;
},
() => null,
);
}
/** Whether the row holds no focus, so the first chip keeps the tab stop. */
export function useFilterFocusEmpty(): boolean {
const store = React.useContext(FilterFocusContext);
return React.useSyncExternalStore(
store.subscribe,
() => store.getSnapshot().id === null,
() => true,
);
}
/** Whether THIS chip owns the row's tab stop. */
export function useFilterChipFocused(id: string): boolean {
const store = React.useContext(FilterFocusContext);
return React.useSyncExternalStore(
store.subscribe,
() => store.getSnapshot().id === id,
() => false,
);
}
/** Which segment of THIS rule owns the tab stop, or null when another rule
* does. A chip needs one boolean, but an advanced row is a grid ROW whose tab
* stop is a (row, column) pair, and the column has to come from this store
* too or the chromes disagree about where focus is after an edit. */
export function useFilterSegmentFocus(id: string): FilterFocus['segment'] {
const store = React.useContext(FilterFocusContext);
return React.useSyncExternalStore(
store.subscribe,
() => {
const snapshot = store.getSnapshot();
return snapshot.id === id ? snapshot.segment : null;
},
() => null,
);
}
/* -------------------------------------------------------------------------- */
/* Resolution store */
/* -------------------------------------------------------------------------- */
/** The instance-wide value-to-label store. `useFilterOptions` caches per HOOK
* INSTANCE, and a chip's display and its editor are two instances, so a
* `loadOptions`-only field rendered its raw id the moment the menu closed.
* Every instance under one root writes here, and `resolveValues` results land
* here too. External rather than React state because labels arrive from
* effects and promises at their own pace, and the version bumps only when a
* NEW label lands, so a subscriber re-renders once per page of results. */
export interface FilterResolutionStore {
subscribe: (onStoreChange: () => void) => () => void;
getVersion: () => number;
/** The option behind a stored value, or undefined while unresolved. */
get: (fieldKey: string, value: string) => FilterOption | undefined;
/** Records options under a field key. New values bump the version. */
set: (fieldKey: string, options: readonly FilterOption[]) => void;
/** Marks values as resolving and returns the subset nobody has claimed yet,
* so two chips holding the same id issue ONE request. Claims are permanent
* for values a fulfilled resolve did not return, which stops an id the
* server does not know from being re-asked forever. */
claim: (fieldKey: string, values: readonly string[]) => string[];
/** Releases claims after a FAILED resolve, so a later mount may retry. */
release: (fieldKey: string, values: readonly string[]) => void;
}
export function createFilterResolutionStore(): FilterResolutionStore {
const resolved = new Map<string, Map<string, FilterOption>>();
const claimed = new Map<string, Set<string>>();
const listeners = new Set<() => void>();
let version = 0;
const bucket = (fieldKey: string) => {
let map = resolved.get(fieldKey);
if (!map) {
map = new Map();
resolved.set(fieldKey, map);
}
return map;
};
return {
subscribe(onStoreChange) {
listeners.add(onStoreChange);
return () => {
listeners.delete(onStoreChange);
};
},
getVersion() {
return version;
},
get(fieldKey, value) {
return resolved.get(fieldKey)?.get(value);
},
set(fieldKey, options) {
const map = bucket(fieldKey);
let landed = false;
for (const option of options) {
if (!map.has(option.value)) landed = true;
map.set(option.value, option);
}
if (!landed) return;
version += 1;
for (const listener of listeners) listener();
},
claim(fieldKey, values) {
let set = claimed.get(fieldKey);
if (!set) {
set = new Set();
claimed.set(fieldKey, set);
}
const map = resolved.get(fieldKey);
const fresh: string[] = [];
for (const value of values) {
if (set.has(value) || map?.has(value)) continue;
set.add(value);
fresh.push(value);
}
return fresh;
},
release(fieldKey, values) {
const set = claimed.get(fieldKey);
if (!set) return;
for (const value of values) set.delete(value);
},
};
}
export { FilterActionsContext, FilterFocusContext, FilterRenderContext, FilterStateContext };components/ui/filters/filters-date.tsx
import { addDays, addMonths, addWeeks, addYears, format, isValid, parse, startOfDay } from 'date-fns';
/**
* A date filter value. NOT a `Date`: a filter gets persisted (saved views,
* shared URLs), and a resolved `Date` would freeze "created today" into one
* fixed day. An absolute pick still stores one day, because "on 14 August"
* does mean that day.
*/
export interface FilterDateValue {
/** An absolute day, `yyyy-MM-dd`. Mutually exclusive with `relative`. */
date?: string;
/** A token re-resolved on every read. */
relative?: FilterRelativeDate;
/** Optional time of day, `HH:mm`. */
time?: string;
}
/** A calendar offset from now, resolved at read time. */
export interface FilterRelativeDate {
unit: 'day' | 'week' | 'month' | 'year';
offset: number;
}
export const FILTER_DATE_FORMAT = 'yyyy-MM-dd';
export const RELATIVE_TODAY: FilterRelativeDate = { unit: 'day', offset: 0 };
export const RELATIVE_TOMORROW: FilterRelativeDate = { unit: 'day', offset: 1 };
export const RELATIVE_YESTERDAY: FilterRelativeDate = {
unit: 'day',
offset: -1,
};
export const RELATIVE_NEXT_WEEK: FilterRelativeDate = {
unit: 'week',
offset: 1,
};
export function applyFilterRelative(relative: FilterRelativeDate, now: Date): Date {
const base = startOfDay(now);
if (relative.unit === 'day') return addDays(base, relative.offset);
if (relative.unit === 'week') return addWeeks(base, relative.offset);
if (relative.unit === 'month') return addMonths(base, relative.offset);
return addYears(base, relative.offset);
}
export function resolveFilterDate(value: FilterDateValue | undefined, now: Date = new Date()): Date | null {
if (!value) return null;
if (value.relative) return applyFilterRelative(value.relative, now);
if (value.date) {
const parsed = parse(value.date, FILTER_DATE_FORMAT, now);
return isValid(parsed) ? parsed : null;
}
return null;
}
export function toFilterDateValue(date: Date, time?: string): FilterDateValue {
const value: FilterDateValue = { date: format(date, FILTER_DATE_FORMAT) };
if (time) value.time = time;
return value;
}
// ----- natural language input -----
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
/**
* Typed formats, most specific first. `date-selector.tsx` overlaps on a few
* of these, but its parser is a callback inside the component returning a
* `DateSelectorValue`, so there is nothing importable.
*/
const EXPLICIT_FORMATS = [
'yyyy-MM-dd',
'MM/dd/yyyy',
'M/d/yyyy',
'dd/MM/yyyy',
'MMMM d, yyyy',
'MMM d, yyyy',
'MMMM d',
'MMM d',
'd MMMM yyyy',
'd MMM yyyy',
];
/**
* Parses a typed phrase, or null when nothing matches. Relative phrasing gives
* a RELATIVE value and an explicit date an ABSOLUTE one; flattening the two is
* what freezes a saved view.
*/
export function parseFilterDate(text: string, now: Date = new Date()): FilterDateValue | null {
const input = text.trim().toLowerCase().replace(/\s+/g, ' ');
if (!input) return null;
if (input === 'today' || input === 'now') return { relative: RELATIVE_TODAY };
if (input === 'tomorrow') return { relative: RELATIVE_TOMORROW };
if (input === 'yesterday') return { relative: RELATIVE_YESTERDAY };
const nextLast = input.match(/^(next|last|this) (day|week|month|year)$/);
if (nextLast) {
const direction = nextLast[1] === 'next' ? 1 : nextLast[1] === 'last' ? -1 : 0;
return {
relative: {
unit: nextLast[2] as FilterRelativeDate['unit'],
offset: direction,
},
};
}
// "in 3 days" / "3 days ago" / "in 2 weeks"
const counted = input.match(/^(?:in )?(\d+) (day|week|month|year)s?(?: ago)?$/);
if (counted) {
const magnitude = Number.parseInt(counted[1], 10);
const past = input.endsWith('ago');
return {
relative: {
unit: counted[2] as FilterRelativeDate['unit'],
offset: past ? -magnitude : magnitude,
},
};
}
// "next tuesday" / "last friday" / bare "tuesday"
const weekday = input.match(/^(?:(next|last|this) )?([a-z]+)$/);
if (weekday) {
const index = WEEKDAYS.indexOf(weekday[2]);
if (index !== -1) {
const today = startOfDay(now);
const current = today.getDay();
let delta = index - current;
const qualifier = weekday[1];
if (qualifier === 'last') {
// Always strictly in the past.
if (delta >= 0) delta -= 7;
} else {
// "next"/"this" and a bare weekday all mean the NEXT one, not today.
if (delta <= 0) delta += 7;
}
return { relative: { unit: 'day', offset: delta } };
}
}
for (const pattern of EXPLICIT_FORMATS) {
const parsed = parse(input, pattern, now);
if (isValid(parsed)) {
// "Aug 14" has no year, so it takes the reference year.
return toFilterDateValue(parsed);
}
}
return null;
}
/**
* Human wording for a value. Relative values render as their phrase, not the
* resolved day, so a chip reading "is today" does not go stale tomorrow.
*/
export function formatFilterDate(value: FilterDateValue | undefined, now: Date = new Date(), pattern = 'MMM d, yyyy'): string {
if (!value) return '';
if (value.relative) {
const { unit, offset } = value.relative;
if (unit === 'day' && offset === 0) return 'today';
if (unit === 'day' && offset === 1) return 'tomorrow';
if (unit === 'day' && offset === -1) return 'yesterday';
const plural = Math.abs(offset) === 1 ? unit : `${unit}s`;
if (offset > 0) return `in ${offset} ${plural}`;
if (offset < 0) return `${Math.abs(offset)} ${plural} ago`;
return `this ${unit}`;
}
const resolved = resolveFilterDate(value, now);
if (!resolved) return '';
const day = format(resolved, pattern);
return value.time ? `${day} ${value.time}` : day;
}
export function isFilterTime(time: string): boolean {
return /^([01]\d|2[0-3]):[0-5]\d$/.test(time);
}components/ui/filters/filters-dnd.tsx
'use client';
import * as React from 'react';
/**
* Gesture model copied from `event-calendar-dnd.tsx`, deliberately not
* imported: filters installs on its own and must not pull a whole calendar into
* `shadcn add filters`. Vanilla-DOM overlay, so a drag renders no React.
*/
export const FILTER_DND_ACTIVATION = {
/** Mouse travel before a press becomes a drag. Below this it stays a click. */
moveDistancePx: 5,
/** Touch long-press before a drag starts, so a swipe still scrolls. */
touchDelayMs: 250,
touchTolerancePx: 5,
autoScrollEdgePx: 40,
autoScrollMaxStepPx: 12,
/** A seed only: `createCarry` measures the real grab offset before paint. */
carryPointerOffsetPx: 12,
} as const;
/** One rule row, or one group's header row. Both are drag sources and targets. */
export const FILTER_ROW_SELECTOR = '[data-slot="filter-row"]';
/** Explicit "drop INSIDE": a row hit test can only ever say "beside". */
export const FILTER_DROP_ZONE_SELECTOR = '[data-drop-parent]';
/** Marked alongside the zone, so lighting the group costs no `:has()`. */
export const FILTER_GROUP_SELECTOR = '[data-slot="filter-group"]';
/** Geometry only, so resolution is a pure function and a table test. */
export interface FilterDropBox {
top: number;
bottom: number;
left: number;
right: number;
/** The group the drop writes into. */
parentId: string;
/** Where in that group's children the node lands, not a slot in this list. */
index: number;
/** How many rows enclose this box. Deeper wins. */
depth: number;
}
export interface FilterDropResolution<T extends FilterDropBox> {
target: T;
/** Null for a zone: INTO the group rather than beside anything. */
edge: 'before' | 'after' | null;
}
function contains(box: FilterDropBox, x: number, y: number, grow = 0): boolean {
return x >= box.left && x <= box.right && y >= box.top - grow && y <= box.bottom + grow;
}
/**
* How far a ROW reaches past its own rect when hit tested: HALF the sibling
* gap, which is `gap-3`, so six. `FILTER_ROW_GAP_CLASS` is the other half of
* one measurement; this moves whenever that does.
*
* The seam between adjacent rows is inside NEITHER rect, so a pointer aimed
* between two rows fell through to whatever did enclose it: at the top level
* nothing did, so the cursor said `no-drop`; one level in it was the group.
* Half the gap makes siblings tile, and the depth sort keeps the child ahead of
* that group. Rows only: zones are explicit strips.
*/
export const FILTER_ROW_SEAM_PX = 6;
/**
* Zones before rows, then the DEEPEST box: a group's rect encloses everything
* it holds, so a nested condition would otherwise resolve to its whole group.
* `seam` is a parameter, not the constant inlined, so the tiling rule itself is
* a table test.
*/
export function resolveFilterDrop<T extends FilterDropBox>(
zones: T[],
rows: T[],
x: number,
y: number,
seam: number = FILTER_ROW_SEAM_PX,
): FilterDropResolution<T> | null {
let zone: T | null = null;
for (const candidate of zones) {
if (!contains(candidate, x, y)) continue;
if (!zone || candidate.depth > zone.depth) zone = candidate;
}
if (zone) return { target: zone, edge: null };
let row: T | null = null;
for (const candidate of rows) {
if (!contains(candidate, x, y, seam)) continue;
if (!row || candidate.depth > row.depth) row = candidate;
}
if (!row) return null;
// The midpoint, not the nearest edge: a row is the width of the panel, so a
// proximity test would leave the indicator undecided across most of one.
const after = y > row.top + (row.bottom - row.top) / 2;
return {
target: { ...row, index: row.index + (after ? 1 : 0) },
edge: after ? 'after' : 'before',
};
}
/** Where a dragged node started, which is what makes a drop a no-op or not. */
export interface FilterDropOrigin {
parentId: string;
index: number;
}
/**
* Both indices name the slot the node already occupies, because
* `moveFilterNodeTo` closes the gap the detach leaves. Copy is never a no-op.
*/
export function isFilterDropNoop(resolution: FilterDropResolution<FilterDropBox> | null, origin: FilterDropOrigin | null, copy: boolean): boolean {
if (!resolution || !origin || copy) return false;
if (resolution.target.parentId !== origin.parentId) return false;
return resolution.target.index === origin.index || resolution.target.index === origin.index + 1;
}
/** Rows unmount mid-gesture, so it is the PANEL leaving that aborts a drag. */
const activeCancels = new Set<() => void>();
/** Cancel and fully revert every in-flight filter row drag. */
export function cancelActiveFilterDrags(): void {
for (const cancel of [...activeCancels]) cancel();
}
let lastDragEndedAt = 0;
/**
* Whether a drag ended within the last few frames. Exported: a consumer's own
* row click handler needs the same answer the suppressor below needs.
*/
export function wasRecentFilterDrag(): boolean {
return performance.now() - lastDragEndedAt < 250;
}
/**
* NOT `{ once: true }` alone: a drag that ends over a different element fires
* no click at all, and a stale arming would eat the user's next click. The
* timestamp is what makes that stale arming harmless.
*/
function suppressTrailingClick(event: MouseEvent) {
window.removeEventListener('click', suppressTrailingClick, true);
if (!wasRecentFilterDrag()) return;
event.stopPropagation();
event.preventDefault();
}
/** The carry is a compositing layer: a subpixel translate blurs its text. */
function snapToPixel(value: number): number {
const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
return Math.round(value * dpr) / dpr;
}
/**
* `card` is a ZONE's group, resolved once rather than walked per frame. Null on
* a row, which stands for itself.
*/
type MeasuredBox = FilterDropBox & {
el: HTMLElement;
card: HTMLElement | null;
};
interface Surface {
zones: MeasuredBox[];
rows: MeasuredBox[];
/**
* Rects are captured ONCE, so one subtraction against this scrollTop corrects
* for scrolling instead of a per-move `getBoundingClientRect`. THE ELEMENT,
* NOT A MIRRORED NUMBER: a mirror tracks only this engine's own scrolling, so
* a wheel mid-gesture left the rects stale while the correction read zero,
* painting the indicator 60px off the pointer.
*/
viewport: HTMLElement | null;
viewportRect: DOMRect | null;
/** The one number kept: where the rects were taken, which cannot change. */
startScrollTop: number;
}
/**
* The nearest scroller, THIS ONE INCLUDED: the panel is exactly what a consumer
* caps with `overflow-y: auto`, and a walk from the parent answered null for it.
*/
function findScrollParent(el: HTMLElement | null): HTMLElement | null {
let node = el ?? null;
while (node) {
const style = getComputedStyle(node);
const overflow = `${style.overflowY} ${style.overflow}`;
if (/(auto|scroll|overlay)/.test(overflow) && node.scrollHeight > node.clientHeight) {
return node;
}
node = node.parentElement;
}
return null;
}
function rowDepth(el: HTMLElement, root: HTMLElement): number {
let depth = 0;
let node = el.parentElement;
while (node && node !== root) {
if (node.matches(FILTER_ROW_SELECTOR)) depth++;
node = node.parentElement;
}
return depth;
}
/**
* Measured once. DESCENDANTS of the dragged node are excluded rather than
* refused later: an indicator the drop ignores is a broken promise. The dragged
* row ITSELF is kept, so its own slot reads as a no-op, not as a hole.
*/
function collectSurface(root: HTMLElement, dragged: HTMLElement): Surface {
const zones: MeasuredBox[] = [];
const rows: MeasuredBox[] = [];
for (const el of root.querySelectorAll<HTMLElement>(FILTER_DROP_ZONE_SELECTOR)) {
if (dragged.contains(el)) continue;
const parentId = el.dataset.dropParent;
if (!parentId) continue;
const rect = el.getBoundingClientRect();
zones.push({
el,
card: el.closest<HTMLElement>(FILTER_GROUP_SELECTOR),
top: rect.top,
bottom: rect.bottom,
left: rect.left,
right: rect.right,
parentId,
index: Number(el.dataset.dropIndex ?? 0),
depth: rowDepth(el, root),
});
}
for (const el of root.querySelectorAll<HTMLElement>(FILTER_ROW_SELECTOR)) {
if (el !== dragged && dragged.contains(el)) continue;
const parentId = el.dataset.parentId;
if (!parentId) continue;
const rect = el.getBoundingClientRect();
rows.push({
el,
card: null,
top: rect.top,
bottom: rect.bottom,
left: rect.left,
right: rect.right,
parentId,
index: Number(el.dataset.index ?? 0),
depth: rowDepth(el, root),
});
}
const viewport = findScrollParent(root);
return {
zones,
rows,
viewport,
viewportRect: viewport?.getBoundingClientRect() ?? null,
startScrollTop: viewport?.scrollTop ?? 0,
};
}
export interface FilterDropDetails {
parentId: string;
index: number;
/** Alt was held at release: copy the node rather than moving it. */
copy: boolean;
}
export interface FilterRowDragOptions {
/** The PANEL, not its body: the top-level append zone is in the footer. */
root: () => HTMLElement | null;
onDrop: (nodeId: string, details: FilterDropDetails) => void;
disabled?: boolean;
}
/**
* Straight to the DOM: a React state write per move is a tree render. A zone
* marks TWO elements, itself and its card, and both clear every frame.
*/
function paint(surface: Surface, hit: FilterDropResolution<MeasuredBox> | null) {
for (const box of surface.zones) {
delete box.el.dataset.dropInto;
if (box.card) delete box.card.dataset.dropInto;
}
for (const box of surface.rows) delete box.el.dataset.dropEdge;
if (!hit) return;
if (hit.edge) {
hit.target.el.dataset.dropEdge = hit.edge;
return;
}
hit.target.el.dataset.dropInto = '';
if (hit.target.card) hit.target.card.dataset.dropInto = '';
}
function startDrag(event: React.PointerEvent<HTMLElement>, nodeId: string, options: FilterRowDragOptions) {
const handle = event.currentTarget;
const root = options.root();
const source = handle.closest<HTMLElement>(FILTER_ROW_SELECTOR);
if (!root || !source) return;
const pointerId = event.pointerId;
const isTouch = event.pointerType === 'touch';
const startX = event.clientX;
const startY = event.clientY;
// Off the row's own attributes, which it already publishes for the hit test.
// Asking the panel would mean threading a position through the drag context.
const origin: FilterDropOrigin | null = source.dataset.parentId
? {
parentId: source.dataset.parentId,
index: Number(source.dataset.index ?? 0),
}
: null;
let active = false;
let finished = false;
let surface: Surface | null = null;
let hit: FilterDropResolution<MeasuredBox> | null = null;
let copy = event.altKey;
let lastEvent: PointerEvent | null = null;
let touchTimer: ReturnType<typeof setTimeout> | null = null;
let rafScroll = 0;
// Three states, not a boolean: `"ok"` lands somewhere new, `"noop"` puts the
// node back where it came from, `"none"` is over nothing at all.
let dropState: 'ok' | 'noop' | 'none' = 'none';
let carryEl: HTMLDivElement | null = null;
let badgeEl: HTMLSpanElement | null = null;
// Where inside the row the pointer went down, so the copy holds that spot.
// Measured in `createCarry`, which runs before anything reads these.
let grabOffsetX = FILTER_DND_ACTIVATION.carryPointerOffsetPx;
let grabOffsetY = FILTER_DND_ACTIVATION.carryPointerOffsetPx;
const createCarry = () => {
const rect = source.getBoundingClientRect();
grabOffsetX = startX - rect.left;
grabOffsetY = startY - rect.top;
carryEl = document.createElement('div');
carryEl.setAttribute('data-slot', 'filters-drag-carry');
carryEl.setAttribute('aria-hidden', 'true');
// `data-drop-invalid` rather than a toggled class name, so the style stays
// one static string Tailwind can see at build time.
//
// Muted and translucent, no border or shadow: the clone carries the row's
// own controls, and a box around them read as a card leaving the page. Only
// the invalid state marks the clone, since nothing else says the drop is
// dead, and it RINGS rather than going dashed: dashed is this builder's
// word for "a row can land here", and the clone is not one.
carryEl.className =
'pointer-events-none fixed ' +
'top-0 left-0 z-100 ' +
'opacity-95 will-change-transform ' +
'data-drop-invalid:ring-destructive/70 data-drop-invalid:ring-2 ' +
'data-drop-invalid:opacity-60';
// A bare anchor: the clip box below owns the size, and no overflow lets the
// badge overhang.
carryEl.style.position = 'fixed';
const clone = source.cloneNode(true) as HTMLElement;
// The source is faded while in flight; its copy must not inherit that.
delete clone.dataset.dragging;
delete clone.dataset.dropNoop;
delete clone.dataset.dropEdge;
if (rect.width > 0) clone.style.width = `${rect.width}px`;
/*
SANITIZED, because the clone lives on `<body>`: two elements would claim
one node id, `aria-hidden` leaves real buttons in the tab order and must
never wrap a focused one, and cloned ids make a `for` resolve to a copy.
*/
const strip = (el: HTMLElement) => {
el.removeAttribute('id');
el.removeAttribute('data-node-id');
el.removeAttribute('data-filter-cell');
if (el.dataset.slot === 'filter-row') el.removeAttribute('data-slot');
// `-1` rather than removed: the attribute is also how the roving scheme
// marks its cells, and a row copied mid-gesture has one cell at `0`.
el.setAttribute('tabindex', '-1');
};
strip(clone);
for (const el of clone.querySelectorAll<HTMLElement>('*')) strip(el);
/*
The CLIPPING box is the inner one: the carry is the badge's containing
block, so `overflow-hidden` there clipped the badge that overhangs it.
*/
const clip = document.createElement('div');
clip.className = 'bg-background overflow-hidden rounded-md';
// Sized only when the rect is real: a document that is not being laid out
// measures zero, and a copy pinned to `0px` is invisible.
if (rect.width > 0) clip.style.width = `${rect.width}px`;
if (rect.height > 0) clip.style.height = `${rect.height}px`;
clip.appendChild(clone);
carryEl.appendChild(clip);
badgeEl = document.createElement('span');
badgeEl.setAttribute('data-slot', 'filters-drag-copy');
badgeEl.className =
'bg-primary text-primary-foreground absolute -end-1.5 -top-1.5 flex ' +
'size-4 items-center justify-center rounded-full text-[10px] leading-none';
badgeEl.textContent = '+';
// Legible BEFORE the release, or Alt is discoverable only by error.
badgeEl.hidden = !copy;
carryEl.appendChild(badgeEl);
// <body>, not the panel: a transform or a `content-visibility` on a wrapper
// becomes the containing block for `position: fixed`, and the clone jumps.
document.body.appendChild(carryEl);
positionCarry(startX, startY);
};
const positionCarry = (x: number, y: number) => {
if (!carryEl) return;
// THE GRAB OFFSET, not a fixed nudge: the grip sits at the row's trailing
// edge, so anchoring at the pointer hung the copy a row's width away.
carryEl.style.transform = `translate3d(${snapToPixel(x - grabOffsetX)}px, ${snapToPixel(y - grabOffsetY)}px, 0)`;
};
// Two things decide the cursor and the RESOLUTION outranks Alt, which is why
// `none` is tested first: `copy` over nothing is still nothing.
const paintCursor = () => {
if (!active) return;
document.body.style.cursor = dropState === 'none' ? 'no-drop' : copy ? 'copy' : 'grabbing';
};
// Deliberately NOT guarded on `dropState === next`: the first resolution of a
// gesture is routinely `"none"`, which is also the initial value, so a guard
// left the first frame of a drag onto nothing wearing no mark at all.
const setDropState = (next: typeof dropState) => {
dropState = next;
// On the SOURCE: "it stays here" is a statement about the row carried.
if (next === 'noop') source.dataset.dropNoop = '';
else delete source.dataset.dropNoop;
// And on the CARRY: over nothing there is no target left to mark.
if (carryEl) {
if (next === 'none') carryEl.dataset.dropInvalid = '';
else delete carryEl.dataset.dropInvalid;
}
paintCursor();
};
const setCopy = (next: boolean) => {
if (copy === next) return;
copy = next;
if (badgeEl) badgeEl.hidden = !next;
paintCursor();
// Alt changes the ANSWER, not just the cursor: a release beside yourself is
// a no-op while moving and a duplicate in place while copying.
if (lastEvent) hitTest(lastEvent.clientX, lastEvent.clientY);
};
const hitTest = (x: number, y: number) => {
if (!surface) return;
// One subtraction instead of a re-measure. Read off the ELEMENT every time:
// see `Surface.viewport`, a mirror misses the user's own scroll.
const scrolled = surface.viewport?.scrollTop ?? surface.startScrollTop;
const drift = scrolled - surface.startScrollTop;
const resolved = resolveFilterDrop(surface.zones, surface.rows, x, y + drift);
const noop = isFilterDropNoop(resolved, origin, copy);
// A no-op commits as NOTHING, not as a move the tree would discard.
hit = noop ? null : resolved;
paint(surface, hit);
setDropState(noop ? 'noop' : hit ? 'ok' : 'none');
};
const autoScroll = (y: number) => {
if (rafScroll) cancelAnimationFrame(rafScroll);
rafScroll = 0;
const viewport = surface?.viewport;
const rect = surface?.viewportRect;
if (!viewport || !rect) return;
const edge = FILTER_DND_ACTIVATION.autoScrollEdgePx;
const step = FILTER_DND_ACTIVATION.autoScrollMaxStepPx;
let delta = 0;
if (y >= rect.top && y < rect.top + edge) {
delta = -step * ((rect.top + edge - y) / edge);
} else if (y <= rect.bottom && y > rect.bottom - edge) {
delta = step * Math.min(1, (y - (rect.bottom - edge)) / edge);
}
if (delta === 0) return;
const tick = () => {
// The read-back STOPS the loop: the browser clamps at the scroll extent,
// so a panel at its limit would keep asking for unusable frames.
const before = viewport.scrollTop;
viewport.scrollTop = before + delta;
if (viewport.scrollTop === before) return;
if (lastEvent) hitTest(lastEvent.clientX, lastEvent.clientY);
rafScroll = requestAnimationFrame(tick);
};
rafScroll = requestAnimationFrame(tick);
};
/**
* A still pointer fires no `pointermove`, so a wheel mid-drag would leave the
* last answer painted while the rows slid out from under it. The overlap
* with the autoScroll tick is deliberate: this is arithmetic over boxes
* already measured, and one redundant pass per frame is cheaper than a rule
* about who owns the repaint.
*/
const onViewportScroll = () => {
if (!active || !lastEvent) return;
hitTest(lastEvent.clientX, lastEvent.clientY);
};
const activate = () => {
if (active) return;
active = true;
surface = collectSurface(root, source);
// Passive: nothing here calls `preventDefault`, and a non-passive listener
// on a scroller is a frame of jank per notch.
surface.viewport?.addEventListener('scroll', onViewportScroll, {
passive: true,
});
source.dataset.dragging = '';
document.body.style.cursor = copy ? 'copy' : 'grabbing';
document.body.style.userSelect = 'none';
createCarry();
// Armed with the GESTURE, not the press: a press that never travels far
// enough strands no overlay, no body style and no listener.
window.addEventListener('blur', onWindowBlur);
};
// Idempotent. pointerup, pointercancel, Escape, window blur and the panel's
// own teardown can all race; whichever lands first wins and the rest no-op.
const cleanup = () => {
if (finished) return;
finished = true;
activeCancels.delete(cancel);
window.removeEventListener('pointermove', onPointerMove);
window.removeEventListener('pointerup', onPointerUp);
window.removeEventListener('pointercancel', onPointerCancel);
window.removeEventListener('keydown', onKeyDown, true);
window.removeEventListener('keyup', onKeyUp, true);
window.removeEventListener('blur', onWindowBlur);
surface?.viewport?.removeEventListener('scroll', onViewportScroll);
if (touchTimer) clearTimeout(touchTimer);
if (rafScroll) cancelAnimationFrame(rafScroll);
if (surface) paint(surface, null);
delete source.dataset.dragging;
delete source.dataset.dropNoop;
carryEl?.remove();
carryEl = null;
badgeEl = null;
document.body.style.cursor = '';
document.body.style.userSelect = '';
};
/** A bare teardown: nothing is committed until release, so no snapshot. */
const cancel = () => {
if (active) lastDragEndedAt = performance.now();
cleanup();
};
const onWindowBlur = () => cancel();
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && active) {
// Stopped, or the popover the builder may be living in closes underneath
// the gesture and takes the panel the drop was aimed at with it.
e.stopPropagation();
e.preventDefault();
cancel();
return;
}
if (e.key === 'Alt') setCopy(true);
};
// Alt tracked on its own keys too: reaching for the modifier without moving
// the mouse fires no pointermove, and the badge has to appear regardless.
const onKeyUp = (e: KeyboardEvent) => {
if (e.key === 'Alt') setCopy(false);
};
const onPointerMove = (e: PointerEvent) => {
// A second finger must not drive or cancel the gesture this one started.
if (e.pointerId !== pointerId) return;
lastEvent = e;
if (!active) {
const distance = Math.hypot(e.clientX - startX, e.clientY - startY);
if (isTouch) {
// Past the tolerance the user is scrolling, so the press stays a scroll.
if (distance > FILTER_DND_ACTIVATION.touchTolerancePx) cancel();
return;
}
if (distance < FILTER_DND_ACTIVATION.moveDistancePx) return;
activate();
}
setCopy(e.altKey);
positionCarry(e.clientX, e.clientY);
hitTest(e.clientX, e.clientY);
autoScroll(e.clientY);
};
const onPointerUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
const landed = active ? hit : null;
const wasCopy = copy;
cleanup();
if (!active) return;
lastDragEndedAt = performance.now();
// The trailing click belongs to the gesture, not to whatever it ended over.
window.addEventListener('click', suppressTrailingClick, true);
if (!landed) return;
options.onDrop(nodeId, {
parentId: landed.target.parentId,
index: landed.target.index,
copy: wasCopy,
});
};
const onPointerCancel = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
cancel();
};
window.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerup', onPointerUp);
window.addEventListener('pointercancel', onPointerCancel);
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
activeCancels.add(cancel);
if (isTouch) {
touchTimer = setTimeout(() => {
activate();
if (lastEvent) {
positionCarry(lastEvent.clientX, lastEvent.clientY);
hitTest(lastEvent.clientX, lastEvent.clientY);
}
}, FILTER_DND_ACTIVATION.touchDelayMs);
}
}
/**
* Only `onPointerDown`: the handle is a real button that Tab reaches, so it must
* not also be `draggable` and race the browser's HTML5 drag, with its ghost, no
* copy affordance and no way to report a drop into a nested target.
*/
export function useFilterRowDrag(options: FilterRowDragOptions) {
// Read at gesture time, not captured at wiring time, so the handler identity
// is stable and a memoized row never re-renders on a re-created callback.
const latest = React.useRef(options);
React.useEffect(() => {
latest.current = options;
});
// A gesture outlives its row by design, but never the panel: its listeners
// are on `window` and its carry on `document.body`.
React.useEffect(() => cancelActiveFilterDrags, []);
return React.useCallback(
(nodeId: string) => ({
onPointerDown: (event: React.PointerEvent<HTMLElement>) => {
if (latest.current.disabled) return;
// Primary button only: a right press strands the drag under a menu.
if (event.button !== 0) return;
startDrag(event, nodeId, latest.current);
},
}),
[],
);
}components/ui/filters/filters-draft.tsx
import type { FilterDraft, FilterDraftStep, FilterOperatorArity } from '@/registry/vcare/ui/filters/filters-types';
/**
* The filter builder's step machine. Pure: no React, Base UI or shadcn import,
* so the whole create and amend flow is a table test in node with no DOM.
*
* Arity arrives ON THE ACTION, which keeps the reducer free of the schema index
* while it still owns the branch that skips the value step. The shipped chrome
* drives `openCreate`, browse, query, `selectField` and `close`; `openAmend`,
* `selectOperator`, `setValue`, `commit`, `back` and `goto` are published
* surface for a consumer composing their own panel.
*/
export type FilterDraftAction<V = unknown> =
| { type: 'openCreate'; cascaderPath?: string[] }
| {
type: 'openAmend';
ruleId: string;
step: FilterDraftStep;
path: string[];
operator: string | null;
value: V | undefined;
cascaderPath?: string[];
}
| { type: 'close' }
/** Where the user is BROWSING, not the selected field's path. */
| { type: 'setCascaderPath'; path: string[] }
| { type: 'setQuery'; query: string }
| {
type: 'selectField';
path: string[];
defaultOperator: string | null;
}
| {
type: 'selectOperator';
operator: string;
arity: FilterOperatorArity;
/** Carried across the operator change, already coerced. */
value: V | undefined;
}
| { type: 'setValue'; value: V | undefined }
| { type: 'commit'; value?: V }
| { type: 'back' }
| { type: 'goto'; step: FilterDraftStep };
export function createFilterDraft<V = unknown>(cascaderPath: string[] = []): FilterDraft<V> {
return {
step: 'field',
status: 'editing',
ruleId: null,
path: [],
cascaderPath,
operator: null,
value: undefined,
query: '',
};
}
/** null means Back closes the builder rather than stepping back. */
function previousStep(step: FilterDraftStep): FilterDraftStep | null {
if (step === 'value') return 'operator';
if (step === 'operator') return 'field';
return null;
}
/**
* `null` is the closed state, not a separate boolean: `{ open, draft }` would
* make "open with no draft" and "closed but still holding one" representable.
*/
export function filterDraftReducer<V = unknown>(state: FilterDraft<V> | null, action: FilterDraftAction<V>): FilterDraft<V> | null {
switch (action.type) {
case 'openCreate':
return createFilterDraft<V>(action.cascaderPath ?? []);
case 'openAmend':
return {
step: action.step,
status: 'editing',
ruleId: action.ruleId,
path: action.path,
// Defaults the picker to the field's own level, so amend opens beside
// its siblings, not at the root. Callers may override.
cascaderPath: action.cascaderPath ?? action.path.slice(0, -1),
operator: action.operator,
value: action.value,
query: '',
};
case 'close':
return null;
case 'setCascaderPath':
if (!state) return state;
if (state.cascaderPath === action.path) return state;
return { ...state, cascaderPath: action.path };
case 'setQuery':
if (!state) return state;
if (state.query === action.query) return state;
return { ...state, query: action.query };
case 'selectField': {
if (!state) return state;
// Choosing a field COMMITS at once; the condition is picked on the chip,
// so the popover never holds a second and third step to walk.
return {
...state,
path: action.path,
operator: action.defaultOperator,
status: 'ready',
// A field change invalidates the value: "Active" means nothing once
// the field becomes "Created at".
value: undefined,
step: 'operator',
query: '',
};
}
case 'selectOperator': {
if (!state) return state;
// arity "none" is the whole filter; a value step would be an empty panel.
if (action.arity === 'none') {
return {
...state,
operator: action.operator,
value: undefined,
status: 'ready',
query: '',
};
}
return {
...state,
operator: action.operator,
value: action.value,
step: 'value',
status: 'editing',
query: '',
};
}
case 'setValue':
if (!state) return state;
return { ...state, value: action.value };
case 'commit':
if (!state) return state;
return {
...state,
value: action.value === undefined ? state.value : action.value,
status: 'ready',
};
case 'back': {
if (!state) return state;
const step = previousStep(state.step);
if (!step) return null;
return { ...state, step, status: 'editing', query: '' };
}
case 'goto':
if (!state) return state;
if (state.step === action.step) return state;
return { ...state, step: action.step, status: 'editing', query: '' };
default:
return state;
}
}
/**
* A path is enough. Not an operator: the flow commits when the field is picked,
* so `operator: ""` is a legitimate committed state. Not a value either, since
* `arity: "none"` has none and an editor may commit `undefined` to clear.
*/
export function isFilterDraftCommittable<V>(draft: FilterDraft<V> | null): draft is FilterDraft<V> {
return Boolean(draft && draft.path.length > 0);
}components/ui/filters/filters-editors.tsx
import * as React from 'react';
import { Cascader, CascaderEmpty, CascaderList, CascaderPanel, CascaderStatus } from '@/registry/vcare/ui/cascader/cascader';
import type { CascaderItemState, CascaderProps } from '@/registry/vcare/ui/cascader/cascader';
import { useCascaderActions, useCascaderHighlight } from '@/registry/vcare/ui/cascader/cascader-context';
import { CascaderFooter } from '@/registry/vcare/ui/cascader/cascader-footer';
import { CascaderItems } from '@/registry/vcare/ui/cascader/cascader-item';
import { CascaderInput, CascaderNav } from '@/registry/vcare/ui/cascader/cascader-nav';
import type { CascaderActionItem, CascaderNode } from '@/registry/vcare/ui/cascader/cascader-types';
import { FilterActionsContext, filterControlSizes, type FilterResolutionStore } from '@/registry/vcare/ui/filters/filters-context';
import {
applyFilterExclusiveSelection,
filterFilterOptions,
joinFilterPath,
normalizeFilterQuery,
warnFilterOnce,
} from '@/registry/vcare/ui/filters/filters-lib';
import type {
AnyFilterEditor,
FilterEditorProps,
FilterEditorRegistry,
FilterField,
FilterIndex,
FilterLabels,
FilterLoadResult,
FilterOperator,
FilterOption,
FilterOptionsState,
} from '@/registry/vcare/ui/filters/filters-types';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { ButtonGroup } from '@/registry/vcare/ui/button-group';
import { Input } from '@/registry/vcare/ui/input';
import { CheckIcon, XIcon } from 'lucide-react';
/* -------------------------------------------------------------------------- */
/* The options service */
/* -------------------------------------------------------------------------- */
interface OptionsInternalState<O> {
items: FilterOption<O>[];
loading: boolean;
error: boolean;
hasMore: boolean;
cursor?: string;
}
const IDLE: OptionsInternalState<never> = {
items: [],
loading: false,
error: false,
hasMore: false,
};
/** Stable no-op subscription, for a hook running outside a `Filters` root. */
const emptySubscribe = () => () => {};
const zeroVersion = () => 0;
/**
* The joined path of a field, from the schema index. Keyed by PATH, not field
* identity, so labels survive a schema rebuild; an unknown field uses its id.
*/
function filterFieldKey<V, O>(field: FilterField<V, O> | undefined, index: FilterIndex | undefined): string | null {
if (!field) return null;
if (index) {
for (const entry of index.all) {
if ((entry.field as unknown) === (field as unknown)) {
return joinFilterPath(entry.path);
}
}
}
return `#${field.id}`;
}
/**
* The shared option service every option-backed editor receives: debouncing,
* aborting, cursor paging and value-to-label resolution. A deliberate fork of
* the cascader's async machinery. Resolution is two-tier: a ref cache written
* in an EFFECT, plus the root's `FilterResolutionStore`, without which a
* `loadOptions`-only field showed its raw id once the menu closed.
*/
export function useFilterOptions<V, O>(field: FilterField<V, O> | undefined, enabled: boolean, debounceMs = 250): FilterOptionsState<O> {
const [query, setQueryState] = React.useState('');
const [state, setState] = React.useState<OptionsInternalState<O>>(IDLE as OptionsInternalState<O>);
const cache = React.useRef(new Map<string, FilterOption<O>>());
const requestId = React.useRef(0);
const abortRef = React.useRef<AbortController | null>(null);
// Read directly, so this degrades outside a `Filters` root instead of throwing.
const actionsContext = React.useContext(FilterActionsContext);
const shared: FilterResolutionStore | null = actionsContext?.resolution ?? null;
const sharedKey = filterFieldKey(field, actionsContext?.index);
// Re-render when a label lands ANYWHERE under this root, not just here.
React.useSyncExternalStore(
shared ? shared.subscribe : emptySubscribe,
shared ? shared.getVersion : zeroVersion,
shared ? shared.getVersion : zeroVersion,
);
const staticOptions = field?.options;
const loadOptions = field?.loadOptions;
const isAsync = Boolean(loadOptions);
// Seeded in an effect, not during render, so the render stays pure.
React.useEffect(() => {
if (!staticOptions) return;
for (const option of staticOptions) cache.current.set(option.value, option);
if (shared && sharedKey) shared.set(sharedKey, staticOptions);
}, [staticOptions, shared, sharedKey]);
React.useEffect(() => {
for (const option of state.items) cache.current.set(option.value, option);
if (shared && sharedKey && state.items.length) {
shared.set(sharedKey, state.items);
}
}, [state.items, shared, sharedKey]);
const run = React.useCallback(
async (nextQuery: string, cursor: string | undefined, append: boolean) => {
if (!loadOptions) return;
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
const id = ++requestId.current;
setState((previous) => ({
...previous,
loading: true,
error: false,
items: append ? previous.items : [],
}));
try {
const result = await loadOptions(nextQuery, {
signal: controller.signal,
cursor,
});
// A superseded request must not write; the id, not the abort, decides.
if (id !== requestId.current) return;
const normalized: FilterLoadResult<O> = Array.isArray(result) ? { items: result } : result;
setState((previous) => ({
items: append ? [...previous.items, ...normalized.items] : normalized.items,
loading: false,
error: false,
hasMore: normalized.hasMore ?? Boolean(normalized.nextCursor),
cursor: normalized.nextCursor,
}));
} catch (error) {
if (id !== requestId.current) return;
if ((error as Error)?.name === 'AbortError') return;
setState((previous) => ({
...previous,
loading: false,
error: true,
hasMore: false,
}));
}
},
[loadOptions],
);
React.useEffect(() => {
if (!enabled || !isAsync) return;
const timer = setTimeout(() => void run(query, undefined, false), debounceMs);
return () => clearTimeout(timer);
}, [enabled, isAsync, query, debounceMs, run]);
React.useEffect(() => {
return () => abortRef.current?.abort();
}, []);
const normalizedQuery = normalizeFilterQuery(query);
// Async results are server-filtered; re-filtering hides what the label omits.
const items = React.useMemo(() => {
if (isAsync) return state.items;
return filterFilterOptions(staticOptions ?? [], normalizedQuery);
}, [isAsync, state.items, staticOptions, normalizedQuery]);
const setQuery = React.useCallback((next: string) => setQueryState(next), []);
const loadMore = React.useCallback(() => {
if (!state.hasMore || state.loading) return;
void run(query, state.cursor, true);
}, [state.hasMore, state.loading, state.cursor, query, run]);
const retry = React.useCallback(() => {
void run(query, undefined, false);
}, [query, run]);
const resolve = React.useCallback(
(value: string) => {
// The ref cache cannot be the only tier: a ref write triggers no render,
// so the chip would paint the raw value and never repaint. The shared
// store holds other instances' pages and re-renders this one on a gain.
const declared = staticOptions?.find((option) => option.value === value);
if (declared) return declared;
const fromShared = shared && sharedKey ? shared.get(sharedKey, value) : undefined;
if (fromShared) return fromShared as FilterOption<O>;
return cache.current.get(value);
},
[staticOptions, shared, sharedKey],
);
return {
items,
loading: state.loading,
error: state.error,
hasMore: state.hasMore,
query,
setQuery,
loadMore,
retry,
resolve,
};
}
/**
* Resolves committed values no loaded page covered, through `resolveValues`: a
* restored saved view holds ids the loader never returned. The claim set marks
* an omitted id asked, so only a REJECTED resolve lets a later mount retry.
*/
export function useFilterValueResolution<V, O>(field: FilterField<V, O> | undefined, values: readonly unknown[]): void {
const actionsContext = React.useContext(FilterActionsContext);
const shared: FilterResolutionStore | null = actionsContext?.resolution ?? null;
const sharedKey = filterFieldKey(field, actionsContext?.index);
const resolveValues = field?.resolveValues;
const staticOptions = field?.options;
// Keyed by CONTENT; NUL cannot occur inside a real stored value.
const valuesKey = values.map((entry) => String(entry)).join('\u0000');
React.useEffect(() => {
if (!resolveValues || !shared || !sharedKey || valuesKey === '') return;
const missing = valuesKey.split('\u0000').filter((value) => {
if (staticOptions?.some((option) => option.value === value)) return false;
return shared.get(sharedKey, value) === undefined;
});
const wanted = shared.claim(sharedKey, missing);
if (wanted.length === 0) return;
// No unmount guard: the store outlives the component.
void Promise.resolve(resolveValues(wanted)).then(
(options) => shared.set(sharedKey, options),
() => shared.release(sharedKey, wanted),
);
}, [resolveValues, shared, sharedKey, valuesKey, staticOptions]);
}
/* -------------------------------------------------------------------------- */
/* Shared chrome */
/* -------------------------------------------------------------------------- */
/**
* The panel every editor renders into. A plain flex column, NOT a combobox: an
* editor inside a Base UI composite would inherit its `aria-activedescendant`
* and arrow keys, which is hostile to a colour picker or a slider.
*/
function EditorPanel({ children, className }: { children: React.ReactNode; className?: string }) {
return (
<div
data-slot="filter-editor"
className={cn(
'flex w-full flex-col gap-2 p-2',
/* The list height cap as a VARIABLE, not the `maxHeight` prop, which
becomes an inline style no consumer class can beat. 16rem is the
256px the menu has always used. */
'[--cascader-max-height:16rem]',
className,
)}
>
{children}
</div>
);
}
function EditorFooter({
onCancel,
onCommit,
labels,
host,
}: Pick<FilterEditorProps, 'labels' | 'host'> & {
onCancel: () => void;
onCommit: () => void;
}) {
// The ONE ladder, not a hardcoded rung: `size="sm"` here measured 4px short
// of the bar's own controls at `size="default"` in all eight styles.
const actions = React.useContext(FilterActionsContext);
const sizes = filterControlSizes({ size: actions?.size ?? 'default' });
// The create host advances on commit and has Back; amend must offer discard.
if (host === 'create') return null;
return (
<div className="flex items-center justify-end gap-1.5 pt-1">
<Button variant="ghost" size={sizes.button} onClick={onCancel}>
{labels.discard}
</Button>
<Button size={sizes.button} onClick={onCommit}>
{labels.apply}
</Button>
</div>
);
}
/**
* `w-full` because `ButtonGroup` is `w-fit`, which collapses inside this
* fixed-width panel. Sera is an underline style, so its direct children flatten
* to one bottom-only edge - `border-b-input`, not transparent, since the
* buttons are the trailing edge and the rule would stop mid-panel.
*/
const EDITOR_FIELD_GROUP = 'w-full';
/**
* Confirm and cancel, an OUTLINE pair FUSED onto the field's trailing edge.
* Returns a FRAGMENT: `ButtonGroup` fuses with selectors matching DIRECT
* children only, so a wrapper div renders three separate boxes. `size="icon"`
* because every style's icon button at that size is exactly its input's height.
*/
function EditorCommitButtons({
onCancel,
onCommit,
labels,
}: Pick<FilterEditorProps, 'labels'> & {
onCancel: () => void;
onCommit: () => void;
}) {
return (
<>
<Button type="button" variant="outline" size="icon" aria-label={labels.apply} onClick={onCommit}>
<CheckIcon aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="icon" aria-label={labels.discard} onClick={onCancel}>
<XIcon aria-hidden="true" />
</Button>
</>
);
}
function useCommitKeys(commit: () => void, cancel: () => void) {
return React.useCallback(
(event: React.KeyboardEvent) => {
if (event.key === 'Enter' && !event.nativeEvent.isComposing) {
event.preventDefault();
commit();
return;
}
if (event.key === 'Escape') {
event.preventDefault();
// Stop here so a surrounding dialog does not also close.
event.stopPropagation();
cancel();
}
},
[commit, cancel],
);
}
/* -------------------------------------------------------------------------- */
/* Text / number */
/* -------------------------------------------------------------------------- */
export function FilterTextEditor<V, O>({ value, onValueChange, commit, cancel, autoFocusProps, labels, host, field }: FilterEditorProps<V, O>) {
const onKeyDown = useCommitKeys(() => commit(), cancel);
return (
// A width, not shrink-to-fit: the popover is `w-auto`, so an unsized box
// changes width between the hosts. `w-72` is measured - it holds about 23
// characters in sera and 27 in nova; `w-64` held about eighteen, too short
// for an email, and `w-80` was the widest control in a bar of compact
// chips. Capped at the viewport because `w-80` is 320px and a 360px phone
// has 40px to spare. A `w-*` on the field wins.
<EditorPanel className={cn('w-72 max-w-[calc(100vw-2rem)] min-w-0', field.className)}>
<ButtonGroup className={EDITOR_FIELD_GROUP}>
<Input
{...autoFocusProps}
value={(value as string) ?? ''}
placeholder={field.placeholder ?? labels.valuePlaceholder}
aria-label={field.label}
onChange={(event) => onValueChange(event.target.value as V)}
onKeyDown={onKeyDown}
/>
{/*
A lone input still belongs in the group: the per-style sheets re-round
the LAST child, so a group with nothing fused draws the bare field.
*/}
{host === 'create' ? null : <EditorCommitButtons labels={labels} onCancel={cancel} onCommit={() => commit()} />}
</ButtonGroup>
</EditorPanel>
);
}
export function FilterNumberEditor<V, O>({ value, onValueChange, commit, cancel, autoFocusProps, labels, host, field }: FilterEditorProps<V, O>) {
const onKeyDown = useCommitKeys(() => commit(), cancel);
return (
// Deliberately not the text editor's `w-72`: number values are short by
// construction, and a wide box around "42" is the opposite defect.
<EditorPanel className={cn('w-56 min-w-0', field.className)}>
<ButtonGroup className={EDITOR_FIELD_GROUP}>
<Input
{...autoFocusProps}
type="number"
value={value === undefined || value === null ? '' : String(value)}
placeholder={field.placeholder}
aria-label={field.label}
onChange={(event) => {
const raw = event.target.value;
onValueChange((raw === '' ? undefined : Number(raw)) as V);
}}
onKeyDown={onKeyDown}
/>
{host === 'create' ? null : <EditorCommitButtons labels={labels} onCancel={cancel} onCommit={() => commit()} />}
</ButtonGroup>
</EditorPanel>
);
}
export function FilterRangeEditor<V, O>({ value, onValueChange, commit, cancel, autoFocusProps, labels, host, field }: FilterEditorProps<V, O>) {
const tuple = (Array.isArray(value) ? value : []) as unknown[];
const onKeyDown = useCommitKeys(() => commit(), cancel);
const update = (index: 0 | 1, raw: string) => {
const next = [tuple[0], tuple[1]];
next[index] = raw === '' ? undefined : Number(raw);
onValueChange(next as V);
};
return (
<EditorPanel>
<div className="flex items-center gap-1.5">
<Input
{...autoFocusProps}
type="number"
value={tuple[0] === undefined ? '' : String(tuple[0])}
aria-label={labels.rangeFrom(field.label)}
onChange={(event) => update(0, event.target.value)}
onKeyDown={onKeyDown}
/>
<span className="text-muted-foreground text-xs">{labels.rangeSeparator}</span>
<Input
type="number"
value={tuple[1] === undefined ? '' : String(tuple[1])}
aria-label={labels.rangeTo(field.label)}
onChange={(event) => update(1, event.target.value)}
onKeyDown={onKeyDown}
/>
</div>
<EditorFooter host={host} labels={labels} onCancel={cancel} onCommit={() => commit()} />
</EditorPanel>
);
}
/* -------------------------------------------------------------------------- */
/* The menu */
/* -------------------------------------------------------------------------- */
/** One row. The shape both the operator menu and the option editors hand over. */
export interface FilterListItem {
value: string;
label: string;
icon?: React.ReactNode;
description?: string;
keywords?: string[];
disabled?: boolean;
/**
* A None row, from `FilterOption.exclusive`. LAYOUT only: what a pick DOES is
* `applyFilterExclusiveSelection`, in the option editor's handler. A consumer
* composing `FilterMenu` into an editor of their own owns the same call.
*/
exclusive?: boolean;
}
/**
* Beyond the cascader's own fields: one divider flag, on the first row of a
* group that is not the first, because grouping happens out here. A separator
* NODE would join the option ring, and `[data-selected] + :not([data-selected])`
* reads the LIVE selection, so unticking a pinned row drew a second line.
*/
interface FilterMenuMeta {
divider?: boolean;
/**
* Carries `FilterListItem.exclusive` down to the row. The rule above it is
* `aria-hidden`, so the row's accessible name is the only channel arriving
* before the press, and `renderItem` receives the node and nothing else.
*
* `[data-slot=filter-menu-exclusive-hint]` is also the handle a consumer
* styles the row through: the cascader's row element takes no attribute of
* ours, so `:has([data-slot=filter-menu-exclusive-hint])` selects it.
*/
exclusive?: boolean;
}
/** Joins a selection into one comparable key; NUL cannot occur in a value. */
const PIN_SEPARATOR = '\u0000';
/** A bound on a race: each attempt costs one task and stops on success. */
const MAX_PIN_RESTORE_ATTEMPTS = 4;
interface PendingPinRestore {
/** The row the user was on when the rows moved. Tracked by VALUE, never index. */
value: string;
/** The index it sat at, which is the half of the signature Base UI keeps. */
index: number;
/** The order the rows landed in, so the target's new position is known. */
order: string[];
attempts: number;
}
/**
* Carries the HIGHLIGHT across a live re-pin. Base UI holds it as an INDEX and
* a keyed reorder MOVES the DOM node rather than remounting it, so the index
* map only rebuilds when the `MutationObserver` fires: until then, ticking a
* row moves the highlight down one. So this ARMS in the layout effect, where
* the map still reads the OLD order, and fires on the signature (SAME index,
* DIFFERENT row) from a TASK, re-trying because the store event and the re-sort
* are unordered. A synthetic `mousemove`, since Base UI exposes no setter.
*/
function FilterMenuPinKeeper({
order,
items,
}: {
order: string[];
/** The data the order was derived from, by identity. */
items: FilterListItem[];
}) {
const { baseId } = useCascaderActions();
const highlight = useCascaderHighlight();
const previousRef = React.useRef<{
order: string[];
items: FilterListItem[];
} | null>(null);
const pendingRef = React.useRef<PendingPinRestore | null>(null);
const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
// From the render: on the reordering commit a ref still holds the OLD row.
const highlightedValue = highlight.value;
const highlightedIndex = highlight.index;
const stop = React.useCallback(() => {
pendingRef.current = null;
if (timerRef.current === null) return;
clearTimeout(timerRef.current);
timerRef.current = null;
}, []);
const startRestore = React.useCallback(() => {
const attempt = () => {
timerRef.current = null;
const pending = pendingRef.current;
if (!pending) return;
const target = pending.order.indexOf(pending.value);
const rows = document.getElementById(`${baseId}-column-0`)?.querySelectorAll<HTMLElement>('[data-slot="cascader-item"]');
// A WINDOWED list renders a subset, so row N is not order[N]. Leave it.
if (target < 0 || !rows || rows.length !== pending.order.length) {
stop();
return;
}
rows[target]?.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));
pending.attempts += 1;
if (pending.attempts >= MAX_PIN_RESTORE_ATTEMPTS) {
stop();
return;
}
timerRef.current = setTimeout(attempt, 0);
};
timerRef.current = setTimeout(attempt, 0);
}, [baseId, stop]);
// No dependency list: the arm must run on the commit that reorders the rows.
React.useLayoutEffect(() => {
const previous = previousRef.current;
previousRef.current = { order, items };
if (!previous || previous.order === order) return;
// New DATA (a page, a query) is Base UI's to highlight; only a re-pin is ours.
if (previous.items !== items) return;
if (!highlightedValue) return;
// Content, not identity: a re-pin can leave the rows in the same order.
if (isSameOrder(previous.order, order)) return;
pendingRef.current = {
value: highlightedValue,
index: highlightedIndex,
order,
attempts: 0,
};
});
React.useEffect(() => {
const pending = pendingRef.current;
if (!pending) return;
// Back where it belongs, or moved by the user: either way the arm is spent.
if (highlightedValue === pending.value || highlightedIndex !== pending.index) {
stop();
return;
}
// Already chasing this one; a second chain would double every dispatch.
if (pending.attempts > 0 || timerRef.current !== null) return;
startRestore();
}, [highlightedValue, highlightedIndex, startRestore, stop]);
React.useEffect(() => stop, [stop]);
return null;
}
/** Element-wise, because the arrays are rebuilt on every selection change. */
function isSameOrder(a: string[], b: string[]) {
if (a.length !== b.length) return false;
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index]) return false;
}
return true;
}
export interface FilterMenuProps {
items: FilterListItem[];
/** Committed values. Drives the check mark and the pinned group. */
selected: string[];
multiple?: boolean;
/** Receives the FULL next selection, so no caller re-derives it. */
onSelectionChange: (values: string[]) => void;
labels: FilterLabels;
ariaLabel: string;
searchPlaceholder?: string;
/** Whether the search field is VISIBLE. It is always rendered regardless. */
searchable?: boolean;
/**
* Viewport height before the list scrolls, in pixels. Omitted on purpose by
* the option editors: it becomes an inline style a consumer's `className`
* cannot outrank, so the panel publishes `--cascader-max-height` instead.
*/
maxHeight?: number;
/**
* Pin selected rows above the rest, with a full-bleed rule between them. Off
* by default; the option editors read `FilterField.pinSelected` per field.
*/
pinSelected?: boolean;
/**
* Order INSIDE each group, plus WHEN the partition is taken. Declaration
* order by default, so the partition is stable rather than a re-sort.
*/
sortSelected?: 'none' | 'label' | 'snapshot';
/** The caller already filtered `items`, so the cascader must not re-filter. */
preFiltered?: boolean;
autoFocusProps?: FilterEditorProps['autoFocusProps'];
/** Controlled query. Pair it with `onQueryChange` to filter outside. */
query?: string;
onQueryChange?: (query: string) => void;
state?: Pick<FilterOptionsState<unknown>, 'loading' | 'error' | 'hasMore' | 'loadMore' | 'retry'>;
}
/**
* One accessible list, shared by the operator menu and every option editor. It
* is the CASCADER configured flat, not a list this file implements, which
* brings the typeahead, RTL handling and live region with it. Only the pinning
* and the paging affordance stay out here.
*/
export function FilterMenu({
items,
selected,
multiple = false,
onSelectionChange,
labels,
ariaLabel,
searchPlaceholder,
searchable = true,
maxHeight,
pinSelected = false,
sortSelected = 'none',
preFiltered = false,
autoFocusProps,
query,
onQueryChange,
state,
}: FilterMenuProps) {
/**
* The pin set as a KEY, not an array: `selected` is a fresh array on most
* renders, so a memo depending on it re-partitions every render.
*/
const liveKey = pinSelected ? selected.join(PIN_SEPARATOR) : '';
/**
* The same set, frozen at OPEN, for `sortSelected: "snapshot"`. LIVE is the
* default: "your picks, then the rest" is about the CURRENT selection, and
* `FilterMenuPinKeeper` pays for rows moving under the pointer.
*/
const [snapshotKey] = React.useState(() => liveKey);
// `pinSelected` re-checked here, not just through `liveKey`: `snapshotKey` is
// frozen at MOUNT, so a menu that lost the prop would keep partitioning.
const pinnedKey = !pinSelected ? '' : sortSelected === 'snapshot' ? snapshotKey : liveKey;
// Uncontrolled unless the caller owns the query, as an option service does.
const [ownQuery, setOwnQuery] = React.useState('');
const currentQuery = query ?? ownQuery;
const setQuery = onQueryChange ?? setOwnQuery;
/**
* Memoized on the SELECTION, not the query: folding the query in re-sorted
* 4,000 rows on every keystroke, for a one pixel rule.
*/
const partitioned = React.useMemo(() => {
const pinned = new Set(pinnedKey ? pinnedKey.split(PIN_SEPARATOR) : []);
/*
Exclusive rows come out BEFORE the pin partition; their position is fixed.
Pinning is by SELECTION, so a ticked None row would lift itself above the
very rule drawn to set it apart and drop back on untick. Grouping by ROLE
means the pinned group counts ordinary picks only, which is also why
picking None draws no pin rule: it clears every other pick.
*/
const exclusive = items.filter((item) => item.exclusive);
const values = exclusive.length ? items.filter((item) => !item.exclusive) : items;
const chosen = pinned.size ? values.filter((item) => pinned.has(item.value)) : [];
const rest = pinned.size ? values.filter((item) => !pinned.has(item.value)) : values;
// The SCHEMA's order inside each group unless the field asks otherwise:
// option order is usually semantic.
const ordered =
sortSelected === 'label'
? [
[...chosen].sort((a, b) => a.label.localeCompare(b.label)),
[...rest].sort((a, b) => a.label.localeCompare(b.label)),
[...exclusive].sort((a, b) => a.label.localeCompare(b.label)),
]
: [chosen, rest, exclusive];
const rows = [...ordered[0], ...ordered[1], ...ordered[2]];
return {
chosenCount: chosen.length,
/** Index of the first exclusive row, or -1 when the list has none. */
exclusiveAt: exclusive.length ? rows.length - exclusive.length : -1,
// The render order alone, so a REORDER is an identity compare.
order: rows.map((item) => item.value),
nodes: rows.map<CascaderNode<FilterMenuMeta>>((item) => ({
value: item.value,
label: item.label,
icon: item.icon,
description: item.description,
keywords: item.keywords,
disabled: item.disabled,
// Only exclusive rows carry `data`, so the ordinary 4,000 keep theirs.
data: item.exclusive ? { exclusive: true } : undefined,
})),
};
}, [items, pinnedKey, sortSelected]);
// No rule under a query: "your picks, then the rest" is about the WHOLE list.
const dividerAt = partitioned.chosenCount && !currentQuery.trim() ? partitioned.chosenCount : -1;
// Survives a search, unlike the pin rule: it is a fact about the row.
const exclusiveDividerAt = partitioned.exclusiveAt;
const nodes = React.useMemo<CascaderNode<FilterMenuMeta>[]>(() => {
const total = partitioned.nodes.length;
// Only a boundary with rows on BOTH sides is one: a rule on row 0 would
// be a line above the top of the list.
const marks = [dividerAt, exclusiveDividerAt].filter((index) => index > 0 && index < total);
if (marks.length === 0) return partitioned.nodes;
// Rows rewritten, not rebuilt: copying 4,000 objects would undo the split.
const next = partitioned.nodes.slice();
for (const index of marks) {
// MERGED, never replaced: the two boundaries usually fall on one row, and
// overwriting `data` dropped the flag the accessible name is built from.
next[index] = {
...next[index],
data: { ...next[index].data, divider: true },
};
}
return next;
}, [partitioned, dividerAt, exclusiveDividerAt]);
const renderItem = React.useCallback(
(node: CascaderNode<FilterMenuMeta>, itemState: CascaderItemState<FilterMenuMeta>) => (
<>
{node.data?.divider ? (
<span
data-slot="filter-menu-divider"
aria-hidden="true"
/* Full bleed, over the per-style `--cascader-list-pad` the shell
publishes: a rule stopping at the row's inset box reads as a gap.
Centred in the 8px the row gives back above itself, not `top-0`. */
className="bg-border absolute inset-x-[calc(var(--cascader-list-pad,4px)*-1)] -top-1 h-px"
/>
) : null}
{node.icon ? (
<span data-slot="filter-menu-icon" className="text-muted-foreground flex shrink-0 items-center justify-center">
{node.icon}
</span>
) : null}
<span className="flex min-w-0 flex-1 flex-col items-start gap-0.5">
<span className="w-full truncate text-start">{node.label}</span>
{node.description ? <span className="text-muted-foreground w-full truncate text-start text-xs">{node.description}</span> : null}
</span>
{/*
What the aria-hidden rule says, for the people it does not reach.
Inside the option element so it joins the row's accessible NAME, not
an `aria-describedby`: a description is announced late or not at all,
and this has to arrive before the press. The cascader's `srDetails`
cannot either: `renderItem` replaces the row body. Empty copy renders
nothing, so `labels.exclusiveHint` of "" silences it.
*/}
{node.data?.exclusive && labels.exclusiveHint ? (
<span data-slot="filter-menu-exclusive-hint" className="sr-only">
{`, ${labels.exclusiveHint}`}
</span>
) : null}
{/* A check mark in both modes, never the cascader's default box. */}
{itemState.selected ? (
<span
data-slot="filter-menu-check"
/* The gutter every style already reserves, on the cascader's own
logical inset. `end-*` rather than `right-2`, so RTL mirrors. */
className="size-4 pointer-events-none absolute end-[var(--cascader-row-inset,8px)]! flex items-center justify-center rtl:right-auto!"
>
<CheckIcon className="text-foreground! **:text-foreground!" />
</span>
) : null}
</>
),
[labels.exclusiveHint],
);
const cascaderLabels = React.useMemo(
() => ({
search: searchPlaceholder ?? labels.searchOptions,
empty: labels.empty,
loading: labels.loading,
loadingMore: labels.loadingMore,
loadMore: labels.loadMore,
error: labels.error,
retry: labels.retry,
// Named after the field, not the cascader's own "Top level" wording.
rootLevel: ariaLabel,
panelLabel: ariaLabel,
// Run FLAT, so the default hint would teach branch keys that do not exist.
keyboardHint: () => '',
// From `FilterLabels`, so the menu ships no English of its own.
resultsAnnouncement: labels.resultsAnnouncement,
actionsLabel: labels.actionsLabel,
}),
[labels, ariaLabel, searchPlaceholder],
);
/**
* Paging and retry in the pinned footer, never a row: a row would join the
* option ring, where arrows land on it and a query filters it away mid-page.
*/
const actions = React.useMemo<CascaderActionItem[]>(() => {
if (state?.error) {
return [{ value: 'retry', label: labels.retry, onSelect: state.retry }];
}
if (state?.hasMore) {
return [
{
value: 'load-more',
label: state.loading ? labels.loadingMore : labels.loadMore,
disabled: state.loading,
onSelect: state.loadMore,
},
];
}
return [];
}, [state, labels]);
const shared = {
// Inline and pinned open with a no-op handler, so the unconditional
// `setOpen(false)` of a single-select commit cannot dismiss the popover.
inline: true,
open: true,
onOpenChange: () => {},
items: nodes,
inputValue: currentQuery,
onInputValueChange: setQuery,
maxHeight,
renderItem,
labels: cascaderLabels,
actions,
// The option service is the ONE filter when it owns the query.
...(preFiltered ? { filter: () => true } : null),
};
const cascaderProps: CascaderProps<FilterMenuMeta> = multiple
? {
...shared,
multiple: true,
value: selected,
onValueChange: (values: string[]) => onSelectionChange(values),
}
: {
...shared,
value: selected[0] ?? '',
onValueChange: (value: string) => onSelectionChange(value ? [value] : []),
};
return (
<Cascader {...cascaderProps}>
<CascaderPanel>
{/*
`searchable: false` hides the FIELD, never removes it: the input owns
focus and `aria-activedescendant`, so a menu without one has no
keyboard. The class goes on the nav so the strip's border goes too.
*/}
<CascaderNav
className={cn(
/* The nav's divider is `border-border/60` and the group separator
is a full-opacity `bg-border`; two strengths read as a mistake. */
'border-border',
!searchable && 'sr-only',
)}
>
<CascaderInput {...(autoFocusProps ?? {})} placeholder={searchPlaceholder ?? labels.searchOptions} aria-label={ariaLabel} />
</CascaderNav>
<CascaderEmpty>{state?.error ? labels.error : state?.loading ? labels.loading : labels.empty}</CascaderEmpty>
{/*
Plain rows, DELIBERATELY not `CascaderVirtualItems`: windowing stands
`FilterMenuPinKeeper` down. The long lists are async and PAGE 25.
*/}
<CascaderList
/**
* Real layout space around the group rule, which is absolutely
* positioned and adds no height. `renderItem` cannot reach the row's
* own box, and a spacer NODE would join the option ring.
*
* `:has()` is affordable here: scoped to this one list, a compound
* whose descendant exists on at most ONE row, and these menus render
* tens of rows rather than thousands.
*/
className="[&>[data-slot=cascader-item]:has([data-slot=filter-menu-divider])]:mt-2"
>
<CascaderItems />
</CascaderList>
<CascaderFooter />
<CascaderStatus />
{/*
Last, so its layout effect reads the reordered DOM after every row has
registered. Not mounted at all for a menu that cannot reorder.
*/}
{pinSelected && sortSelected !== 'snapshot' ? <FilterMenuPinKeeper order={partitioned.order} items={items} /> : null}
</CascaderPanel>
</Cascader>
);
}
/* -------------------------------------------------------------------------- */
/* Option based editors */
/* -------------------------------------------------------------------------- */
function OptionEditor<V, O>(props: FilterEditorProps<V, O> & { multiple: boolean }) {
const { multiple, options, labels, autoFocusProps, commit, cancel, onValueChange, value, field } = props;
const selected = React.useMemo(() => {
if (value === undefined || value === null) return [];
return (Array.isArray(value) ? value : [value]) as string[];
}, [value]);
const announce = React.useContext(FilterActionsContext)?.announce;
return (
/*
A DELIBERATELY narrow default: 12rem holds around 22 characters at every
style's row size. `field.className` lands LAST, so a consumer's `w-*` wins.
*/
<EditorPanel className={cn('w-48 min-w-0 gap-0 p-0', field.className)}>
<FilterMenu
items={options.items}
selected={selected}
multiple={multiple}
onSelectionChange={(raw) => {
/*
The ONE place the None rule is applied: every route into a selection
arrives here, so click and keyboard cannot disagree, and only the
editor can ANSWER it - `options.resolve` sees the schema and every
loaded page, where the menu holds only the rows on screen.
*/
const values = applyFilterExclusiveSelection(raw, selected, (value) => Boolean(options.resolve(value)?.exclusive));
/*
Identity is the test: the rule hands back `raw` itself unless it
intervened. Announced because nothing else reports it: focus never
moved, and nobody is on the rows that lost their check marks.
*/
if (values !== raw && announce) {
const arrived = values.find((entry) => !selected.includes(entry));
const cleared = raw.length - values.length;
if (arrived !== undefined && cleared > 0) {
announce(labels.exclusiveAnnouncement(options.resolve(arrived)?.label ?? arrived, cleared));
}
} else if (values === raw && raw.length > 1) {
/*
The hole in the rule, made LOUD. An unresolvable value is treated
as ordinary and cannot be told from an id whose label has not
arrived, so this warns rather than acts. Needs a SEEN None row.
*/
const hasNoneRow = options.items.some((item) => item.exclusive) || Boolean(field.options?.some((option) => option.exclusive));
const unresolved = hasNoneRow ? raw.find((entry) => options.resolve(entry) === undefined) : undefined;
if (unresolved !== undefined) {
warnFilterOnce(
`exclusive-unresolved:${field.id}`,
`field "${field.id}" has an exclusive option, but the value ` +
`"${unresolved}" resolves to no option, so the None rule ` +
`cannot tell whether it is the exclusive one and has left ` +
`it in place. Declare the exclusive option in the field's ` +
`\`options\` even when the rest of the list is async, or ` +
`cover stored values with \`resolveValues\`.`,
);
}
}
if (!multiple) {
const next = values[0];
// Base UI deselects the committed row; an empty filter is no gain.
if (next === undefined) {
cancel();
return;
}
onValueChange(next as V);
commit(next as V);
return;
}
onValueChange(values as V);
// Every toggle commits with the popover open: several picks, one gesture.
commit(values as V, { close: false });
}}
labels={labels}
ariaLabel={field.label}
searchable={field.searchable ?? true}
// Not a composed `Search ${label}...`: hardcoded English no `labels`
// override could reach, and lowercasing a label is locale-hostile.
searchPlaceholder={field.placeholder}
pinSelected={field.pinSelected ?? false}
sortSelected={field.sortSelected}
// `useFilterOptions` already applied the query, locally or server side.
preFiltered
query={options.query}
onQueryChange={options.setQuery}
state={options}
autoFocusProps={autoFocusProps}
/>
</EditorPanel>
);
}
export function FilterSelectEditor<V, O>(props: FilterEditorProps<V, O>) {
return <OptionEditor {...props} multiple={false} />;
}
export function FilterMultiSelectEditor<V, O>(props: FilterEditorProps<V, O>) {
return <OptionEditor {...props} multiple />;
}
/* -------------------------------------------------------------------------- */
/* Boolean */
/* -------------------------------------------------------------------------- */
/**
* Module level, so the menu's index is not rebuilt on every render. Not in
* `FilterLabels`: the chip's own display spells the same two words out.
*/
const BOOLEAN_ITEMS: FilterListItem[] = [
{ value: 'true', label: 'True' },
{ value: 'false', label: 'False' },
];
export function FilterBooleanEditor<V, O>({ value, onValueChange, commit, labels, autoFocusProps, field }: FilterEditorProps<V, O>) {
return (
// Two words, and `field.className` lands last so a consumer's `w-*` wins.
<EditorPanel className={cn('w-40 min-w-0 gap-0 p-0', field.className)}>
<FilterMenu
items={BOOLEAN_ITEMS}
selected={value === true ? ['true'] : value === false ? ['false'] : []}
onSelectionChange={(values) => {
/* Deselecting the committed row leaves nothing to filter on, so it is
a no-op rather than a commit of `false`. */
if (values.length === 0) return;
const next = (values[0] === 'true') as V;
onValueChange(next);
commit(next);
}}
labels={labels}
ariaLabel={field.label}
/* Two rows: a search over them is more chrome than list, but the
field is still rendered, hidden, because it owns the keyboard. */
searchable={false}
autoFocusProps={autoFocusProps}
/>
</EditorPanel>
);
}
/* -------------------------------------------------------------------------- */
/* Resolution */
/* -------------------------------------------------------------------------- */
export type { AnyFilterEditor, FilterEditorRegistry } from '@/registry/vcare/ui/filters/filters-types';
export const DEFAULT_FILTER_EDITORS: FilterEditorRegistry = {
text: FilterTextEditor,
number: FilterNumberEditor,
range: FilterRangeEditor,
select: FilterSelectEditor,
multiselect: FilterMultiSelectEditor,
boolean: FilterBooleanEditor,
};
/**
* Picks the editor for a (field, operator) pair: the field's own `editor`, then
* the operator's ARITY, then the field's `type`. Arity outranks type because
* "between" wants two boxes whatever the field said.
*/
export function resolveFilterEditor<V, O>(
field: FilterField<V, O>,
operator: FilterOperator | undefined,
editors: FilterEditorRegistry,
): AnyFilterEditor | undefined {
if (typeof field.editor === 'function') {
// The one place a consumer's typed editor meets the erased registry.
return field.editor as unknown as AnyFilterEditor;
}
if (typeof field.editor === 'string') {
const named = editors[field.editor];
if (named) return named;
}
const arity = operator?.arity ?? 'one';
if (arity === 'none') return undefined;
if (arity === 'range') return editors.range;
if (arity === 'many') {
// An option-backed field gets checkboxes; anything else receives an array.
if (field.options || field.loadOptions) return editors.multiselect;
}
return editors[field.type ?? 'text'] ?? editors.text;
}components/ui/filters/filters-i18n.tsx
import type { FilterDraftStep, FilterIssue, FilterIssueReason, FilterLabels } from '@/registry/vcare/ui/filters/filters-types';
/**
* The shipped English copy. `stepAnnouncement` (consumer-composed create
* wizard) and `showRecords` (a consumer's own panel heading) are unread by the
* shipped chrome and kept on purpose; do not prune them as dead keys.
*/
export const DEFAULT_FILTER_LABELS: FilterLabels = {
addFilter: 'Add filter',
advancedFilter: 'Advanced filter',
showRecords: 'In this view, show records',
builderEmpty: 'No filters yet',
builderEmptyHint: 'Add a filter to narrow down what you see.',
addCondition: 'Add filter',
addConditionGroup: 'Add group',
addToGroup: 'Add filter to this group',
removeGroup: 'Remove group',
wrapInGroup: 'Wrap in group',
ungroup: 'Ungroup',
moveToTopLevel: 'Move to top',
moveToGroup: (position) => `Move to group ${position}`,
reorder: 'Reorder',
reorderHint: 'Press Alt with Arrow Up or Arrow Down to reorder',
groupAll: 'All of the following are true...',
groupAny: 'Any of the following are true...',
groupPlaceholder: 'Drag filters here',
rowLabel: (condition, depth) => `${condition}, level ${depth}`,
groupLabel: (description, depth) => `${description} level ${depth}`,
groupAnnouncement: (added) => (added ? 'Group added' : 'Group removed'),
reorderAnnouncement: (label, position, total) => `${label} moved to position ${position} of ${total}`,
// Destination FIRST after the verb: it is the half a plain reorder cannot
// say and the half the user cannot see once the row has stopped moving.
// Position stays last, so this still ends on the "of N" a reorder ends on.
moveAnnouncement: (label, destination, position, total) => `${label} moved into ${destination}, position ${position} of ${total}`,
clearAll: 'Clear all',
groupMenu: 'Group options',
searchFields: 'Search attributes...',
searchOperators: 'Search operators...',
searchOptions: 'Search...',
back: 'Back',
clear: 'Clear',
apply: 'Apply',
discard: 'Discard changes',
empty: 'No results',
loading: 'Loading...',
loadingMore: 'Loading more...',
loadMore: 'Load more',
error: 'Could not load',
retry: 'Retry',
where: 'Where',
and: 'And',
or: 'Or',
combinator: 'Change combinator',
// The word first: it is what the control SAYS and what a truncated pill
// stops showing. The action follows, so the name still names an action.
combinatorLabel: (word) => `${word}, change combinator`,
duplicate: 'Duplicate',
negate: 'Negate',
convertToAdvanced: 'Advanced editor',
remove: 'Remove',
chipMenu: (fieldLabel) => `${fieldLabel} filter options`,
filtersLabel: 'Filters',
filterLabel: (condition) => condition,
readOnly: 'Read only. These filters cannot be changed.',
pathSeparator: ' > ',
valuePlaceholder: 'enter text...',
selectPlaceholder: 'Select...',
noValue: 'no value',
selectCondition: 'Select condition',
incomplete: 'incomplete filter',
branchAffordance: 'opens a list',
exclusiveHint: 'cannot be combined with the other options',
exclusiveAnnouncement: (label, cleared) =>
cleared === 1 ? `${label} selected. 1 other selection cleared.` : `${label} selected. ${cleared} other selections cleared.`,
itemCount: (count) => `${count} items`,
fieldsLabel: 'Attributes',
resultsAnnouncement: (count) => (count === 1 ? '1 result' : `${count} results`),
actionsLabel: 'Actions',
stepAnnouncement: (step, label) => {
if (step === 'field') return `Choose an attribute. ${label}`;
if (step === 'operator') return `Choose a condition for ${label}`;
return `Enter a value for ${label}`;
},
countAnnouncement: (count) => (count === 1 ? '1 filter applied' : `${count} filters applied`),
valueCount: (count) => `${count} selected`,
valueDetail: (summary, values) => `${summary}: ${values.join(', ')}`,
valueRange: (from, to) => `${from} to ${to}`,
rangeFrom: (fieldLabel) => `${fieldLabel} from`,
rangeTo: (fieldLabel) => `${fieldLabel} to`,
rangeSeparator: 'to',
negated: (operatorLabel) => `not ${operatorLabel}`,
issueOperator: 'Choose a condition',
issueValue: 'Enter a value',
issueRange: 'Enter both ends of the range',
issueRangeOrder: 'The end of the range comes before its start',
issueEmptyGroup: 'This group has no conditions yet',
// "Row", not "condition": an empty GROUP is counted here too and a group is
// not a condition. Rule and group divs alike carry `data-slot="filter-row"`.
issueSummary: (count) => (count === 1 ? '1 row needs attention' : `${count} rows need attention`),
};
/**
* Shallow merge over the defaults, like the cascader's. A deep merge would leak
* the default back into a replaced function-valued label for the arguments the
* consumer did not think about.
*/
export function resolveFilterLabels(labels?: Partial<FilterLabels>): FilterLabels {
if (!labels) return DEFAULT_FILTER_LABELS;
return { ...DEFAULT_FILTER_LABELS, ...labels };
}
/**
* The sentence for one issue. Takes the ISSUE, not just the reason: a field's
* `validate` supplies its own words, so `custom` has nothing to look up.
*/
export function filterIssueLabel(issue: Pick<FilterIssue, 'reason' | 'message'> | FilterIssueReason, labels: FilterLabels): string {
const reason = typeof issue === 'string' ? issue : issue.reason;
if (typeof issue !== 'string' && issue.message) return issue.message;
if (reason === 'missing-operator') return labels.issueOperator;
if (reason === 'incomplete-range') return labels.issueRange;
if (reason === 'reversed-range') return labels.issueRangeOrder;
if (reason === 'empty-group') return labels.issueEmptyGroup;
return labels.issueValue;
}
/** The search placeholder for a step's panel. */
export function stepPlaceholder(step: FilterDraftStep, labels: FilterLabels): string {
if (step === 'field') return labels.searchFields;
if (step === 'operator') return labels.searchOperators;
return labels.searchOptions;
}components/ui/filters/filters-lib.tsx
import { collapseCascaderPath } from '@/registry/vcare/ui/cascader/cascader-lib';
import type { CascaderCollapse } from '@/registry/vcare/ui/cascader/cascader-types';
import type { FilterField, FilterIndex, FilterOperator, FilterOption } from '@/registry/vcare/ui/filters/filters-types';
/* -------------------------------------------------------------------------- */
/* Menus */
/* -------------------------------------------------------------------------- */
/**
* One menu size for the chip's kebab and the builder's three menus, which draw
* the same rows. `w-max` OVERRIDES the shadcn content width, which pins to the
* anchor and hides horizontal overflow, so a menu hung off a 28px icon button
* CUT every longer row. Floor 128px, down from 224px: the rows run about 130px,
* and five of the eight styles already floor a dropdown there (luma, maia and
* sera sit at 192px). The 24rem cap stops a pathological label pushing the menu
* off the side of a phone. Past it a row truncates rather than wraps, since a
* wrapped row changes HEIGHT and would slide the destructive row under the
* pointer: `min-w-0` lets a row shrink below its content at all (a flex child's
* floor is its content otherwise) and the label span carries `truncate`, see
* `FILTER_MENU_LABEL_CLASS`.
*/
export const FILTER_MENU_CLASS = 'w-max min-w-32 max-w-[min(24rem,calc(100vw-2rem))] [&_[data-slot=dropdown-menu-item]]:min-w-0';
/**
* What a menu row's LABEL wears, and it has to be a real span: `text-overflow`
* needs a block container, not the anonymous flex item a bare text child is.
* `min-w-0` so the span can shrink below its own content.
*/
export const FILTER_MENU_LABEL_CLASS = 'min-w-0 truncate';
/**
* The FIELD PICKER's panel, shared by the Add filter popover and the advanced
* row's attribute cell so one schema is never drawn at two widths. `w-auto`
* grows to the longest row, so the 224px floor (down from 256px) only decides
* the reported case: a flat schema of short names in a mostly empty panel.
* Measured: 224px still clears the search input, the breadcrumb and a leaf
* row's icon-plus-label.
*/
export const FILTER_FIELD_PICKER_CLASS = 'w-auto min-w-56 p-0';
/* -------------------------------------------------------------------------- */
/* Paths */
/* -------------------------------------------------------------------------- */
/** Root key for `childrenOf`; a control char cannot collide with a field id. */
export const FILTER_ROOT_KEY = '\u0000root';
/** Separator between path segments in the flat map keys. */
const PATH_SEPARATOR = '\u0000';
export function joinFilterPath(path: readonly string[]): string {
return path.join(PATH_SEPARATOR);
}
export function splitFilterPath(key: string): string[] {
return key === '' ? [] : key.split(PATH_SEPARATOR);
}
/** The joined key of a path's parent, or `FILTER_ROOT_KEY` at the top level. */
export function parentFilterKey(path: readonly string[]): string {
return path.length <= 1 ? FILTER_ROOT_KEY : joinFilterPath(path.slice(0, -1));
}
/* -------------------------------------------------------------------------- */
/* Signature */
/* -------------------------------------------------------------------------- */
/**
* A content hash of the schema, used to skip a rebuild. Identity alone is
* useless: every block and example declares `fields` as an inline literal, so a
* memo keyed on the array misses on every parent render. Render props (`icon`,
* `renderValue`, a component-valued `editor`) are hashed by PRESENCE only,
* because inline JSX recreates them: swapping one's body keeps serving the
* previous field objects, so change a structural field or give `fields` a
* stable identity.
*/
export function computeFilterSchemaSignature<V, O>(fields: readonly FilterField<V, O>[]): string {
const parts: string[] = [];
const walk = (list: readonly FilterField<V, O>[], depth: number) => {
for (const field of list) {
parts.push(
depth +
':' +
field.id +
'|' +
(field.label ?? '') +
'|' +
(field.type ?? '') +
'|' +
(field.defaultOperator ?? '') +
'|' +
(field.column ?? '') +
'|' +
(field.selectable ? '1' : '0') +
(field.disabled ? '1' : '0') +
(field.icon ? '1' : '0') +
(field.renderValue ? '1' : '0') +
(field.loadOptions ? '1' : '0') +
(field.resolveValues ? '1' : '0') +
'|' +
(typeof field.editor === 'string' ? field.editor : field.editor ? 'fn' : '') +
'|' +
(field.keywords?.join(',') ?? '') +
'|' +
(field.count ?? '') +
'|' +
// Options are part of the shape, and `exclusive` rides along: it
// decides what a pick DOES, so turning it on must force a rebuild.
(field.options ? field.options.map((option) => option.value + '~' + option.label + (option.exclusive ? '~x' : '')).join(',') : '') +
'|' +
(Array.isArray(field.operators) ? field.operators.map((operator) => operator.value).join(',') : field.operators ? 'fn' : ''),
);
if (field.fields?.length) walk(field.fields, depth + 1);
}
};
walk(fields, 0);
return parts.join('\n');
}
/* -------------------------------------------------------------------------- */
/* Index */
/* -------------------------------------------------------------------------- */
const EMPTY_INDEX: FilterIndex<never, never> = {
byPath: new Map(),
childrenOf: new Map(),
parentOf: new Map(),
all: [],
roots: [],
signature: '',
};
/**
* Normalizes a field schema into flat maps. When `previous`'s signature
* matches, the PREVIOUS OBJECT is returned: an equal-but-new one would leave
* every downstream memo missing exactly as often as before. Duplicate sibling
* ids are ignored after the first, as the cascader does for node values, and
* `findFilterSchemaIssues` reports them in development.
*/
export function buildFilterIndex<V = unknown, O = unknown>(
fields: readonly FilterField<V, O>[],
previous?: FilterIndex<V, O> | null,
/** A signature the caller already computed, to avoid walking twice. */
precomputedSignature?: string,
): FilterIndex<V, O> {
const signature = precomputedSignature ?? computeFilterSchemaSignature(fields);
if (previous && previous.signature === signature) return previous;
if (fields.length === 0) {
return { ...(EMPTY_INDEX as unknown as FilterIndex<V, O>), signature };
}
const byPath = new Map<string, FilterField<V, O>>();
const childrenOf = new Map<string, FilterField<V, O>[]>();
const parentOf = new Map<string, string>();
const all: { field: FilterField<V, O>; path: string[] }[] = [];
const roots: FilterField<V, O>[] = [];
const walk = (list: readonly FilterField<V, O>[], parentPath: string[], parentKey: string) => {
const accepted: FilterField<V, O>[] = [];
const seen = new Set<string>();
for (const field of list) {
if (seen.has(field.id)) continue;
seen.add(field.id);
const path = [...parentPath, field.id];
const key = joinFilterPath(path);
if (byPath.has(key)) continue;
byPath.set(key, field);
parentOf.set(key, parentKey === FILTER_ROOT_KEY ? '' : parentKey);
all.push({ field, path });
accepted.push(field);
if (field.fields?.length) walk(field.fields, path, key);
}
childrenOf.set(parentKey, accepted);
if (parentKey === FILTER_ROOT_KEY) roots.push(...accepted);
};
walk(fields, [], FILTER_ROOT_KEY);
return { byPath, childrenOf, parentOf, all, roots, signature };
}
export function getFilterField<V, O>(index: FilterIndex<V, O>, path: readonly string[]): FilterField<V, O> | undefined {
return index.byPath.get(joinFilterPath(path));
}
/** The ancestor chain for a path, root first and the field itself last. */
export function getFilterFieldChain<V, O>(index: FilterIndex<V, O>, path: readonly string[]): FilterField<V, O>[] {
const chain: FilterField<V, O>[] = [];
for (let i = 1; i <= path.length; i++) {
const field = index.byPath.get(joinFilterPath(path.slice(0, i)));
if (!field) break;
chain.push(field);
}
return chain;
}
/** Child fields of a path. Pass an empty path for the root level. */
export function getFilterChildren<V, O>(index: FilterIndex<V, O>, path: readonly string[]): FilterField<V, O>[] {
const key = path.length === 0 ? FILTER_ROOT_KEY : joinFilterPath(path);
return index.childrenOf.get(key) ?? [];
}
export function isFilterBranch<V, O>(field: FilterField<V, O>): boolean {
return Boolean(field.fields?.length);
}
/**
* Whether a field DECLARES itself filterable on: leaves always, a branch only
* with `selectable`. The shipped pickers ignore it, see `isFilterFieldPickable`.
*/
export function isFilterFieldSelectable<V, O>(field: FilterField<V, O>): boolean {
if (field.disabled) return false;
return isFilterBranch(field) ? Boolean(field.selectable) : true;
}
/**
* Whether the SHIPPED pickers may commit a field: leaves only. A row that both
* drills in and commits cannot disambiguate a click - its chevron and child
* count promise "opens a list", so the press that opened it also filtered on
* the parent and dismissed the picker. `selectable` stays honoured by
* `isFilterFieldSelectable` for a chrome that separates the two.
*/
export function isFilterFieldPickable<V, O>(field: FilterField<V, O>): boolean {
if (field.disabled) return false;
return !isFilterBranch(field);
}
/** Trailing count for a branch row. */
export function getFilterFieldCount<V, O>(field: FilterField<V, O>): number {
return field.count ?? field.fields?.length ?? 0;
}
/** Renders a path as "Name > First" using the caller's separator. */
export function formatFilterPath<V, O>(index: FilterIndex<V, O>, path: readonly string[], separator: string): string {
const chain = getFilterFieldChain(index, path);
if (chain.length === 0) return path.join(separator);
return chain.map((field) => field.label).join(separator);
}
/** How a path is shortened; the cascader's own union, so the two cannot drift. */
export type FilterPathCollapse = CascaderCollapse;
export type FilterPathSegment<V = unknown, O = unknown> =
| { type: 'field'; field: FilterField<V, O> }
/** The run that was elided, kept so a host can surface it. */
| { type: 'ellipsis'; hidden: FilterField<V, O>[] };
/**
* Shortens an ancestor chain to at most `maxSegments` names, on the cascader's
* arithmetic so the chip's path and the builder's attribute cell cannot round
* differently. The adapter is POSITIONAL because a `FilterField`'s `id` is
* unique only among its siblings, so the index is the only key that survives a
* collapser keyed on `value`. Default `"none"`: no upgrade shortens a path.
*/
export function collapseFilterPath<V, O>(
chain: readonly FilterField<V, O>[],
options: { maxSegments?: number; collapse?: FilterPathCollapse } = {},
): FilterPathSegment<V, O>[] {
const segments = collapseCascaderPath(
chain.map((field, index) => ({ value: String(index), label: field.label })),
{ maxSegments: options.maxSegments, collapse: options.collapse ?? 'none' },
);
return segments.map((segment) =>
segment.type === 'node'
? { type: 'field' as const, field: chain[Number(segment.node.value)] }
: {
type: 'ellipsis' as const,
hidden: segment.hidden.map((node) => chain[Number(node.value)]),
},
);
}
/* -------------------------------------------------------------------------- */
/* Combinator */
/* -------------------------------------------------------------------------- */
export type FilterCombinatorSlot = 'where' | 'toggle' | 'echo';
/**
* Which of the three forms the combinator slot before rule `index` takes. A
* group has exactly ONE combinator, so only one slot may be interactive: three
* editable "and"s down a column would imply three independent choices.
*/
export function filterCombinatorSlot(index: number): FilterCombinatorSlot {
if (index === 0) return 'where';
return index === 1 ? 'toggle' : 'echo';
}
/* -------------------------------------------------------------------------- */
/* Matching */
/* -------------------------------------------------------------------------- */
/** `toLocaleLowerCase`, so Turkish dotted and dotless i fold as a reader expects. */
export function foldFilterText(text: string): string {
return text.toLocaleLowerCase();
}
export function normalizeFilterQuery(query: string): string {
return foldFilterText(query.trim());
}
/** Whether a field matches a normalized query, by label or keywords. */
export function matchesFilterQuery<V, O>(field: FilterField<V, O>, normalizedQuery: string): boolean {
if (normalizedQuery === '') return true;
if (foldFilterText(field.label).includes(normalizedQuery)) return true;
if (field.keywords) {
for (const keyword of field.keywords) {
if (foldFilterText(keyword).includes(normalizedQuery)) return true;
}
}
return false;
}
/**
* Filters one level, preserving input order. Unused here like
* `searchFilterDeep`: kept so a consumer's own picker need not re-implement the
* fold and the keyword matching.
*/
export function filterFilterLevel<V, O>(fields: readonly FilterField<V, O>[], normalizedQuery: string): FilterField<V, O>[] {
if (normalizedQuery === '') return fields as FilterField<V, O>[];
return fields.filter((field) => matchesFilterQuery(field, normalizedQuery));
}
/**
* Searches every SELECTABLE field at any depth, because a result the user
* cannot pick is a dead end. Unused here - the shipped picker is the cascader
* and delegates deep search to it - but it keeps a consumer's own picker from
* re-implementing the fold, the keyword matching and the selectable rule.
*/
export function searchFilterDeep<V, O>(
index: FilterIndex<V, O>,
normalizedQuery: string,
limit = 200,
): { field: FilterField<V, O>; path: string[] }[] {
if (normalizedQuery === '') return [];
const results: { field: FilterField<V, O>; path: string[] }[] = [];
for (const entry of index.all) {
if (results.length >= limit) break;
if (!isFilterFieldSelectable(entry.field)) continue;
if (matchesFilterQuery(entry.field, normalizedQuery)) results.push(entry);
}
return results;
}
/** Filters an option list by a normalized query, by label or keywords. */
export function filterFilterOptions<O>(options: readonly FilterOption<O>[], normalizedQuery: string): FilterOption<O>[] {
if (normalizedQuery === '') return options as FilterOption<O>[];
return options.filter((option) => {
if (foldFilterText(option.label).includes(normalizedQuery)) return true;
if (option.keywords) {
for (const keyword of option.keywords) {
if (foldFilterText(keyword).includes(normalizedQuery)) return true;
}
}
return false;
});
}
/* -------------------------------------------------------------------------- */
/* Exclusive options */
/* -------------------------------------------------------------------------- */
/**
* The None rule, as pure algebra over two selections: pick the `exclusive`
* option and it is the only pick, pick anything else and it goes. Written
* against the DELTA, not the result, which is what makes it total: an empty
* delta is a removal, including UNTICKING the exclusive row; an exclusive
* arrival is the whole answer; an ordinary arrival drops every exclusive value,
* restored ones included; both at once gives it to the LAST exclusive.
* `isExclusive` is a lookup, not an array, because a query hiding the None row
* while it stays SELECTED would answer "not exclusive" for the value the click
* must clear. Never applied on read - a saved view is the consumer's data - so
* it heals on the first ordinary pick, and only while `isExclusive` can ANSWER:
* a None row on a `loadOptions` field belongs in the static `options`.
*/
export function applyFilterExclusiveSelection(
next: readonly string[],
previous: readonly string[],
isExclusive: (value: string) => boolean,
): string[] {
const held = new Set(previous);
const added = next.filter((value) => !held.has(value));
if (added.length === 0) return next as string[];
let arrived: string | null = null;
for (const value of added) {
if (isExclusive(value)) arrived = value;
}
if (arrived !== null) return [arrived];
const kept = next.filter((value) => !isExclusive(value));
// The same array when nothing was exclusive, which is nearly every call: a
// fresh one would commit a new value on every toggle of an ordinary row.
return kept.length === next.length ? (next as string[]) : kept;
}
/* -------------------------------------------------------------------------- */
/* Ids */
/* -------------------------------------------------------------------------- */
/**
* Builds a deterministic id generator. `Date.now()` and `Math.random()`, as the
* old `createFilter` used, give the server and the client different ids for the
* same query, so any page shipping default filters hydrated mismatched.
*/
export function createFilterIdFactory(seed: string): () => string {
let counter = 0;
return () => {
counter += 1;
return `${seed}${counter}`;
};
}
/* -------------------------------------------------------------------------- */
/* Development checks */
/* -------------------------------------------------------------------------- */
const warned = new Set<string>();
/** Warns once per key. Never throws, and is a no-op in production. */
export function warnFilterOnce(key: string, message: string): void {
if (process.env.NODE_ENV === 'production') return;
if (warned.has(key)) return;
warned.add(key);
console.warn(`[filters] ${message}`);
}
/** Clears the warn-once memory. For tests. */
export function resetFilterWarnings(): void {
warned.clear();
}
export interface FilterSchemaIssues {
/** Ids that are empty, or that collide with a sibling. */
duplicatePaths: string[];
emptyIds: string[];
/** Branches that declare `selectable` but hold no children. */
emptyBranches: string[];
/** Fields whose `defaultOperator` is not in their operator list. */
unknownDefaultOperators: string[];
}
/** Reported, never thrown: a bad schema must degrade, not blank the page. */
export function findFilterSchemaIssues<V, O>(
fields: readonly FilterField<V, O>[],
resolveOperators: (field: FilterField<V, O>) => FilterOperator[],
): FilterSchemaIssues {
const duplicatePaths: string[] = [];
const emptyIds: string[] = [];
const emptyBranches: string[] = [];
const unknownDefaultOperators: string[] = [];
const walk = (list: readonly FilterField<V, O>[], parentPath: string[]) => {
const seen = new Set<string>();
for (const field of list) {
const label = [...parentPath, field.id].join('.');
if (!field.id) emptyIds.push(label);
else if (seen.has(field.id)) duplicatePaths.push(label);
seen.add(field.id);
if (field.selectable && field.fields && field.fields.length === 0) {
emptyBranches.push(label);
}
if (field.defaultOperator) {
const operators = resolveOperators(field);
if (!operators.some((op) => op.value === field.defaultOperator)) {
unknownDefaultOperators.push(`${label} -> ${field.defaultOperator}`);
}
}
if (field.fields?.length) walk(field.fields, [...parentPath, field.id]);
}
};
walk(fields, []);
return { duplicatePaths, emptyIds, emptyBranches, unknownDefaultOperators };
}components/ui/filters/filters-operators.tsx
import type { FilterField, FilterOperator, FilterValueType } from '@/registry/vcare/ui/filters/filters-types';
/**
* Every operator label, keyed by value. Split from `FilterLabels`: operator
* wording is reworded per domain, chrome copy is translated once per app.
*/
export type FilterOperatorLabels = Record<string, string>;
export const DEFAULT_FILTER_OPERATOR_LABELS: FilterOperatorLabels = {
contains: 'contains',
not_contains: 'does not contain',
starts_with: 'starts with',
ends_with: 'ends with',
is: 'is',
is_not: 'is not',
is_any_of: 'is any of',
is_none_of: 'is none of',
has_any_of: 'has any of',
has_all_of: 'has all of',
has_none_of: 'has none of',
eq: 'equals',
neq: 'does not equal',
gt: 'is greater than',
gte: 'is greater than or equal to',
lt: 'is less than',
lte: 'is less than or equal to',
between: 'is between',
not_between: 'is not between',
is_before: 'is before',
is_after: 'is after',
is_on_or_before: 'is on or before',
is_on_or_after: 'is on or after',
empty: 'is empty',
not_empty: 'is not empty',
};
/**
* Operator catalog per value type: value, arity, inverse, labels resolved at
* build time so translating one operator never restates the catalog. `arity`
* of "none" drops the chip's value segment and the wizard's value step, in a
* consumer's own `operators` array as much as in this catalog.
*/
const CATALOG: Record<FilterValueType, { value: string; arity?: FilterOperator['arity']; inverse?: string }[]> = {
text: [
{ value: 'contains', inverse: 'not_contains' },
{ value: 'not_contains', inverse: 'contains' },
{ value: 'starts_with' },
{ value: 'ends_with' },
{ value: 'is', inverse: 'is_not' },
{ value: 'is_not', inverse: 'is' },
{ value: 'empty', arity: 'none', inverse: 'not_empty' },
{ value: 'not_empty', arity: 'none', inverse: 'empty' },
],
number: [
{ value: 'eq', inverse: 'neq' },
{ value: 'neq', inverse: 'eq' },
{ value: 'gt', inverse: 'lte' },
{ value: 'gte', inverse: 'lt' },
{ value: 'lt', inverse: 'gte' },
{ value: 'lte', inverse: 'gt' },
{ value: 'between', arity: 'range', inverse: 'not_between' },
{ value: 'not_between', arity: 'range', inverse: 'between' },
{ value: 'empty', arity: 'none', inverse: 'not_empty' },
{ value: 'not_empty', arity: 'none', inverse: 'empty' },
],
range: [
{ value: 'between', arity: 'range', inverse: 'not_between' },
{ value: 'not_between', arity: 'range', inverse: 'between' },
{ value: 'empty', arity: 'none', inverse: 'not_empty' },
{ value: 'not_empty', arity: 'none', inverse: 'empty' },
],
select: [
{ value: 'is', inverse: 'is_not' },
{ value: 'is_not', inverse: 'is' },
{ value: 'is_any_of', arity: 'many', inverse: 'is_none_of' },
{ value: 'is_none_of', arity: 'many', inverse: 'is_any_of' },
{ value: 'empty', arity: 'none', inverse: 'not_empty' },
{ value: 'not_empty', arity: 'none', inverse: 'empty' },
],
multiselect: [
{ value: 'has_any_of', arity: 'many', inverse: 'has_none_of' },
{ value: 'has_all_of', arity: 'many' },
{ value: 'has_none_of', arity: 'many', inverse: 'has_any_of' },
{ value: 'empty', arity: 'none', inverse: 'not_empty' },
{ value: 'not_empty', arity: 'none', inverse: 'empty' },
],
boolean: [
{ value: 'is', inverse: 'is_not' },
{ value: 'is_not', inverse: 'is' },
{ value: 'empty', arity: 'none', inverse: 'not_empty' },
{ value: 'not_empty', arity: 'none', inverse: 'empty' },
],
};
export const DEFAULT_FILTER_VALUE_TYPE: FilterValueType = 'text';
/**
* Builds the operator catalog for one set of labels. Callers memoize on the
* label object: the old primitive built its equivalent inside
* `getOperatorsForField`, keyed on a `values` array that was fresh after every
* filter update, so every miss reallocated four arrays of 27 objects each.
*/
export function createFilterOperators(labels: FilterOperatorLabels): Record<FilterValueType, FilterOperator[]> {
const built = {} as Record<FilterValueType, FilterOperator[]>;
for (const type of Object.keys(CATALOG) as FilterValueType[]) {
built[type] = CATALOG[type].map((entry) => ({
value: entry.value,
label: labels[entry.value] ?? entry.value,
arity: entry.arity ?? 'one',
inverse: entry.inverse,
}));
}
return built;
}
export const DEFAULT_FILTER_OPERATORS: Record<FilterValueType, FilterOperator[]> = createFilterOperators(DEFAULT_FILTER_OPERATOR_LABELS);
/**
* The operators for a field: its own `operators` wins, array or function,
* otherwise the catalog entry for its `type`. No implicit select to multiselect
* promotion by selection count: that changed the list as the user picked.
*/
export function resolveFilterOperators<V, O>(
field: FilterField<V, O>,
catalog: Record<FilterValueType, FilterOperator[]> = DEFAULT_FILTER_OPERATORS,
): FilterOperator[] {
if (typeof field.operators === 'function') return field.operators(field);
if (field.operators) return field.operators;
return catalog[field.type ?? DEFAULT_FILTER_VALUE_TYPE] ?? catalog.text;
}
export function visibleFilterOperators(operators: readonly FilterOperator[]): FilterOperator[] {
return operators.filter((operator) => !operator.hidden);
}
export function getFilterOperator(operators: readonly FilterOperator[], value: string | null | undefined): FilterOperator | undefined {
if (!value) return undefined;
return operators.find((operator) => operator.value === value);
}
export function getFilterArity(operator: FilterOperator | undefined): FilterOperator['arity'] {
return operator?.arity ?? 'one';
}
export function operatorTakesValue(operator: FilterOperator | undefined): boolean {
return getFilterArity(operator) !== 'none';
}
/**
* The operator a field starts with: `defaultOperator` when it names one the
* field offers, otherwise the first visible operator. Falling back rather than
* trusting the schema keeps the rule out of a state its own list cannot show.
*/
export function getDefaultFilterOperator<V, O>(field: FilterField<V, O>, operators: readonly FilterOperator[]): string | null {
if (field.defaultOperator) {
const named = getFilterOperator(operators, field.defaultOperator);
if (named) return named.value;
}
const visible = visibleFilterOperators(operators);
return visible[0]?.value ?? operators[0]?.value ?? null;
}
/**
* Negating a rule: swap to the declared `inverse` so the chip reads "does not
* contain", else toggle `negated` so Negate still works without an inverse.
*/
export function negateFilterOperator(
operator: FilterOperator | undefined,
operators: readonly FilterOperator[],
negated: boolean | undefined,
): { operator: string | null; negated: boolean } {
if (operator?.inverse) {
const inverse = getFilterOperator(operators, operator.inverse);
if (inverse) return { operator: inverse.value, negated: Boolean(negated) };
}
return { operator: operator?.value ?? null, negated: !negated };
}
/**
* Reshapes a value when arity changes: widening "is" to "is any of" keeps what
* the user picked, narrowing keeps the first of them, `"none"` always drops it.
*/
export function coerceFilterValue(value: unknown, from: FilterOperator | undefined, to: FilterOperator | undefined): unknown {
const nextArity = getFilterArity(to);
if (nextArity === 'none') return undefined;
if (value === undefined || value === null) return value;
const previousArity = getFilterArity(from);
if (previousArity === nextArity) return value;
const asArray = Array.isArray(value) ? value : [value];
if (nextArity === 'many') return asArray;
if (nextArity === 'one') return asArray[0];
if (nextArity === 'range') {
return [asArray[0], asArray[1]] as [unknown, unknown];
}
return value;
}components/ui/filters/filters-query.tsx
import type {
FilterCombinator,
FilterGroupNode,
FilterIssue,
FilterNode,
FilterOperator,
FilterQuery,
FilterRule,
} from '@/registry/vcare/ui/filters/filters-types';
export function isFilterRule<V>(node: FilterNode<V>): node is FilterRule<V> {
return node.type === 'rule';
}
export function isFilterGroup<V>(node: FilterNode<V>): node is FilterGroupNode<V> {
return node.type === 'group';
}
/**
* A rule. `id` is passed in, never generated here: a non-deterministic value in
* a pure function broke hydration. Callers use `createFilterIdFactory`.
*/
export function createFilterRule<V = unknown>(input: { id: string; path: string[]; operator: string; value?: V; negated?: boolean }): FilterRule<V> {
const rule: FilterRule<V> = {
id: input.id,
type: 'rule',
path: input.path,
operator: input.operator,
value: input.value,
};
if (input.negated) rule.negated = true;
return rule;
}
export function createFilterGroup<V = unknown>(input: { id: string; combinator?: FilterCombinator; rules?: FilterNode<V>[] }): FilterGroupNode<V> {
return {
id: input.id,
type: 'group',
combinator: input.combinator ?? 'and',
rules: input.rules ?? [],
};
}
/** An empty query. The root is always a group, never a bare array. */
export function createFilterQuery<V = unknown>(rules: FilterNode<V>[] = [], combinator: FilterCombinator = 'and', id = 'root'): FilterQuery<V> {
return { id, type: 'group', combinator, rules };
}
/** Every rule in the tree, depth first. Groups are flattened away. */
export function flattenFilterRules<V>(query: FilterQuery<V>): FilterRule<V>[] {
const out: FilterRule<V>[] = [];
const walk = (node: FilterNode<V>) => {
if (isFilterRule(node)) {
out.push(node);
return;
}
for (const child of node.rules) walk(child);
};
walk(query);
return out;
}
/**
* One rule, flattened for a predicate. `values` is always an array even though
* `FilterRule.value` is singular, so no caller re-derives arity.
*/
export interface FilterCondition {
/** Full field path, `["name", "first"]`. */
path: string[];
/** First path segment, for the common flat-schema case. */
field: string;
operator: string;
/** `[]` for an operator that takes no value. */
values: unknown[];
negated: boolean;
}
/**
* Whether a rule says anything yet. A rule exists as soon as an attribute is
* picked, so `operator: ""` is a real state: `flattenFilterConditions` leaves
* it out, `countFilterRules` still counts it, and `collectFilterIssues` reports
* it as `missing-operator`.
*/
export function isFilterRuleComplete<V>(rule: FilterRule<V>): boolean {
return rule.operator !== '';
}
/**
* Flattens a query to conditions. Lossy: safe only when the query is flat or
* every group shares the root's combinator. Read `query.combinator` and walk
* the tree yourself for anything else. Incomplete rules are left out.
*/
export function flattenFilterConditions<V>(query: FilterQuery<V>): FilterCondition[] {
return flattenFilterRules(query)
.filter(isFilterRuleComplete)
.map((rule) => ({
path: rule.path,
field: rule.path[0],
operator: rule.operator,
values: rule.value === undefined || rule.value === null ? [] : Array.isArray(rule.value) ? (rule.value as unknown[]) : [rule.value],
negated: Boolean(rule.negated),
}));
}
/** How many rules the query holds, at any depth. */
export function countFilterRules<V>(query: FilterQuery<V>): number {
let count = 0;
const walk = (node: FilterNode<V>) => {
if (isFilterRule(node)) {
count += 1;
return;
}
for (const child of node.rules) walk(child);
};
walk(query);
return count;
}
/** Whether the query would match everything. */
export function isFilterQueryEmpty<V>(query: FilterQuery<V>): boolean {
return countFilterRules(query) === 0;
}
/**
* How an arity is answered for one rule. The caller resolves it, since arity
* lives on the FIELD's operator list. `null` is a rule it cannot judge.
*/
export type FilterArityResolver<V> = (rule: FilterRule<V>) => FilterOperator['arity'] | null;
/** Runs a field's own `validate`. A resolver like `arityOf`: no schema here. */
export type FilterValidateResolver<V> = (rule: FilterRule<V>) => string | null | undefined | false;
/** A value slot the user has not filled in. `false` and `0` are values. */
function isBlankFilterValue(value: unknown): boolean {
return value === undefined || value === null || value === '';
}
/**
* Compares two range bounds, or gives up. Numbers, dates and ISO strings only:
* inventing an order for a range of colour names would flag a correct filter as
* reversed. `Date.parse` must parse BOTH strings before they are compared.
*/
function compareFilterBounds(from: unknown, to: unknown): number | null {
if (typeof from === 'number' && typeof to === 'number') {
return Number.isNaN(from) || Number.isNaN(to) ? null : from - to;
}
if (from instanceof Date && to instanceof Date) {
const a = from.getTime();
const b = to.getTime();
return Number.isNaN(a) || Number.isNaN(b) ? null : a - b;
}
if (typeof from === 'string' && typeof to === 'string') {
const a = Date.parse(from);
const b = Date.parse(to);
return Number.isNaN(a) || Number.isNaN(b) ? null : a - b;
}
return null;
}
/**
* Every reason a query cannot be run as written, in document order: the five
* ways this builder can hold a condition that SILENTLY does the wrong thing.
* `missing-operator` and `empty-group` carry no predicate and are dropped by
* `flattenFilterConditions`; `missing-value` reaches the consumer with a
* `values` array that is empty or all blank, which most backends read as
* "match nothing"; `incomplete-range` is the same for a range and often
* arrives with one bound FILLED, so an emptiness check will not catch it;
* `reversed-range` is legal and matches nothing anywhere. A group of exactly
* ONE node is NOT an issue (it is what "Convert to group" produces), and the
* root is exempt from `empty-group`.
*/
export function collectFilterIssues<V>(
query: FilterQuery<V>,
arityOf: FilterArityResolver<V>,
validateOf?: FilterValidateResolver<V>,
): FilterIssue[] {
const issues: FilterIssue[] = [];
const visit = (group: FilterGroupNode<V>, isRoot: boolean) => {
if (!isRoot && group.rules.length === 0) {
issues.push({
nodeId: group.id,
column: 'group',
reason: 'empty-group',
});
}
for (const child of group.rules) {
if (isFilterGroup(child)) {
visit(child, false);
continue;
}
// Asked FIRST: `null` means the caller cannot judge this rule at all, so
// even `missing-operator` would point at a control that is not on screen.
const arity = arityOf(child);
if (arity === null) continue;
if (!isFilterRuleComplete(child)) {
issues.push({
nodeId: child.id,
column: 'operator',
reason: 'missing-operator',
});
continue;
}
if (arity === 'none') continue;
const values = child.value === undefined || child.value === null ? [] : Array.isArray(child.value) ? (child.value as unknown[]) : [child.value];
if (arity === 'range') {
if (values.length < 2 || isBlankFilterValue(values[0]) || isBlankFilterValue(values[1])) {
issues.push({
nodeId: child.id,
column: 'value',
reason: 'incomplete-range',
});
continue;
}
const order = compareFilterBounds(values[0], values[1]);
if (order !== null && order > 0) {
issues.push({
nodeId: child.id,
column: 'value',
reason: 'reversed-range',
});
}
continue;
}
// `many` and `one` collapse here: both are unsatisfied by an empty list,
// and `one` normalises to a single-element list above.
if (values.length === 0 || values.every(isBlankFilterValue)) {
issues.push({
nodeId: child.id,
column: 'value',
reason: 'missing-value',
});
continue;
}
// LAST, and only on a rule the primitive is already happy with: stacking
// a second message on one cell breaks the one-issue-per-node shape.
const message = validateOf?.(child);
if (message) {
issues.push({
nodeId: child.id,
column: 'value',
reason: 'custom',
message,
});
}
}
};
visit(query, true);
return issues;
}
/** Locates a node and its parent. Returns null when the id is unknown. */
export function findFilterNode<V>(
query: FilterQuery<V>,
id: string,
): {
node: FilterNode<V>;
parent: FilterGroupNode<V> | null;
index: number;
} | null {
if (query.id === id) return { node: query, parent: null, index: -1 };
const walk = (
group: FilterGroupNode<V>,
): {
node: FilterNode<V>;
parent: FilterGroupNode<V>;
index: number;
} | null => {
for (let i = 0; i < group.rules.length; i++) {
const child = group.rules[i];
if (child.id === id) return { node: child, parent: group, index: i };
if (isFilterGroup(child)) {
const found = walk(child);
if (found) return found;
}
}
return null;
};
return walk(query);
}
/** The rule with this id, or null when the id names a group or is unknown. */
export function findFilterRule<V>(query: FilterQuery<V>, id: string): FilterRule<V> | null {
const found = findFilterNode(query, id);
if (!found || !isFilterRule(found.node)) return null;
return found.node;
}
/**
* Rebuilds the tree, applying `transform` to the group holding `id`. An
* unchanged subtree comes back BY IDENTITY, so `React.memo` holds for all but
* the moved chip. Tests assert it with `toBe`. `removeFilterNode` and
* `detachFilterNode` drop children rather than replace a group, so they
* hand-roll the same identity-preserving walk.
*/
function rewriteGroup<V>(
group: FilterGroupNode<V>,
shouldRewrite: (group: FilterGroupNode<V>) => boolean,
transform: (group: FilterGroupNode<V>) => FilterGroupNode<V>,
): FilterGroupNode<V> {
if (shouldRewrite(group)) return transform(group);
let changed = false;
const rules = group.rules.map((child) => {
if (!isFilterGroup(child)) return child;
const next = rewriteGroup(child, shouldRewrite, transform);
if (next !== child) changed = true;
return next;
});
return changed ? { ...group, rules } : group;
}
/** Replaces a rule's fields. Unknown ids return the query unchanged. */
export function updateFilterRule<V>(query: FilterQuery<V>, id: string, updates: Partial<Omit<FilterRule<V>, 'id' | 'type'>>): FilterQuery<V> {
return rewriteGroup(
query,
(group) => group.rules.some((child) => child.id === id && isFilterRule(child)),
(group) => ({
...group,
rules: group.rules.map((child) => (child.id === id && isFilterRule(child) ? { ...child, ...updates } : child)),
}),
) as FilterQuery<V>;
}
/**
* Removes a node, plus any group it empties, all the way up (not the root): an
* empty group is invisible in the flat UI yet still compiles to parentheses.
*/
export function removeFilterNode<V>(query: FilterQuery<V>, id: string): FilterQuery<V> {
const prune = (group: FilterGroupNode<V>): FilterGroupNode<V> => {
let changed = false;
const rules: FilterNode<V>[] = [];
for (const child of group.rules) {
if (child.id === id) {
changed = true;
continue;
}
if (isFilterGroup(child)) {
const next = prune(child);
if (next !== child) changed = true;
if (next.rules.length === 0) continue;
rules.push(next);
continue;
}
rules.push(child);
}
return changed ? { ...group, rules } : group;
};
return prune(query) as FilterQuery<V>;
}
/** Appends a node to a group, defaulting to the root. */
export function insertFilterNode<V>(query: FilterQuery<V>, node: FilterNode<V>, parentId?: string, index?: number): FilterQuery<V> {
const targetId = parentId ?? query.id;
return rewriteGroup(
query,
(group) => group.id === targetId,
(group) => {
const rules = [...group.rules];
const at = index === undefined ? rules.length : Math.max(0, Math.min(index, rules.length));
rules.splice(at, 0, node);
return { ...group, rules };
},
) as FilterQuery<V>;
}
/**
* A deep copy under fresh ids, the whole way down: children keeping their old
* ids would give two live nodes one id, and every lookup here is by id.
*/
function cloneFilterNode<V>(node: FilterNode<V>, nextId: () => string): FilterNode<V> {
return isFilterRule(node)
? { ...node, id: nextId() }
: {
...node,
id: nextId(),
rules: node.rules.map((child) => cloneFilterNode(child, nextId)),
};
}
/** Copies a node in beside the original. */
export function duplicateFilterNode<V>(query: FilterQuery<V>, id: string, nextId: () => string): FilterQuery<V> {
const found = findFilterNode(query, id);
if (!found || !found.parent) return query;
return insertFilterNode(query, cloneFilterNode(found.node, nextId), found.parent.id, found.index + 1);
}
export function setFilterCombinator<V>(query: FilterQuery<V>, groupId: string, combinator: FilterCombinator): FilterQuery<V> {
return rewriteGroup(
query,
(group) => group.id === groupId,
(group) => (group.combinator === combinator ? group : { ...group, combinator }),
) as FilterQuery<V>;
}
export function toggleFilterCombinator<V>(query: FilterQuery<V>, groupId: string): FilterQuery<V> {
const found = findFilterNode(query, groupId);
if (!found || !isFilterGroup(found.node)) return query;
return setFilterCombinator(query, groupId, found.node.combinator === 'and' ? 'or' : 'and');
}
/** Moves a node within its own group. Out of range moves are no-ops. */
export function moveFilterNode<V>(query: FilterQuery<V>, id: string, delta: number): FilterQuery<V> {
const found = findFilterNode(query, id);
if (!found || !found.parent) return query;
const from = found.index;
const to = from + delta;
if (to < 0 || to >= found.parent.rules.length || delta === 0) return query;
return rewriteGroup(
query,
(group) => group.id === found.parent!.id,
(group) => {
const rules = [...group.rules];
const [moved] = rules.splice(from, 1);
rules.splice(to, 0, moved);
return { ...group, rules };
},
) as FilterQuery<V>;
}
/** Whether `id` names `node` itself or anything beneath it. */
function containsFilterNode<V>(node: FilterNode<V>, id: string): boolean {
if (node.id === id) return true;
if (isFilterRule(node)) return false;
return node.rules.some((child) => containsFilterNode(child, id));
}
/**
* Removes a node WITHOUT pruning what it empties. A move cannot reuse
* `removeFilterNode`: it would delete the group the drop is aimed at.
*/
function detachFilterNode<V>(group: FilterGroupNode<V>, id: string): FilterGroupNode<V> {
let changed = false;
const rules: FilterNode<V>[] = [];
for (const child of group.rules) {
if (child.id === id) {
changed = true;
continue;
}
if (isFilterGroup(child)) {
const next = detachFilterNode(child, id);
if (next !== child) changed = true;
rules.push(next);
continue;
}
rules.push(child);
}
return changed ? { ...group, rules } : group;
}
/**
* Moves a node into another group, at an index: the cross-parent form of
* `moveFilterNode`, which only reorders within one parent. Refuses a group into
* itself or a descendant, which would leave a cycle, and refuses the root.
*/
export function moveFilterNodeTo<V>(query: FilterQuery<V>, id: string, parentId: string, index: number): FilterQuery<V> {
const found = findFilterNode(query, id);
if (!found || !found.parent) return query;
if (containsFilterNode(found.node, parentId)) return query;
const destination = findFilterNode(query, parentId);
if (!destination || !isFilterGroup(destination.node)) return query;
// Within one parent the node's own slot disappears when it detaches, so
// indexes after it shift down by one: without this a drag down is a no-op.
const sameParent = found.parent.id === parentId;
const target = sameParent && found.index < index ? index - 1 : index;
if (sameParent && target === found.index) return query;
return insertFilterNode(detachFilterNode(query, id), found.node, parentId, target);
}
/**
* Copies a node into a group at a position: the Alt path of the drag layer. Not
* `duplicateFilterNode` then `moveFilterNodeTo`, which emits two queries for one
* gesture and needs the id the first step minted and never returned. The clone
* is taken BEFORE the insert, so copying a group into itself stays finite.
*/
export function copyFilterNodeTo<V>(query: FilterQuery<V>, id: string, parentId: string, index: number, nextId: () => string): FilterQuery<V> {
const found = findFilterNode(query, id);
if (!found || !found.parent) return query;
const destination = findFilterNode(query, parentId);
if (!destination || !isFilterGroup(destination.node)) return query;
return insertFilterNode(query, cloneFilterNode(found.node, nextId), parentId, index);
}
/**
* Wraps a node in a new group: the "Wrap in condition group" action, and the
* keyboard path to nesting for a user who cannot drag.
*/
export function wrapFilterNodeInGroup<V>(query: FilterQuery<V>, id: string, groupId: string, combinator: FilterCombinator = 'or'): FilterQuery<V> {
const found = findFilterNode(query, id);
if (!found || !found.parent) return query;
return rewriteGroup(
query,
(group) => group.id === found.parent!.id,
(group) => ({
...group,
rules: group.rules.map((child) => (child.id === id ? createFilterGroup<V>({ id: groupId, combinator, rules: [child] }) : child)),
}),
) as FilterQuery<V>;
}
/**
* Dissolves a group into its parent, splicing its rules in at the position the
* group held so wrap and unwrap round-trip. The root, a rule id and an unknown
* id each return the query unchanged.
*/
export function unwrapFilterGroup<V>(query: FilterQuery<V>, groupId: string): FilterQuery<V> {
if (query.id === groupId) return query;
const found = findFilterNode(query, groupId);
if (!found || !found.parent || !isFilterGroup(found.node)) return query;
const dissolved = found.node;
return rewriteGroup(
query,
(group) => group.id === found.parent!.id,
(group) => {
const rules = [...group.rules];
rules.splice(found.index, 1, ...dissolved.rules);
return { ...group, rules };
},
) as FilterQuery<V>;
}
/** Empties the query, keeping the root's identity fields. */
export function clearFilterQuery<V>(query: FilterQuery<V>): FilterQuery<V> {
return query.rules.length === 0 ? query : { ...query, rules: [] };
}
/**
* Drops empty groups and collapses a group whose only child is a group. Not
* automatic: a user mid-edit may hold an almost-empty group. Call on persist.
*/
export function pruneFilterQuery<V>(query: FilterQuery<V>): FilterQuery<V> {
const prune = (node: FilterNode<V>): FilterNode<V> | null => {
if (isFilterRule(node)) return node;
const rules: FilterNode<V>[] = [];
for (const child of node.rules) {
const next = prune(child);
if (next) rules.push(next);
}
if (rules.length === 0) return null;
if (rules.length === 1 && isFilterGroup(rules[0])) return rules[0];
return { ...node, rules };
};
const rules: FilterNode<V>[] = [];
for (const child of query.rules) {
const next = prune(child);
if (next) rules.push(next);
}
return { ...query, rules };
}components/ui/filters/filters-types.tsx
import type * as React from 'react';
/* -------------------------------------------------------------------------- */
/* Query tree */
/* -------------------------------------------------------------------------- */
export type FilterCombinator = 'and' | 'or';
/**
* One condition. `path` maps one to one onto the cascader's `details.path`, so
* a field selection commits untranslated. `value` is SINGULAR and the
* operator's `arity` decides its shape: `"many"` holds an array, `"range"` a
* tuple, `"none"` undefined.
*/
export interface FilterRule<V = unknown> {
id: string;
type: 'rule';
/** Field path, root first. `["name", "first"]` for a nested attribute. */
path: string[];
operator: string;
value: V | undefined;
/** Flips the meaning in place. Set by Negate when there is no `inverse`. */
negated?: boolean;
}
/** Rules under one combinator; nests, so nesting is never a later break. */
export interface FilterGroupNode<V = unknown> {
id: string;
type: 'group';
combinator: FilterCombinator;
rules: FilterNode<V>[];
}
export type FilterNode<V = unknown> = FilterRule<V> | FilterGroupNode<V>;
/** A whole query. Always a group, so flat and nested are one code path. */
export type FilterQuery<V = unknown> = FilterGroupNode<V>;
export type FilterChangeReason = 'add' | 'update' | 'remove' | 'duplicate' | 'negate' | 'reorder' | 'combinator' | 'clear';
/** Second argument to `onQueryChange`, so nobody has to diff two trees. */
export interface FilterChangeDetails<V = unknown, O = unknown> {
reason: FilterChangeReason;
/** The rule that changed, or null for whole-query changes like `clear`. */
rule: FilterRule<V> | null;
/** The field the rule points at, resolved. Null when the path is unknown. */
field: FilterField<V, O> | null;
}
/* -------------------------------------------------------------------------- */
/* Operators */
/* -------------------------------------------------------------------------- */
/**
* How many values an operator takes. Answers "does this need a value editor"
* for every operator, a consumer's own included, in place of the hardcoded
* `operator === "empty"` checks it replaced.
*/
export type FilterOperatorArity = 'none' | 'one' | 'many' | 'range';
export interface FilterOperator {
value: string;
label: string;
/** Defaults to `"one"`. */
arity?: FilterOperatorArity;
/** The opposite operator. Negate flips to it, else sets `rule.negated`. */
inverse?: string;
/** Hidden from the operator list but still valid in a restored query. */
hidden?: boolean;
}
/* -------------------------------------------------------------------------- */
/* Fields */
/* -------------------------------------------------------------------------- */
/**
* Which built-in editor a field uses by DEFAULT: `editor` overrides it, and an
* operator may override both. No date type on purpose - every product wants a
* different date control, and a built-in one would add a calendar dependency to
* every install, so a date ships as an `editor`.
*/
export type FilterValueType = 'text' | 'number' | 'range' | 'select' | 'multiselect' | 'boolean';
export interface FilterOption<O = unknown> {
value: string;
label: string;
icon?: React.ReactNode;
description?: string;
keywords?: string[];
disabled?: boolean;
/**
* The row that means NONE OF THE ABOVE: Unassigned, No label, No due date.
* Picking it clears every other pick and picking anything else clears it, and
* it is drawn apart under a rule of its own, because a list that wipes a
* selection must not look like one that does not; hide that line with
* `"[&_[data-slot=filter-menu-divider]]:hidden"`. Applied under EVERY
* operator, negative ones included. The value must be RESOLVABLE, since the
* rule runs through the option service: an option that exists only in an
* unfetched `loadOptions` page is invisible to it.
*/
exclusive?: boolean;
/** Arbitrary payload, carried untouched through every render callback. */
data?: O;
}
export interface FilterLoadContext {
/** Aborted when the query changes, the editor closes, or a load supersedes. */
signal: AbortSignal;
cursor?: string;
}
/** Result of `loadOptions`, or a bare array. Shape-locked to the cascader. */
export interface FilterLoadResult<O = unknown> {
items: FilterOption<O>[];
nextCursor?: string;
/** Defaults to whether `nextCursor` was supplied. */
hasMore?: boolean;
}
/** A field, or a branch. A group is a field with `fields`, not `selectable`. */
export interface FilterField<V = unknown, O = unknown> {
/** Stable id. Unique among its siblings; the full path must be unique. */
id: string;
label: string;
icon?: React.ReactNode;
description?: string;
keywords?: string[];
/** Trailing count. Defaults to known children; set it when they are lazy. */
count?: number;
fields?: FilterField<V, O>[];
/** Whether a BRANCH is itself filterable. Leaves always are. */
selectable?: boolean;
disabled?: boolean;
type?: FilterValueType;
options?: FilterOption<O>[];
/** Async options, paged via `cursor`. Any `options` also seed the cache. */
loadOptions?: (query: string, context: FilterLoadContext) => FilterOption<O>[] | Promise<FilterOption<O>[] | FilterLoadResult<O>>;
/** Resolves stored values the loader never returned, for restored chips. */
resolveValues?: (values: string[]) => FilterOption<O>[] | Promise<FilterOption<O>[]>;
/** Operators for this field. Falls back to the catalog for its `type`. */
operators?: FilterOperator[] | ((field: FilterField<V, O>) => FilterOperator[]);
/**
* The operator this field FALLS BACK to, not a way to preselect one. Both
* create paths deliberately start a rule on `operator: ""` so the condition
* menu opens with nothing chosen, so this is read when an existing rule
* changes field, and it is the value `FilterFieldPicker` hands to `onSelect`.
* Ignored, with a dev warning, when it names an operator the field does not
* offer; the first visible operator wins instead.
*/
defaultOperator?: string;
/** Overrides the editor chosen from `type`. See `FilterEditorProps`. */
editor?: FilterEditorRef<V, O>;
renderValue?: (context: FilterValueDisplayContext<V, O>) => React.ReactNode;
/** The value as PLAIN TEXT for a11y; the default is `String(value)`. */
valueText?: (context: FilterValueDisplayContext<V, O>) => string;
/** Placeholder for the value editor's input, or an option list's search. */
placeholder?: string;
/** SHOWS the search box (default true). Off keeps it, hidden: it owns focus. */
searchable?: boolean;
/**
* Whether an option-backed editor STACKS the picks at the top of its list.
* Off by default, because a short closed list is read as a whole and lifting
* a row out of a memorised order costs more than it buys. The partition is
* taken LIVE unless `sortSelected: "snapshot"`, so ticking a row moves the
* rows below it and the highlight is carried across by VALUE. Exclusive
* options never join the stack; they are grouped by ROLE.
*/
pinSelected?: boolean;
/**
* How an option list is ordered INSIDE each group, plus WHEN the partition is
* taken under `pinSelected`. With pinning off there is no partition, so
* `"snapshot"` is the same thing as `"none"`.
*
* - `"none"` (default) keeps declaration order. Not alphabetical, because
* option order is usually semantic (To do, In progress, Done).
* - `"label"` sorts with `localeCompare`, so "Ã…lesund" files next to
* "Alesund" rather than after "Zurich".
* - `"snapshot"` keeps declaration order too, and freezes the partition as
* the menu opened it: a steady pointer target where the other two re-pin
* live.
*/
sortSelected?: 'none' | 'label' | 'snapshot';
/**
* This field's own validity check. Return a MESSAGE to mark the value cell
* invalid, or `null` / `undefined` / `false` when the value is fine. A string
* rather than a schema object keeps the primitive library-agnostic.
*
* ORDER MATTERS: the built-in checks run first and this runs only when they
* pass, so a validator never re-answers "is there a value at all". Not called
* for a valueless operator, nor for a rule whose field the schema no longer
* has, and shown only once the user has committed a value to that rule.
*/
validate?: (context: FilterValidateContext<V, O>) => string | null | undefined | false;
/**
* Reaches the value editor's PANEL. Merged last through tailwind-merge, so a
* `w-*` here beats the default rather than losing to it on source order.
*
* HEIGHT IS A VARIABLE, NOT A UTILITY: a `max-h-*` here bounds the PANEL and
* does nothing to the list inside it, which owns its own `max-height`. Write
* `--cascader-max-height: 28rem` as an arbitrary property instead; the cap is
* the SMALLER of that and the space the popup has.
*/
className?: string;
/** The storage column when it differs from the UI path. Never read here. */
column?: string;
data?: unknown;
}
/* -------------------------------------------------------------------------- */
/* Editors */
/* -------------------------------------------------------------------------- */
/**
* Where an editor renders. The SAME component serves both: `"create"` is the
* wizard step, which has Back and advances on commit, `"amend"` the
* chip-anchored popover, which offers Discard instead.
*/
export type FilterEditorHost = 'create' | 'amend';
export interface FilterOptionsState<O = unknown> {
items: FilterOption<O>[];
loading: boolean;
error: boolean;
hasMore: boolean;
/** Current search text. Debounced before it reaches `loadOptions`. */
query: string;
setQuery: (query: string) => void;
loadMore: () => void;
retry: () => void;
/** Resolves a stored value to its option, from cache when possible. */
resolve: (value: string) => FilterOption<O> | undefined;
}
export interface FilterCommitOptions {
/** Dismiss the host after writing. Defaults to true. */
close?: boolean;
}
export interface FilterEditorProps<V = unknown, O = unknown> {
field: FilterField<V, O>;
operator: FilterOperator;
/** The DRAFT value. An editor edits a draft; the host commits it. */
value: V | undefined;
onValueChange: (value: V | undefined) => void;
host: FilterEditorHost;
/**
* Spread onto whichever element should take focus, so no editor reaches for
* `setTimeout`. A CALLBACK ref at `HTMLElement` is the one shape assignable
* to every element's own ref prop, so it spreads onto an input, a slider or a
* button without a cast.
*/
autoFocusProps: {
ref: React.RefCallback<HTMLElement>;
autoFocus: boolean;
};
/** Accept the draft. `{ close: false }` writes through without dismissing. */
commit: (value?: V, options?: FilterCommitOptions) => void;
cancel: () => void;
/** Step back. Only meaningful when `host === "create"`. */
back: () => void;
options: FilterOptionsState<O>;
labels: FilterLabels;
}
export type FilterEditor<V = unknown, O = unknown> = React.ComponentType<FilterEditorProps<V, O>>;
/**
* An editor with its generics erased, for the registry. `unknown` rather than
* `never`: props are contravariant, so a `FilterEditor<never, never>` registry
* accepts nothing at all. The single widening cast happens where it renders.
*/
export type AnyFilterEditor = React.ComponentType<FilterEditorProps<unknown, unknown>>;
export type FilterEditorRegistry = Record<string, AnyFilterEditor>;
/**
* A registered editor's name, or a component. The `any` arm lets a CONCRETE
* editor sit on an unknown-typed field without a cast: props are contravariant,
* so `FilterEditor<DateValue>` is not a `FilterEditor<unknown>`. The widening
* happens once, inside `resolveFilterEditor`.
*/
export type FilterEditorRef<V = unknown, O = unknown> =
| string
| FilterEditor<V, O>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
| FilterEditor<any, any>;
/** Context for a custom builder empty state. Its actions ARE the footer's. */
export interface FilterEmptyStateContext {
labels: FilterLabels;
/** The bar is locked. A custom state should not offer an action here. */
readOnly: boolean;
/** Which box the builder is in, for a state that wants to be denser inline. */
mode: 'popover' | 'inline';
/** Appends a condition and opens its attribute picker. */
addFilter: () => void;
addGroup: () => void;
}
export interface FilterValueDisplayContext<V = unknown, O = unknown> {
value: V | undefined;
/** `value` normalised to an array, so callbacks never re-derive it. */
values: unknown[];
field: FilterField<V, O>;
operator: FilterOperator;
/** Options already resolved for `value`, when the field is option-backed. */
options: FilterOption<O>[];
labels: FilterLabels;
}
/* -------------------------------------------------------------------------- */
/* Index */
/* -------------------------------------------------------------------------- */
/** Normalized schema, keyed by SIGNATURE: call sites inline the array. */
export interface FilterIndex<V = unknown, O = unknown> {
/** Every field by its joined path, `"name.first"`. */
byPath: Map<string, FilterField<V, O>>;
/** Child fields by parent path. Root fields are keyed by `FILTER_ROOT_KEY`. */
childrenOf: Map<string, FilterField<V, O>[]>;
/** Parent path by path. Empty string for a root field. */
parentOf: Map<string, string>;
/** Every field in stable, depth-first order. Deep search walks it, and the
* builder seeds a new row from the FIRST pickable entry, so order is load
* bearing, not incidental. */
all: { field: FilterField<V, O>; path: string[] }[];
/** Top level fields, in input order. */
roots: FilterField<V, O>[];
/** Content hash; equal schemas share one, so a rebuild reuses the index. */
signature: string;
}
/* -------------------------------------------------------------------------- */
/* Draft */
/* -------------------------------------------------------------------------- */
export type FilterDraftStep = 'field' | 'operator' | 'value';
/**
* The in-flight filter. `cascaderPath` is kept SEPARATE from `path`: `path` is
* what the user chose, `cascaderPath` is where they were browsing when they
* chose it, and Back has to return there. Deriving it from `path` breaks the
* moment a deep search jumps across the tree.
*/
export interface FilterDraft<V = unknown> {
step: FilterDraftStep;
/** `"ready"` = complete: the host writes it into the query and closes. The
* pure reducer decides that, not a click handler. */
status: 'editing' | 'ready';
/** Set when amending an existing rule, null when creating a new one. */
ruleId: string | null;
/** The chosen field path. Empty until the field step commits. */
path: string[];
cascaderPath: string[];
operator: string | null;
value: V | undefined;
query: string;
}
/* -------------------------------------------------------------------------- */
/* Labels */
/* -------------------------------------------------------------------------- */
/** Every user facing string. `stepAnnouncement` alone is headless-only. */
export interface FilterLabels {
addFilter: string;
advancedFilter: string;
/** The line above the builder's rows, "In this view, show records". */
showRecords: string;
/** Empty-state title. The HINT below is withheld from a read-only bar. */
builderEmpty: string;
builderEmptyHint: string;
/** Appends a condition to the root group, from the builder's footer. */
addCondition: string;
addConditionGroup: string;
/** A group's own add button: the only keyboard route into a nested group. It
* NAMES a button that shows `addCondition`, so a translation must contain
* that string, which is what WCAG Label in Name asks for. */
addToGroup: string;
removeGroup: string;
wrapInGroup: string;
/** Dissolves a group into its parent. The inverse of `wrapInGroup`. */
ungroup: string;
/** Moves a condition to the root group. The keyboard path to that drag. */
moveToTopLevel: string;
/** Groups have no names, so they are numbered in document order, one-based. */
moveToGroup: (position: number) => string;
/** Accessible name of a row's or a group's drag handle. */
reorder: string;
/** Description on the drag handle, teaching the Alt+Arrow keyboard model. */
reorderHint: string;
groupAll: string;
groupAny: string;
groupPlaceholder: string;
/** Names a builder row. Depth is in it: indentation is invisible to AT. */
rowLabel: (condition: string, depth: number) => string;
groupLabel: (description: string, depth: number) => string;
groupAnnouncement: (added: boolean) => string;
/** Alt+Arrow is otherwise silent. The total says whether this is the end. */
reorderAnnouncement: (label: string, position: number, total: number) => string;
/** A cross-PARENT move; a plain reorder announcement cannot be told apart.
* `destination` is the group's own headline, or the bar's label at the top
* level. */
moveAnnouncement: (label: string, destination: string, position: number, total: number) => string;
clearAll: string;
/** Names a group's menu; distinct from `chipMenu`, which is per-rule. */
groupMenu: string;
searchFields: string;
searchOperators: string;
searchOptions: string;
back: string;
clear: string;
apply: string;
discard: string;
empty: string;
loading: string;
loadingMore: string;
loadMore: string;
error: string;
retry: string;
/** Leading word before the first chip, where a combinator would otherwise go. */
where: string;
and: string;
or: string;
/** Accessible name of the combinator toggle between two chips. */
combinator: string;
/** Builder combinator toggle. English "and" wants 58.72px of a 64px track,
* so the name must CONTAIN the word: truncated, the pill shows "a...". */
combinatorLabel: (word: string) => string;
duplicate: string;
negate: string;
/** Chip kebab's route into the builder. Needs `onConvertToAdvanced`. */
convertToAdvanced: string;
remove: string;
/** Names a chip's menu button. The builder's row menu reads the same key. */
chipMenu: (fieldLabel: string) => string;
filtersLabel: string;
filterLabel: (condition: string) => string;
/** Prose, not ARIA: `aria-readonly` is invalid on toolbar, group and button. */
readOnly: string;
/** Joins ancestors in a nested field path, "Name > First", for the names
* `formatFilterPath` builds. The chip draws a decorative chevron instead. */
pathSeparator: string;
valuePlaceholder: string;
/** Empty word for an OPTION value; `placeholder` is the search prompt. */
selectPlaceholder: string;
/** Spoken for an empty value: "contains enter text..." is not a name. */
noValue: string;
/** Shown in the operator segment before a condition has been chosen. */
selectCondition: string;
/** Appended to a chip with no condition, matching the dashed outline. */
incomplete: string;
/** Appended to a branch row's accessible name in the field picker. */
branchAffordance: string;
/** A FRAGMENT, appended after a comma to an exclusive row's accessible name.
* Warns before the press; `exclusiveAnnouncement` is the receipt after. */
exclusiveHint: string;
/** The clearing moves nothing on screen, so it is otherwise silent. */
exclusiveAnnouncement: (label: string, cleared: number) => string;
itemCount: (count: number) => string;
fieldsLabel: string;
/** Live-region text after a query narrows an option list or the picker. */
resultsAnnouncement: (count: number) => string;
/** Accessible name of an option menu's footer (Load more, Retry). */
actionsLabel: string;
/** For a CONSUMER-composed wizard; the shipped flow announces counts. */
stepAnnouncement: (step: FilterDraftStep, label: string) => string;
countAnnouncement: (count: number) => string;
valueCount: (count: number) => string;
/** Spells out the list behind the `valueCount` summary, and contains it. */
valueDetail: (summary: string, values: string[]) => string;
valueRange: (from: string, to: string) => string;
rangeFrom: (fieldLabel: string) => string;
rangeTo: (fieldLabel: string) => string;
rangeSeparator: string;
/** Rendered for a `negated` rule, wrapping the operator label. */
negated: (operatorLabel: string) => string;
/** Guidance ("Choose a condition"), not diagnosis: shown three ways over. */
issueOperator: string;
issueValue: string;
issueRange: string;
issueRangeOrder: string;
issueEmptyGroup: string;
/** The roll-up, and the name of the button that jumps to the first issue. */
issueSummary: (count: number) => string;
}
/* -------------------------------------------------------------------------- */
/* Validation */
/* -------------------------------------------------------------------------- */
/** Why a node cannot run as written. `collectFilterIssues` produces these. */
export type FilterIssueReason =
| 'missing-operator'
| 'missing-value'
| 'incomplete-range'
| 'reversed-range'
| 'empty-group'
/** The one reason whose message is the validator's, not `FilterLabels`. */
| 'custom';
export interface FilterIssue {
nodeId: string;
/** WHICH cell to mark. Two reasons share the value cell; groups have none. */
column: 'operator' | 'value' | 'group';
reason: FilterIssueReason;
/** Set only for `reason: "custom"`; the rest look up `FilterLabels`. */
message?: string;
}
/**
* What a field's `validate` is handed. Mirrors `FilterValueDisplayContext`.
* SYNCHRONOUS: issues are collected in a pure memo pass, so a check that has to
* hit a server belongs in the consumer's own submit path.
*/
export interface FilterValidateContext<V = unknown, O = unknown> {
value: V | undefined;
values: unknown[];
field: FilterField<V, O>;
operator: FilterOperator;
/** How many values this operator takes, already resolved. */
arity: FilterOperatorArity;
rule: FilterRule<V>;
labels: FilterLabels;
}components/ui/filters/filters.tsx
'use client';
import * as React from 'react';
import { FiltersAdvanced } from '@/registry/vcare/ui/filters/filters-advanced';
import { FiltersBuilder } from '@/registry/vcare/ui/filters/filters-builder';
import { FilterChip } from '@/registry/vcare/ui/filters/filters-chip';
import {
createFilterFocusStore,
createFilterResolutionStore,
createFilterRowStateStore,
FilterActionsContext,
filterControlSizes,
FilterFocusContext,
filterReadOnlyProps,
FilterRenderContext,
FilterRowStateProvider,
FilterStateContext,
isFilterLocked,
useFilterActions,
useFilterFocusStore,
useFilterState,
type FilterActionsContextValue,
} from '@/registry/vcare/ui/filters/filters-context';
import { filterDraftReducer, isFilterDraftCommittable, type FilterDraftAction } from '@/registry/vcare/ui/filters/filters-draft';
import { DEFAULT_FILTER_EDITORS, resolveFilterEditor, type FilterEditorRegistry } from '@/registry/vcare/ui/filters/filters-editors';
import { resolveFilterLabels } from '@/registry/vcare/ui/filters/filters-i18n';
import {
buildFilterIndex,
computeFilterSchemaSignature,
createFilterIdFactory,
findFilterSchemaIssues,
formatFilterPath,
getFilterField,
warnFilterOnce,
type FilterPathCollapse,
} from '@/registry/vcare/ui/filters/filters-lib';
import {
createFilterOperators,
DEFAULT_FILTER_OPERATOR_LABELS,
DEFAULT_FILTER_OPERATORS,
getFilterOperator,
negateFilterOperator,
operatorTakesValue,
resolveFilterOperators,
type FilterOperatorLabels,
} from '@/registry/vcare/ui/filters/filters-operators';
import {
clearFilterQuery,
copyFilterNodeTo,
countFilterRules,
createFilterGroup,
createFilterQuery,
createFilterRule,
duplicateFilterNode,
findFilterNode,
findFilterRule,
flattenFilterRules,
insertFilterNode,
isFilterRule,
moveFilterNode,
moveFilterNodeTo,
removeFilterNode,
setFilterCombinator,
toggleFilterCombinator,
unwrapFilterGroup,
updateFilterRule,
wrapFilterNodeInGroup,
} from '@/registry/vcare/ui/filters/filters-query';
import type {
FilterChangeDetails,
FilterCombinator,
FilterDraft,
FilterDraftStep,
FilterEditor,
FilterEmptyStateContext,
FilterField,
FilterLabels,
FilterQuery,
FilterRule,
FilterValueDisplayContext,
} from '@/registry/vcare/ui/filters/filters-types';
import { cva } from 'class-variance-authority';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
/* -------------------------------------------------------------------------- */
/* Variants */
/* -------------------------------------------------------------------------- */
const filtersBarVariants = cva('flex flex-wrap items-center', {
variants: {
// The rungs `FILTER_CONTROL_SIZES` holds, fed the RESOLVED rung at both
// call sites, which is what keeps the two ladders in step: a cva default
// only applies to a value nobody passed, so a raw `"lg"` reaching here
// would leave the bar with no gap at all.
size: {
sm: 'gap-1.5',
default: 'gap-2',
},
},
defaultVariants: { size: 'default' },
});
/* -------------------------------------------------------------------------- */
/* Controllable */
/* -------------------------------------------------------------------------- */
function useControllableQuery<V, O>(
controlled: FilterQuery<V> | undefined,
uncontrolledDefault: FilterQuery<V> | undefined,
onChange: ((query: FilterQuery<V>, details: FilterChangeDetails<V, O>) => void) | undefined,
) {
const isControlled = controlled !== undefined;
const [internal, setInternal] = React.useState<FilterQuery<V>>(() => uncontrolledDefault ?? createFilterQuery<V>());
const query = isControlled ? controlled : internal;
const queryRef = React.useRef(query);
React.useEffect(() => {
queryRef.current = query;
});
const setQuery = React.useCallback(
(next: FilterQuery<V>, details: FilterChangeDetails<V, O>) => {
if (next === queryRef.current) return;
queryRef.current = next;
if (!isControlled) setInternal(next);
onChange?.(next, details);
},
[isControlled, onChange],
);
return { query, queryRef, setQuery };
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
export interface FiltersProps<V = unknown, O = unknown> {
/** The field schema. Nested via each field's own `fields`. */
fields: FilterField<V, O>[];
query?: FilterQuery<V>;
defaultQuery?: FilterQuery<V>;
onQueryChange?: (query: FilterQuery<V>, details: FilterChangeDetails<V, O>) => void;
labels?: Partial<FilterLabels>;
/** Operator wording, overridden independently of the chrome copy. */
operatorLabels?: FilterOperatorLabels;
/** Extra or replacement value editors, resolved by a field's `editor` name. */
editors?: FilterEditorRegistry;
/**
* Which chrome draws the query. `"basic"` is the flat chip row, joined by an
* implicit AND and drawing no combinator, because a chip row has nowhere to
* put a parenthesis, and it draws a nested rule at any depth as a flat chip.
*/
variant?: 'basic' | 'advanced';
/** Where the advanced builder lives. `"inline"` renders the panel in place. */
advancedMode?: 'popover' | 'inline';
/**
* Where the panel sits against its trigger. Stating it settles a twin split:
* on overflow Base UI flips edges, Radix only shifts along the axis.
*/
advancedAlign?: 'start' | 'center' | 'end';
/**
* Whether the advanced builder's rows can be REORDERED. Off by default: a
* move changes nothing about what the query MEANS, and costs a grip on every
* row plus a gesture a touch screen starts by accident. On, drag and
* Alt+Arrow move any row but the lone root.
*/
reorderable?: boolean;
/**
* The density of the whole bar, chips included. TWO RUNGS and no `lg`,
* resolved through `filterControlSizes` to whatever the ACTIVE STYLE calls
* that rung (nova 7/8, sera 9/10, mira 6/7, maia and luma 8/9, lyra and rhea
* 7/8, vega 8/9). Chips need no `ButtonGroup` variant: `items-stretch` gives
* the pill the height of its one definite-height child, the kebab.
*/
size?: 'sm' | 'default';
disabled?: boolean;
readOnly?: boolean;
/**
* ONE VETO POINT for every change the BAR makes to the query, and only those.
* Return `false` to refuse; anything else commits, and `details.reason` names
* the action. One hook and not fourteen because every write goes through
* `emit`: the Delete key, Alt+Arrow and a drag alike. It can only refuse, and
* it sits BEHIND the lock, so a locked bar never asks it. Returning a
* REPLACEMENT tree was rejected: the announcement is already computed from
* the proposed tree, so the bar would say one thing and commit another.
*/
onBeforeQueryChange?: (query: FilterQuery<V>, details: FilterChangeDetails<V, O>) => boolean | void;
/**
* Offers "Convert to advanced filter" in every chip's kebab; its presence IS
* the switch, since `variant` belongs to the consumer. Not drawn in advanced.
*/
onConvertToAdvanced?: () => void;
/**
* Classes for the dropdown MENUS and the field PICKER panel, one prop each
* rather than one per mount point. Merged after the default, so `w-*` wins.
*/
menuClassName?: string;
fieldPickerClassName?: string;
/**
* How a NESTED attribute path is shortened when too deep to read. `"none"` is
* the default, so an upgrade changes nothing under a consumer; the collapser
* is the cascader's, and the full path survives as the accessible NAME.
*/
pathCollapse?: FilterPathCollapse;
/**
* How many names survive the collapse, the elided run not counted. Inert
* while `pathCollapse` is `"none"`. Three is the cascader's own default.
*/
maxPathSegments?: number;
/** Replaces the default Add filter button. */
trigger?: React.ReactNode;
/** Renders a Clear button once the query holds anything. */
showClear?: boolean;
renderValue?: (context: FilterValueDisplayContext<V, O>) => React.ReactNode;
renderChip?: (rule: FilterRule<V>) => React.ReactNode;
/**
* Replaces the advanced builder's empty state, which exists at all because a
* builder with no rows is a footer floating in blank space. `null` for none.
*/
renderEmpty?: (context: FilterEmptyStateContext) => React.ReactNode;
className?: string;
children?: React.ReactNode;
}
export function Filters<V = unknown, O = unknown>({
fields,
query: controlledQuery,
defaultQuery,
onQueryChange,
labels: labelsProp,
operatorLabels: operatorLabelsProp,
editors: editorsProp,
variant = 'basic',
advancedMode = 'popover',
advancedAlign = 'start',
reorderable = false,
size = 'default',
disabled = false,
readOnly = false,
onBeforeQueryChange,
onConvertToAdvanced,
menuClassName,
fieldPickerClassName,
pathCollapse = 'none',
maxPathSegments = 3,
trigger,
showClear = false,
renderValue,
renderChip,
renderEmpty,
className,
children,
}: FiltersProps<V, O>) {
const { query, queryRef, setQuery } = useControllableQuery<V, O>(controlledQuery, defaultQuery, onQueryChange);
const [draft, dispatchDraftRaw] = React.useReducer(filterDraftReducer<V>, null as FilterDraft<V> | null);
// Text AND a counter: `aria-live` fires on a DOM mutation and React writes
// nothing when the string is already there, so a repeat was silent. Measured
// with a MutationObserver: "Group added" three times, one mutation.
const [announced, setAnnounced] = React.useState({ seq: 0, text: '' });
const announcement = announced.text;
const setAnnouncement = React.useCallback((text: string) => {
setAnnounced((prev) => ({ seq: prev.seq + 1, text }));
}, []);
// Seeded from useId: ids from Date.now() plus Math.random() broke hydration.
const idSeed = React.useId();
const nextId = React.useMemo(() => createFilterIdFactory(`${idSeed}f`), [idSeed]);
const focusStore = React.useMemo(() => createFilterFocusStore(), []);
const rowStateStore = React.useMemo(() => createFilterRowStateStore(), []);
// One per root: the value-to-label store every `useFilterOptions` shares.
const resolutionStore = React.useMemo(() => createFilterResolutionStore(), []);
/* -------------------------------- derived ------------------------------- */
// `fields` is an inline literal at every real call site, so the CHEAP walk
// runs every render and the EXPENSIVE index memoizes on its result. Not a
// ref caching the previous index: writing a ref during render is the
// impurity this rewrite removed, and it misbehaves under StrictMode.
const signature = computeFilterSchemaSignature(fields);
const index = React.useMemo(
() => buildFilterIndex<V, O>(fields, null, signature),
// Not `fields`: its identity changes every render at every real call site.
// eslint-disable-next-line react-hooks/exhaustive-deps
[signature],
);
const labels = React.useMemo(() => resolveFilterLabels(labelsProp), [labelsProp]);
const operatorCatalog = React.useMemo(() => {
if (!operatorLabelsProp) return DEFAULT_FILTER_OPERATORS;
return createFilterOperators({
...DEFAULT_FILTER_OPERATOR_LABELS,
...operatorLabelsProp,
});
}, [operatorLabelsProp]);
const editors = React.useMemo(() => ({ ...DEFAULT_FILTER_EDITORS, ...editorsProp }), [editorsProp]);
const resolveOperators = React.useCallback((field: FilterField<V, O>) => resolveFilterOperators(field, operatorCatalog), [operatorCatalog]);
const ruleCount = React.useMemo(() => countFilterRules(query), [query]);
/* --------------------------- latest-props ref --------------------------- */
const latest = React.useRef({
index,
labels,
operatorCatalog,
resolveOperators,
draft,
nextId,
setQuery,
queryRef,
disabled,
readOnly,
onBeforeQueryChange,
});
React.useEffect(() => {
latest.current = {
index,
labels,
operatorCatalog,
resolveOperators,
draft,
nextId,
setQuery,
queryRef,
disabled,
readOnly,
onBeforeQueryChange,
};
});
/* -------------------------------- actions ------------------------------- */
// Every mutator below reads state through `latest`, so no keystroke rebuilds
// one. The lock flags are the ONE exception, for the reason on `locked`.
/**
* THE MUTATION BOUNDARY, asked here and not at the nine buttons, because the
* routes into a query are not only buttons. It needs BOTH the closure and
* the ref: `latest` is written in a passive effect and effects run
* child-first, so a consumer effect in the commit that turns `readOnly` on
* runs BEFORE the ref learns of it, while the ref is what a stale handler
* reads afterwards.
*/
const locked = React.useCallback(() => disabled || readOnly || isFilterLocked(latest.current), [disabled, readOnly]);
// Reports whether the write LANDED: `onBeforeQueryChange` is discoverable
// only here, and a vetoed remove that still announced a count would lie.
const emit = React.useCallback(
(next: FilterQuery<V>, reason: FilterChangeDetails<V, O>['reason'], rule: FilterRule<V> | null): boolean => {
// The backstop, redundant with each mutator's own early return, and
// FIRST, so the consumer hook cannot approve what the lock refused.
if (locked()) return false;
const field = rule ? (getFilterField(latest.current.index, rule.path) ?? null) : null;
const details: FilterChangeDetails<V, O> = { reason, rule, field };
// Strictly `false`, so a handler that forgets to return is not a veto.
if (latest.current.onBeforeQueryChange?.(next, details) === false) {
return false;
}
latest.current.setQuery(next, details);
return true;
},
[locked],
);
/**
* Drops the roving tab stop when the node holding it no longer exists: a cell
* claims it when the store names it, and the "row one takes it" fallback
* fires only when the store is EMPTY, so a deleted id left twenty cells at
* `tabindex="-1"` with focus on the BODY. Keyed on the committed `query`, so
* a consumer's Reset or saved-view load is repaired too: add a condition,
* press Reset, and 25 cells stayed untabbable in both twins.
*/
React.useEffect(() => {
const { id } = focusStore.getSnapshot();
if (!id || findFilterNode(query, id)) return;
focusStore.set({ id: null, segment: null, autoOpen: false });
}, [query, focusStore]);
const addRule = React.useCallback(
(rule: FilterRule<V>, parentId?: string) => {
if (locked()) return;
const next = insertFilterNode(latest.current.queryRef.current, rule, parentId);
if (!emit(next, 'add', rule)) return;
setAnnouncement(latest.current.labels.countAnnouncement(countFilterRules(next)));
},
[emit, locked, setAnnouncement],
);
const addGroup = React.useCallback(
(parentId?: string, combinator: FilterCombinator = 'or') => {
// Before `nextId`, so a LOCKED bar cannot drift the SSR-seeded sequence.
if (locked()) return '';
const id = latest.current.nextId();
// `or` by default: `a AND (b AND c)` is just `a AND b AND c`.
const next = insertFilterNode(latest.current.queryRef.current, createFilterGroup<V>({ id, combinator }), parentId);
// `""` on a veto: every caller moves focus onto the id it gets back, and
// focusing a group that was never created strands the tab stop. The id
// is already burnt, deliberately: a veto is a client-time decision the
// server never took part in.
if (!emit(next, 'add', null)) return '';
setAnnouncement(latest.current.labels.groupAnnouncement(true));
return id;
},
[emit, locked, setAnnouncement],
);
const updateRule = React.useCallback(
(id: string, updates: Partial<Omit<FilterRule<V>, 'id' | 'type'>>) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = updateFilterRule(current, id, updates);
if (next === current) return;
// THE VALUE, not the field or the operator: picking an attribute leaves
// the value empty, so arming there reddens the flow the primitive itself
// walks a user through. A field re-pick sends `value: undefined` in the
// SAME patch, so `path` and not the presence of `value` tells the two
// apart. Clearing a typed value still arms it: no `path` in that patch.
if ('path' in updates) rowStateStore.unmark(id);
else if ('value' in updates) rowStateStore.mark(id);
emit(next, 'update', findFilterRule(next, id));
},
[emit, locked, rowStateStore],
);
const removeNode = React.useCallback(
(id: string) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const removed = findFilterRule(current, id);
const next = removeFilterNode(current, id);
if (next === current) return;
if (!emit(next, 'remove', removed)) return;
// A rule removal reports the COUNT; a group has no rule to report and
// takes an unknown number of conditions with it, so it says so instead.
setAnnouncement(removed ? latest.current.labels.countAnnouncement(countFilterRules(next)) : latest.current.labels.groupAnnouncement(false));
},
[emit, locked, setAnnouncement],
);
const duplicateNode = React.useCallback(
(id: string) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = duplicateFilterNode(current, id, latest.current.nextId);
if (next === current) return;
if (!emit(next, 'duplicate', findFilterRule(current, id))) return;
// The count, not "duplicated": a GROUP adds an unknown number of rows.
setAnnouncement(latest.current.labels.countAnnouncement(countFilterRules(next)));
},
[emit, locked, setAnnouncement],
);
const negateRule = React.useCallback(
(id: string) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const rule = findFilterRule(current, id);
if (!rule) return;
const field = getFilterField(latest.current.index, rule.path);
if (!field) return;
const operators = latest.current.resolveOperators(field);
const flipped = negateFilterOperator(getFilterOperator(operators, rule.operator), operators, rule.negated);
const next = updateFilterRule(current, id, {
operator: flipped.operator ?? rule.operator,
negated: flipped.negated || undefined,
});
emit(next, 'negate', findFilterRule(next, id));
},
[emit, locked],
);
// Says where a node LANDED, the one mutator a screen reader hears nothing
// else about: focus stays on the handle and the name does not change. Reads
// the tree AFTER the move: the position and sibling count announced are the
// ones the user has just arrived at.
const announceReorder = React.useCallback(
(next: FilterQuery<V>, id: string, fromParentId: string | null) => {
const found = findFilterNode(next, id);
if (!found || !found.parent) return;
const label = isFilterRule(found.node)
? formatFilterPath(latest.current.index, found.node.path, latest.current.labels.pathSeparator)
: found.node.combinator === 'and'
? latest.current.labels.groupAll
: latest.current.labels.groupAny;
const position = found.index + 1;
const total = found.parent.rules.length;
// A move that changed the node's CONTAINER is a different event, named by
// the group's own headline, or the bar's label at the top level.
if (fromParentId && fromParentId !== found.parent.id) {
const destination =
found.parent.id === next.id
? latest.current.labels.filtersLabel
: found.parent.combinator === 'and'
? latest.current.labels.groupAll
: latest.current.labels.groupAny;
setAnnouncement(latest.current.labels.moveAnnouncement(label, destination, position, total));
return;
}
setAnnouncement(latest.current.labels.reorderAnnouncement(label, position, total));
},
[setAnnouncement],
);
const moveNode = React.useCallback(
(id: string, delta: number) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = moveFilterNode(current, id, delta);
if (next === current) return;
if (!emit(next, 'reorder', findFilterRule(next, id))) return;
// Within the owning group by construction, so there is no destination.
announceReorder(next, id, null);
},
[emit, announceReorder, locked],
);
// Also the drag layer's drop commit, so a drag and Alt+Arrow say the same.
const moveNodeTo = React.useCallback(
(id: string, parentId: string, index: number) => {
if (locked()) return;
const current = latest.current.queryRef.current;
// BEFORE the move: the only place the old parent still exists.
const fromParentId = findFilterNode(current, id)?.parent?.id ?? null;
const next = moveFilterNodeTo(current, id, parentId, index);
if (next === current) return;
if (!emit(next, 'reorder', findFilterRule(next, id))) return;
announceReorder(next, id, fromParentId);
},
[emit, announceReorder, locked],
);
const copyNodeTo = React.useCallback(
(id: string, parentId: string, index: number) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = copyFilterNodeTo(current, id, parentId, index, latest.current.nextId);
if (next === current) return;
if (!emit(next, 'duplicate', findFilterRule(current, id))) return;
// The count again: an Alt-drag of a GROUP adds an unknown number of rows.
setAnnouncement(latest.current.labels.countAnnouncement(countFilterRules(next)));
},
[emit, locked, setAnnouncement],
);
const wrapNodeInGroup = React.useCallback(
(id: string, combinator: FilterCombinator = 'or') => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = wrapFilterNodeInGroup(current, id, latest.current.nextId(), combinator);
if (next === current) return;
if (!emit(next, 'add', findFilterRule(next, id))) return;
setAnnouncement(latest.current.labels.groupAnnouncement(true));
},
[emit, locked, setAnnouncement],
);
const unwrapGroup = React.useCallback(
(groupId: string) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = unwrapFilterGroup(current, groupId);
if (next === current) return;
// The conditions survive in place, so the count has not changed.
if (!emit(next, 'remove', null)) return;
setAnnouncement(latest.current.labels.groupAnnouncement(false));
},
[emit, locked, setAnnouncement],
);
// What a combinator change SOUNDS like: the pill's name changes with it, but
// a name change on the FOCUSED element is not re-announced by NVDA or JAWS.
// The group's own headline, not the bare word: it says what the query MEANS
// now, which is the thing that changed.
const announceCombinator = React.useCallback(
(combinator: FilterCombinator) => {
setAnnouncement(combinator === 'and' ? latest.current.labels.groupAll : latest.current.labels.groupAny);
},
[setAnnouncement],
);
const setCombinatorAction = React.useCallback(
(groupId: string, combinator: FilterCombinator) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = setFilterCombinator(current, groupId, combinator);
if (next === current) return;
if (!emit(next, 'combinator', null)) return;
announceCombinator(combinator);
},
[emit, locked, announceCombinator],
);
const toggleCombinatorAction = React.useCallback(
(groupId: string) => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = toggleFilterCombinator(current, groupId);
if (next === current) return;
if (!emit(next, 'combinator', null)) return;
// Read off the COMMITTED tree, so the sentence cannot disagree with it.
const group = findFilterNode(next, groupId)?.node;
if (group && !isFilterRule(group)) announceCombinator(group.combinator);
},
[emit, locked, announceCombinator],
);
const clearQueryAction = React.useCallback(() => {
if (locked()) return;
const current = latest.current.queryRef.current;
const next = clearFilterQuery(current);
if (next === current) return;
if (!emit(next, 'clear', null)) return;
setAnnouncement(latest.current.labels.countAnnouncement(0));
}, [emit, locked, setAnnouncement]);
// The live region, opened to the chrome inside the bar. The setter itself is
// not published: it is a channel anything could write anything to.
const announce = React.useCallback(
(message: string) => {
if (!message) return;
setAnnouncement(message);
},
[setAnnouncement],
);
// A draft is a MUTATION in progress, so it locks with the rest, except
// `close`: a panel open when the bar turned read only must still dismiss.
const dispatchDraft = React.useCallback(
(action: FilterDraftAction<V>) => {
if (action.type !== 'close' && locked()) return;
dispatchDraftRaw(action);
},
[locked],
);
const openCreate = React.useCallback(() => {
if (locked()) return;
dispatchDraftRaw({ type: 'openCreate' });
}, [locked]);
const openAmend = React.useCallback(
(id: string, step: FilterDraftStep) => {
if (locked()) return;
const rule = findFilterRule(latest.current.queryRef.current, id);
if (!rule) return;
dispatchDraftRaw({
type: 'openAmend',
ruleId: id,
step,
path: rule.path,
operator: rule.operator,
value: rule.value,
});
},
[locked],
);
const closeDraft = React.useCallback(() => dispatchDraftRaw({ type: 'close' }), []);
const getQuery = React.useCallback(() => latest.current.queryRef.current, []);
const getDraft = React.useCallback(() => latest.current.draft, []);
/* ------------------------- draft -> query commit ------------------------ */
// The draft becomes a rule exactly once, when the reducer says it is ready.
// Here rather than in each click handler, which is what lets the "arity none
// skips the value step" branch live in the pure reducer.
React.useEffect(() => {
if (!draft || draft.status !== 'ready') return;
if (!isFilterDraftCommittable(draft)) return;
if (draft.ruleId) {
updateRule(draft.ruleId, {
path: draft.path,
operator: draft.operator ?? '',
value: draft.value,
});
} else if (!locked()) {
// Asked here too: this branch burns an id and points the focus store at
// it, and a store naming a chip that never existed eats the tab stop.
const id = nextId();
addRule(
createFilterRule<V>({
id,
path: draft.path,
// Empty on purpose: the chip renders "Select condition" and opens.
operator: '',
value: undefined,
}),
);
focusStore.set({ id, segment: 'operator', autoOpen: true });
}
dispatchDraftRaw({ type: 'close' });
}, [draft, addRule, updateRule, nextId, focusStore, locked]);
/* ---------------------------- dev diagnostics --------------------------- */
React.useEffect(() => {
if (process.env.NODE_ENV === 'production') return;
const issues = findFilterSchemaIssues(fields, (field) => resolveFilterOperators(field, operatorCatalog));
if (issues.duplicatePaths.length) {
warnFilterOnce(
`dup:${issues.duplicatePaths.join(',')}`,
`duplicate sibling field ids are ignored after the first: ${issues.duplicatePaths.join(', ')}`,
);
}
if (issues.emptyIds.length) {
warnFilterOnce('empty-id', 'every field needs a non-empty id');
}
if (issues.unknownDefaultOperators.length) {
warnFilterOnce(
`op:${issues.unknownDefaultOperators.join(',')}`,
`defaultOperator names an operator the field does not offer: ${issues.unknownDefaultOperators.join(', ')}`,
);
}
}, [fields, operatorCatalog]);
/* ------------------------------- contexts ------------------------------- */
const actions = React.useMemo<FilterActionsContextValue<V, O>>(
() => ({
index,
labels,
operatorCatalog,
editors,
size,
disabled,
readOnly,
variant,
menuClassName,
fieldPickerClassName,
convertToAdvanced: onConvertToAdvanced,
pathCollapse,
maxPathSegments,
resolveOperators,
// The same lookup the chrome uses, so a headless consumer can ask it too.
resolveEditor: (field, operator) => resolveFilterEditor(field, operator, editors) as FilterEditor<V, O> | undefined,
resolution: resolutionStore,
addRule,
addGroup,
updateRule,
removeNode,
duplicateNode,
negateRule,
moveNode,
moveNodeTo,
copyNodeTo,
wrapNodeInGroup,
unwrapGroup,
setCombinator: setCombinatorAction,
toggleCombinator: toggleCombinatorAction,
clearQuery: clearQueryAction,
openCreate,
openAmend,
closeDraft,
dispatchDraft,
announce,
getQuery,
getDraft,
nextId,
}),
// Every input is memoized and every action `[]`-stable, so this
// republishes on a real schema or config change, never on a keystroke.
[
index,
labels,
operatorCatalog,
editors,
size,
disabled,
readOnly,
variant,
menuClassName,
fieldPickerClassName,
onConvertToAdvanced,
pathCollapse,
maxPathSegments,
resolveOperators,
resolutionStore,
addRule,
addGroup,
updateRule,
removeNode,
duplicateNode,
negateRule,
moveNode,
moveNodeTo,
copyNodeTo,
wrapNodeInGroup,
unwrapGroup,
setCombinatorAction,
toggleCombinatorAction,
clearQueryAction,
openCreate,
openAmend,
closeDraft,
dispatchDraft,
announce,
getQuery,
getDraft,
nextId,
],
);
const state = React.useMemo(
() => ({
query,
draft,
ruleCount,
announcement,
announcementSeq: announced.seq,
}),
[query, draft, ruleCount, announcement, announced.seq],
);
const renderContext = React.useMemo(() => ({ renderValue, renderChip, renderEmpty }), [renderValue, renderChip, renderEmpty]);
return (
<FilterActionsContext.Provider value={actions as unknown as FilterActionsContextValue}>
<FilterStateContext.Provider value={state as never}>
<FilterRenderContext.Provider value={renderContext as never}>
<FilterRowStateProvider value={rowStateStore}>
<FilterFocusContext.Provider value={focusStore}>
{children ??
(variant === 'advanced' ? (
<FiltersAdvanced<V, O>
mode={advancedMode}
align={advancedAlign}
trigger={trigger}
reorderable={reorderable}
className={className}
/>
) : (
<FiltersRow trigger={trigger} showClear={showClear} className={className} />
))}
</FilterFocusContext.Provider>
</FilterRowStateProvider>
</FilterRenderContext.Provider>
</FilterStateContext.Provider>
</FilterActionsContext.Provider>
);
}
/* -------------------------------------------------------------------------- */
/* Row */
/* -------------------------------------------------------------------------- */
export interface FiltersRowProps {
trigger?: React.ReactNode;
showClear?: boolean;
className?: string;
}
/**
* The chip row: a toolbar with a roving tabindex, where the predecessor made
* every segment of every chip its own tab stop. There is NO combinator here,
* because a chip row can draw a word between two pills but not a parenthesis.
*/
export function FiltersRow({ trigger, showClear, className }: FiltersRowProps) {
const actions = useFilterActions();
const sizes = filterControlSizes(actions);
const { query, ruleCount, announcement, announcementSeq } = useFilterState();
const focusStore = useFilterFocusStore();
const rootRef = React.useRef<HTMLDivElement>(null);
// The keys consult this even though the actions already refuse: an ungated
// Enter would ARM `autoOpen` for a popover that then refuses to open. Gated
// per branch, never at the top of `onKeyDown`: the arrows, Home and End are
// how a read-only bar is read.
const locked = isFilterLocked(actions);
// Flattened, not `query.rules.filter(isFilterRule)`: a query built in the
// advanced builder would otherwise hide nested conditions that still filter.
const rules = React.useMemo(() => flattenFilterRules(query), [query]);
const chips = () => Array.from(rootRef.current?.querySelectorAll<HTMLElement>('[data-slot="filter-chip"]') ?? []);
const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
const target = (event.target as HTMLElement).closest<HTMLElement>('[data-slot="filter-chip"]');
if (!target) return;
// A key pressed inside an open popover belongs to that popover.
if (event.target !== target) return;
const all = chips();
const current = all.indexOf(target);
if (current === -1) return;
const rtl = getComputedStyle(target).direction === 'rtl';
const forward = rtl ? 'ArrowLeft' : 'ArrowRight';
const backward = rtl ? 'ArrowRight' : 'ArrowLeft';
const focusAt = (index: number) => {
const next = all[Math.max(0, Math.min(index, all.length - 1))];
if (!next) return;
event.preventDefault();
next.focus();
};
const ruleId = target.dataset.ruleId;
if (!ruleId) return;
if (event.altKey && (event.key === forward || event.key === backward)) {
if (locked) return;
event.preventDefault();
actions.moveNode(ruleId, event.key === forward ? 1 : -1);
return;
}
if (event.key === forward) return focusAt(current + 1);
if (event.key === backward) return focusAt(current - 1);
if (event.key === 'Home') return focusAt(0);
if (event.key === 'End') return focusAt(all.length - 1);
if (event.key === 'Backspace' || event.key === 'Delete') {
if (locked) return;
event.preventDefault();
actions.removeNode(ruleId);
// The neighbour taking this chip's place, so a run of deletes keeps focus.
requestAnimationFrame(() => {
const remaining = chips();
remaining[Math.min(current, remaining.length - 1)]?.focus();
});
return;
}
if (event.key === 'Enter' || event.key === ' ') {
if (locked) return;
event.preventDefault();
// Enter RESUMES the chip: the attribute segment is display only, so the
// target is whichever step the flow has not reached, never nothing.
const rule = findFilterRule(actions.getQuery(), ruleId);
if (!rule) return;
const field = getFilterField(actions.index, rule.path);
// No popover to open, so autoOpen would sit armed until another chip
// spent it. The chip stays reachable and Delete still removes it.
if (!field) return;
const operator = getFilterOperator(actions.resolveOperators(field), rule.operator);
const segment = rule.operator && operatorTakesValue(operator) ? 'value' : 'operator';
focusStore.set({ id: ruleId, segment, autoOpen: true });
}
};
return (
<div
ref={rootRef}
data-slot="filters"
data-empty={rules.length === 0 || undefined}
/* A presence hook, so a consumer can tint the whole read-only bar. */
data-readonly={actions.readOnly || undefined}
className={cn(
/* `sizes.button` and not `actions.size`: the gap ladder and the control
ladder must answer for the same rung, normalized in one place. */
filtersBarVariants({ size: sizes.button }),
/* An empty toolbar is still a flex child, so it took a gap with no
width. The gap goes, not the toolbar, which owns the row's name. */
rules.length === 0 && 'gap-0',
className,
)}
>
<div
role="toolbar"
aria-label={actions.labels.filtersLabel}
aria-orientation="horizontal"
/* `role=toolbar` disallows `aria-readonly`, and `aria-disabled` would
deny arrowing; a description is legal here and spoken on entry. */
{...(actions.readOnly ? { 'aria-description': actions.labels.readOnly } : null)}
className={cn(filtersBarVariants({ size: sizes.button }))}
onKeyDown={onKeyDown}
>
{rules.map((rule, index) => (
<FilterChip key={rule.id} rule={rule} index={index} />
))}
</div>
<FiltersBuilder trigger={trigger} />
{showClear && ruleCount > 0 ? (
// `ms-auto` and not `ml-auto`, so Clear stays on the trailing edge
// under RTL, where the whole bar mirrors.
<Button
variant="outline"
/* The same rung as the Add filter trigger beside it. */
size={sizes.button}
className="ms-auto"
/* `disabled` for the hard flag, `aria-disabled` for the soft one, so
a read-only Clear keeps its tab stop and can still be found. */
disabled={actions.disabled}
{...filterReadOnlyProps(actions)}
onClick={() => actions.clearQuery()}
>
{actions.labels.clear}
</Button>
) : null}
{/* Keyed on the sequence, so the same sentence twice is two
announcements (see `announced` for the measurement). A replaced live
element stops being watched. */}
<div aria-live="polite" role="status" className="sr-only">
<span key={announcementSeq}>{announcement}</span>
</div>
</div>
);
}
/* -------------------------------------------------------------------------- */
/* Exports */
/* -------------------------------------------------------------------------- */
// The full pure READ surface, so one import reaches everything a predicate, a
// saved view or a backend query needs. It stops at the query TREE and compiles
// nothing: `flattenFilterConditions` is the hand-off a server compiles from.
// No SQL emitter, because a server has to re-validate anything a browser sends
// and should compile from the tree rather than parse a client's string. SQL is
// one target of that hand-off beside Prisma, Drizzle, a REST query string and
// Elasticsearch.
export {
// The panel does not DRAW the built-in reasons, so this is the only way to
// surface "missing value", "empty group" and the rest.
collectFilterIssues,
copyFilterNodeTo,
createFilterGroup,
createFilterQuery,
createFilterRule,
countFilterRules,
flattenFilterConditions,
flattenFilterRules,
isFilterQueryEmpty,
isFilterRuleComplete,
moveFilterNodeTo,
pruneFilterQuery,
unwrapFilterGroup,
wrapFilterNodeInGroup,
} from '@/registry/vcare/ui/filters/filters-query';
// The two resolver signatures `collectFilterIssues` takes.
export type { FilterArityResolver, FilterValidateResolver } from '@/registry/vcare/ui/filters/filters-query';
export {
// The read-only contract: the gate, and the props a mutating control wears.
filterReadOnlyProps,
isFilterLocked,
useFilterActions,
useFilterState,
useFilterFocus,
// What a custom chip needs to rebuild the roving scheme `renderChip` drops.
useFilterChipAutoOpen,
useFilterChipFocused,
useFilterFocusEmpty,
useFilterFocusStore,
useFilterRender,
useFilterSegmentFocus,
} from '@/registry/vcare/ui/filters/filters-context';
export {
FilterChip,
FilterOperatorPopover,
FilterRuleMenuItems,
FilterValuePopover,
useFilterRuleDisplay,
} from '@/registry/vcare/ui/filters/filters-chip';
export { FiltersAdvanced, FiltersAdvancedPanel, FilterAdvancedRow } from '@/registry/vcare/ui/filters/filters-advanced';
export { FiltersBuilder, FilterFieldPicker } from '@/registry/vcare/ui/filters/filters-builder';
export { DEFAULT_FILTER_LABELS } from '@/registry/vcare/ui/filters/filters-i18n';
export { DEFAULT_FILTER_OPERATORS, DEFAULT_FILTER_OPERATOR_LABELS } from '@/registry/vcare/ui/filters/filters-operators';
export { DEFAULT_FILTER_EDITORS, useFilterOptions, useFilterValueResolution } from '@/registry/vcare/ui/filters/filters-editors';
export type * from '@/registry/vcare/ui/filters/filters-types';Usage
import { Filters, FiltersRow, useFilterActions, useFilterState, useFilterFocus, useFilterChipFocused } from "@/components/ui/filters/filters"Examples
Advanced
import { Filters } from "@/registry/vcare/ui/filters/filters"
import type { FilterField } from "@/registry/vcare/ui/filters/filters-types"
const fields: FilterField[] = [
{ id: "status", label: "Status", type: "select", options: [{ value: "paid", label: "Paid" }, { value: "due", label: "Due" }] },
{ id: "amount", label: "Amount", type: "number" },
{ id: "patient", label: "Patient", type: "text" },
]
export default function FiltersAdvanced() {
return (
<div className="w-full">
<Filters fields={fields} variant="advanced" />
</div>
)
}Exports
Filters, FiltersRow, useFilterActions, useFilterState, useFilterFocus, useFilterChipFocused, useFilterFocusEmpty, useFilterFocusStore, useFilterRender, useFilterSegmentFocus, FilterChip, FilterOperatorPopover, FilterRuleMenuItems, FilterValuePopover, useFilterRuleDisplay, FiltersAdvanced, FiltersAdvancedPanel, FilterAdvancedRow, FiltersBuilder, FilterFieldPicker, DEFAULT_FILTER_LABELS, DEFAULT_FILTER_OPERATORS, DEFAULT_FILTER_OPERATOR_LABELS, DEFAULT_FILTER_EDITORS, useFilterOptions, useFilterValueResolution
Dependencies
class-variance-authority@^0.7.1(npm)date-fns@^4.4.0(npm)lucide-react@^1.80.0(npm)@vcare/button(registry)@vcare/button-group(registry)@vcare/cascader(registry)@vcare/dropdown-menu(registry)@vcare/input(registry)@vcare/popover(registry)@vcare/tooltip(registry)@vcare/utils(registry)
Raw item: /r/filters.json