{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "reui-filters",
  "title": "Filters",
  "description": "A stepped filter builder with nested attributes, popover value editors and a boolean query tree, in a chip bar or an advanced builder.",
  "dependencies": [
    "class-variance-authority",
    "date-fns",
    "lucide-react"
  ],
  "registryDependencies": [
    "@tealmac/reui-cascader",
    "button",
    "button-group",
    "dropdown-menu",
    "input",
    "popover",
    "tooltip"
  ],
  "files": [
    {
      "path": "registry/tealmac/reui-filters/filters-advanced.tsx",
      "content": "/**\n * filters-advanced - adapted for tealmac UI from ReUI \"filters/filters-advanced\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n/* eslint-disable jsx-a11y/no-static-element-interactions -- keyboard handling is on the focusable parent (arrow keys, Enter, Escape); the flagged elements are pointer-only affordances or key-event forwarders, as in the ReUI original. */\n\"use client\"\n\nimport * as React from \"react\"\nimport {\n  ChevronDownIcon,\n  CircleAlertIcon,\n  CopyIcon,\n  EllipsisVerticalIcon,\n  FolderPlusIcon,\n  GripVerticalIcon,\n  ListFilterIcon,\n  PlusIcon,\n  RefreshCwIcon,\n  Trash2Icon,\n  UngroupIcon,\n  XIcon,\n} from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\"\nimport { Input } from \"@/components/ui/input\"\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/components/ui/popover\"\nimport {\n  Tooltip,\n  TooltipContent,\n  TooltipProvider,\n  TooltipTrigger,\n} from \"@/components/ui/tooltip\"\nimport { FilterFieldPicker } from \"@/components/reui/filters/filters-builder\"\nimport {\n  FilterMoveToMenuItems,\n  FilterOperatorPopover,\n  FilterRuleMenuItems,\n  FilterValuePopover,\n  useFilterRuleDisplay,\n} from \"@/components/reui/filters/filters-chip\"\nimport {\n  filterControlSizes,\n  filterReadOnlyProps,\n  FilterReorderProvider,\n  isFilterLocked,\n  useFilterActions,\n  useFilterChipAutoOpen,\n  useFilterChipFocused,\n  useFilterFocusEmpty,\n  useFilterFocusStore,\n  useFilterRender,\n  useFilterReorderable,\n  useFilterRowPending,\n  useFilterRowStateStore,\n  useFilterSegmentFocus,\n  useFilterState,\n  type FilterActionsContextValue,\n} from \"@/components/reui/filters/filters-context\"\nimport {\n  FILTER_ROW_SELECTOR,\n  useFilterRowDrag,\n} from \"@/components/reui/filters/filters-dnd\"\nimport { filterIssueLabel } from \"@/components/reui/filters/filters-i18n\"\nimport {\n  FILTER_FIELD_PICKER_CLASS,\n  FILTER_MENU_CLASS,\n  FILTER_MENU_LABEL_CLASS,\n  filterCombinatorSlot,\n  getFilterField,\n  isFilterFieldPickable,\n  joinFilterPath,\n} from \"@/components/reui/filters/filters-lib\"\nimport {\n  getFilterArity,\n  getFilterOperator,\n  operatorTakesValue,\n} from \"@/components/reui/filters/filters-operators\"\nimport {\n  collectFilterIssues,\n  createFilterRule,\n  isFilterRule,\n} from \"@/components/reui/filters/filters-query\"\nimport type {\n  FilterCombinator,\n  FilterEmptyStateContext,\n  FilterField,\n  FilterGroupNode,\n  FilterIssue,\n  FilterNode,\n  FilterOperator,\n  FilterQuery,\n  FilterRule,\n} from \"@/components/reui/filters/filters-types\"\n\n/* -------------------------------------------------------------------------- */\n/*                                  Columns                                   */\n/* -------------------------------------------------------------------------- */\n\nconst CONTENT_COLUMNS = [\"combinator\", \"field\", \"operator\", \"value\"] as const\n\nconst ACTION_COLUMNS = [\"drag\", \"menu\", \"add\", \"remove\"] as const\n\n/** Every column a row may draw, in two bands. Navigation is by COLUMN NAME and\n * never position: the BANDS keep ArrowDown off a group's footer button. */\ntype FilterColumn =\n  (typeof CONTENT_COLUMNS)[number] | (typeof ACTION_COLUMNS)[number]\n\n/** The nearest column in `band` that `available` has; backward wins a tie. */\nfunction nearestColumn(\n  band: readonly FilterColumn[],\n  from: FilterColumn,\n  available: Map<string | null, HTMLElement>\n): HTMLElement | undefined {\n  const at = band.indexOf(from)\n  if (at === -1) return undefined\n  for (let step = 0; step < band.length; step++) {\n    const before = step === 0 ? undefined : available.get(band[at - step] ?? \"\")\n    if (before) return before\n    const after = available.get(band[at + step] ?? \"\")\n    if (after) return after\n  }\n  return undefined\n}\n\n/** Marks a focusable cell control, read by the keyboard walker. Not\n * `data-slot`: a cell control is handed to a Radix trigger through `asChild`,\n * which merges its own, so a slot here would be two owners on one attribute. */\nconst CELL_ATTRIBUTE = \"data-filter-cell\"\n\n/** Marks a cell the user TYPES into: the builder claims the arrows, Home, End\n * and Delete, and each means something else in a text box. */\nconst CELL_INPUT_ATTRIBUTE = \"data-filter-cell-input\"\n\nconst ROW_SELECTOR = FILTER_ROW_SELECTOR\n\n/** Hands every row's handle its pointer wiring: only the panel, which owns the\n * body element, can measure a drop. */\n\nconst FilterDragContext = React.createContext<ReturnType<\n  typeof useFilterRowDrag\n> | null>(null)\n\n/** What each node is missing, by id. An empty map by default, so a row mounted\n * outside the shipped panel gets \"nothing is wrong\" instead of a throw. */\nconst FilterIssueContext = React.createContext<\n  ReadonlyMap<string, FilterIssue>\n>(new Map())\n\nfunction cellProps(column: FilterColumn, active: FilterColumn | null) {\n  return {\n    \"data-filter-cell\": column,\n    // ONE tab stop for the whole builder; the arrows move within it.\n    tabIndex: active === column ? 0 : -1,\n  }\n}\n\n/** What an INVALID cell wears: `aria-invalid` to announce it, `data-invalid`\n * to style it, `aria-description` for the sentence. */\nfunction issueProps(\n  issue: FilterIssue | undefined,\n  column: FilterIssue[\"column\"],\n  message: string\n) {\n  if (!issue || issue.column !== column) return null\n  return {\n    \"aria-invalid\": true,\n    \"data-invalid\": \"\",\n    \"aria-description\": message,\n    // NO `title`: the hint icon carries the sentence in a real tooltip, and a\n    // native one would clobber the truncation `title` beside it.\n  } as const\n}\n\n/** Sera's uppercase and wide tracking cost about a third of a cell, so where\n * every other style drew \"migration\" sera drew \"MIGRATI...\". */\nconst SERA_TEXT_CLASS = \"style-sera:normal-case style-sera:tracking-normal\"\n\nconst CELL_CLASS = cn(\n  \"w-full min-w-0 justify-between gap-1.5 font-normal\",\n  // `>svg` is the caret and only the caret: a field's own type icon sits in a\n  // nested span, where it keeps full strength because it is content.\n  \"[&>svg]:text-muted-foreground\",\n  // WHAT A CELL GIVES UP FIRST: padding, icon and caret cost about 44px before\n  // a character is drawn, and the name is what nothing else can reconstruct.\n  // Container queries and not a viewport breakpoint: the question is how wide\n  // THIS cell is, and one panel holds a 300px cell and a 40px one.\n  \"@max-[7rem]/cell:gap-0 @max-[7rem]/cell:[&>svg]:hidden\",\n  \"@max-[5rem]/cell:[&_span>svg]:hidden\",\n  SERA_TEXT_CLASS\n)\n\n/** What an invalid cell looks like. A ring, not a border: a border changes the\n * box, so a cell turning invalid would nudge every cell beside it. */\nconst CELL_INVALID_CLASS =\n  \"data-invalid:ring-destructive/40 data-invalid:ring-1\"\n\n/** Width of the leading combinator column. The 58.72px pill put this track at\n * 4rem and it does not shrink now the pill has: it is sized for the longest of\n * the three things in it, \"Where\", 51.44px in every style. */\nconst COMBINATOR_CLASS = cn(\n  \"w-16 shrink-0 items-center justify-center\",\n  // 6px of its own on TOP of the band's `gap-1.5`: this column is the\n  // sentence's connective, not a fourth control butted against the attribute.\n  \"me-1.5\"\n)\n\n/** The two static words in that column, CENTRED because the pill's own\n * `justify-center` centres its word. `w-full`, or `truncate` has no box. */\nconst COMBINATOR_TEXT_CLASS = cn(\n  \"text-muted-foreground w-full truncate px-1 text-center text-sm\",\n  SERA_TEXT_CLASS\n)\n\n/** A row is TWO BANDS. The trailing pair of every row at every depth shares one\n * vertical axis - 0.00px of spread from 1104px to 240px, eight styles, depth\n * three - and only because the content band may shrink to nothing. */\nconst ROW_BAND_CLASS = \"flex min-w-0 items-center gap-1.5\"\n\nconst CONTENT_BAND_CLASS = \"flex min-w-0 flex-1 items-center gap-1.5\"\n\n/** FLEX and not a block: a `Button` is `inline-flex`, so a block wrapper builds\n * a line box as tall as its font's strut - 28px buttons in 28.141px wrappers. */\nconst CELL_BOX_CLASS = \"@container/cell flex min-w-0 shrink grow-0\"\n\n/** THE DEFAULT WIDTH OF EACH CONTENT CELL. An INLINE FALLBACK and not a\n * declaration on the panel: declared, the panel would beat anything an ANCESTOR\n * set, which is where a consumer sets it in popover mode. So all four work:\n *\n *   <Filters variant=\"advanced\" className=\"[--filter-field-width:14rem]\" />\n *   <FiltersAdvancedPanel className=\"[--filter-operator-width:7rem]\" />\n *   <Card className=\"[--filter-value-width:16rem]\"><Filters … /></Card>\n *   [data-slot=\"filters-advanced\"] { --filter-field-width: 14rem } */\nconst FIELD_CELL_CLASS = \"basis-[var(--filter-field-width,11rem)]\"\nconst OPERATOR_CELL_CLASS = \"basis-[var(--filter-operator-width,9rem)]\"\nconst VALUE_CELL_CLASS = \"basis-[var(--filter-value-width,12rem)]\"\n\n/** The trailing band. `pe-1` is on the BAND and not the gutter, since a group\n * card is `pe-0`; the footer and `DROP_SLOT_INDICATOR` restate the same four. */\nconst ACTION_BAND_CLASS = cn(\n  \"text-muted-foreground flex shrink-0 items-center gap-0.5 pe-1\"\n)\n\n/** What the grip and the kebab wear while open. TWO ATTRIBUTES, because Radix\n * sets `data-state=\"open\"` and Base UI `data-popup-open`, so one selector alone\n * would be dead in one twin, silently, in a byte-locked file. */\nconst ACTION_CONTROL_CLASS = cn(\n  \"hover:inset-ring hover:inset-ring-border\",\n  // Base UI.\n  \"data-popup-open:inset-ring data-popup-open:inset-ring-border\",\n  // Radix.\n  \"data-[state=open]:inset-ring data-[state=open]:inset-ring-border\"\n)\n\n/** The gap between sibling rows, one third of one measurement:\n * `FILTER_ROW_SEAM_PX` is HALF of it and the footer's `-mt-*` cancels it. */\nconst FILTER_ROW_GAP_CLASS = \"gap-3\"\nconst FILTER_ROW_GAP_CANCEL_CLASS = \"-mt-3\"\nconst FILTER_ROW_HALF_GAP_CLASS = {\n  // The slot names the BOUNDARY between two rows, which is the middle of the\n  // gap: 6px of it less HALF the rule's own 2px, so its CENTRE lands there.\n  before: \"data-[drop-edge=before]:after:mb-[5px]\",\n  after: \"data-[drop-edge=after]:after:mt-[5px]\",\n} as const\n\n/** POPOVER: the popover content is `p-0`, so this IS the popup's own inner\n * padding. INLINE there is no popup, and a panel that pads itself as well is a\n * second inset the page did not ask for. */\nconst PANEL_PAD_VAR = \"--filter-panel-pad\"\nconst PANEL_PAD_POPOVER = \"0.75rem\"\nconst PANEL_PAD_INLINE = \"0px\"\n\n/** The panel's ONE horizontal rhythm: a row's trailing controls sit at the\n * content edge, which IS this padding, so a footer that disagrees breaks it. */\nconst PANEL_GUTTER_CLASS = \"px-(--filter-panel-pad)\"\n\nconst PANEL_CLASS = \"flex w-full min-w-0 flex-col gap-2 py-(--filter-panel-pad)\"\n\n/** A RING and not a border, the whole answer to the staggered trailing\n * controls: a border pushes the content edge inward a pixel per level. */\nconst GROUP_CARD_CLASS = cn(\n  \"bg-muted/40 min-w-0 flex-1 rounded-md\",\n  \"inset-ring inset-ring-border\",\n  \"ps-2 pe-0\",\n  \"data-invalid:inset-ring-destructive/50\",\n  // The DESTINATION of a drop into this group, told apart from the insertion\n  // slot by STYLE and not size: dashed is not there yet, solid exists.\n  \"data-drop-into:bg-muted/60\",\n  \"data-drop-into:outline-1 data-drop-into:outline-solid\",\n  \"data-drop-into:outline-border data-drop-into:-outline-offset-2\"\n)\n\n/** THE CONTAINER a row measures its own room against, on the panel body and on\n * every group's list, so a row asks how wide the list it is IN is. */\nconst TRACK_CONTAINER_CLASS = \"@container/track\"\n\n/** When a group stops putting its combinator BESIDE the card. A DEPTH budget\n * was wrong both ways: at 380px the depth-three row painted zero pixels of\n * field, operator and value and fanned the kebab column out by up to 119px.\n * 26rem is what a row MEASURES: 134px of fixed cost plus about 200px of cells. */\nconst GROUP_COMBINATOR_WRAP_CLASS = \"@max-[26rem]/track:w-full\"\n\n/** The combinator itself, once its wrapper has a whole line. Pinned to the\n * same 4rem the gutter track is, so it is the same control at every width. */\nconst GROUP_COMBINATOR_WRAPPED_CLASS = \"@max-[26rem]/track:w-16\"\n\n/** How a row shows where a dragged node would land. `data-drop-edge` is an\n * insertion BETWEEN rows, drawn here; `data-drop-into` is painted on the CARD,\n * so \"inside this group\" and \"after this group\" are not one picture. */\nconst DROP_SLOT_INDICATOR = cn(\n  // The SOURCE in flight, faded rather than hidden. THREE FIFTHS is a contrast\n  // measurement: at 35 under a `blur-[1px]` the text composited to #a9a9a9,\n  // 2.35:1 on the light panel, under even the 3:1 line for a non-text mark.\n  \"relative rounded-md\",\n  \"data-dragging:opacity-60\",\n  // THE INSERTION LINE lives in the gap rather than overlaying a real row.\n  // `end-1` and not `end-0`: four pixels of `pe-1` are the kebab column.\n  \"data-drop-edge:after:absolute\",\n  \"data-drop-edge:after:start-0 data-drop-edge:after:end-1\",\n  \"data-drop-edge:after:h-0.5 data-drop-edge:after:rounded-full\",\n  \"data-drop-edge:after:bg-primary\",\n  \"data-drop-edge:after:z-10\",\n  \"data-[drop-edge=before]:after:bottom-full\",\n  FILTER_ROW_HALF_GAP_CLASS.before,\n  \"data-[drop-edge=after]:after:top-full\",\n  FILTER_ROW_HALF_GAP_CLASS.after\n)\n\n/** What a CONDITION row draws, which is what a group's row draws: the slot and\n * nothing else. It used to add a faint dashed outline of its own, a second\n * dashed rectangle a few pixels from the first saying what it already said. */\nconst DROP_INDICATOR = DROP_SLOT_INDICATOR\n\n/** How the footer says \"append to the top level\": the same RULE the rows draw.\n * `data-drop-into` and not `data-drop-edge`, because an explicit zone is a\n * DESTINATION. Both ends restate the padding VARIABLE, since `inset` resolves\n * against the PADDING box and `inset-x-0` overran every rule above it. */\nconst FOOTER_DROP_CLASS = cn(\n  \"data-drop-into:after:absolute\",\n  \"data-drop-into:after:start-(--filter-panel-pad)\",\n  \"data-drop-into:after:end-[calc(var(--filter-panel-pad)+4px)]\",\n  \"data-drop-into:after:top-0 data-drop-into:after:h-0.5\",\n  \"data-drop-into:after:rounded-full data-drop-into:after:bg-primary\"\n)\n\n/** The cells a row owns ITSELF: a group's row contains its children's rows, so\n * a bare `querySelectorAll` would let ArrowRight walk into the first of them. */\nfunction ownCells(row: HTMLElement): HTMLElement[] {\n  return Array.from(\n    row.querySelectorAll<HTMLElement>(`[${CELL_ATTRIBUTE}]`)\n  ).filter((cell) => cell.closest<HTMLElement>(ROW_SELECTOR) === row)\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                Shared cells                                */\n/* -------------------------------------------------------------------------- */\n\ninterface RowPosition {\n  index: number\n  parentId: string\n  combinator: FilterCombinator\n  depth: number\n}\n\n/** The leading and/or slot: one group is joined by ONE operator, and mixing is\n * what a nested group is FOR. */\nfunction CombinatorCell({\n  index,\n  parentId,\n  combinator,\n  active,\n  onFocus,\n  className,\n}: {\n  index: number\n  parentId: string\n  combinator: FilterCombinator\n  active: FilterColumn | null\n  onFocus: (column: FilterColumn) => () => void\n  className?: string\n}) {\n  const actions = useFilterActions()\n  const sizes = filterControlSizes(actions)\n  const slot = filterCombinatorSlot(index)\n  const word = combinator === \"and\" ? actions.labels.and : actions.labels.or\n\n  if (slot === \"where\") {\n    return (\n      <span className={cn(COMBINATOR_TEXT_CLASS, className)}>\n        {actions.labels.where}\n      </span>\n    )\n  }\n\n  if (slot === \"echo\") {\n    return <span className={cn(COMBINATOR_TEXT_CLASS, className)}>{word}</span>\n  }\n\n  const name = actions.labels.combinatorLabel(word)\n\n  return (\n    <Button\n      variant=\"outline\"\n      size={sizes.button}\n      /* The WORD is in the name: the track is fixed, so a locale whose\n         word overflows draws \"a...\". */\n      aria-label={name}\n      title={name}\n      disabled={actions.disabled}\n      {...filterReadOnlyProps(actions)}\n      className={cn(\n        \"group/combinator relative w-full min-w-0 justify-center px-1.5 font-normal\",\n        SERA_TEXT_CLASS,\n        className\n      )}\n      {...cellProps(\"combinator\", active)}\n      onFocus={onFocus(\"combinator\")}\n      onClick={() => actions.toggleCombinator(parentId)}\n    >\n      <span className=\"truncate\">{word}</span>\n      {/* ABSOLUTELY POSITIONED, so the word still centres at 0.00px. */}\n      <span\n        aria-hidden=\"true\"\n        className={cn(\n          \"pointer-events-none absolute end-1 opacity-0 transition-opacity\",\n          \"group-hover/combinator:opacity-60\",\n          \"group-focus-visible/combinator:opacity-60\",\n          \"[&_svg]:size-3\"\n        )}\n      >\n        <RefreshCwIcon />\n      </span>\n    </Button>\n  )\n}\n\n/** Whether dragging this node could change the tree at all; the grip is drawn\n * only when it could. Every destination outside the footer zone lives inside\n * some row and the drop layer discards any inside the dragged one, so the sole\n * child of the root is the one case with nowhere to go. A pure function of the\n * QUERY, deliberately blind to `disabled` and `readOnly`: a locked bar keeps\n * its grip, because \"you may not move this\" and \"there is nowhere to move it\"\n * are different sentences. */\nfunction canFilterNodeMove(\n  query: FilterQuery<unknown>,\n  position: { parentId: string }\n) {\n  if (position.parentId !== query.id) return true\n  return query.rules.length > 1\n}\n\n/** The error, as a QUIET mark the pointer can ask about: ONE per ROW, and\n * `aria-hidden`, since the cell carries it as `aria-description`. */\nfunction RowIssueHint({\n  message,\n  className,\n}: {\n  message: string\n  className?: string\n}) {\n  if (!message) return null\n  return (\n    <TooltipProvider delayDuration={200}>\n      <Tooltip>\n        <TooltipTrigger asChild>\n          <span\n            data-slot=\"filter-row-issue\"\n            /* Focusable so a keyboard user can summon it, but OUT of the\n               tab order: the sentence is already on the invalid cell. */\n            tabIndex={-1}\n            aria-hidden=\"true\"\n            className={cn(\n              \"text-destructive flex shrink-0 items-center justify-center [&_svg]:size-3.5\",\n              className\n            )}\n          >\n            <CircleAlertIcon />\n          </span>\n        </TooltipTrigger>\n        <TooltipContent side=\"top\">{message}</TooltipContent>\n      </Tooltip>\n    </TooltipProvider>\n  )\n}\n\n/** The drag handle: what ARMS the gesture, since arming the row would turn\n * every text selection into a drag, and the only thing a screen reader can be\n * told about, which is why Alt+arrow hangs off it. */\nfunction RowHandle({\n  nodeId,\n  active,\n  onFocus,\n}: {\n  nodeId: string\n  active: FilterColumn | null\n  onFocus: (column: FilterColumn) => () => void\n}) {\n  const actions = useFilterActions()\n  const sizes = filterControlSizes(actions)\n  const dragProps = React.useContext(FilterDragContext)\n  const locked = isFilterLocked(actions)\n\n  return (\n    <Button\n      variant=\"ghost\"\n      size={sizes.icon}\n      aria-label={actions.labels.reorder}\n      /* The activation is the DRAG, which no click performs, so without these\n         a screen reader finds a \"Reorder\" button that appears broken. */\n      aria-keyshortcuts=\"Alt+ArrowUp Alt+ArrowDown\"\n      aria-description={actions.labels.reorderHint}\n      disabled={actions.disabled}\n      {...filterReadOnlyProps(actions)}\n      /* `touch-none`, or a finger on the handle becomes a page scroll the\n         gesture then fights. Muted at rest, never hidden. */\n      className={cn(\n        \"focus-visible:text-foreground cursor-grab touch-none\",\n        \"active:cursor-grabbing\",\n        ACTION_CONTROL_CLASS\n      )}\n      {...cellProps(\"drag\", active)}\n      onFocus={onFocus(\"drag\")}\n      /* Not armed at all while locked; the engine refuses it again. */\n      {...(locked ? null : dragProps?.(nodeId))}\n    >\n      <GripVerticalIcon />\n    </Button>\n  )\n}\n\n/** Which cell of a row owns the builder's single tab stop. An operator change\n * can take the value column out from under the focus pointing at it. */\nfunction useActiveColumn(\n  nodeId: string,\n  columns: FilterColumn[],\n  isFirstRow: boolean\n): FilterColumn | null {\n  const focused = useFilterChipFocused(nodeId)\n  const segment = useFilterSegmentFocus(nodeId)\n  const noFocus = useFilterFocusEmpty()\n\n  if (focused) {\n    return segment && columns.includes(segment as FilterColumn)\n      ? (segment as FilterColumn)\n      : columns[0]\n  }\n  return noFocus && isFirstRow ? columns[0] : null\n}\n\nfunction useFilterIssue(nodeId: string): FilterIssue | undefined {\n  return React.useContext(FilterIssueContext).get(nodeId)\n}\n\n/* -------------------------------------------------------------------------- */\n/*                              Inline free text                              */\n/* -------------------------------------------------------------------------- */\n\n/** Whether a value is FREE TEXT, and therefore typed in the row itself. The\n * CHIP row keeps its popover for every value, deliberately, which is why this\n * lives here and not in the shared display hook. NUMBER is in: empty clears,\n * and anything unparseable snaps back to the last committed number. */\nfunction usesInlineTextEditor<V, O>(\n  field: FilterField<V, O>,\n  operator: FilterOperator | undefined,\n  hasCustomDisplay: boolean\n): boolean {\n  if (field.editor) return false\n  if (field.options || field.loadOptions) return false\n  if (field.renderValue || field.valueText || hasCustomDisplay) return false\n  const type = field.type ?? \"text\"\n  if (type !== \"text\" && type !== \"number\") return false\n  return getFilterArity(operator) === \"one\"\n}\n\n/** The value cell as a real text box. COMMIT IS BLUR AND ENTER: per keystroke\n * makes the ROOT the source of truth for every character, and debouncing only\n * adds a window where the cell and the query disagree with no event. */\nfunction FilterInlineValueCell<V, O>({\n  rule,\n  field,\n  issue,\n  issueText,\n  active,\n  onFocus,\n}: {\n  rule: FilterRule<V>\n  field: FilterField<V, O>\n  issue: FilterIssue | undefined\n  issueText: string\n  active: FilterColumn | null\n  onFocus: (column: FilterColumn) => () => void\n}) {\n  const actions = useFilterActions<V, O>()\n  const focusStore = useFilterFocusStore()\n  const locked = isFilterLocked(actions)\n  const numeric = (field.type ?? \"text\") === \"number\"\n  // The handoff the value POPOVER honours, answered by taking the caret.\n  const autoOpen = useFilterChipAutoOpen(rule.id) === \"value\"\n  const inputRef = React.useRef<HTMLInputElement>(null)\n\n  const committed =\n    rule.value === undefined || rule.value === null ? \"\" : String(rule.value)\n  const [draft, setDraft] = React.useState(committed)\n  // STATE and not a ref: the sync below runs during render.\n  const [seed, setSeed] = React.useState(committed)\n\n  // Adjusting state during render; an effect would paint the stale text.\n  if (seed !== committed) {\n    setSeed(committed)\n    setDraft(committed)\n  }\n\n  // CONSUMED as it is honoured: a flag left standing is spent by the next row.\n  React.useEffect(() => {\n    if (!autoOpen) return\n    if (!locked) {\n      const input = inputRef.current\n      input?.focus()\n      // SELECTED: the condition step may have coerced a value across.\n      input?.select()\n    }\n    focusStore.set({ id: rule.id, segment: \"value\", autoOpen: false })\n  }, [autoOpen, locked, focusStore, rule.id])\n\n  const commit = () => {\n    if (draft === seed) return\n\n    if (numeric) {\n      const text = draft.trim()\n      // Empty clears rather than writing 0, which silently matches rows.\n      if (text === \"\") {\n        actions.updateRule(rule.id, { value: undefined as V })\n        return\n      }\n      const parsed = Number(text)\n      // Revert, do not write: a NaN compares false against every row.\n      if (!Number.isFinite(parsed)) {\n        setDraft(seed)\n        return\n      }\n      actions.updateRule(rule.id, { value: parsed as V })\n      return\n    }\n\n    actions.updateRule(rule.id, { value: draft as V })\n  }\n\n  return (\n    /* A FRAGMENT, not a wrapper: the positioning context for the error mark\n       is the CELL itself, which already carries the column's basis. */\n    <>\n      <Input\n        ref={inputRef}\n        aria-label={field.label}\n        placeholder={field.placeholder ?? actions.labels.valuePlaceholder}\n        /* The RIGHT KEYPAD only: `type=\"number\"` brings spinners. */\n        inputMode={numeric ? \"decimal\" : undefined}\n        value={draft}\n        /* `h-full` and no size class: `Input` has ONE height per style, so\n           at `size=\"sm\"` it was a pixel taller in nova and two in sera. */\n        className={cn(\"h-full\", issueText && \"pe-7\", CELL_INVALID_CLASS)}\n        /* Native `readOnly`, not `disabled`: it keeps its tab stop. */\n        readOnly={locked}\n        disabled={actions.disabled}\n        {...filterReadOnlyProps(actions)}\n        {...cellProps(\"value\", active)}\n        {...{ [CELL_INPUT_ATTRIBUTE]: \"\" }}\n        {...issueProps(issue, \"value\", issueText)}\n        onFocus={onFocus(\"value\")}\n        onChange={(event) => setDraft(event.target.value)}\n        onBlur={commit}\n        onKeyDown={(event) => {\n          if (event.key === \"Enter\" && !event.nativeEvent.isComposing) {\n            event.preventDefault()\n            commit()\n            return\n          }\n          if (event.key === \"Escape\") {\n            /* Only when there is something to revert; Escape belongs to the\n               surface the builder sits in. */\n            if (draft === seed) return\n            event.preventDefault()\n            event.stopPropagation()\n            setDraft(seed)\n          }\n        }}\n      />\n      <RowIssueHint\n        message={issueText}\n        /* `pointer-events-none`, so a click still lands in the input. */\n        className=\"pointer-events-none absolute end-2 top-1/2 -translate-y-1/2 [&>*]:pointer-events-auto\"\n      />\n    </>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Rule row                                  */\n/* -------------------------------------------------------------------------- */\n\nexport interface FilterAdvancedRowProps<V = unknown> {\n  rule: FilterRule<V>\n  position: RowPosition\n}\n\nfunction FilterAdvancedRowImpl<V, O>({\n  rule,\n  position,\n}: FilterAdvancedRowProps<V>) {\n  const actions = useFilterActions<V, O>()\n  const render = useFilterRender<V, O>()\n  const sizes = filterControlSizes(actions)\n  const focusStore = useFilterFocusStore()\n  const locked = isFilterLocked(actions)\n  const { query } = useFilterState<V>()\n\n  const field = getFilterField(actions.index, rule.path)\n  const operators = field ? actions.resolveOperators(field) : []\n  const operator = getFilterOperator(operators, rule.operator)\n  const takesValue = Boolean(rule.operator) && operatorTakesValue(operator)\n  const inlineValue =\n    takesValue && field\n      ? usesInlineTextEditor(field, operator, Boolean(render.renderValue))\n      : false\n\n  const issue = useFilterIssue(rule.id)\n  const issueText = issue ? filterIssueLabel(issue, actions.labels) : \"\"\n\n  const {\n    pathText,\n    pathLabel,\n    pathCollapsed,\n    operatorLabel,\n    valueLabel,\n    valueText,\n    valueFullText,\n    valueEmpty,\n  } = useFilterRuleDisplay<V, O>(rule, field, operator)\n\n  /* ------------------------------ field cell ------------------------------ */\n\n  const fieldAutoOpen = useFilterChipAutoOpen(rule.id) === \"field\"\n  const [pickerOpen, setPickerOpen] = React.useState(false)\n  // Controlled so both can REFUSE to open while locked.\n  const [menuOpen, setMenuOpen] = React.useState(false)\n  // Seeded from the rule's own level, so amending opens beside its siblings.\n  const [pickerPath, setPickerPath] = React.useState<string[]>(() =>\n    rule.path.slice(0, -1)\n  )\n  const [pickerQuery, setPickerQuery] = React.useState(\"\")\n\n  // A new row arrives with a GUESS at its field, so the one choice not yet the\n  // user's own opens itself. CONSUMED as it is honoured: `pickerOpen` is a\n  // dependency, so a flag left standing reopened the picker in the frame it\n  // closed, a keyboard trap on the one row a user creates most.\n  React.useEffect(() => {\n    if (!fieldAutoOpen || pickerOpen) return\n    if (!locked) setPickerOpen(true)\n    focusStore.set({ id: rule.id, segment: \"field\", autoOpen: false })\n  }, [fieldAutoOpen, pickerOpen, locked, focusStore, rule.id])\n\n  // Re-seed on each open, so a browse that was abandoned last time does not\n  // decide where this one starts.\n  React.useEffect(() => {\n    if (!pickerOpen) return\n    setPickerPath(rule.path.slice(0, -1))\n    setPickerQuery(\"\")\n  }, [pickerOpen, rule.path])\n\n  /*\n   * The focus handoff to the condition, and THE ONE PLACE the twins cannot\n   * share an implementation. Committing an attribute closes this picker and\n   * opens the operator menu in the same commit, so both want focus. Base UI\n   * orders that for free; Radix opens the menu first, then this popover's\n   * `FocusScope` restores focus to the cell, which is a `focusin` outside the\n   * menu's `DismissableLayer`, so the menu dismisses itself in the frame it\n   * appeared. Suppressed ONLY on the close that hands off, so every other\n   * close still returns focus to the cell rather than to the BODY.\n   *\n   * LATCHED and not read at close time, because the operator popover consumes\n   * the flag the instant its menu opens, before this one has unmounted.\n   */\n  const handoffRef = React.useRef(false)\n  React.useEffect(() => {\n    if (!pickerOpen) return\n    handoffRef.current = false\n    return focusStore.subscribe(() => {\n      if (focusStore.getSnapshot().autoOpen) handoffRef.current = true\n    })\n  }, [focusStore, pickerOpen])\n\n  const onCloseAutoFocus = (event: Event) => {\n    if (!handoffRef.current) return\n    handoffRef.current = false\n    event.preventDefault()\n  }\n\n  /* ------------------------------- tab stop ------------------------------- */\n\n  const slot = filterCombinatorSlot(position.index)\n  const reorderable = useFilterReorderable()\n  const canMove = reorderable && canFilterNodeMove(query, position)\n  const rowStateStore = useFilterRowStateStore()\n  // Still waiting for its attribute, so neither later cell is drawn.\n  const pending = useFilterRowPending(rule.id)\n\n  const columns = React.useMemo(() => {\n    const list: FilterColumn[] = []\n    if (slot === \"toggle\") list.push(\"combinator\")\n    list.push(\"field\")\n    if (!pending) {\n      list.push(\"operator\")\n      if (takesValue) list.push(\"value\")\n    }\n    // The grip is only a tab stop when it is drawn.\n    if (canMove) list.push(\"drag\")\n    list.push(\"menu\")\n    return list\n  }, [slot, takesValue, canMove, pending])\n\n  const active = useActiveColumn(\n    rule.id,\n    columns,\n    position.depth === 1 && position.index === 0\n  )\n\n  const onCellFocus = React.useCallback(\n    (column: FilterColumn) => () =>\n      focusStore.set({ id: rule.id, segment: column, autoOpen: false }),\n    [focusStore, rule.id]\n  )\n\n  /* -------------------------------- render -------------------------------- */\n\n  if (!field) return null\n\n  return (\n    <div\n      /* A GROUP, not a grid row: four depths of grid describes to no\n         assistive technology at all. */\n      role=\"group\"\n      aria-label={actions.labels.rowLabel(\n        `${pathText} ${operatorLabel}`,\n        position.depth\n      )}\n      data-slot=\"filter-row\"\n      data-node-id={rule.id}\n      data-parent-id={position.parentId}\n      data-index={position.index}\n      data-depth={position.depth}\n      className={cn(\"group/row\", ROW_BAND_CLASS, DROP_INDICATOR)}\n    >\n      <div className={cn(COMBINATOR_CLASS, CELL_BOX_CLASS)}>\n        <CombinatorCell\n          index={position.index}\n          parentId={position.parentId}\n          combinator={position.combinator}\n          active={active}\n          onFocus={onCellFocus}\n        />\n      </div>\n\n      {/* THE CONTENT BAND: sized to itself, not to a share of the row. */}\n      <div className={CONTENT_BAND_CLASS}>\n        <div className={cn(CELL_BOX_CLASS, FIELD_CELL_CLASS)}>\n          <Popover\n            open={pickerOpen}\n            onOpenChange={(next) => {\n              if (next && locked) return\n              setPickerOpen(next)\n            }}\n          >\n            <PopoverTrigger\n              asChild\n              disabled={actions.disabled}\n              {...filterReadOnlyProps(actions)}\n            >\n              <Button\n                variant=\"outline\"\n                size={sizes.button}\n                /* The path is truncated on screen, so the name carries all\n                   of it: \"Primary loca... > State\" identifies nothing. */\n                aria-label={pathText}\n                /* And as a `title` - unless the path is COLLAPSED, where the\n                   ellipsis inside already carries this exact sentence. */\n                title={pathCollapsed ? undefined : pathText}\n                className={CELL_CLASS}\n                {...cellProps(\"field\", active)}\n                onFocus={onCellFocus(\"field\")}\n              >\n                <span className=\"flex min-w-0 items-center gap-1.5 truncate\">\n                  {field.icon}\n                  <span className=\"truncate\">{pathLabel}</span>\n                </span>\n                <ChevronDownIcon />\n              </Button>\n            </PopoverTrigger>\n            <PopoverContent\n              align=\"start\"\n              onCloseAutoFocus={onCloseAutoFocus}\n              className={cn(\n                FILTER_FIELD_PICKER_CLASS,\n                actions.fieldPickerClassName\n              )}\n            >\n              <FilterFieldPicker<V, O>\n                path={pickerPath}\n                onPathChange={setPickerPath}\n                query={pickerQuery}\n                onQueryChange={setPickerQuery}\n                onSelect={(path, defaultOperator) => {\n                  setPickerOpen(false)\n                  // BUILDING versus AMENDING, the fork of the stepped\n                  // flow. Naming `operator` retires the field handoff.\n                  focusStore.set({\n                    id: rule.id,\n                    segment: pending ? \"operator\" : \"field\",\n                    autoOpen: pending,\n                  })\n                  // BEFORE the same-path early return, or a row minted\n                  // on a guessed field the user then picks stays pending.\n                  rowStateStore.resolvePending(rule.id)\n                  // Re-picking the field it has is a dismissal.\n                  if (joinFilterPath(path) === joinFilterPath(rule.path)) return\n                  // On the create path the condition stays UNSET, so the\n                  // menu opening next has nothing selected.\n                  actions.updateRule(rule.id, {\n                    path,\n                    operator: pending ? \"\" : (defaultOperator ?? \"\"),\n                    value: undefined,\n                  })\n                }}\n              />\n            </PopoverContent>\n          </Popover>\n        </div>\n\n        {pending ? null : (\n          <div className={cn(CELL_BOX_CLASS, OPERATOR_CELL_CLASS)}>\n            <FilterOperatorPopover\n              rule={rule}\n              field={field}\n              trigger={\n                <Button\n                  variant=\"outline\"\n                  size={sizes.button}\n                  /* No `aria-label`: the label IS the name. */\n                  title={operatorLabel}\n                  className={cn(\n                    CELL_CLASS,\n                    CELL_INVALID_CLASS,\n                    \"text-muted-foreground\"\n                  )}\n                  {...cellProps(\"operator\", active)}\n                  {...issueProps(issue, \"operator\", issueText)}\n                  onFocus={onCellFocus(\"operator\")}\n                >\n                  <span className=\"truncate\">{operatorLabel}</span>\n                  <ChevronDownIcon />\n                </Button>\n              }\n            />\n          </div>\n        )}\n\n        {/* The cell stays even with no value: dropping it would shift the\n            trailing buttons into the value column on that row alone. It goes\n            ENTIRELY while the row is PENDING, the one case that argument does\n            not cover: a row choosing its attribute has no column count yet. */}\n        {pending ? null : (\n          <div\n            className={cn(\n              CELL_BOX_CLASS,\n              VALUE_CELL_CLASS,\n              /* The positioning context for an inline editor's error mark. */\n              \"relative\",\n              /* What lets an inline box match the buttons beside it: as tall as\n                 the row, so `h-full` inside resolves to the button height. */\n              \"self-stretch\"\n            )}\n          >\n            {takesValue ? (\n              inlineValue ? (\n                <FilterInlineValueCell<V, O>\n                  rule={rule}\n                  field={field}\n                  issue={issue}\n                  issueText={issueText}\n                  active={active}\n                  onFocus={onCellFocus}\n                />\n              ) : (\n                <FilterValuePopover\n                  rule={rule}\n                  field={field}\n                  operator={operator}\n                  trigger={\n                    <Button\n                      variant=\"outline\"\n                      size={sizes.button}\n                      /* The VALUE is the name, never the attribute.\n                         Locked, it grows to the whole list. */\n                      aria-label={locked ? valueFullText : valueText}\n                      title={valueFullText}\n                      className={cn(\n                        CELL_CLASS,\n                        CELL_INVALID_CLASS,\n                        \"h-full\",\n                        valueEmpty && \"text-muted-foreground\"\n                      )}\n                      {...cellProps(\"value\", active)}\n                      {...issueProps(issue, \"value\", issueText)}\n                      onFocus={onCellFocus(\"value\")}\n                    >\n                      {/* FREE OUTPUT: whatever the field draws. */}\n                      <span className=\"min-w-0 flex-1 truncate text-start\">\n                        {valueLabel}\n                      </span>\n                      {/* The error, INSIDE the control that failed. */}\n                      <RowIssueHint message={issueText} />\n                    </Button>\n                  }\n                />\n              )\n            ) : null}\n          </div>\n        )}\n      </div>\n\n      {/* The WEIGHT is on the CLUSTER: a `ghost` button names no colour, so\n          the kebab took the full `--foreground`. */}\n      <div className={ACTION_BAND_CLASS}>\n        {canMove ? (\n          <RowHandle nodeId={rule.id} active={active} onFocus={onCellFocus} />\n        ) : null}\n        <DropdownMenu\n          open={menuOpen}\n          onOpenChange={(next) => {\n            if (next && locked) return\n            setMenuOpen(next)\n          }}\n        >\n          <DropdownMenuTrigger\n            asChild\n            disabled={actions.disabled}\n            {...filterReadOnlyProps(actions)}\n          >\n            <Button\n              variant=\"ghost\"\n              size={sizes.icon}\n              aria-label={actions.labels.chipMenu(field.label)}\n              className={ACTION_CONTROL_CLASS}\n              {...cellProps(\"menu\", active)}\n              onFocus={onCellFocus(\"menu\")}\n            >\n              <EllipsisVerticalIcon />\n            </Button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent\n            align=\"end\"\n            className={cn(FILTER_MENU_CLASS, actions.menuClassName)}\n          >\n            {/* Grouping is HERE, not on a chip: the keyboard path to\n                `a AND (b OR c)`. */}\n            <FilterRuleMenuItems ruleId={rule.id} allowGrouping />\n          </DropdownMenuContent>\n        </DropdownMenu>\n      </div>\n    </div>\n  )\n}\n\n/** One rule, as a row, memoized: the query tree shares structure, so editing\n * one row of twenty re-renders one. */\nexport const FilterAdvancedRow = React.memo(\n  FilterAdvancedRowImpl\n) as typeof FilterAdvancedRowImpl\n\n/** A rule whose field the schema no longer has: dropping it would lose a saved\n * view's data, rendering nothing would leave it filtering invisibly. */\nfunction FilterUnknownRow<V>({\n  rule,\n  position,\n}: {\n  rule: FilterRule<V>\n  position: RowPosition\n}) {\n  const actions = useFilterActions()\n  const sizes = filterControlSizes(actions)\n  return (\n    <div\n      role=\"group\"\n      aria-label={actions.labels.rowLabel(\n        rule.path.join(actions.labels.pathSeparator),\n        position.depth\n      )}\n      data-slot=\"filter-row\"\n      data-node-id={rule.id}\n      data-parent-id={position.parentId}\n      data-index={position.index}\n      data-depth={position.depth}\n      data-unknown=\"\"\n      /* The DROP language too: the hit test pushes every row carrying\n         `data-parent-id` into the surface, and this row carries one. */\n      className={cn(ROW_BAND_CLASS, DROP_INDICATOR)}\n    >\n      <span className=\"text-muted-foreground min-w-0 flex-1 truncate text-sm\">\n        {rule.path.join(actions.labels.pathSeparator)}\n      </span>\n      {/* The same trailing band, so the broken row lands on the kebab column. */}\n      <div className={ACTION_BAND_CLASS}>\n        <Button\n          variant=\"ghost\"\n          size={sizes.icon}\n          aria-label={actions.labels.remove}\n          className={ACTION_CONTROL_CLASS}\n          /* Outside the roving scheme: a real tab stop keeps it removable. */\n          data-filter-cell=\"remove\"\n          /* It had no gate, so the one row whose purpose is to be removed\n             could be removed from a read-only bar. */\n          disabled={actions.disabled}\n          {...filterReadOnlyProps(actions)}\n          onClick={() => actions.removeNode(rule.id)}\n        >\n          <XIcon />\n        </Button>\n      </div>\n    </div>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Group                                   */\n/* -------------------------------------------------------------------------- */\n\n/** A nested group: an indented card, its conditions, and one way to add\n * another. The HEADLINE went; the pill outside already says \"or\". */\nfunction FilterAdvancedGroup<V, O>({\n  group,\n  position,\n}: {\n  group: FilterGroupNode<V>\n  position: RowPosition\n}) {\n  const actions = useFilterActions<V, O>()\n  const sizes = filterControlSizes(actions)\n  const focusStore = useFilterFocusStore()\n\n  const { query } = useFilterState<V>()\n\n  const issue = useFilterIssue(group.id)\n  const issueText = issue ? filterIssueLabel(issue, actions.labels) : \"\"\n\n  const reorderable = useFilterReorderable()\n  const canMove = reorderable && canFilterNodeMove(query, position)\n  const rowStateStore = useFilterRowStateStore()\n\n  const slot = filterCombinatorSlot(position.index)\n  const columns = React.useMemo(() => {\n    const list: FilterColumn[] = []\n    if (slot === \"toggle\") list.push(\"combinator\")\n    // DOM order, which the arrow walker reads: a group's own controls are all\n    // in its footer now, add first and the trailing pair after it.\n    list.push(\"add\")\n    if (canMove) list.push(\"drag\")\n    list.push(\"menu\")\n    return list\n  }, [slot, canMove])\n\n  const active = useActiveColumn(\n    group.id,\n    columns,\n    position.depth === 1 && position.index === 0\n  )\n\n  const onCellFocus = React.useCallback(\n    (column: FilterColumn) => () =>\n      focusStore.set({ id: group.id, segment: column, autoOpen: false }),\n    [focusStore, group.id]\n  )\n\n  const description =\n    group.combinator === \"and\"\n      ? actions.labels.groupAll\n      : actions.labels.groupAny\n\n  const addInto = () => {\n    const id = addFilterRow(actions, group.id)\n    if (!id) return\n    rowStateStore.markPending(id)\n    focusStore.set({ id, segment: \"field\", autoOpen: true })\n  }\n\n  return (\n    <div\n      role=\"group\"\n      aria-label={actions.labels.groupLabel(description, position.depth)}\n      data-slot=\"filter-row\"\n      data-node-id={group.id}\n      data-parent-id={position.parentId}\n      data-index={position.index}\n      data-depth={position.depth}\n      /* `flex-wrap` is the whole of the narrow-panel fix. `items-center`\n         measures the flex line, so the pill centres on the card. */\n      className={cn(\"flex flex-wrap items-center gap-1.5\", DROP_SLOT_INDICATOR)}\n    >\n      <div\n        className={cn(\n          COMBINATOR_CLASS,\n          CELL_BOX_CLASS,\n          GROUP_COMBINATOR_WRAP_CLASS\n        )}\n      >\n        <CombinatorCell\n          index={position.index}\n          parentId={position.parentId}\n          combinator={position.combinator}\n          active={active}\n          onFocus={onCellFocus}\n          className={GROUP_COMBINATOR_WRAPPED_CLASS}\n        />\n      </div>\n\n      {/* The CARD lights up as the drop destination, not the header strip the\n          engine measured. This `data-invalid` only styles; the announcement\n          rides the footer's add button, which is the focusable control. */}\n      <div\n        data-slot=\"filter-group\"\n        data-invalid={issue ? \"\" : undefined}\n        className={GROUP_CARD_CLASS}\n      >\n        {/* Eight pixels, because it is a DROP TARGET and a zone beats a row. */}\n        <div\n          data-slot=\"filter-group-header\"\n          className=\"flex h-2 items-center\"\n          /* The TOP of the card means the top of the list: index 0 PREPENDS.\n             It used to append, so the one place a pointer can aim to say \"into\n             this group\" put the row at the far other end of it. */\n          data-drop-parent={group.id}\n          data-drop-index={0}\n        />\n\n        {/* A CONTAINER: the box every child row divides up. */}\n        <div\n          className={cn(\n            TRACK_CONTAINER_CLASS,\n            \"flex flex-col\",\n            FILTER_ROW_GAP_CLASS\n          )}\n        >\n          {group.rules.length === 0 ? (\n            <p\n              className={cn(\n                /* 70% foreground, not the muted token: on the card's tint the\n                   muted foreground measured 4.35:1 in light, under 4.5:1 AA. */\n                \"text-foreground/70 rounded-md border border-dashed px-2 py-3\",\n                \"text-center text-xs\",\n                \"data-drop-into:border-primary/60 data-drop-into:bg-primary/5\",\n                \"data-drop-into:text-primary\"\n              )}\n              data-slot=\"filter-group-empty\"\n              data-drop-parent={group.id}\n              data-drop-index={0}\n            >\n              {actions.labels.groupPlaceholder}\n            </p>\n          ) : (\n            group.rules.map((node, index) => (\n              <FilterAdvancedNode<V, O>\n                key={node.id}\n                node={node}\n                position={{\n                  index,\n                  parentId: group.id,\n                  combinator: group.combinator,\n                  depth: position.depth + 1,\n                }}\n              />\n            ))\n          )}\n        </div>\n\n        {/* `flex-nowrap`, or the group's kebab leaves the kebab column. */}\n        <div\n          data-slot=\"filter-group-footer\"\n          className=\"text-muted-foreground flex flex-nowrap items-center gap-2 pt-2 pb-2\"\n          data-drop-parent={group.id}\n          data-drop-index={group.rules.length}\n        >\n          <Button\n            variant=\"outline\"\n            size={sizes.button}\n            aria-label={actions.labels.addToGroup}\n            className={cn(\n              /* `shrink` and not merely `min-w-0`: `shrink-0` is baked into\n                 the shadcn button's own base class. */\n              \"min-w-0 shrink font-normal\",\n              \"overflow-hidden\",\n              CELL_INVALID_CLASS\n            )}\n            disabled={actions.disabled}\n            {...filterReadOnlyProps(actions)}\n            {...cellProps(\"add\", active)}\n            /* An EMPTY group is flagged on the control that fills it. */\n            {...issueProps(issue, \"group\", issueText)}\n            onFocus={onCellFocus(\"add\")}\n            onClick={addInto}\n          >\n            <PlusIcon />\n            {actions.labels.addCondition}\n          </Button>\n\n          <div className={cn(\"ms-auto\", ACTION_BAND_CLASS)}>\n            {canMove ? (\n              <RowHandle\n                nodeId={group.id}\n                active={active}\n                onFocus={onCellFocus}\n              />\n            ) : null}\n            <FilterGroupMenu\n              group={group}\n              active={active}\n              onFocus={onCellFocus}\n            />\n          </div>\n        </div>\n      </div>\n    </div>\n  )\n}\n\n/** A group's kebab. A menu row affords six words, where two icons said none. */\nfunction FilterGroupMenu<V>({\n  group,\n  active,\n  onFocus,\n}: {\n  group: FilterGroupNode<V>\n  active: FilterColumn | null\n  onFocus: (column: FilterColumn) => () => void\n}) {\n  const actions = useFilterActions()\n  const sizes = filterControlSizes(actions)\n  const locked = isFilterLocked(actions)\n  const [open, setOpen] = React.useState(false)\n\n  return (\n    <DropdownMenu\n      open={open}\n      onOpenChange={(next) => {\n        if (next && locked) return\n        setOpen(next)\n      }}\n    >\n      <DropdownMenuTrigger\n        asChild\n        disabled={actions.disabled}\n        {...filterReadOnlyProps(actions)}\n      >\n        <Button\n          variant=\"ghost\"\n          size={sizes.icon}\n          aria-label={actions.labels.groupMenu}\n          className={ACTION_CONTROL_CLASS}\n          {...cellProps(\"menu\", active)}\n          onFocus={onFocus(\"menu\")}\n        >\n          <EllipsisVerticalIcon />\n        </Button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align=\"end\"\n        className={cn(FILTER_MENU_CLASS, actions.menuClassName)}\n      >\n        <DropdownMenuItem\n          disabled={locked}\n          onClick={() => actions.duplicateNode(group.id)}\n        >\n          <CopyIcon aria-hidden=\"true\" />\n          <span className={FILTER_MENU_LABEL_CLASS}>\n            {actions.labels.duplicate}\n          </span>\n        </DropdownMenuItem>\n        <DropdownMenuItem\n          disabled={locked}\n          onClick={() => actions.unwrapGroup(group.id)}\n        >\n          {/* The inverse of the row menu's layers glyph. */}\n          <UngroupIcon aria-hidden=\"true\" />\n          <span className={FILTER_MENU_LABEL_CLASS}>\n            {actions.labels.ungroup}\n          </span>\n        </DropdownMenuItem>\n        <FilterMoveToMenuItems nodeId={group.id} />\n        <DropdownMenuSeparator />\n        <DropdownMenuItem\n          variant=\"destructive\"\n          disabled={locked}\n          onClick={() => actions.removeNode(group.id)}\n        >\n          {/* No colour: the destructive variant paints the row's svgs. */}\n          <Trash2Icon aria-hidden=\"true\" />\n          <span className={FILTER_MENU_LABEL_CLASS}>\n            {actions.labels.removeGroup}\n          </span>\n        </DropdownMenuItem>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  )\n}\n\nfunction FilterAdvancedNode<V, O>({\n  node,\n  position,\n}: {\n  node: FilterNode<V>\n  position: RowPosition\n}) {\n  const actions = useFilterActions<V, O>()\n\n  if (!isFilterRule(node)) {\n    return <FilterAdvancedGroup<V, O> group={node} position={position} />\n  }\n  if (!getFilterField(actions.index, node.path)) {\n    return <FilterUnknownRow<V> rule={node} position={position} />\n  }\n  return <FilterAdvancedRow<V, O> rule={node} position={position} />\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Adding                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Appends a condition on the first attribute anyone may filter on, at any\n * depth. `isFilterFieldPickable` is the picker's own rule. */\nfunction addFilterRow<V, O>(\n  actions: FilterActionsContextValue<V, O>,\n  parentId?: string\n): string | null {\n  // Before `nextId` and before `addRule`: while the store points at a row that\n  // was never created, the whole panel drops out of the tab order.\n  if (isFilterLocked(actions)) return null\n\n  const entry = actions.index.all.find((candidate) =>\n    isFilterFieldPickable(candidate.field)\n  )\n  if (!entry) return null\n\n  const id = actions.nextId()\n  actions.addRule(\n    createFilterRule<V>({\n      id,\n      path: entry.path,\n      // Deliberately empty: the row arrives PENDING, and a seeded default\n      // would open the next menu with its own answer highlighted.\n      operator: \"\",\n    }),\n    parentId\n  )\n  return id\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Panel                                   */\n/* -------------------------------------------------------------------------- */\n\n/** The panel draws NO border, NO background and NO radius, and takes no\n * element to be drawn as: a surface is the page's decision. */\nexport interface FiltersAdvancedPanelProps {\n  /** Which of the two boxes the panel sits in, the only thing deciding whether\n   * it pads itself: a popover's content is `p-0`, so this padding IS its\n   * inner padding, and `\"inline\"` is a page that owns its own. */\n  mode?: \"popover\" | \"inline\"\n  /** Replaces the empty state for this panel only. Wins over\n   * `Filters.renderEmpty`, the precedence a field has over the root's. */\n  renderEmpty?: (context: FilterEmptyStateContext) => React.ReactNode\n  /** Whether rows can be reordered. See `FiltersProps.reorderable`. */\n  reorderable?: boolean\n  className?: string\n}\n\n/** The builder itself: nested groups over the query tree the chips read. A\n * group is a parenthesised list joined by ONE operator, so nesting is a real\n * tree: a flat model cannot represent `a AND (b OR c)` without inventing\n * precedence, and invented precedence returns the wrong rows. */\nexport function FiltersAdvancedPanel<V, O>({\n  mode = \"popover\",\n  renderEmpty,\n  reorderable = false,\n  className,\n}: FiltersAdvancedPanelProps) {\n  const actions = useFilterActions<V, O>()\n  const panelRender = useFilterRender<V, O>()\n  const sizes = filterControlSizes(actions)\n  const { query, ruleCount, announcement, announcementSeq } =\n    useFilterState<V>()\n  const focusStore = useFilterFocusStore()\n  const rowStateStore = useFilterRowStateStore()\n  // A version counter, because the store is mutable and stable by identity.\n  const rowStateVersion = React.useSyncExternalStore(\n    rowStateStore.subscribe,\n    () => rowStateStore.version(),\n    () => 0\n  )\n  const bodyRef = React.useRef<HTMLDivElement>(null)\n  const locked = isFilterLocked(actions)\n\n  /* ------------------------------ validation ------------------------------ */\n\n  /** What is unfinished, computed ONCE: an empty group is a fact about a\n   * group, not about any row inside it. */\n  const issues = React.useMemo(\n    () =>\n      collectFilterIssues(\n        query,\n        (rule) => {\n          const field = getFilterField(actions.index, rule.path)\n          if (!field) return null\n          return getFilterArity(\n            getFilterOperator(actions.resolveOperators(field), rule.operator)\n          )\n        },\n        // The same normalisation the display callbacks get.\n        (rule) => {\n          const field = getFilterField(actions.index, rule.path)\n          if (!field?.validate) return null\n          const operator = getFilterOperator(\n            actions.resolveOperators(field),\n            rule.operator\n          )\n          if (!operator) return null\n          return field.validate({\n            value: rule.value,\n            values:\n              rule.value === undefined || rule.value === null\n                ? []\n                : Array.isArray(rule.value)\n                  ? (rule.value as unknown[])\n                  : [rule.value],\n            field,\n            operator,\n            arity: getFilterArity(operator) ?? \"one\",\n            rule,\n            labels: actions.labels,\n          })\n        }\n      ),\n    [query, actions]\n  )\n\n  /** Every issue, keyed by node: what the tree IS, drawn or not. */\n  const issueMap = React.useMemo(\n    () => new Map(issues.map((issue) => [issue.nodeId, issue])),\n    [issues]\n  )\n\n  /** The issues a row may DRAW: the ones on a value committed once. */\n  const visibleIssueMap = React.useMemo(() => {\n    const visible = new Map<string, FilterIssue>()\n    for (const issue of issues) {\n      // CUSTOM ONLY. The built-in reasons describe a row as HALF BUILT,\n      // so every Add filter produced a red row on the happy path.\n      if (issue.reason !== \"custom\") continue\n      if (rowStateStore.has(issue.nodeId)) visible.set(issue.nodeId, issue)\n    }\n    return visible\n  }, [issues, rowStateStore, rowStateVersion])\n\n  /** Says out loud that a VISIBLE error has appeared, which would\n   * otherwise happen in silence. The DRAWN issues, on a RISE only. */\n  const announcedIssues = React.useRef({\n    count: visibleIssueMap.size,\n    seq: announcementSeq,\n  })\n  React.useEffect(() => {\n    const before = announcedIssues.current\n    announcedIssues.current = {\n      count: visibleIssueMap.size,\n      seq: announcementSeq,\n    }\n    if (announcementSeq !== before.seq) return\n    if (visibleIssueMap.size <= before.count) return\n    actions.announce(actions.labels.issueSummary(visibleIssueMap.size))\n  }, [visibleIssueMap, announcementSeq, actions])\n\n  /** Sends focus to the first thing that needs it. Walked and not selected\n   * by id: a node id is consumer-supplied, and `CSS.escape` is not\n   * optional in a hand-built selector. */\n  const focusFirstIssue = React.useCallback(() => {\n    const first = issues[0]\n    const body = bodyRef.current\n    if (!first || !body) return\n    const row = Array.from(\n      body.querySelectorAll<HTMLElement>(ROW_SELECTOR)\n    ).find((candidate) => candidate.dataset.nodeId === first.nodeId)\n    if (!row) return\n    // A group's issue is drawn on the add button that resolves it.\n    const column = first.column === \"group\" ? \"add\" : first.column\n    const target = ownCells(row).find(\n      (cell) => cell.getAttribute(CELL_ATTRIBUTE) === column\n    )\n    target?.focus()\n  }, [issues])\n\n  /* ---------------------------- focus recovery ---------------------------- */\n\n  /** Whether the panel, or a menu of its own, held focus a moment ago. A\n   * blur WITH a `relatedTarget` is focus arriving somewhere real; a blur\n   * with none, or none at all when the element is simply removed, is what\n   * this exists to repair. */\n  const heldFocus = React.useRef(false)\n  const addRowRef = React.useRef<HTMLButtonElement>(null)\n\n  /** Puts focus back after a mutation that destroyed the thing holding it:\n   * measured at 50, 200, 600 and 1200ms after Convert to group, Remove,\n   * Ungroup and Move to group, `document.activeElement` was the BODY,\n   * because a menu restores focus to a trigger the action unmounted. */\n  const restoreFocus = React.useCallback(() => {\n    // A handoff is mid-air and owns focus: between one step being answered\n    // and the next opening `document.activeElement` IS the body.\n    if (focusStore.getSnapshot().autoOpen) return\n    if (!heldFocus.current) return\n    const active = document.activeElement\n    if (active && active !== document.body) return\n    const rows = Array.from(\n      bodyRef.current?.querySelectorAll<HTMLElement>(ROW_SELECTOR) ?? []\n    )\n    const { id, segment } = focusStore.getSnapshot()\n    const row = id\n      ? rows.find((candidate) => candidate.dataset.nodeId === id)\n      : undefined\n    const cells = row ? ownCells(row) : []\n    const target =\n      cells.find((entry) => entry.getAttribute(CELL_ATTRIBUTE) === segment) ??\n      cells[0] ??\n      (rows[0] ? ownCells(rows[0])[0] : undefined) ??\n      addRowRef.current ??\n      undefined\n    target?.focus()\n  }, [focusStore])\n\n  // In the passive effect, not a frame later: React removes the control in\n  // the mutation phase, so a menu's restore then aims at a detached node.\n  React.useEffect(() => {\n    restoreFocus()\n  }, [query, announcementSeq, restoreFocus])\n\n  /* -------------------------------- adding -------------------------------- */\n\n  const addRow = React.useCallback(() => {\n    const id = addFilterRow(actions)\n    if (!id) return\n    // PENDING until the attribute is chosen, the first of three questions.\n    rowStateStore.markPending(id)\n    focusStore.set({ id, segment: \"field\", autoOpen: true })\n  }, [actions, focusStore, rowStateStore])\n\n  const addGroup = React.useCallback(() => {\n    const id = actions.addGroup()\n    // An empty id means it refused, and focusing a group never created\n    // would strand the tab stop.\n    if (!id) return\n    // Onto the group's own chrome, not into it: it arrives empty.\n    focusStore.set({ id, segment: \"add\", autoOpen: false })\n  }, [actions, focusStore])\n\n  /* ------------------------------- keyboard ------------------------------- */\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const cell = (event.target as HTMLElement).closest<HTMLElement>(\n      `[${CELL_ATTRIBUTE}]`\n    )\n    // A key pressed inside an open popover belongs to that popover; its\n    // content is portaled out, so this is belt and braces.\n    //\n    // ArrowDown must never reach here: a menu button owns it, so the row menu\n    // opens rather than moving the tab stop down a row. THE TWIN DIFFERENCE,\n    // and not cosmetic: Base UI stops that key at the trigger and needs no\n    // guard, while Radix's menu trigger calls `preventDefault` and lets the\n    // event bubble, so without this line ArrowDown opened the menu AND ran the\n    // walker. `defaultPrevented` rather than a key list, because the question\n    // is whether the control the key landed on already acted on it.\n    if (event.defaultPrevented) return\n    if (!cell || event.target !== cell) return\n\n    const body = bodyRef.current\n    const row = cell.closest<HTMLElement>(ROW_SELECTOR)\n    if (!body || !row) return\n\n    /* A cell the user TYPES into keeps the keys that edit text; only the\n       VERTICAL keys stay. */\n    const editing = cell.hasAttribute(CELL_INPUT_ATTRIBUTE)\n\n    // DOM order for the two places that mean \"the whole builder\".\n    const rows = Array.from(body.querySelectorAll<HTMLElement>(ROW_SELECTOR))\n    const cells = ownCells(row)\n    const rowIndex = rows.indexOf(row)\n    const cellIndex = cells.indexOf(cell)\n\n    const rtl = getComputedStyle(cell).direction === \"rtl\"\n    const forward = rtl ? \"ArrowLeft\" : \"ArrowRight\"\n    const backward = rtl ? \"ArrowRight\" : \"ArrowLeft\"\n\n    const focus = (target: HTMLElement | undefined) => {\n      if (!target) return\n      event.preventDefault()\n      target.focus()\n    }\n\n    const from = cell.getAttribute(CELL_ATTRIBUTE) as FilterColumn\n    const band = (CONTENT_COLUMNS as readonly FilterColumn[]).includes(from)\n      ? CONTENT_COLUMNS\n      : ACTION_COLUMNS\n\n    /* The rows that draw a cell in this BAND, in cell order: by ROW it went\n       BACKWARDS at +212, -166, +122, -76, +38 pixels once a group's own\n       controls moved to its footer. */\n    const bandRows: HTMLElement[] = []\n    const seen = new Set<HTMLElement>()\n    for (const entry of body.querySelectorAll<HTMLElement>(\n      `[${CELL_ATTRIBUTE}]`\n    )) {\n      const column = entry.getAttribute(CELL_ATTRIBUTE) as FilterColumn\n      if (!(band as readonly FilterColumn[]).includes(column)) continue\n      const owner = entry.closest<HTMLElement>(ROW_SELECTOR)\n      if (!owner || seen.has(owner)) continue\n      seen.add(owner)\n      bandRows.push(owner)\n    }\n    const bandIndex = bandRows.indexOf(row)\n\n    const focusRow = (step: number) => {\n      const nextRow = bandRows[bandIndex + step]\n      if (!nextRow) return\n      const cellsThere = ownCells(nextRow)\n      const byColumn = new Map(\n        cellsThere.map((entry) => [entry.getAttribute(CELL_ATTRIBUTE), entry])\n      )\n      // The band, then anything at all, which keeps a consumer's cell\n      // reachable.\n      focus(nearestColumn(band, from, byColumn) ?? cellsThere[0])\n    }\n\n    const nodeId = row.dataset.nodeId\n    if (!nodeId) return\n\n    // Alt reorders rather than navigates, within the owning group only:\n    // changing depth with an arrow would make one gesture mean two things.\n    if (\n      event.altKey &&\n      (event.key === \"ArrowUp\" || event.key === \"ArrowDown\")\n    ) {\n      // Plain arrows, Home and End are deliberately NOT gated.\n      if (locked || !reorderable) return\n      event.preventDefault()\n      actions.moveNode(nodeId, event.key === \"ArrowDown\" ? 1 : -1)\n      return\n    }\n\n    if (event.key === \"ArrowDown\") return focusRow(1)\n    if (event.key === \"ArrowUp\") return focusRow(-1)\n    if (editing) return\n\n    if (event.key === forward) return focus(cells[cellIndex + 1])\n    if (event.key === backward) return focus(cells[cellIndex - 1])\n    if (event.key === \"Home\") {\n      return focus(event.ctrlKey ? ownCells(rows[0])[0] : cells[0])\n    }\n    if (event.key === \"End\") {\n      const scope = event.ctrlKey ? ownCells(rows[rows.length - 1]) : cells\n      return focus(scope[scope.length - 1])\n    }\n\n    if (event.key === \"Backspace\" || event.key === \"Delete\") {\n      if (locked) return\n      event.preventDefault()\n      actions.removeNode(nodeId)\n      // Focus the row that takes this one's place, so removing several\n      // does not throw focus to the body.\n      requestAnimationFrame(() => {\n        const remaining = Array.from(\n          bodyRef.current?.querySelectorAll<HTMLElement>(ROW_SELECTOR) ?? []\n        )\n        const target = remaining[Math.min(rowIndex, remaining.length - 1)]\n        if (target) ownCells(target)[0]?.focus()\n      })\n    }\n  }\n\n  /* --------------------------------- drag --------------------------------- */\n\n  /** Pointer drag, not HTML5 drag and drop: its drag image is a\n   * browser-owned snapshot no copy badge can be drawn on, and a nested\n   * drop would mean hit-testing on every `dragover`. */\n  const dragProps = useFilterRowDrag({\n    // THE PANEL, reached through the body, because the top level's append\n    // zone is in the FOOTER and the footer is the body's sibling.\n    root: () => bodyRef.current?.parentElement ?? null,\n    disabled: locked,\n    onDrop: (nodeId, drop) => {\n      if (drop.copy) actions.copyNodeTo(nodeId, drop.parentId, drop.index)\n      else actions.moveNodeTo(nodeId, drop.parentId, drop.index)\n    },\n  })\n\n  /* -------------------------------- render -------------------------------- */\n\n  const panelProps = {\n    // The panel's programmatic NAME. `group`, because the rows inside are\n    // groups too, so the tree reads as a query rather than as a landmark.\n    role: \"group\",\n    \"aria-label\": actions.labels.advancedFilter,\n    // WHAT IS IN IT, on entry, for a reader who did not press the trigger.\n    // The read-only half rides along: `aria-readonly` is illegal here.\n    \"aria-description\": actions.readOnly\n      ? `${actions.labels.countAnnouncement(ruleCount)} ${actions.labels.readOnly}`\n      : actions.labels.countAnnouncement(ruleCount),\n    \"data-slot\": \"filters-advanced\",\n    \"data-readonly\": actions.readOnly || undefined,\n    // Capture, and on the PANEL, so portaled menus report too.\n    onFocusCapture: () => {\n      heldFocus.current = true\n    },\n    onBlurCapture: (event: React.FocusEvent) => {\n      if (event.relatedTarget) heldFocus.current = false\n    },\n  } as const\n\n  /** The empty state, resolved once: the panel's own prop, else the root's.\n   * Assembled here so a replacement gets the SAME two actions the footer\n   * calls, focus handoff included. */\n  const renderEmptyState = renderEmpty ?? panelRender.renderEmpty\n  const emptyState = renderEmptyState\n    ? renderEmptyState({\n        labels: actions.labels,\n        readOnly: Boolean(actions.readOnly),\n        mode,\n        addFilter: addRow,\n        addGroup,\n      })\n    : null\n\n  const body = (\n    <>\n      {/* VISIBLE, not an ARIA attribute: `aria-readonly` is illegal on every\n          role here, and dimmed controls owe the reader a reason. */}\n      {actions.readOnly ? (\n        <p\n          data-slot=\"filters-readonly\"\n          className={cn(\"text-muted-foreground text-xs\", PANEL_GUTTER_CLASS)}\n        >\n          {actions.labels.readOnly}\n        </p>\n      ) : null}\n\n      {query.rules.length > 0 ? (\n        <div\n          ref={bodyRef}\n          data-slot=\"filters-advanced-body\"\n          /* NO `overflow-x`: nothing here is ever wider than its box. */\n          className={cn(\n            TRACK_CONTAINER_CLASS,\n            \"flex min-w-0 flex-col\",\n            FILTER_ROW_GAP_CLASS,\n            PANEL_GUTTER_CLASS\n          )}\n          onKeyDown={onKeyDown}\n        >\n          <FilterReorderProvider value={reorderable}>\n            <FilterDragContext.Provider value={reorderable ? dragProps : null}>\n              <FilterIssueContext.Provider value={visibleIssueMap}>\n                {query.rules.map((node, index) => (\n                  <FilterAdvancedNode<V, O>\n                    key={node.id}\n                    node={node}\n                    position={{\n                      index,\n                      parentId: query.id,\n                      combinator: query.combinator,\n                      depth: 1,\n                    }}\n                  />\n                ))}\n              </FilterIssueContext.Provider>\n            </FilterDragContext.Provider>\n          </FilterReorderProvider>\n        </div>\n      ) : /*\n          THE EMPTY STATE, a real state and not a missing one: with no rules\n          the body renders nothing, so the panel used to open as a footer\n          floating in a blank popover. The HINT is withheld when the bar is\n          locked, since it points at two disabled buttons.\n        */\n      // The CALLBACK's presence decides, not its result: a consumer returning\n      // null wants a blank panel, and `??` would hand them the default back.\n      renderEmptyState ? (\n        emptyState\n      ) : (\n        <div\n          data-slot=\"filters-advanced-empty\"\n          className={cn(\n            \"flex flex-col items-center justify-center gap-1 py-8 text-center\",\n            PANEL_GUTTER_CLASS\n          )}\n        >\n          <span\n            aria-hidden=\"true\"\n            /* `rounded-full` is the one radius literal safe in every\n               style, square or round. */\n            className=\"bg-muted text-muted-foreground mb-1 flex size-9 items-center justify-center rounded-full [&_svg]:size-4\"\n          >\n            <ListFilterIcon />\n          </span>\n          <p className=\"text-sm font-medium\">{actions.labels.builderEmpty}</p>\n          {actions.readOnly ? null : (\n            <p className=\"text-muted-foreground text-xs\">\n              {actions.labels.builderEmptyHint}\n            </p>\n          )}\n        </div>\n      )}\n\n      {/* `shrink-0` on all three: a button clips its label rather than\n          reflowing it, so Clear all read as \"ear all filters\". */}\n      <div\n        data-slot=\"filters-advanced-footer\"\n        /* THE APPEND TARGET FOR THE TOP LEVEL, which every group's footer had\n           and the root did not: at depth the strip under the last row is a 48px\n           \"put it here\", while at the root it was 47px of `no-drop`. */\n        data-drop-parent={query.id}\n        data-drop-index={query.rules.length}\n        className={cn(\n          \"relative flex flex-wrap items-center gap-2\",\n          PANEL_GUTTER_CLASS,\n          /* FOUR PIXELS MORE than the gutter, which is what a row's action\n             band spends after its kebab. */\n          \"pe-[calc(var(--filter-panel-pad)+4px)]\",\n          FOOTER_DROP_CLASS,\n          /* The strip's BOX reaches the body's bottom edge and pads its\n             content back down, so the append zone TILES with the last row.\n             `pt-5` and not `pt-2`: the row above already grows 4px into this\n             strip, so at `pt-2` the toolbar read as the last filter's tail. */\n          query.rules.length > 0 && cn(FILTER_ROW_GAP_CANCEL_CLASS, \"pt-5\")\n        )}\n      >\n        <Button\n          /* The last resort of `restoreFocus`: the only control that exists\n             at every query. */\n          ref={addRowRef}\n          /* OUTLINE, and the only pair in the panel with a box: they are\n             what the footer is FOR. */\n          variant=\"outline\"\n          size={sizes.button}\n          className=\"shrink-0 font-normal\"\n          disabled={actions.disabled}\n          {...filterReadOnlyProps(actions)}\n          onClick={addRow}\n        >\n          <PlusIcon />\n          {actions.labels.addCondition}\n        </Button>\n\n        <Button\n          variant=\"outline\"\n          size={sizes.button}\n          className=\"shrink-0 font-normal\"\n          disabled={actions.disabled}\n          {...filterReadOnlyProps(actions)}\n          onClick={addGroup}\n        >\n          <FolderPlusIcon />\n          {actions.labels.addConditionGroup}\n        </Button>\n\n        {/* NO PANEL-LEVEL SUMMARY: a validator's no belongs on the cell. */}\n        {ruleCount > 0 ? (\n          <Button\n            variant=\"ghost\"\n            size={sizes.button}\n            className=\"text-muted-foreground hover:text-foreground ms-auto shrink-0\"\n            disabled={actions.disabled}\n            {...filterReadOnlyProps(actions)}\n            onClick={() => actions.clearQuery()}\n          >\n            {actions.labels.clearAll}\n          </Button>\n        ) : null}\n      </div>\n\n      {/* The `key` is what makes a REPEATED sentence audible: `aria-live`\n          fires on a mutation and React writes nothing when the string is\n          unchanged, so three presses mutated the region once. */}\n      <div aria-live=\"polite\" role=\"status\" className=\"sr-only\">\n        <span key={announcementSeq}>{announcement}</span>\n      </div>\n    </>\n  )\n\n  return (\n    <div\n      {...panelProps}\n      /* An inline style because it is a VALUE: one declaration to beat\n         rather than three classes in three places. */\n      style={\n        {\n          [PANEL_PAD_VAR]:\n            mode === \"inline\" ? PANEL_PAD_INLINE : PANEL_PAD_POPOVER,\n        } as React.CSSProperties\n      }\n      className={cn(PANEL_CLASS, className)}\n    >\n      {body}\n    </div>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Root                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface FiltersAdvancedProps {\n  /** Where the builder lives. `\"popover\"` hangs it off a trigger; `\"inline\"`\n   * renders the same panel with no popup, for a sidebar or a settings page. */\n  mode?: \"popover\" | \"inline\"\n  /** Replaces the default trigger. Ignored inline. */\n  trigger?: React.ReactNode\n  /** Whether rows can be reordered. See `FiltersProps.reorderable`. */\n  reorderable?: boolean\n  /** Popover placement. */\n  align?: \"start\" | \"center\" | \"end\"\n  className?: string\n}\n\nexport function FiltersAdvanced<V, O>({\n  mode = \"popover\",\n  trigger,\n  reorderable = false,\n  align = \"start\",\n  className,\n}: FiltersAdvancedProps) {\n  const actions = useFilterActions<V, O>()\n  const sizes = filterControlSizes(actions)\n  const { ruleCount } = useFilterState<V>()\n  const [open, setOpen] = React.useState(false)\n\n  if (mode === \"inline\") {\n    return (\n      <FiltersAdvancedPanel<V, O>\n        mode=\"inline\"\n        reorderable={reorderable}\n        className={className}\n      />\n    )\n  }\n\n  return (\n    <Popover open={open} onOpenChange={setOpen}>\n      {/* `actions.disabled` alone, and READ ONLY DELIBERATELY DOES NOT\n          GATE IT: opening this panel is reading, not writing. */}\n      <PopoverTrigger\n        asChild\n        /* On the TRIGGER rather than the button below it, so a consumer's own\n           trigger wears the same state. Still `actions.disabled` alone. */\n        disabled={actions.disabled}\n      >\n        {trigger ? (\n          (trigger as React.ReactElement)\n        ) : (\n          <Button\n            variant=\"outline\"\n            size={sizes.button}\n            /* THE COUNT IN THE NAME, not only in the box: a consumer who\n               replaces `trigger` never had the badge, which is hidden. */\n            aria-label={\n              ruleCount > 0\n                ? `${actions.labels.advancedFilter}, ${actions.labels.countAnnouncement(ruleCount)}`\n                : undefined\n            }\n          >\n            <ListFilterIcon />\n            {actions.labels.advancedFilter}\n            {ruleCount > 0 ? (\n              <span\n                aria-hidden=\"true\"\n                className=\"bg-muted text-muted-foreground rounded-sm px-1.5 text-xs tabular-nums\"\n              >\n                {ruleCount}\n              </span>\n            ) : null}\n          </Button>\n        )}\n      </PopoverTrigger>\n      {/* Wide enough for a nested group to keep real words at depth three;\n          the rows truncate rather than wrap. */}\n      <PopoverContent\n        align={align}\n        /* THE POPUP'S OWN NAME: it is a `role=\"dialog\"`, and the panel's is\n           one level in, on its `role=\"group\"`. */\n        aria-label={actions.labels.advancedFilter}\n        className={cn(\"w-[42rem] max-w-[95vw] p-0\", className)}\n      >\n        {/* `mode` defaults to \"popover\", which keeps the panel's padding. */}\n        <FiltersAdvancedPanel<V, O> reorderable={reorderable} />\n      </PopoverContent>\n    </Popover>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-advanced.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-builder.tsx",
      "content": "/**\n * filters-builder - adapted for tealmac UI from ReUI \"filters/filters-builder\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n\"use client\"\n\nimport * as React from \"react\"\nimport { ListFilterPlusIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/components/ui/popover\"\nimport {\n  Cascader,\n  CascaderEmpty,\n  CascaderList,\n  CascaderPanel,\n  CascaderStatus,\n} from \"@/components/reui/cascader/cascader\"\nimport { CascaderFooter } from \"@/components/reui/cascader/cascader-footer\"\nimport {\n  CascaderBreadcrumb,\n  CascaderInput,\n  CascaderNav,\n} from \"@/components/reui/cascader/cascader-nav\"\nimport type {\n  CascaderActionItem,\n  CascaderLabels,\n  CascaderNode,\n} from \"@/components/reui/cascader/cascader-types\"\nimport { CascaderVirtualItems } from \"@/components/reui/cascader/cascader-virtual\"\nimport {\n  filterControlSizes,\n  filterReadOnlyProps,\n  useFilterActions,\n  useFilterFocusStore,\n  useFilterState,\n} from \"@/components/reui/filters/filters-context\"\nimport {\n  FILTER_FIELD_PICKER_CLASS,\n  getFilterField,\n  getFilterFieldCount,\n  joinFilterPath,\n  splitFilterPath,\n} from \"@/components/reui/filters/filters-lib\"\nimport { getDefaultFilterOperator } from \"@/components/reui/filters/filters-operators\"\nimport type { FilterField } from \"@/components/reui/filters/filters-types\"\n\n/**\n * Projects ONLY the field tree: operators or values as nodes would force the\n * wizard through a combobox that owns the arrows and `aria-activedescendant`.\n */\nfunction toCascaderNodes<V, O>(\n  fields: readonly FilterField<V, O>[],\n  parentPath: string[] = []\n): CascaderNode<FilterField<V, O>>[] {\n  return fields.map((field) => {\n    const path = [...parentPath, field.id]\n    const node: CascaderNode<FilterField<V, O>> = {\n      value: joinFilterPath(path),\n      label: field.label,\n      icon: field.icon,\n      description: field.description,\n      keywords: field.keywords,\n      disabled: field.disabled,\n      data: field,\n    }\n    if (field.fields?.length) {\n      node.children = toCascaderNodes(field.fields, path)\n      node.count = getFilterFieldCount(field)\n    }\n    return node\n  })\n}\n\nexport interface FilterFieldPickerProps {\n  /** The level being browsed. Not the chosen field. */\n  path: string[]\n  onPathChange: (path: string[]) => void\n  query: string\n  onQueryChange: (query: string) => void\n  /** A field was chosen, with its starting operator already resolved. */\n  onSelect: (path: string[], defaultOperator: string | null) => void\n  /** Viewport height before the list scrolls. */\n  maxHeight?: number\n  /** Cascader-only strings; the `FilterLabels` bridge below covers the rest. */\n  labels?: Partial<CascaderLabels>\n  /** Pinned footer rows, OUT of the option ring so arrows never land on one. */\n  actions?: CascaderActionItem[]\n}\n\n/**\n * Fully controlled, not draft-driven, so ONE picker serves both the create\n * popover (driven by the draft reducer) and an advanced row (its own state).\n */\nexport function FilterFieldPicker<V, O>({\n  path,\n  onPathChange,\n  query,\n  onQueryChange,\n  onSelect,\n  maxHeight = 260,\n  labels: labelsProp,\n  actions: actionItems,\n}: FilterFieldPickerProps) {\n  const actions = useFilterActions<V, O>()\n\n  const items = React.useMemo(\n    () => toCascaderNodes(actions.index.roots),\n    [actions.index]\n  )\n\n  // Bridges `FilterLabels` onto the cascader's own key names. `labelsProp` is\n  // spread LAST, so a consumer override always wins.\n  const cascaderLabels = React.useMemo<Partial<CascaderLabels>>(\n    () => ({\n      search: actions.labels.searchFields,\n      back: actions.labels.back,\n      empty: actions.labels.empty,\n      pathSeparator: actions.labels.pathSeparator.trim() || \"/\",\n      itemCount: actions.labels.itemCount,\n      branchAffordance: actions.labels.branchAffordance,\n      rootLevel: actions.labels.fieldsLabel,\n      panelLabel: actions.labels.fieldsLabel,\n      resultsAnnouncement: actions.labels.resultsAnnouncement,\n      actionsLabel: actions.labels.actionsLabel,\n      ...labelsProp,\n    }),\n    [actions.labels, labelsProp]\n  )\n\n  return (\n    <Cascader\n      inline\n      /* Pinned open: inline renders no popup and forces `open`, so the\n         single-select commit's `setOpen(false)` dismisses nothing. That avoids\n         the `multiple` plus `max` workaround and its `aria-multiselectable`. */\n      open\n      onOpenChange={() => {}}\n      items={items}\n      /* No `selectable` predicate: LEAVES commit, branches navigate. Honouring\n         a branch's opt-in made one click mean both drill and commit. */\n      searchScope=\"deep\"\n      /* Nothing is ever selected, so the ~24px check gutter is dead space. */\n      indicator={false}\n      path={path}\n      onPathChange={onPathChange}\n      /* Controlled: the single-select arm of `commit()` never clears the query,\n         so an uncontrolled one would bleed into the next step. */\n      inputValue={query}\n      onInputValueChange={onQueryChange}\n      value=\"\"\n      onValueChange={(value) => {\n        const nextPath = splitFilterPath(value)\n        const field = getFilterField(actions.index, nextPath)\n        if (!field) return\n        onSelect(\n          nextPath,\n          getDefaultFilterOperator(field, actions.resolveOperators(field))\n        )\n      }}\n      labels={cascaderLabels}\n      actions={actionItems}\n      /* Set here only: `CascaderList` takes its own `maxHeight` and that WINS,\n         so a second copy on the list is a divergence waiting to happen. */\n      maxHeight={maxHeight}\n    >\n      <CascaderPanel>\n        <CascaderNav>\n          <CascaderInput placeholder={actions.labels.searchFields} />\n        </CascaderNav>\n        <CascaderBreadcrumb />\n        <CascaderEmpty />\n        <CascaderList>\n          {/* WINDOWED: the picker is where scale lives and nothing here pins.\n            Below the threshold it renders what `CascaderItems` does. */}\n          <CascaderVirtualItems />\n        </CascaderList>\n        <CascaderFooter />\n        <CascaderStatus />\n      </CascaderPanel>\n    </Cascader>\n  )\n}\n\nfunction FieldStep<V, O>() {\n  const actions = useFilterActions<V, O>()\n  const { draft } = useFilterState<V>()\n\n  return (\n    <FilterFieldPicker<V, O>\n      path={draft?.cascaderPath ?? []}\n      onPathChange={(next) =>\n        actions.dispatchDraft({ type: \"setCascaderPath\", path: next })\n      }\n      query={draft?.query ?? \"\"}\n      onQueryChange={(query) =>\n        actions.dispatchDraft({ type: \"setQuery\", query })\n      }\n      onSelect={(path, defaultOperator) =>\n        actions.dispatchDraft({ type: \"selectField\", path, defaultOperator })\n      }\n    />\n  )\n}\n\nexport interface FiltersBuilderProps {\n  /** Replaces the default Add filter button. */\n  trigger?: React.ReactNode\n  className?: string\n}\n\n/**\n * The Add filter popover. ONE panel, the field step: picking a field commits\n * the rule and opens the operator menu on the new chip. `open` derives from the\n * draft and `openCreate` is gated, so read-only and disabled shut every route.\n */\nexport function FiltersBuilder<V, O>({\n  trigger,\n  className,\n}: FiltersBuilderProps) {\n  const actions = useFilterActions<V, O>()\n  const sizes = filterControlSizes(actions)\n  const { draft, ruleCount } = useFilterState<V>()\n  const focusStore = useFilterFocusStore()\n  const open = draft !== null && draft.ruleId === null\n  // The HANDOFF close, the one that must not FADE: the panel is a 224px card\n  // dissolving over the very menu the user is now meant to read.\n  const committing =\n    draft !== null && draft.ruleId === null && draft.status === \"ready\"\n  // LATCHED, because `committing` is true for one render only, before the exit\n  // it suppresses begins. Adjusted during render; an effect is one frame late.\n  const [instantExit, setInstantExit] = React.useState(false)\n  if (committing && !instantExit) setInstantExit(true)\n  else if (open && !committing && instantExit) setInstantExit(false)\n  // Icon-only once chips sit beside it. Both states come off ONE size ladder,\n  // so they share height and radius in every style at every bar size. The\n  // hardcoded `icon`/`default` pair this replaced IS the `default` rung, so it\n  // drifted the moment the bar was `sm`.\n  const compact = ruleCount > 0\n\n  // The focus handoff to the new chip, and THE ONE PLACE the twins cannot share\n  // an implementation. Radix opens the chip's popover FIRST, so this one's\n  // `FocusScope` restore lands as a `focusin` outside the chip's\n  // `DismissableLayer` and the operator menu dismissed itself in the same\n  // frame. Suppressed ONLY on the handoff close, so every other close keeps its\n  // restore; LATCHED because the chip consumes `autoOpen` before this popover\n  // unmounts.\n  const handoffRef = React.useRef(false)\n  React.useEffect(() => {\n    if (!open) return\n    handoffRef.current = false\n    return focusStore.subscribe(() => {\n      if (focusStore.getSnapshot().autoOpen) handoffRef.current = true\n    })\n  }, [focusStore, open])\n\n  const onCloseAutoFocus = (event: Event) => {\n    if (!handoffRef.current) return\n    handoffRef.current = false\n    event.preventDefault()\n  }\n\n  return (\n    <Popover\n      open={open}\n      onOpenChange={(next) => {\n        if (!next) actions.closeDraft()\n        else actions.openCreate()\n      }}\n    >\n      <PopoverTrigger\n        /* On the TRIGGER so a consumer's own `trigger` wears the state too. */\n        asChild\n        disabled={actions.disabled}\n        {...filterReadOnlyProps(actions)}\n      >\n        {trigger ? (\n          (trigger as React.ReactElement)\n        ) : (\n          <Button\n            variant=\"outline\"\n            size={compact ? sizes.icon : sizes.button}\n            aria-label={compact ? actions.labels.addFilter : undefined}\n            /* THE RESET BOUNCE: the button's base class carries\n               `transition-all`, so flipping the size class eased padding 0 to\n               `px-6` in sera over 150ms. Naming a transition REPLACES it. */\n            className=\"transition-[color,background-color,border-color,box-shadow]\"\n          >\n            {/* No filter-plus glyph in phosphor or remixicon. */}\n            <ListFilterPlusIcon />\n            {compact ? null : actions.labels.addFilter}\n          </Button>\n        )}\n      </PopoverTrigger>\n      {/* The default, then the root override, then this `className` last, so\n        the specific wins. */}\n      <PopoverContent\n        align=\"start\"\n        onCloseAutoFocus={onCloseAutoFocus}\n        className={cn(\n          FILTER_FIELD_PICKER_CLASS,\n          /* See `instantExit`. Both PROPERTIES (an `exit` animation AND a\n             transition each paint over the successor) and both twins (Base UI\n             `data-ending-style`, Radix `data-[state=closed]`); only one can\n             match in a given build. The string stays identical on both sides\n             because listing only the Base UI half left the radix twin fading\n             a 224px card over its successor. */\n          instantExit &&\n            cn(\n              \"data-ending-style:animate-none data-ending-style:transition-none\",\n              \"data-[state=closed]:animate-none data-[state=closed]:transition-none\"\n            ),\n          actions.fieldPickerClassName,\n          className\n        )}\n      >\n        <FieldStep<V, O> />\n      </PopoverContent>\n    </Popover>\n  )\n}\n\n/** Exported for custom field pickers. */\nexport { toCascaderNodes }\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-builder.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-chip.tsx",
      "content": "/**\n * filters-chip - adapted for tealmac UI from ReUI \"filters/filters-chip\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n\"use client\"\n\nimport * as React from \"react\"\nimport {\n  ArrowLeftRightIcon,\n  ChevronRightIcon,\n  CopyIcon,\n  CornerDownRightIcon,\n  EllipsisVerticalIcon,\n  LayersIcon,\n  SlidersHorizontalIcon,\n  Trash2Icon,\n  XIcon,\n} from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { ButtonGroup, ButtonGroupText } from \"@/components/ui/button-group\"\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\"\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/components/ui/popover\"\nimport {\n  Tooltip,\n  TooltipContent,\n  TooltipProvider,\n  TooltipTrigger,\n} from \"@/components/ui/tooltip\"\nimport {\n  filterControlSizes,\n  filterReadOnlyProps,\n  isFilterLocked,\n  useFilterActions,\n  useFilterChipAutoOpen,\n  useFilterChipFocused,\n  useFilterFocusEmpty,\n  useFilterFocusStore,\n  useFilterRender,\n  useFilterReorderable,\n} from \"@/components/reui/filters/filters-context\"\nimport {\n  FilterMenu,\n  useFilterOptions,\n  useFilterValueResolution,\n} from \"@/components/reui/filters/filters-editors\"\nimport {\n  collapseFilterPath,\n  FILTER_MENU_CLASS,\n  FILTER_MENU_LABEL_CLASS,\n  formatFilterPath,\n  getFilterField,\n  getFilterFieldChain,\n} from \"@/components/reui/filters/filters-lib\"\nimport {\n  coerceFilterValue,\n  getFilterArity,\n  getFilterOperator,\n  operatorTakesValue,\n  visibleFilterOperators,\n} from \"@/components/reui/filters/filters-operators\"\nimport {\n  findFilterNode,\n  isFilterGroup,\n} from \"@/components/reui/filters/filters-query\"\nimport type {\n  FilterEditorProps,\n  FilterField,\n  FilterGroupNode,\n  FilterOperator,\n  FilterRule,\n} from \"@/components/reui/filters/filters-types\"\n\n/** Which part of the chip a pointer or key is aimed at. No `field`: the chip's\n *  attribute segment is display only, and only the builder re-picks one. */\ntype ChipSegment = \"operator\" | \"value\" | \"menu\"\n\n/** The ref half of `autoFocusProps`: a CALLBACK ref, the one shape an editor\n *  can spread onto any element without a cast, and a no-op here. */\nconst noopAutoFocusRef: React.RefCallback<HTMLElement> = () => {}\n\nfunction defaultValueDisplay<V>(\n  value: V | undefined,\n  operator: FilterOperator | undefined,\n  resolveOption: (value: string) => { label: string } | undefined,\n  labels: ReturnType<typeof useFilterActions>[\"labels\"],\n  // The field's own word for \"no value yet\", which a generic label cannot beat.\n  fieldPlaceholder?: string,\n  /** Whether the value is PICKED rather than typed: a select's search prompt\n   *  and \"enter text...\" both give way to `labels.selectPlaceholder`. */\n  optionBacked?: boolean\n): string {\n  const emptyLabel = optionBacked\n    ? labels.selectPlaceholder\n    : (fieldPlaceholder ?? labels.valuePlaceholder)\n  if (value === undefined || value === null || value === \"\") {\n    return emptyLabel\n  }\n\n  if (getFilterArity(operator) === \"range\" && Array.isArray(value)) {\n    const [from, to] = value as unknown[]\n    return labels.valueRange(String(from ?? \"\"), String(to ?? \"\"))\n  }\n\n  if (Array.isArray(value)) {\n    const values = value as string[]\n    if (values.length === 0) return emptyLabel\n    if (values.length === 1) {\n      return resolveOption(values[0])?.label ?? String(values[0])\n    }\n    return labels.valueCount(values.length)\n  }\n\n  if (typeof value === \"boolean\") return value ? \"True\" : \"False\"\n\n  return resolveOption(String(value))?.label ?? String(value)\n}\n\n/** The same display with the option's own icon in front. A status filter reads\n *  as its colour before its word, so dropping the swatch the picker showed\n *  makes the chip harder to scan than the list it came from. */\nfunction valueWithIcon<V>(\n  value: V | undefined,\n  text: string,\n  resolveOption: (value: string) => { icon?: React.ReactNode } | undefined\n): React.ReactNode {\n  const single =\n    value === undefined || value === null || Array.isArray(value)\n      ? Array.isArray(value) && value.length === 1\n        ? String(value[0])\n        : null\n      : String(value)\n  const icon = single ? resolveOption(single)?.icon : null\n  if (!icon) return text\n  return (\n    <span className=\"flex items-center gap-1.5\">\n      {icon}\n      {text}\n    </span>\n  )\n}\n\n/** The glyph between two ancestors in a nested attribute path, a chevron\n *  because the `pathSeparator` string read as loud as the names it parts.\n *  DECORATIVE: `aria-hidden`, and the plain string is still what\n *  `formatFilterPath` joins for the chip's accessible name and `title`. */\nfunction FilterPathSeparator() {\n  return (\n    <ChevronRightIcon\n      aria-hidden=\"true\"\n      data-slot=\"filter-path-separator\"\n      /* The full muted token, not the `/60` the string carried: a size-3\n         chevron composites to about 2.3:1 on white at 60%. ONE margin for both\n         hosts, 3px a side against a 12px glyph; the chip's old 8px read as\n         three names. Centred by two tokens each inert in the other host, and\n         NOT `align-middle`, which resolves against the x-height and sat the\n         glyph 1.27px low; 0.3635em is half Inter's cap height, 0.375rem half\n         `size-3`. `inline-block` because the reset makes every `svg` a block,\n         which broke the builder's inline `Repository > Stars` into three. */\n      className=\"text-muted-foreground mx-[3px] inline-block size-3 shrink-0 self-center align-[calc(0.3635em_-_0.375rem)]\"\n    />\n  )\n}\n\n/** The elided run of a collapsed path, with the FULL path behind it. THE\n *  TOOLTIP IS NOT THE ACCESSIBLE ROUTE: it is hover and focus, so the segment\n *  is `aria-hidden` and the whole path stays in the control's NAME. The host's\n *  own `title` is dropped while collapsed (`pathCollapsed`) or both fire. */\nfunction FilterPathEllipsis({ full }: { full: string }) {\n  return (\n    <TooltipProvider>\n      <Tooltip>\n        <TooltipTrigger asChild>\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"filter-path-ellipsis\"\n            /* A path SEGMENT with no air of its own: the chevron's margin\n               is all that parts a name from the next, and this used to STACK\n               an `mx` on it. Plain inline, no `vertical-align`: `middle` sat\n               the dots 1.7px low and inline-block grew the run to 21.17px. */\n            className=\"text-muted-foreground shrink-0 self-center\"\n          >\n            ...\n          </span>\n        </TooltipTrigger>\n        <TooltipContent>{full}</TooltipContent>\n      </Tooltip>\n    </TooltipProvider>\n  )\n}\n\n/** Everything a rule needs in order to be READ, in either chrome. */\nexport interface FilterRuleDisplay {\n  pathText: string\n  pathLabel: React.ReactNode\n  /** Whether `pathLabel` shows fewer names than the path has, so the cell's\n   *  own `title` can step aside for the ellipsis segment's tooltip. */\n  pathCollapsed: boolean\n  operatorLabel: string\n  valueLabel: React.ReactNode\n  /** The same value as PLAIN TEXT, for an accessible name. Never scraped from\n   *  the `renderValue` node: whatever text survives inside avatars and a count\n   *  badge announces \"plus one\" for two people. Kept separate from\n   *  `valueLabel`, not derived from it: a React node has no honest text to\n   *  read back. A field whose values do not stringify supplies `valueText`\n   *  itself, or the built-in fallback says \"[object Object]\" to exactly the\n   *  audience the visible display is hiding it from. */\n  valueText: string\n  /** The same value with any collapsed COUNT spelled out. \"3 selected\" cannot\n   *  be recovered from, which is fine while the editor opens and not once\n   *  locked, so the control carries this as `title` and, locked, as its name. */\n  valueFullText: string\n  valueEmpty: boolean\n}\n\n/** How one rule reads, resolved once and shared by both chromes, so a consumer\n *  `renderValue`, the field's own and the built-in cannot disagree. */\nexport function useFilterRuleDisplay<V, O>(\n  rule: FilterRule<V>,\n  field: FilterField<V, O> | undefined,\n  operator: FilterOperator | undefined\n): FilterRuleDisplay {\n  const actions = useFilterActions<V, O>()\n  const render = useFilterRender<V, O>()\n  // Lazily: a label needs no options until an editor actually opens.\n  const optionsState = useFilterOptions<V, O>(field, false)\n\n  const values =\n    rule.value === undefined || rule.value === null\n      ? []\n      : Array.isArray(rule.value)\n        ? (rule.value as unknown[])\n        : [rule.value]\n\n  // Saved views: values the loader has never returned are resolved through the\n  // field's own `resolveValues`, so a restored chip reads \"John Doe\", not an id.\n  useFilterValueResolution(field, values)\n\n  const pathText = formatFilterPath(\n    actions.index,\n    rule.path,\n    actions.labels.pathSeparator\n  )\n\n  const chain = getFilterFieldChain(actions.index, rule.path)\n  // The CASCADER's collapser, from the actions context rather than per host, so\n  // a deep path reads the same on a chip and in a builder row.\n  const segments = collapseFilterPath(chain, {\n    maxSegments: actions.maxPathSegments,\n    collapse: actions.pathCollapse,\n  })\n  const pathCollapsed = segments.some((segment) => segment.type === \"ellipsis\")\n  const pathLabel = chain.length\n    ? segments.map((segment, index) => (\n        <React.Fragment\n          /* Positional, because a field id is unique among its SIBLINGS only:\n             \"Company > Team > Company\" is a legal path and its two ids collide. */\n          key={\n            segment.type === \"field\"\n              ? `${index}:${segment.field.id}`\n              : `${index}:ellipsis`\n          }\n        >\n          {index > 0 ? <FilterPathSeparator /> : null}\n          {segment.type === \"field\" ? (\n            <span>{segment.field.label}</span>\n          ) : (\n            <FilterPathEllipsis full={pathText} />\n          )}\n        </React.Fragment>\n      ))\n    : pathText\n\n  const operatorLabel = operator\n    ? rule.negated\n      ? actions.labels.negated(operator.label)\n      : operator.label\n    : rule.operator || actions.labels.selectCondition\n\n  const valueEmpty =\n    rule.value === undefined ||\n    rule.value === null ||\n    rule.value === (\"\" as unknown as V) ||\n    values.length === 0\n\n  if (!field) {\n    return {\n      pathText,\n      pathLabel,\n      pathCollapsed,\n      operatorLabel,\n      valueLabel: \"\",\n      valueText: \"\",\n      valueFullText: \"\",\n      valueEmpty,\n    }\n  }\n\n  const valueContext = {\n    value: rule.value,\n    values,\n    field,\n    operator: operator ?? { value: rule.operator, label: rule.operator },\n    // Resolved, not empty: a custom display needs the option behind each value.\n    options: values\n      .map((entry) => optionsState.resolve(String(entry)))\n      .filter(Boolean) as NonNullable<\n      ReturnType<typeof optionsState.resolve>\n    >[],\n    labels: actions.labels,\n  }\n\n  // Computed even when a custom display replaces it: this is the string the\n  // accessible name is built from. `field.valueText` overrides it.\n  const valueText = field.valueText\n    ? field.valueText(valueContext)\n    : defaultValueDisplay(\n        rule.value,\n        operator,\n        optionsState.resolve,\n        actions.labels,\n        field.placeholder,\n        // Option-backed by the FIELD, not the operator: `is any of` is\n        // multi-value on a plain text field too, and that one is typed into.\n        field.type === \"select\" ||\n          field.type === \"multiselect\" ||\n          Boolean(field.options?.length) ||\n          Boolean(field.loadOptions)\n      )\n\n  const valueLabel = render.renderValue\n    ? render.renderValue(valueContext)\n    : field.renderValue\n      ? field.renderValue(valueContext)\n      : valueWithIcon(rule.value, valueText, optionsState.resolve)\n\n  // The list behind the count, or the same text again. Multi-value only: a\n  // RANGE also stores an array but already spells both ends out (\"10 to 99\").\n  const valueFullText =\n    field.valueText ||\n    !Array.isArray(rule.value) ||\n    getFilterArity(operator) === \"range\" ||\n    values.length < 2\n      ? valueText\n      : actions.labels.valueDetail(\n          valueText,\n          values.map(\n            (entry) =>\n              optionsState.resolve(String(entry))?.label ?? String(entry)\n          )\n        )\n\n  return {\n    pathText,\n    pathLabel,\n    pathCollapsed,\n    operatorLabel,\n    valueLabel,\n    valueText,\n    valueFullText,\n    valueEmpty,\n  }\n}\n\ninterface FilterValueEditorProps<V = unknown, O = unknown> {\n  rule: FilterRule<V>\n  field: FilterField<V, O>\n  operator: FilterOperator\n  /** Whether the surface holding it is showing. Gates the option service. */\n  open: boolean\n  onClose: () => void\n}\n\n/** The value editor - draft, option service, commit - with NO surface of its\n *  own, so surface and wiring can be replaced independently. The draft lives\n *  here, so a text filter dispatches once on commit, not once per keystroke. */\nfunction FilterValueEditor<V, O>({\n  rule,\n  field,\n  operator,\n  open,\n  onClose,\n}: FilterValueEditorProps<V, O>) {\n  const actions = useFilterActions<V, O>()\n  const [draft, setDraft] = React.useState<V | undefined>(rule.value)\n\n  React.useEffect(() => {\n    if (open) setDraft(rule.value)\n  }, [open, rule.value])\n\n  const options = useFilterOptions<V, O>(field, open)\n  // A LOOKUP, not a definition: every result is a module-level built-in or the\n  // consumer's own component, so the editor is never remounted mid-edit.\n  const editor = React.useMemo(\n    () => actions.resolveEditor(field, operator),\n    [actions, field, operator]\n  )\n\n  if (!editor) return null\n\n  const editorProps: FilterEditorProps<V, O> = {\n    field,\n    operator,\n    value: draft,\n    onValueChange: (next) => setDraft(next as V),\n    host: \"amend\",\n    autoFocusProps: {\n      ref: noopAutoFocusRef,\n      autoFocus: true,\n    },\n    commit: (next, commitOptions) => {\n      actions.updateRule(rule.id, {\n        value: (next === undefined ? draft : next) as V,\n      })\n      // A multi-select commits per toggle and asks to stay put; others dismiss.\n      if (commitOptions?.close === false) return\n      onClose()\n    },\n    cancel: onClose,\n    // The same as cancel, honestly: `back` means something only to a `create`\n    // host.\n    back: onClose,\n    options,\n    labels: actions.labels,\n  }\n\n  // `createElement` rather than JSX: the component comes out of a lookup, so\n  // `<Editor />` trips `react-hooks/static-components`. The fragment keeps the\n  // props object, which carries a ref, from looking like a ref read in render.\n  return <>{React.createElement(editor, editorProps)}</>\n}\n\n/** One step of the flow, released when the panel that owes it has LEFT THE\n *  DOM: both popovers keep portal content mounted through the exit transition,\n *  so this unmount IS that moment and nothing is timed. `onRelease` is used AS\n *  the cleanup, so an unmemoized callback fires its step early. */\nfunction FilterStepHandoff({ onRelease }: { onRelease: () => void }) {\n  React.useEffect(() => onRelease, [onRelease])\n  return null\n}\n\n/** The value host: the editor in a popover anchored to the value segment, and\n *  BOTH routes end here. The operator popover used to draw the editor itself,\n *  so a handed-off panel sat a segment's width left of a second press. */\nexport interface FilterValuePopoverProps<V = unknown, O = unknown> {\n  rule: FilterRule<V>\n  field: FilterField<V, O>\n  operator: FilterOperator | undefined\n  /** The element that opens it, WITH its own children: a chip segment must be\n   *  a direct child of its `ButtonGroup` for the pill to fuse. */\n  trigger: React.ReactElement\n  className?: string\n}\n\nexport function FilterValuePopover<V, O>({\n  rule,\n  field,\n  operator,\n  trigger,\n  className,\n}: FilterValuePopoverProps<V, O>) {\n  const actions = useFilterActions<V, O>()\n  const focusStore = useFilterFocusStore()\n  const autoOpen = useFilterChipAutoOpen(rule.id) === \"value\"\n  const [open, setOpen] = React.useState(false)\n  const locked = isFilterLocked(actions)\n\n  // The last step of the flow as well as the amend route; by now the condition\n  // menu has UNMOUNTED (see `FilterStepHandoff`). CONSUMED as it is honoured,\n  // or Escape closes the editor and this effect reopens it in the same frame.\n  // The `set` stays OUTSIDE the `locked` guard on purpose: a handoff nobody\n  // spends sits armed until some later chip spends it, and a chip that opened\n  // because a DIFFERENT chip was arrowed onto is worse than one that opened\n  // nothing.\n  React.useEffect(() => {\n    if (!autoOpen || open) return\n    if (!locked) setOpen(true)\n    focusStore.set({ id: rule.id, segment: \"value\", autoOpen: false })\n  }, [autoOpen, open, focusStore, rule.id, locked])\n\n  // Nothing to open, but the trigger still renders so the value keeps its\n  // place, and it wears the bar's state: that hangs on the TRIGGER below,\n  // which this path never reaches, so the segment used to look live.\n  if (!operator || !actions.resolveEditor(field, operator)) {\n    return React.cloneElement(\n      trigger as React.ReactElement<Record<string, unknown>>,\n      { disabled: actions.disabled, ...filterReadOnlyProps(actions) }\n    )\n  }\n\n  return (\n    // REFUSES to open while locked rather than leaving it to the trigger: an\n    // `aria-disabled` control that still opens an editor is one that lied.\n    <Popover\n      open={open}\n      onOpenChange={(next) => {\n        if (next && locked) return\n        setOpen(next)\n      }}\n    >\n      {/* The trigger IS the segment, never a wrapper, and `asChild` keeps it\n          from becoming one. `ButtonGroup` fuses DIRECT children only\n          (`[&>*:not(:last-child)]:rounded-r-none`,\n          `[&>*:not(:first-child)]:border-l-0`), so a nested one keeps its own\n          border and the chip reads as separate badges. */}\n      <PopoverTrigger\n        asChild\n        disabled={actions.disabled}\n        {...filterReadOnlyProps(actions)}\n      >\n        {trigger}\n      </PopoverTrigger>\n      <PopoverContent align=\"start\" className={cn(\"w-auto p-0\", className)}>\n        <FilterValueEditor<V, O>\n          rule={rule}\n          field={field}\n          operator={operator}\n          open={open}\n          onClose={() => {\n            setOpen(false)\n            focusStore.set({ id: rule.id, segment: \"value\", autoOpen: false })\n          }}\n        />\n      </PopoverContent>\n    </Popover>\n  )\n}\n\n/* A chip's ATTRIBUTE is fixed once the chip exists: no field popover here. A\n   new field invalidates the operator and the value, so \"amending\" threw both\n   away. The builder keeps its picker, where a row reads as a form. */\n\n/** The condition menu, and the step after it. The list is the cascader run\n *  flat: the old hand-rolled one marked the keyboard HIGHLIGHT with\n *  `aria-selected` and had no Home, End or typeahead. It HANDS OFF to the\n *  value popover once its own panel has left the DOM; advancing in place\n *  anchored the editor to the CONDITION segment and doubled up in the row. */\nexport interface FilterOperatorPopoverProps<V = unknown, O = unknown> {\n  rule: FilterRule<V>\n  field: FilterField<V, O>\n  trigger: React.ReactElement\n  className?: string\n}\n\nexport function FilterOperatorPopover<V, O>({\n  rule,\n  field,\n  trigger,\n  className,\n}: FilterOperatorPopoverProps<V, O>) {\n  const actions = useFilterActions<V, O>()\n  const focusStore = useFilterFocusStore()\n  const autoOpen = useFilterChipAutoOpen(rule.id) === \"operator\"\n  const [open, setOpen] = React.useState(false)\n  const locked = isFilterLocked(actions)\n  /** Whether the close this panel is going through IS the step being handed\n   *  on. A ref, so it survives the render that closes the popover. Every OPEN\n   *  clears it, so an Escape or an outside press finds it already lowered and\n   *  spends nothing; `release` leaves it standing because one twin asks again\n   *  later: Radix reads it from `onCloseAutoFocus`, a macrotask after the\n   *  unmount. Clearing it in `release` would break that twin only. */\n  const handoff = React.useRef(false)\n  const operators = actions.resolveOperators(field)\n  const operator = getFilterOperator(operators, rule.operator)\n\n  // Memoized because the array IS the menu's identity: the cascader rebuilds\n  // its index per `items` identity, so a fresh array rebuilds it per keystroke.\n  const items = React.useMemo(\n    () =>\n      visibleFilterOperators(operators).map((entry) => ({\n        value: entry.value,\n        label: entry.label,\n      })),\n    [operators]\n  )\n\n  // Opened by the root the moment the chip is created. CONSUMED here, or the\n  // handoff re-opens the menu on the frame Escape closes it. Consumed even\n  // while locked, for the reason on the value popover's copy.\n  React.useEffect(() => {\n    if (!autoOpen || open) return\n    handoff.current = false\n    if (!locked) setOpen(true)\n    focusStore.set({ id: rule.id, segment: \"operator\", autoOpen: false })\n  }, [autoOpen, open, focusStore, rule.id, locked])\n\n  const close = () => {\n    handoff.current = false\n    setOpen(false)\n    focusStore.set({ id: rule.id, segment: \"operator\", autoOpen: false })\n  }\n\n  /** The parked step, spent on the frame this panel stops existing. Memoized\n   *  on nothing that changes, and load bearing: `FilterStepHandoff` uses this\n   *  AS its cleanup, so a new identity mid-flow fires the step too early. */\n  const release = React.useCallback(() => {\n    if (!handoff.current) return\n    focusStore.set({ id: rule.id, segment: \"value\", autoOpen: true })\n  }, [focusStore, rule.id])\n\n  // The chip going away takes its step with it: React destroys a deleted\n  // subtree top down, so this runs before the panel's own cleanup.\n  React.useEffect(\n    () => () => {\n      handoff.current = false\n    },\n    []\n  )\n\n  return (\n    <Popover\n      open={open}\n      onOpenChange={(next) => {\n        if (next && locked) return\n        /* Escape, an outside press, a second press: none is the step being\n           taken, so none may spend it. RETIRED ON OPEN, not on close, and that\n           is a twin difference: in Radix an item choice dismisses through here\n           too, so retiring on close wiped the request before the unmount. */\n        if (next) handoff.current = false\n        setOpen(next)\n      }}\n    >\n      {/* `asChild` for the reason spelled out on the value popover's copy. */}\n      <PopoverTrigger\n        asChild\n        disabled={actions.disabled}\n        {...filterReadOnlyProps(actions)}\n      >\n        {trigger}\n      </PopoverTrigger>\n      <PopoverContent\n        align=\"start\"\n        /* RADIX ONLY, the last hop of the handoff. Radix restores focus to\n           this trigger a macrotask AFTER the panel unmounts, which is after\n           `release` has opened the value editor; that restore pulls focus back\n           onto the condition segment and the value menu dismisses itself.\n           Suppressed only while the flag is up, and lowered as it is spent.\n           Base UI hands focus over in the other order and needs nothing. The\n           same guard `FiltersBuilder` runs for the field picker, for the same\n           reason, so the two move together. */\n        onCloseAutoFocus={(event) => {\n          if (!handoff.current) return\n          handoff.current = false\n          event.preventDefault()\n        }}\n        /* `w-auto` with a FLOOR: a catalog sizes to its longest label, and a\n           boolean field's \"is\" and \"is not\" would read as a scrap of paper. */\n        className={cn(\"w-auto min-w-40 p-0\", className)}\n      >\n        {/* INSIDE the panel deliberately: only a child of the content is\n            unmounted by the exit transition rather than by the close. */}\n        <FilterStepHandoff onRelease={release} />\n        <FilterMenu\n          items={items}\n          selected={rule.operator ? [rule.operator] : []}\n          onSelectionChange={(values) => {\n            const value = values[0]\n            /* Deselecting the committed operator is a step back rather than a\n               choice, so pressing the current row simply closes. */\n            if (value === undefined) {\n              close()\n              return\n            }\n            const chosen = getFilterOperator(operators, value)\n            /* BUILDING versus AMENDING, the same fork the advanced row draws\n               at its field step. A rule reaches this menu with no operator\n               exactly once, while it is being added, and only then is the\n               value the step after this one. Re-picking the condition on a\n               rule that already has one is an edit of that one cell: it\n               commits and closes, and the user opens the value themselves. */\n            const building = !rule.operator\n            actions.updateRule(rule.id, {\n              operator: value,\n              /* The value moves with the operator: \"is\" to \"is any of\" would\n                 leave a bare string where every reader expects an array. */\n              value: coerceFilterValue(\n                rule.value,\n                getFilterOperator(operators, rule.operator),\n                chosen\n              ) as V,\n            })\n            if (building && operatorTakesValue(chosen)) {\n              /* PARKED, not opened: `release` hands the row to its value\n                 surface once this panel has unmounted. */\n              handoff.current = true\n              setOpen(false)\n              return\n            }\n            close()\n          }}\n          labels={actions.labels}\n          ariaLabel={field.label}\n          searchPlaceholder={actions.labels.searchOperators}\n          /* No visible search field: a CLOSED enum of six to ten labels, all\n             on screen. Still RENDERED, visually hidden, because it owns focus\n             and `aria-activedescendant`: arrows, Home, End and typeahead. */\n          searchable={false}\n          /* Taller than a value list on purpose: the operator set is CLOSED, so\n             all of it fits and the height buys the whole catalog. A value list\n             is open ended and would only push its own footer off the screen. */\n          maxHeight={320}\n          /* Deliberately unpinned: one selected operator in a short list, so\n             lifting it would lose the catalog's declared reading order. */\n        />\n      </PopoverContent>\n    </Popover>\n  )\n}\n\n/** The keyboard path to a CROSS-GROUP move: Alt+Arrow reorders within the\n *  owning group only and Wrap creates a NEW group, so the drag layer's\n *  cross-group move had no keyboard parity. Numbered in document order. */\nexport function FilterMoveToMenuItems({ nodeId }: { nodeId: string }) {\n  const actions = useFilterActions()\n  // A menu ITEM takes the native word: both twins already make `disabled`\n  // roving-focusable and `aria-disabled`.\n  const reorderable = useFilterReorderable()\n  const locked = isFilterLocked(actions)\n  // Read at render time: the menu's content mounts when the menu opens, so\n  // this is the tree the user is looking at.\n  const query = actions.getQuery()\n  const found = findFilterNode(query, nodeId)\n  if (!found || !found.parent) return null\n\n  const destinations: { id: string; label: string; size: number }[] = []\n  if (found.parent.id !== query.id) {\n    destinations.push({\n      id: query.id,\n      label: actions.labels.moveToTopLevel,\n      size: query.rules.length,\n    })\n  }\n\n  let position = 0\n  // `inside` suppresses the PUSH and not the walk, so the numbering stays\n  // document order rather than renumbering every group after this one. Counted\n  // before the exclusions for the same reason: the current parent is not\n  // offered but still holds its number, so the numbering is stable whichever\n  // row's menu is open.\n  const visit = (group: FilterGroupNode<unknown>, inside: boolean) => {\n    for (const child of group.rules) {\n      if (!isFilterGroup(child)) continue\n      position += 1\n      // Itself and everything under it: `moveFilterNodeTo` already refuses that\n      // move - it would detach the subtree and leave a cycle - so offering it\n      // would be a menu row that quietly does nothing.\n      const within = inside || child.id === nodeId\n      if (!within && child.id !== found.parent!.id) {\n        destinations.push({\n          id: child.id,\n          label: actions.labels.moveToGroup(position),\n          size: child.rules.length,\n        })\n      }\n      visit(child, within)\n    }\n  }\n  visit(query, false)\n\n  if (destinations.length === 0) return null\n\n  // The THIRD route into a move, gated on the same switch as the grip and\n  // Alt+Arrow: ungated, a builder that draws no handle still reordered here.\n  if (!reorderable) return null\n\n  return (\n    <>\n      {destinations.map((destination) => (\n        <DropdownMenuItem\n          key={destination.id}\n          disabled={locked}\n          onClick={() =>\n            actions.moveNodeTo(nodeId, destination.id, destination.size)\n          }\n        >\n          {/* A bend into the destination: movement, not duplication or nesting. */}\n          <CornerDownRightIcon aria-hidden=\"true\" />\n          <span className={FILTER_MENU_LABEL_CLASS}>{destination.label}</span>\n        </DropdownMenuItem>\n      ))}\n    </>\n  )\n}\n\n/** The per-rule actions, without the trigger: the chip's kebab and a builder\n *  row's kebab act on the same rule. `allowGrouping` is the CHROME's answer;\n *  \"Convert to advanced filter\" is the CONSUMER's, and hides itself there. */\nexport function FilterRuleMenuItems({\n  ruleId,\n  /** Offer \"Wrap in condition group\". Off for the chip row, which cannot draw\n   *  a group; on in the builder, the only way to nest without dragging. */\n  allowGrouping = false,\n}: {\n  ruleId: string\n  allowGrouping?: boolean\n}) {\n  const actions = useFilterActions()\n  // Gated here as well as at the trigger, because this is EXPORTED: a consumer\n  // composing their own menu gets rows that say they are unavailable.\n  const locked = isFilterLocked(actions)\n  return (\n    /* Every row leads with an icon. `IconPlaceholder` because the source ships\n       under five icon sets; no size class, because each style already sizes an\n       unsized svg in a menu row; `aria-hidden`, the label IS the name. */\n    <>\n      <DropdownMenuItem\n        disabled={locked}\n        onClick={() => actions.duplicateNode(ruleId)}\n      >\n        <CopyIcon aria-hidden=\"true\" />\n        <span className={FILTER_MENU_LABEL_CLASS}>\n          {actions.labels.duplicate}\n        </span>\n      </DropdownMenuItem>\n      <DropdownMenuItem\n        disabled={locked}\n        onClick={() => actions.negateRule(ruleId)}\n      >\n        {/* Two arrows swapping: negation flips to the declared inverse. */}\n        <ArrowLeftRightIcon aria-hidden=\"true\" />\n        <span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.negate}</span>\n      </DropdownMenuItem>\n      {allowGrouping ? (\n        <DropdownMenuItem\n          disabled={locked}\n          onClick={() => actions.wrapNodeInGroup(ruleId)}\n        >\n          {/* Layers: braces read as grouping in only three of the five sets. */}\n          <LayersIcon aria-hidden=\"true\" />\n          <span className={FILTER_MENU_LABEL_CLASS}>\n            {actions.labels.wrapInGroup}\n          </span>\n        </DropdownMenuItem>\n      ) : null}\n      {allowGrouping ? <FilterMoveToMenuItems nodeId={ruleId} /> : null}\n      {/* OPTIONAL, and gated on both halves of \"would this do anything\": the\n          handler is the consumer's opt-in, and an already-advanced bar has\n          nothing to convert. NOT gated on `locked`: it changes no query, is\n          handed no mutator, and the shipped kebab will not open while locked. */}\n      {actions.convertToAdvanced && actions.variant !== \"advanced\" ? (\n        <DropdownMenuItem onClick={() => actions.convertToAdvanced?.()}>\n          {/* Sliders: the one \"advanced settings\" glyph in all five sets. */}\n          <SlidersHorizontalIcon aria-hidden=\"true\" />\n          <span className={FILTER_MENU_LABEL_CLASS}>\n            {actions.labels.convertToAdvanced}\n          </span>\n        </DropdownMenuItem>\n      ) : null}\n      <DropdownMenuItem\n        variant=\"destructive\"\n        disabled={locked}\n        onClick={() => actions.removeNode(ruleId)}\n      >\n        {/* No colour: the destructive variant already paints the row's svgs. */}\n        <Trash2Icon aria-hidden=\"true\" />\n        <span className={FILTER_MENU_LABEL_CLASS}>{actions.labels.remove}</span>\n      </DropdownMenuItem>\n    </>\n  )\n}\n\nexport interface FilterChipProps<V = unknown> {\n  rule: FilterRule<V>\n  index: number\n}\n\n/** One filter, as a chip. Memoization means something here: the actions\n *  context is stable, the focus store is subscribed to a boolean and the query\n *  shares structure, so editing one filter of forty re-renders one chip. */\nfunction FilterChipImpl<V, O>({ rule, index }: FilterChipProps<V>) {\n  const actions = useFilterActions<V, O>()\n  const render = useFilterRender<V, O>()\n  const focusStore = useFilterFocusStore()\n  const focused = useFilterChipFocused(rule.id)\n  const noFocus = useFilterFocusEmpty()\n  const locked = isFilterLocked(actions)\n  // THE CHIP'S HEIGHT, by way of the one button in it that has one:\n  // `ButtonGroup` is `items-stretch` and no style gives a text segment a\n  // height, so the kebab's rung is the pill's. The RADIUS survives because\n  // every style whose `icon-sm` rounds differently re-pins it in a group.\n  const sizes = filterControlSizes(actions)\n  // The kebab is CONTROLLED so it can refuse to open: every mutating row\n  // behind it is gated. That puts \"Convert to advanced filter\" out of reach\n  // while locked; a consumer-composed menu still draws it.\n  const [menuOpen, setMenuOpen] = React.useState(false)\n  // Exactly one chip is in the tab order at a time. Before anything has been\n  // focused that is the first chip, so Tab reaches the row in one press.\n  const isTabStop = focused || (noFocus && index === 0)\n\n  const field = getFilterField(actions.index, rule.path)\n  const operators = field ? actions.resolveOperators(field) : []\n  const operator = getFilterOperator(operators, rule.operator)\n\n  const {\n    pathText,\n    pathLabel,\n    pathCollapsed,\n    operatorLabel,\n    valueLabel,\n    valueText,\n    valueFullText,\n    valueEmpty,\n  } = useFilterRuleDisplay<V, O>(rule, field, operator)\n\n  if (!field) {\n    // A rule pointing at a field the schema no longer has. Dropping it loses a\n    // saved view's data; rendering nothing leaves an invisible condition still\n    // filtering. It carries the SAME roving wiring as a real chip: `data-slot`\n    // alone joined the arrow-key query with no `tabIndex` to land on.\n    return (\n      <ButtonGroup\n        data-slot=\"filter-chip\"\n        data-unknown=\"\"\n        role=\"group\"\n        aria-label={actions.labels.filterLabel(\n          rule.path.join(actions.labels.pathSeparator)\n        )}\n        data-focused={focused || undefined}\n        data-rule-id={rule.id}\n        data-index={index}\n        tabIndex={isTabStop ? 0 : -1}\n        onFocusCapture={() => {\n          if (!focused)\n            focusStore.set({ id: rule.id, segment: null, autoOpen: false })\n        }}\n      >\n        <ButtonGroupText className=\"bg-background dark:bg-input/30 text-muted-foreground\">\n          {rule.path.join(actions.labels.pathSeparator)}\n        </ButtonGroupText>\n        <Button\n          variant=\"outline\"\n          size={sizes.icon}\n          className=\"bg-background dark:bg-input/30\"\n          aria-label={actions.labels.remove}\n          /* It had no gate at all, so the one chip whose whole purpose is to be\n             removed could be removed from a bar that refuses every other edit. */\n          disabled={actions.disabled}\n          {...filterReadOnlyProps(actions)}\n          onClick={() => actions.removeNode(rule.id)}\n        >\n          <XIcon />\n        </Button>\n      </ButtonGroup>\n    )\n  }\n\n  if (render.renderChip) return <>{render.renderChip(rule)}</>\n\n  const focusSegment = (segment: ChipSegment) =>\n    focusStore.set({ id: rule.id, segment, autoOpen: false })\n\n  // A rule with no condition yet, KEPT rather than removed (see\n  // `isFilterRuleComplete`), so it has to read as unfinished. Through WORDS:\n  // the dashed outline it replaces degraded to an underline under sera.\n  const incomplete = !rule.operator\n\n  // The same test the value segment renders under, so the name matches the\n  // chip: `valueText` alone appended a placeholder to valueless conditions.\n  const hasValue = Boolean(rule.operator) && operatorTakesValue(operator)\n\n  // The value's spoken form in the chip's NAME: a name is not a prompt, so\n  // \"Description contains enter text...\" becomes \"no value\".\n  const valueName =\n    valueEmpty && !field.valueText ? actions.labels.noValue : valueText\n\n  return (\n    <ButtonGroup\n      data-slot=\"filter-chip\"\n      role=\"group\"\n      aria-label={actions.labels.filterLabel(\n        `${pathText} ${operatorLabel}${hasValue ? ` ${valueName}` : \"\"}`.trim() +\n          (incomplete ? `, ${actions.labels.incomplete}` : \"\")\n      )}\n      data-focused={focused || undefined}\n      data-incomplete={incomplete || undefined}\n      data-rule-id={rule.id}\n      tabIndex={isTabStop ? 0 : -1}\n      className={cn(\n        /* Sera is an underline style, so the boxed segments are normalised to\n           its bottom-border-only look or the chip reads as a mix of both. */\n        \"style-sera:*:border-transparent style-sera:*:border-b-input style-sera:*:rounded-none\"\n      )}\n      onFocusCapture={() => {\n        if (!focused)\n          focusStore.set({ id: rule.id, segment: null, autoOpen: false })\n      }}\n      data-index={index}\n    >\n      {/* DISPLAY ONLY: a div, not a button, not a tab stop, no popover. The\n          attribute is fixed for the life of the chip. */}\n      <ButtonGroupText\n        /* Dropped while the path is collapsed: the ellipsis inside carries the\n           same sentence as a tooltip, and the two would stack. */\n        title={pathCollapsed ? undefined : pathText}\n        className=\"bg-background dark:bg-input/30 cursor-default gap-1.5\"\n      >\n        {field.icon}\n        {/* Zero gap INSIDE the path, so the separator's own margin is the only\n            air around a chevron; `gap-1.5` used to stack 6px a side on it. */}\n        <span className=\"flex items-center\">{pathLabel}</span>\n      </ButtonGroupText>\n\n      <FilterOperatorPopover\n        rule={rule}\n        field={field}\n        trigger={\n          <ButtonGroupText\n            asChild\n            className={cn(\n              \"hover:bg-accent bg-background dark:bg-input/30 cursor-default\",\n              /* The operator is connective tissue between the field and the\n                 value, so it reads quieter than either - unless it is still\n                 the prompt \"Select condition\", the one thing to act on. */\n              incomplete ? \"text-foreground\" : \"text-muted-foreground\"\n            )}\n            onPointerDown={() => focusSegment(\"operator\")}\n          >\n            {/* ONE element that is both the group text and the trigger: an\n                extra wrapper here is the direct child the group would fuse. */}\n            <button type=\"button\">{operatorLabel}</button>\n          </ButtonGroupText>\n        }\n      />\n\n      {/* No condition, no value: `getFilterArity(undefined)` defaults to \"one\",\n          so testing the operator alone renders a stray value segment. */}\n      {hasValue ? (\n        <FilterValuePopover\n          rule={rule}\n          field={field}\n          operator={operator}\n          trigger={\n            <ButtonGroupText\n              asChild\n              /* Named explicitly rather than by its contents: avatars or a\n                 \"+2\" badge, and \"plus two\" says nothing about two people. It\n                 grows to the whole list when the editor cannot be opened,\n                 since locked it must carry what a press no longer reveals. */\n              aria-label={locked ? valueFullText : valueText}\n              /* The pointer's route to the same thing, and only when there is\n                 more to say than the segment already says. */\n              title={valueFullText === valueText ? undefined : valueFullText}\n              className={cn(\n                \"hover:bg-accent bg-background dark:bg-input/30 cursor-default\",\n                valueEmpty && \"text-muted-foreground\"\n              )}\n              onPointerDown={() => focusSegment(\"value\")}\n            >\n              {/* One element, for the reason on the operator segment. */}\n              <button type=\"button\">{valueLabel}</button>\n            </ButtonGroupText>\n          }\n        />\n      ) : null}\n\n      <DropdownMenu\n        open={menuOpen}\n        onOpenChange={(next) => {\n          if (next && locked) return\n          setMenuOpen(next)\n        }}\n      >\n        <DropdownMenuTrigger\n          asChild\n          disabled={actions.disabled}\n          {...filterReadOnlyProps(actions)}\n        >\n          <Button\n            variant=\"outline\"\n            size={sizes.icon}\n            /* The same surface the three text segments force. Styles whose\n               outline button is transparent in dark (sera, luma, rhea) left\n               the kebab as a notch in an otherwise filled pill. */\n            className=\"bg-background dark:bg-input/30\"\n            aria-label={actions.labels.chipMenu(field.label)}\n            onPointerDown={() => focusSegment(\"menu\")}\n          >\n            <EllipsisVerticalIcon />\n          </Button>\n        </DropdownMenuTrigger>\n        {/* The SAME sizing the builder's menus use, from one constant: a menu\n            that cuts \"Convert to group\" in one chrome is one defect twice. */}\n        <DropdownMenuContent\n          align=\"end\"\n          className={cn(FILTER_MENU_CLASS, actions.menuClassName)}\n        >\n          <FilterRuleMenuItems ruleId={rule.id} />\n        </DropdownMenuContent>\n      </DropdownMenu>\n    </ButtonGroup>\n  )\n}\n\nexport const FilterChip = React.memo(FilterChipImpl) as typeof FilterChipImpl\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-chip.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-context.tsx",
      "content": "/**\n * filters-context - adapted for tealmac UI from ReUI \"filters/filters-context\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n\"use client\"\n\nimport * as React from \"react\"\n\nimport type { FilterDraftAction } from \"@/components/reui/filters/filters-draft\"\nimport type { FilterPathCollapse } from \"@/components/reui/filters/filters-lib\"\nimport type {\n  FilterCombinator,\n  FilterDraft,\n  FilterDraftStep,\n  FilterEditor,\n  FilterEditorRegistry,\n  FilterEmptyStateContext,\n  FilterField,\n  FilterIndex,\n  FilterLabels,\n  FilterOperator,\n  FilterOption,\n  FilterQuery,\n  FilterRule,\n  FilterValueDisplayContext,\n  FilterValueType,\n} from \"@/components/reui/filters/filters-types\"\n\n/** Four publishing channels, not one, so a chip never re-renders at the rate\n *  of the fastest: `actions` republishes on a schema, labels or config change,\n *  `state` on every query edit and keystroke, `render` on a `renderValue` /\n *  `renderChip` identity change, `focus` on every arrow key. The reorder flag\n *  and the row-state store further down are contexts too, but not channels the\n *  query is published through. */\n\n/* -------------------------------------------------------------------------- */\n/*                                   Actions                                  */\n/* -------------------------------------------------------------------------- */\n\n/** Stable for the life of the component, bar a config change. Every mutator\n *  reads a latest-props ref rather than closing over the state it needs, so a\n *  keystroke rebuilds no handler and no memoized chip re-renders. The two lock\n *  flags are published rather than kept only in that ref: a refusal that lives\n *  in a ref arrives one commit late. The two resolvers are the deliberate\n *  exception: they are read DURING render, so they memoize on the values they\n *  read instead of going through the ref. Every mutator is also the MUTATION\n *  BOUNDARY - `disabled` and `readOnly` are enforced here, not at the call\n *  sites that draw the buttons, so a route added next month is refused by\n *  construction rather than by remembering. See `isFilterLocked`. */\nexport interface FilterActionsContextValue<V = unknown, O = unknown> {\n  /** Normalized schema. Also on the state context, from the same memo. */\n  index: FilterIndex<V, O>\n  labels: FilterLabels\n  operatorCatalog: Record<FilterValueType, FilterOperator[]>\n  editors: FilterEditorRegistry\n  size: \"sm\" | \"default\"\n  /** The bar is off: nothing operable, and the controls leave the tab order. */\n  disabled: boolean\n  /** Readable and navigable, but not changeable. See `isFilterLocked`. */\n  readOnly: boolean\n\n  /** Which chrome is drawing, so a chip kebab can hide its convert row. */\n  variant: \"basic\" | \"advanced\"\n\n  /** Consumer classes for the menus and the field picker, merged AFTER the\n   *  primitive's own defaults so a consumer `w-*` wins through tailwind-merge\n   *  rather than on source order. On the context: four chromes mount the same\n   *  menu, and a per-chrome prop is set in four places and missed in a fifth. */\n  menuClassName: string | undefined\n  fieldPickerClassName: string | undefined\n\n  /** Turns on the chip kebab's \"Convert to advanced filter\" row: present means\n   *  offered. A callback with no boolean beside it, since only the consumer\n   *  can switch chromes. Changes no query, so it skips the mutation boundary,\n   *  which is safe only because it is handed no setter: a consumer's handler\n   *  has no route to the query at all. */\n  convertToAdvanced: (() => void) | undefined\n\n  /** Path shortening, published so BOTH chromes render the same path. */\n  pathCollapse: FilterPathCollapse\n  maxPathSegments: number\n\n  /** Operators for a field, memoized on the catalog and the schema. */\n  resolveOperators: (field: FilterField<V, O>) => FilterOperator[]\n  resolveEditor: (\n    field: FilterField<V, O>,\n    operator: FilterOperator | undefined\n  ) => FilterEditor<V, O> | undefined\n  /** Value-to-label store shared by every `useFilterOptions` under the root. */\n  resolution: FilterResolutionStore\n\n  /** Appends a rule. Defaults to the ROOT group. The parent is a parameter\n   *  rather than always the root because a nested group's add button is the\n   *  keyboard path into that group, and routing it through the root then\n   *  moving it would be two edits and two announcements for one action. */\n  addRule: (rule: FilterRule<V>, parentId?: string) => void\n  /** Appends an empty group and returns its id, so the caller can focus it.\n   *  Returns an EMPTY STRING when the bar is disabled or read only, the one\n   *  mutator that has to report its refusal: focusing a group that was never\n   *  created strands the tab stop. `\"\"` rather than `string | null` keeps the\n   *  callers that already test the id honest without widening a published\n   *  signature. */\n  addGroup: (parentId?: string, combinator?: FilterCombinator) => string\n  updateRule: (\n    id: string,\n    updates: Partial<Omit<FilterRule<V>, \"id\" | \"type\">>\n  ) => void\n  /** Removes a rule OR a group, and prunes the groups that empties. Node-level\n   *  rather than rule-level because a chip only ever removes a rule, while a\n   *  builder row's trash and a group header's trash are the same button on two\n   *  kinds of node. */\n  removeNode: (id: string) => void\n  duplicateNode: (id: string) => void\n  negateRule: (id: string) => void\n  /** Reorders within the node's own parent. Out of range moves are no-ops. */\n  moveNode: (id: string, delta: number) => void\n  /** Moves a node into another group, at an index. The drag-and-drop half. */\n  moveNodeTo: (id: string, parentId: string, index: number) => void\n  /** Copies a node into another group, at an index. The Alt-drag half, apart\n   *  from `duplicateNode` (which copies BESIDE, with no destination): the two\n   *  composed would emit two queries for one gesture, and a controlled\n   *  consumer would persist a tree the user never asked for. */\n  copyNodeTo: (id: string, parentId: string, index: number) => void\n  /** Nests one node in a new group. The keyboard half of the same idea. */\n  wrapNodeInGroup: (id: string, combinator?: FilterCombinator) => void\n  /** Dissolves a group into its parent. The inverse of `wrapNodeInGroup`. */\n  unwrapGroup: (groupId: string) => void\n  setCombinator: (groupId: string, combinator: FilterCombinator) => void\n  toggleCombinator: (groupId: string) => void\n  clearQuery: () => void\n\n  openCreate: () => void\n  openAmend: (id: string, step: FilterDraftStep) => void\n  closeDraft: () => void\n  dispatchDraft: (action: FilterDraftAction<V>) => void\n\n  /** Writes the bar's live region, for a change no visible surface reports: an\n   *  editor's popover is the one place something destructive happens to rows\n   *  the user is not on, with focus, name and text unchanged afterwards. Not a\n   *  query write, so it skips `emit` and asks the lock nothing. */\n  announce: (message: string) => void\n\n  /** Getters for event handlers, so a handler never closes over stale state. */\n  getQuery: () => FilterQuery<V>\n  getDraft: () => FilterDraft<V> | null\n  /** Fresh id from the SSR-safe factory. */\n  nextId: () => string\n}\n\n/* -------------------------------------------------------------------------- */\n/*                             The mutation lock                              */\n/* -------------------------------------------------------------------------- */\n\n/** `disabled` and `readOnly` are NOT two words for one state. `disabled` is\n *  the native attribute: not operable, out of the tab order. `readOnly` blocks\n *  MUTATION and preserves NAVIGATION, because a read-only bar exists so a\n *  keyboard or screen reader user can walk the chips and find out what the\n *  view is filtered by. Collapsing the two once put the native attribute on\n *  all thirteen advanced-builder cell controls while the roving tab stop sat\n *  on a disabled element, so not one row could be reached from the keyboard.\n *\n *  So a mutating control keeps its tab stop and wears `aria-disabled` plus\n *  `data-readonly` (`filterReadOnlyProps`), this repo's convention for\n *  \"present, focusable, not operable\". `aria-readonly` is never used, being\n *  disallowed on the button, group and toolbar roles, so the BAR says it in\n *  prose through `labels.readOnly`. The refusal itself is enforced once, where\n *  all fourteen query writes pass through `emit` in `filters.tsx`. */\nexport function isFilterLocked(state: {\n  disabled: boolean\n  readOnly: boolean\n}): boolean {\n  return state.disabled || state.readOnly\n}\n\n/** What a MUTATING control wears while the bar is read only. `null` when the\n *  bar is disabled, because the native attribute already says it. A\n *  conditional spread, not explicit `undefined`s: `aria-disabled=\"false\"` on\n *  an enabled control is noise, and `data-readonly` is a presence hook. */\nexport function filterReadOnlyProps(state: {\n  disabled: boolean\n  readOnly: boolean\n}) {\n  if (state.disabled || !state.readOnly) return null\n  return { \"aria-disabled\": true, \"data-readonly\": \"\" } as const\n}\n\n/* -------------------------------------------------------------------------- */\n/*                               The size ladder                              */\n/* -------------------------------------------------------------------------- */\n\n/** The two shadcn button sizes one filters size resolves to. Two rungs because\n *  shadcn ships a separate ladder for labelled and for icon-only buttons, and\n *  pairing them keeps a row's kebab as tall as the cell beside it. */\nexport interface FilterControlSizes {\n  /** Labelled buttons: the row cells, both triggers, the panel footer. */\n  button: \"sm\" | \"default\"\n  /** Icon-only buttons, and also the CHIP's height: a chip is an\n   *  `items-stretch` `ButtonGroup` and no style gives its text segment a\n   *  height, so the segments stretch to the kebab, the one child that has one.\n   *  Sizing the kebab sizes the pill. */\n  icon: \"icon-sm\" | \"icon\"\n}\n\n/** ONE ladder, keyed off `size`, for every control the chrome renders, because\n *  the alternative already happened: five advanced-builder cells took\n *  `actions.size` while seven sites hardcoded `icon-sm` and three `sm`, giving\n *  one row three heights. Nothing here is a pixel - each value is a shadcn\n *  size NAME that `Button` resolves per style, since the control-height ladder\n *  is per style (nova 7/8, sera 9/10, mira 6/7, and so on), and the glyph size\n *  rides the same name, so pinning an icon size in here would fight the style\n *  rather than match it. Two rungs only: `lg` would make the bar taller than\n *  the style's own default control height (want taller, pick a taller STYLE),\n *  and `icon-xs` is a 20-24px square in most styles, too small for a chip's\n *  own label to clear. */\nconst FILTER_CONTROL_SIZES: Record<\"sm\" | \"default\", FilterControlSizes> = {\n  sm: { button: \"sm\", icon: \"icon-sm\" },\n  default: { button: \"default\", icon: \"icon\" },\n}\n\n/** The pair for a bar's size, off anything with a `size`, so a\n *  consumer-composed chrome uses the same ladder as the shipped one. The\n *  fallback is for JavaScript callers: a `\"lg\"` TypeScript would have rejected\n *  must still draw buttons rather than throw on `.button`. */\nexport function filterControlSizes(state: {\n  size: \"sm\" | \"default\"\n}): FilterControlSizes {\n  return FILTER_CONTROL_SIZES[state.size] ?? FILTER_CONTROL_SIZES.default\n}\n\nconst FilterActionsContext =\n  React.createContext<FilterActionsContextValue | null>(null)\n\nexport function useFilterActions<\n  V = unknown,\n  O = unknown,\n>(): FilterActionsContextValue<V, O> {\n  const context = React.useContext(FilterActionsContext)\n  if (!context) {\n    throw new Error(\"useFilterActions must be used inside <Filters>\")\n  }\n  return context as unknown as FilterActionsContextValue<V, O>\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    State                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Volatile by construction: typing one character into a value editor\n *  republishes it. Subscribe from the bar and the panel, never from a chip. */\nexport interface FilterStateContextValue<V = unknown> {\n  query: FilterQuery<V>\n  draft: FilterDraft<V> | null\n  ruleCount: number\n  /** Live region text. Empty except immediately after an announced change. */\n  announcement: string\n  /** How many announcements have been made, so a REPEATED one is still heard:\n   *  `aria-live` reports a DOM mutation and React writes nothing when the\n   *  string is unchanged, so the chrome keys the region's contents on this. A\n   *  counter rather than a timestamp: it is compared for identity, never read\n   *  as a value, and is stable across a rerender that a clock is not. */\n  announcementSeq: number\n}\n\nconst FilterStateContext = React.createContext<FilterStateContextValue | null>(\n  null\n)\n\nexport function useFilterState<V = unknown>(): FilterStateContextValue<V> {\n  const context = React.useContext(FilterStateContext)\n  if (!context) {\n    throw new Error(\"useFilterState must be used inside <Filters>\")\n  }\n  return context as unknown as FilterStateContextValue<V>\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Render                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Consumer render overrides, on their own channel. They must be\n *  always-current closures yet change identity on every parent render when\n *  written inline, so isolating them re-renders only what calls them. */\nexport interface FilterRenderContextValue<V = unknown, O = unknown> {\n  renderValue?: (context: FilterValueDisplayContext<V, O>) => React.ReactNode\n  renderChip?: (rule: FilterRule<V>) => React.ReactNode\n  renderEmpty?: (context: FilterEmptyStateContext) => React.ReactNode\n}\n\nconst FilterRenderContext = React.createContext<FilterRenderContextValue>({})\n\nexport function useFilterRender<\n  V = unknown,\n  O = unknown,\n>(): FilterRenderContextValue<V, O> {\n  return React.useContext(FilterRenderContext) as FilterRenderContextValue<V, O>\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                 Focus store                                */\n/* -------------------------------------------------------------------------- */\n\n/** Which chip currently owns the row's single tab stop. */\nexport interface FilterFocus {\n  id: string | null\n  /** Which cell inside that row, for restoring focus after an edit. A chip\n   *  draws only `field`, `operator`, `value` and `menu`; the rest are advanced\n   *  builder cells, where a GROUP header is a row too (its `field` is the\n   *  combinator sentence). One union, because the chromes share the store. */\n  segment:\n    | \"combinator\"\n    | \"field\"\n    | \"operator\"\n    | \"value\"\n    | \"add\"\n    | \"menu\"\n    | \"ungroup\"\n    | \"remove\"\n    | \"drag\"\n    | null\n  /** Open that segment's popover, not merely focus it. Picking a field commits\n   *  the rule straight away and the chip appears with no condition yet, so the\n   *  operator menu has to open ON THE CHIP without a second click. */\n  autoOpen: boolean\n}\n\n/** An external store, deliberately NOT React state. A roving tabindex\n *  republishes on every arrow key, and `setState` would re-render the whole\n *  bar to move one outline. The SELECTOR hooks below each narrow to one value,\n *  so arrowing across forty chips re-renders two components. `useFilterFocus`\n *  is the exception: it returns the whole snapshot. */\nexport interface FilterFocusStore {\n  subscribe: (onStoreChange: () => void) => () => void\n  getSnapshot: () => FilterFocus\n  /** No-ops when nothing changed. */\n  set: (next: FilterFocus) => void\n}\n\nconst NO_FOCUS: FilterFocus = { id: null, segment: null, autoOpen: false }\n\nexport function createFilterFocusStore(): FilterFocusStore {\n  let snapshot: FilterFocus = NO_FOCUS\n  const listeners = new Set<() => void>()\n\n  return {\n    subscribe(onStoreChange) {\n      listeners.add(onStoreChange)\n      return () => {\n        listeners.delete(onStoreChange)\n      }\n    },\n    // The SAME object until something actually changes, which is what\n    // `useSyncExternalStore` requires to avoid an infinite render loop.\n    getSnapshot() {\n      return snapshot\n    },\n    set(next) {\n      if (\n        next.id === snapshot.id &&\n        next.segment === snapshot.segment &&\n        next.autoOpen === snapshot.autoOpen\n      ) {\n        return\n      }\n      snapshot = next\n      for (const listener of listeners) listener()\n    },\n  }\n}\n\n/** A shared, permanently empty store, so the hook degrades to \"nothing\n *  focused\" outside a `Filters`. Nothing ever writes to it: each root creates\n *  and writes its own. */\nconst FALLBACK_FOCUS_STORE = createFilterFocusStore()\n\nconst FilterFocusContext =\n  React.createContext<FilterFocusStore>(FALLBACK_FOCUS_STORE)\n\n/* -------------------------------------------------------------------------- */\n/*                                 Reordering                                 */\n/* -------------------------------------------------------------------------- */\n\n/** Whether rows may be reordered at all, published once for the subtree. Two\n *  files have to agree about it: the builder gates the grip and Alt+Arrow,\n *  while the row and group menus commit the same mutator by a third route, so\n *  gating only the builder left it off for a pointer and on from a menu. */\nconst FilterReorderContext = React.createContext(false)\n\nexport const FilterReorderProvider = FilterReorderContext.Provider\n\nexport function useFilterReorderable(): boolean {\n  return React.useContext(FilterReorderContext)\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Touched                                  */\n/* -------------------------------------------------------------------------- */\n\n/** Which rules the user has actually edited the VALUE of, which decides WHEN\n *  an error may appear: \"Add filter\" mints a row with no value, so flagging\n *  every invalid row turns the builder red before the user did anything wrong.\n *  An issue is still COLLECTED for every rule - the footer count,\n *  `onQueryChange` and tree validity do not change - and only DRAWN once the\n *  user has committed a value. An external store for the focus store's reason,\n *  keyed by rule id and never pruned: a stale id costs one Set entry, and\n *  reconciling against the query on every commit is hot-path work. */\nexport interface FilterRowStateStore {\n  subscribe: (listener: () => void) => () => void\n  /** Bumped on every write. What a memo depends on, since the Sets are mutable. */\n  version: () => number\n  /** Whether this rule has had a value committed to it by the user. */\n  has: (id: string) => boolean\n  mark: (id: string) => void\n  /** Starts this rule over. Changing a rule's ATTRIBUTE resets its operator\n   *  and its value, so it has to reset this too, or the row stays warned about\n   *  a value that no longer exists on a field the user navigated away from. */\n  unmark: (id: string) => void\n  /** Whether this rule is still being CREATED: minted by Add filter and not\n   *  yet given an attribute. The row enters the query with a guessed field to\n   *  keep the tree valid, so while pending the builder draws only that cell. */\n  isPending: (id: string) => boolean\n  markPending: (id: string) => void\n  /** The attribute was chosen. The rest of the row appears. */\n  resolvePending: (id: string) => void\n  /** Forgets everything. The bar's own Clear all, and a whole-tree replace. */\n  reset: () => void\n}\n\nexport function createFilterRowStateStore(): FilterRowStateStore {\n  const touched = new Set<string>()\n  const pending = new Set<string>()\n  const listeners = new Set<() => void>()\n  let version = 0\n  const notify = () => {\n    version += 1\n    for (const listener of listeners) listener()\n  }\n  return {\n    subscribe: (listener) => {\n      listeners.add(listener)\n      return () => listeners.delete(listener)\n    },\n    version: () => version,\n    has: (id) => touched.has(id),\n    mark: (id) => {\n      if (touched.has(id)) return\n      touched.add(id)\n      notify()\n    },\n    unmark: (id) => {\n      if (!touched.delete(id)) return\n      notify()\n    },\n    isPending: (id) => pending.has(id),\n    markPending: (id) => {\n      if (pending.has(id)) return\n      pending.add(id)\n      notify()\n    },\n    resolvePending: (id) => {\n      if (!pending.delete(id)) return\n      notify()\n    },\n    reset: () => {\n      if (touched.size === 0 && pending.size === 0) return\n      touched.clear()\n      pending.clear()\n      notify()\n    },\n  }\n}\n\nconst FALLBACK_ROW_STATE_STORE = createFilterRowStateStore()\n\nconst FilterRowStateContext = React.createContext<FilterRowStateStore>(\n  FALLBACK_ROW_STATE_STORE\n)\n\nexport const FilterRowStateProvider = FilterRowStateContext.Provider\n\n/** The store itself, for handlers that write without subscribing. */\nexport function useFilterRowStateStore(): FilterRowStateStore {\n  return React.useContext(FilterRowStateContext)\n}\n\n/** Whether THIS rule is still waiting for its attribute. */\nexport function useFilterRowPending(id: string): boolean {\n  const store = React.useContext(FilterRowStateContext)\n  return React.useSyncExternalStore(\n    store.subscribe,\n    () => store.isPending(id),\n    () => false\n  )\n}\n\n/** Whether THIS rule may show an error yet. */\nexport function useFilterTouched(id: string): boolean {\n  const store = React.useContext(FilterRowStateContext)\n  return React.useSyncExternalStore(\n    store.subscribe,\n    () => store.has(id),\n    () => false\n  )\n}\n\n/** The whole focus snapshot, so the caller re-renders on EVERY move anywhere\n *  in the row. A chip wants `useFilterChipFocused` or `useFilterSegmentFocus`\n *  below instead. */\nexport function useFilterFocus(): FilterFocus {\n  const store = React.useContext(FilterFocusContext)\n  return React.useSyncExternalStore(\n    store.subscribe,\n    store.getSnapshot,\n    store.getSnapshot\n  )\n}\n\n/** The store itself, for event handlers that write without subscribing. */\nexport function useFilterFocusStore(): FilterFocusStore {\n  return React.useContext(FilterFocusContext)\n}\n\n/** The segment of THIS chip that should open itself, or null. */\nexport function useFilterChipAutoOpen(\n  id: string\n): FilterFocus[\"segment\"] | null {\n  const store = React.useContext(FilterFocusContext)\n  return React.useSyncExternalStore(\n    store.subscribe,\n    () => {\n      const snapshot = store.getSnapshot()\n      return snapshot.autoOpen && snapshot.id === id ? snapshot.segment : null\n    },\n    () => null\n  )\n}\n\n/** Whether the row holds no focus, so the first chip keeps the tab stop. */\nexport function useFilterFocusEmpty(): boolean {\n  const store = React.useContext(FilterFocusContext)\n  return React.useSyncExternalStore(\n    store.subscribe,\n    () => store.getSnapshot().id === null,\n    () => true\n  )\n}\n\n/** Whether THIS chip owns the row's tab stop. */\nexport function useFilterChipFocused(id: string): boolean {\n  const store = React.useContext(FilterFocusContext)\n  return React.useSyncExternalStore(\n    store.subscribe,\n    () => store.getSnapshot().id === id,\n    () => false\n  )\n}\n\n/** Which segment of THIS rule owns the tab stop, or null when another rule\n *  does. A chip needs one boolean, but an advanced row is a grid ROW whose tab\n *  stop is a (row, column) pair, and the column has to come from this store\n *  too or the chromes disagree about where focus is after an edit. */\nexport function useFilterSegmentFocus(id: string): FilterFocus[\"segment\"] {\n  const store = React.useContext(FilterFocusContext)\n  return React.useSyncExternalStore(\n    store.subscribe,\n    () => {\n      const snapshot = store.getSnapshot()\n      return snapshot.id === id ? snapshot.segment : null\n    },\n    () => null\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                              Resolution store                              */\n/* -------------------------------------------------------------------------- */\n\n/** The instance-wide value-to-label store. `useFilterOptions` caches per HOOK\n *  INSTANCE, and a chip's display and its editor are two instances, so a\n *  `loadOptions`-only field rendered its raw id the moment the menu closed.\n *  Every instance under one root writes here, and `resolveValues` results land\n *  here too. External rather than React state because labels arrive from\n *  effects and promises at their own pace, and the version bumps only when a\n *  NEW label lands, so a subscriber re-renders once per page of results. */\nexport interface FilterResolutionStore {\n  subscribe: (onStoreChange: () => void) => () => void\n  getVersion: () => number\n  /** The option behind a stored value, or undefined while unresolved. */\n  get: (fieldKey: string, value: string) => FilterOption | undefined\n  /** Records options under a field key. New values bump the version. */\n  set: (fieldKey: string, options: readonly FilterOption[]) => void\n  /** Marks values as resolving and returns the subset nobody has claimed yet,\n   *  so two chips holding the same id issue ONE request. Claims are permanent\n   *  for values a fulfilled resolve did not return, which stops an id the\n   *  server does not know from being re-asked forever. */\n  claim: (fieldKey: string, values: readonly string[]) => string[]\n  /** Releases claims after a FAILED resolve, so a later mount may retry. */\n  release: (fieldKey: string, values: readonly string[]) => void\n}\n\nexport function createFilterResolutionStore(): FilterResolutionStore {\n  const resolved = new Map<string, Map<string, FilterOption>>()\n  const claimed = new Map<string, Set<string>>()\n  const listeners = new Set<() => void>()\n  let version = 0\n\n  const bucket = (fieldKey: string) => {\n    let map = resolved.get(fieldKey)\n    if (!map) {\n      map = new Map()\n      resolved.set(fieldKey, map)\n    }\n    return map\n  }\n\n  return {\n    subscribe(onStoreChange) {\n      listeners.add(onStoreChange)\n      return () => {\n        listeners.delete(onStoreChange)\n      }\n    },\n    getVersion() {\n      return version\n    },\n    get(fieldKey, value) {\n      return resolved.get(fieldKey)?.get(value)\n    },\n    set(fieldKey, options) {\n      const map = bucket(fieldKey)\n      let landed = false\n      for (const option of options) {\n        if (!map.has(option.value)) landed = true\n        map.set(option.value, option)\n      }\n      if (!landed) return\n      version += 1\n      for (const listener of listeners) listener()\n    },\n    claim(fieldKey, values) {\n      let set = claimed.get(fieldKey)\n      if (!set) {\n        set = new Set()\n        claimed.set(fieldKey, set)\n      }\n      const map = resolved.get(fieldKey)\n      const fresh: string[] = []\n      for (const value of values) {\n        if (set.has(value) || map?.has(value)) continue\n        set.add(value)\n        fresh.push(value)\n      }\n      return fresh\n    },\n    release(fieldKey, values) {\n      const set = claimed.get(fieldKey)\n      if (!set) return\n      for (const value of values) set.delete(value)\n    },\n  }\n}\n\nexport {\n  FilterActionsContext,\n  FilterFocusContext,\n  FilterRenderContext,\n  FilterStateContext,\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-context.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-date.tsx",
      "content": "/**\n * filters-date - adapted for tealmac UI from ReUI \"filters/filters-date\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\nimport {\n  addDays,\n  addMonths,\n  addWeeks,\n  addYears,\n  format,\n  isValid,\n  parse,\n  startOfDay,\n} from \"date-fns\"\n\n/**\n * A date filter value. NOT a `Date`: a filter gets persisted (saved views,\n * shared URLs), and a resolved `Date` would freeze \"created today\" into one\n * fixed day. An absolute pick still stores one day, because \"on 14 August\"\n * does mean that day.\n */\nexport interface FilterDateValue {\n  /** An absolute day, `yyyy-MM-dd`. Mutually exclusive with `relative`. */\n  date?: string\n  /** A token re-resolved on every read. */\n  relative?: FilterRelativeDate\n  /** Optional time of day, `HH:mm`. */\n  time?: string\n}\n\n/** A calendar offset from now, resolved at read time. */\nexport interface FilterRelativeDate {\n  unit: \"day\" | \"week\" | \"month\" | \"year\"\n  offset: number\n}\n\nexport const FILTER_DATE_FORMAT = \"yyyy-MM-dd\"\n\nexport const RELATIVE_TODAY: FilterRelativeDate = { unit: \"day\", offset: 0 }\nexport const RELATIVE_TOMORROW: FilterRelativeDate = { unit: \"day\", offset: 1 }\nexport const RELATIVE_YESTERDAY: FilterRelativeDate = {\n  unit: \"day\",\n  offset: -1,\n}\nexport const RELATIVE_NEXT_WEEK: FilterRelativeDate = {\n  unit: \"week\",\n  offset: 1,\n}\n\nexport function applyFilterRelative(\n  relative: FilterRelativeDate,\n  now: Date\n): Date {\n  const base = startOfDay(now)\n  if (relative.unit === \"day\") return addDays(base, relative.offset)\n  if (relative.unit === \"week\") return addWeeks(base, relative.offset)\n  if (relative.unit === \"month\") return addMonths(base, relative.offset)\n  return addYears(base, relative.offset)\n}\n\nexport function resolveFilterDate(\n  value: FilterDateValue | undefined,\n  now: Date = new Date()\n): Date | null {\n  if (!value) return null\n  if (value.relative) return applyFilterRelative(value.relative, now)\n  if (value.date) {\n    const parsed = parse(value.date, FILTER_DATE_FORMAT, now)\n    return isValid(parsed) ? parsed : null\n  }\n  return null\n}\n\nexport function toFilterDateValue(date: Date, time?: string): FilterDateValue {\n  const value: FilterDateValue = { date: format(date, FILTER_DATE_FORMAT) }\n  if (time) value.time = time\n  return value\n}\n\n// ----- natural language input -----\n\nconst WEEKDAYS = [\n  \"sunday\",\n  \"monday\",\n  \"tuesday\",\n  \"wednesday\",\n  \"thursday\",\n  \"friday\",\n  \"saturday\",\n]\n\n/**\n * Typed formats, most specific first. `date-selector.tsx` overlaps on a few\n * of these, but its parser is a callback inside the component returning a\n * `DateSelectorValue`, so there is nothing importable.\n */\nconst EXPLICIT_FORMATS = [\n  \"yyyy-MM-dd\",\n  \"MM/dd/yyyy\",\n  \"M/d/yyyy\",\n  \"dd/MM/yyyy\",\n  \"MMMM d, yyyy\",\n  \"MMM d, yyyy\",\n  \"MMMM d\",\n  \"MMM d\",\n  \"d MMMM yyyy\",\n  \"d MMM yyyy\",\n]\n\n/**\n * Parses a typed phrase, or null when nothing matches. Relative phrasing gives\n * a RELATIVE value and an explicit date an ABSOLUTE one; flattening the two is\n * what freezes a saved view.\n */\nexport function parseFilterDate(\n  text: string,\n  now: Date = new Date()\n): FilterDateValue | null {\n  const input = text.trim().toLowerCase().replace(/\\s+/g, \" \")\n  if (!input) return null\n\n  if (input === \"today\" || input === \"now\") return { relative: RELATIVE_TODAY }\n  if (input === \"tomorrow\") return { relative: RELATIVE_TOMORROW }\n  if (input === \"yesterday\") return { relative: RELATIVE_YESTERDAY }\n\n  const nextLast = input.match(/^(next|last|this) (day|week|month|year)$/)\n  if (nextLast) {\n    const direction =\n      nextLast[1] === \"next\" ? 1 : nextLast[1] === \"last\" ? -1 : 0\n    return {\n      relative: {\n        unit: nextLast[2] as FilterRelativeDate[\"unit\"],\n        offset: direction,\n      },\n    }\n  }\n\n  // \"in 3 days\" / \"3 days ago\" / \"in 2 weeks\"\n  const counted = input.match(\n    /^(?:in )?(\\d+) (day|week|month|year)s?(?: ago)?$/\n  )\n  if (counted) {\n    const magnitude = Number.parseInt(counted[1], 10)\n    const past = input.endsWith(\"ago\")\n    return {\n      relative: {\n        unit: counted[2] as FilterRelativeDate[\"unit\"],\n        offset: past ? -magnitude : magnitude,\n      },\n    }\n  }\n\n  // \"next tuesday\" / \"last friday\" / bare \"tuesday\"\n  const weekday = input.match(/^(?:(next|last|this) )?([a-z]+)$/)\n  if (weekday) {\n    const index = WEEKDAYS.indexOf(weekday[2])\n    if (index !== -1) {\n      const today = startOfDay(now)\n      const current = today.getDay()\n      let delta = index - current\n      const qualifier = weekday[1]\n\n      if (qualifier === \"last\") {\n        // Always strictly in the past.\n        if (delta >= 0) delta -= 7\n      } else {\n        // \"next\"/\"this\" and a bare weekday all mean the NEXT one, not today.\n        if (delta <= 0) delta += 7\n      }\n\n      return { relative: { unit: \"day\", offset: delta } }\n    }\n  }\n\n  for (const pattern of EXPLICIT_FORMATS) {\n    const parsed = parse(input, pattern, now)\n    if (isValid(parsed)) {\n      // \"Aug 14\" has no year, so it takes the reference year.\n      return toFilterDateValue(parsed)\n    }\n  }\n\n  return null\n}\n\n/**\n * Human wording for a value. Relative values render as their phrase, not the\n * resolved day, so a chip reading \"is today\" does not go stale tomorrow.\n */\nexport function formatFilterDate(\n  value: FilterDateValue | undefined,\n  now: Date = new Date(),\n  pattern = \"MMM d, yyyy\"\n): string {\n  if (!value) return \"\"\n\n  if (value.relative) {\n    const { unit, offset } = value.relative\n    if (unit === \"day\" && offset === 0) return \"today\"\n    if (unit === \"day\" && offset === 1) return \"tomorrow\"\n    if (unit === \"day\" && offset === -1) return \"yesterday\"\n\n    const plural = Math.abs(offset) === 1 ? unit : `${unit}s`\n    if (offset > 0) return `in ${offset} ${plural}`\n    if (offset < 0) return `${Math.abs(offset)} ${plural} ago`\n    return `this ${unit}`\n  }\n\n  const resolved = resolveFilterDate(value, now)\n  if (!resolved) return \"\"\n  const day = format(resolved, pattern)\n  return value.time ? `${day} ${value.time}` : day\n}\n\nexport function isFilterTime(time: string): boolean {\n  return /^([01]\\d|2[0-3]):[0-5]\\d$/.test(time)\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-date.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-dnd.tsx",
      "content": "/**\n * filters-dnd - adapted for tealmac UI from ReUI \"filters/filters-dnd\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n\"use client\"\n\n// Title: Filters Dnd\n// Description: Pointer-based drag layer for the advanced condition builder - a carry clone that follows the pointer, drop indicators between rows and into groups, and Alt to copy.\nimport * as React from \"react\"\n\n/**\n * Gesture model copied from `event-calendar-dnd.tsx`, deliberately not\n * imported: filters installs on its own and must not pull a whole calendar into\n * `shadcn add filters`. Vanilla-DOM overlay, so a drag renders no React.\n */\nexport const FILTER_DND_ACTIVATION = {\n  /** Mouse travel before a press becomes a drag. Below this it stays a click. */\n  moveDistancePx: 5,\n  /** Touch long-press before a drag starts, so a swipe still scrolls. */\n  touchDelayMs: 250,\n  touchTolerancePx: 5,\n  autoScrollEdgePx: 40,\n  autoScrollMaxStepPx: 12,\n  /** A seed only: `createCarry` measures the real grab offset before paint. */\n  carryPointerOffsetPx: 12,\n} as const\n\n/** One rule row, or one group's header row. Both are drag sources and targets. */\nexport const FILTER_ROW_SELECTOR = '[data-slot=\"filter-row\"]'\n\n/** Explicit \"drop INSIDE\": a row hit test can only ever say \"beside\". */\nexport const FILTER_DROP_ZONE_SELECTOR = \"[data-drop-parent]\"\n\n/** Marked alongside the zone, so lighting the group costs no `:has()`. */\nexport const FILTER_GROUP_SELECTOR = '[data-slot=\"filter-group\"]'\n\n/** Geometry only, so resolution is a pure function and a table test. */\nexport interface FilterDropBox {\n  top: number\n  bottom: number\n  left: number\n  right: number\n  /** The group the drop writes into. */\n  parentId: string\n  /** Where in that group's children the node lands, not a slot in this list. */\n  index: number\n  /** How many rows enclose this box. Deeper wins. */\n  depth: number\n}\n\nexport interface FilterDropResolution<T extends FilterDropBox> {\n  target: T\n  /** Null for a zone: INTO the group rather than beside anything. */\n  edge: \"before\" | \"after\" | null\n}\n\nfunction contains(box: FilterDropBox, x: number, y: number, grow = 0): boolean {\n  return (\n    x >= box.left &&\n    x <= box.right &&\n    y >= box.top - grow &&\n    y <= box.bottom + grow\n  )\n}\n\n/**\n * How far a ROW reaches past its own rect when hit tested: HALF the sibling\n * gap, which is `gap-3`, so six. `FILTER_ROW_GAP_CLASS` is the other half of\n * one measurement; this moves whenever that does.\n *\n * The seam between adjacent rows is inside NEITHER rect, so a pointer aimed\n * between two rows fell through to whatever did enclose it: at the top level\n * nothing did, so the cursor said `no-drop`; one level in it was the group.\n * Half the gap makes siblings tile, and the depth sort keeps the child ahead of\n * that group. Rows only: zones are explicit strips.\n */\nexport const FILTER_ROW_SEAM_PX = 6\n\n/**\n * Zones before rows, then the DEEPEST box: a group's rect encloses everything\n * it holds, so a nested condition would otherwise resolve to its whole group.\n * `seam` is a parameter, not the constant inlined, so the tiling rule itself is\n * a table test.\n */\nexport function resolveFilterDrop<T extends FilterDropBox>(\n  zones: T[],\n  rows: T[],\n  x: number,\n  y: number,\n  seam: number = FILTER_ROW_SEAM_PX\n): FilterDropResolution<T> | null {\n  let zone: T | null = null\n  for (const candidate of zones) {\n    if (!contains(candidate, x, y)) continue\n    if (!zone || candidate.depth > zone.depth) zone = candidate\n  }\n  if (zone) return { target: zone, edge: null }\n\n  let row: T | null = null\n  for (const candidate of rows) {\n    if (!contains(candidate, x, y, seam)) continue\n    if (!row || candidate.depth > row.depth) row = candidate\n  }\n  if (!row) return null\n\n  // The midpoint, not the nearest edge: a row is the width of the panel, so a\n  // proximity test would leave the indicator undecided across most of one.\n  const after = y > row.top + (row.bottom - row.top) / 2\n  return {\n    target: { ...row, index: row.index + (after ? 1 : 0) },\n    edge: after ? \"after\" : \"before\",\n  }\n}\n\n/** Where a dragged node started, which is what makes a drop a no-op or not. */\nexport interface FilterDropOrigin {\n  parentId: string\n  index: number\n}\n\n/**\n * Both indices name the slot the node already occupies, because\n * `moveFilterNodeTo` closes the gap the detach leaves. Copy is never a no-op.\n */\nexport function isFilterDropNoop(\n  resolution: FilterDropResolution<FilterDropBox> | null,\n  origin: FilterDropOrigin | null,\n  copy: boolean\n): boolean {\n  if (!resolution || !origin || copy) return false\n  if (resolution.target.parentId !== origin.parentId) return false\n  return (\n    resolution.target.index === origin.index ||\n    resolution.target.index === origin.index + 1\n  )\n}\n\n/** Rows unmount mid-gesture, so it is the PANEL leaving that aborts a drag. */\nconst activeCancels = new Set<() => void>()\n\n/** Cancel and fully revert every in-flight filter row drag. */\nexport function cancelActiveFilterDrags(): void {\n  for (const cancel of [...activeCancels]) cancel()\n}\n\nlet lastDragEndedAt = 0\n\n/**\n * Whether a drag ended within the last few frames. Exported: a consumer's own\n * row click handler needs the same answer the suppressor below needs.\n */\nexport function wasRecentFilterDrag(): boolean {\n  return performance.now() - lastDragEndedAt < 250\n}\n\n/**\n * NOT `{ once: true }` alone: a drag that ends over a different element fires\n * no click at all, and a stale arming would eat the user's next click. The\n * timestamp is what makes that stale arming harmless.\n */\nfunction suppressTrailingClick(event: MouseEvent) {\n  window.removeEventListener(\"click\", suppressTrailingClick, true)\n  if (!wasRecentFilterDrag()) return\n  event.stopPropagation()\n  event.preventDefault()\n}\n\n/** The carry is a compositing layer: a subpixel translate blurs its text. */\nfunction snapToPixel(value: number): number {\n  const dpr = typeof window !== \"undefined\" ? window.devicePixelRatio || 1 : 1\n  return Math.round(value * dpr) / dpr\n}\n\n/**\n * `card` is a ZONE's group, resolved once rather than walked per frame. Null on\n * a row, which stands for itself.\n */\ntype MeasuredBox = FilterDropBox & {\n  el: HTMLElement\n  card: HTMLElement | null\n}\n\ninterface Surface {\n  zones: MeasuredBox[]\n  rows: MeasuredBox[]\n  /**\n   * Rects are captured ONCE, so one subtraction against this scrollTop corrects\n   * for scrolling instead of a per-move `getBoundingClientRect`. THE ELEMENT,\n   * NOT A MIRRORED NUMBER: a mirror tracks only this engine's own scrolling, so\n   * a wheel mid-gesture left the rects stale while the correction read zero,\n   * painting the indicator 60px off the pointer.\n   */\n  viewport: HTMLElement | null\n  viewportRect: DOMRect | null\n  /** The one number kept: where the rects were taken, which cannot change. */\n  startScrollTop: number\n}\n\n/**\n * The nearest scroller, THIS ONE INCLUDED: the panel is exactly what a consumer\n * caps with `overflow-y: auto`, and a walk from the parent answered null for it.\n */\nfunction findScrollParent(el: HTMLElement | null): HTMLElement | null {\n  let node = el ?? null\n  while (node) {\n    const style = getComputedStyle(node)\n    const overflow = `${style.overflowY} ${style.overflow}`\n    if (\n      /(auto|scroll|overlay)/.test(overflow) &&\n      node.scrollHeight > node.clientHeight\n    ) {\n      return node\n    }\n    node = node.parentElement\n  }\n  return null\n}\n\nfunction rowDepth(el: HTMLElement, root: HTMLElement): number {\n  let depth = 0\n  let node = el.parentElement\n  while (node && node !== root) {\n    if (node.matches(FILTER_ROW_SELECTOR)) depth++\n    node = node.parentElement\n  }\n  return depth\n}\n\n/**\n * Measured once. DESCENDANTS of the dragged node are excluded rather than\n * refused later: an indicator the drop ignores is a broken promise. The dragged\n * row ITSELF is kept, so its own slot reads as a no-op, not as a hole.\n */\nfunction collectSurface(root: HTMLElement, dragged: HTMLElement): Surface {\n  const zones: MeasuredBox[] = []\n  const rows: MeasuredBox[] = []\n\n  for (const el of root.querySelectorAll<HTMLElement>(\n    FILTER_DROP_ZONE_SELECTOR\n  )) {\n    if (dragged.contains(el)) continue\n    const parentId = el.dataset.dropParent\n    if (!parentId) continue\n    const rect = el.getBoundingClientRect()\n    zones.push({\n      el,\n      card: el.closest<HTMLElement>(FILTER_GROUP_SELECTOR),\n      top: rect.top,\n      bottom: rect.bottom,\n      left: rect.left,\n      right: rect.right,\n      parentId,\n      index: Number(el.dataset.dropIndex ?? 0),\n      depth: rowDepth(el, root),\n    })\n  }\n\n  for (const el of root.querySelectorAll<HTMLElement>(FILTER_ROW_SELECTOR)) {\n    if (el !== dragged && dragged.contains(el)) continue\n    const parentId = el.dataset.parentId\n    if (!parentId) continue\n    const rect = el.getBoundingClientRect()\n    rows.push({\n      el,\n      card: null,\n      top: rect.top,\n      bottom: rect.bottom,\n      left: rect.left,\n      right: rect.right,\n      parentId,\n      index: Number(el.dataset.index ?? 0),\n      depth: rowDepth(el, root),\n    })\n  }\n\n  const viewport = findScrollParent(root)\n  return {\n    zones,\n    rows,\n    viewport,\n    viewportRect: viewport?.getBoundingClientRect() ?? null,\n    startScrollTop: viewport?.scrollTop ?? 0,\n  }\n}\n\nexport interface FilterDropDetails {\n  parentId: string\n  index: number\n  /** Alt was held at release: copy the node rather than moving it. */\n  copy: boolean\n}\n\nexport interface FilterRowDragOptions {\n  /** The PANEL, not its body: the top-level append zone is in the footer. */\n  root: () => HTMLElement | null\n  onDrop: (nodeId: string, details: FilterDropDetails) => void\n  disabled?: boolean\n}\n\n/**\n * Straight to the DOM: a React state write per move is a tree render. A zone\n * marks TWO elements, itself and its card, and both clear every frame.\n */\nfunction paint(\n  surface: Surface,\n  hit: FilterDropResolution<MeasuredBox> | null\n) {\n  for (const box of surface.zones) {\n    delete box.el.dataset.dropInto\n    if (box.card) delete box.card.dataset.dropInto\n  }\n  for (const box of surface.rows) delete box.el.dataset.dropEdge\n  if (!hit) return\n  if (hit.edge) {\n    hit.target.el.dataset.dropEdge = hit.edge\n    return\n  }\n  hit.target.el.dataset.dropInto = \"\"\n  if (hit.target.card) hit.target.card.dataset.dropInto = \"\"\n}\n\nfunction startDrag(\n  event: React.PointerEvent<HTMLElement>,\n  nodeId: string,\n  options: FilterRowDragOptions\n) {\n  const handle = event.currentTarget\n  const root = options.root()\n  const source = handle.closest<HTMLElement>(FILTER_ROW_SELECTOR)\n  if (!root || !source) return\n\n  const pointerId = event.pointerId\n  const isTouch = event.pointerType === \"touch\"\n  const startX = event.clientX\n  const startY = event.clientY\n\n  // Off the row's own attributes, which it already publishes for the hit test.\n  // Asking the panel would mean threading a position through the drag context.\n  const origin: FilterDropOrigin | null = source.dataset.parentId\n    ? {\n        parentId: source.dataset.parentId,\n        index: Number(source.dataset.index ?? 0),\n      }\n    : null\n\n  let active = false\n  let finished = false\n  let surface: Surface | null = null\n  let hit: FilterDropResolution<MeasuredBox> | null = null\n  let copy = event.altKey\n  let lastEvent: PointerEvent | null = null\n  let touchTimer: ReturnType<typeof setTimeout> | null = null\n  let rafScroll = 0\n\n  // Three states, not a boolean: `\"ok\"` lands somewhere new, `\"noop\"` puts the\n  // node back where it came from, `\"none\"` is over nothing at all.\n  let dropState: \"ok\" | \"noop\" | \"none\" = \"none\"\n\n  let carryEl: HTMLDivElement | null = null\n  let badgeEl: HTMLSpanElement | null = null\n  // Where inside the row the pointer went down, so the copy holds that spot.\n  // Measured in `createCarry`, which runs before anything reads these.\n  let grabOffsetX = FILTER_DND_ACTIVATION.carryPointerOffsetPx\n  let grabOffsetY = FILTER_DND_ACTIVATION.carryPointerOffsetPx\n\n  const createCarry = () => {\n    const rect = source.getBoundingClientRect()\n    grabOffsetX = startX - rect.left\n    grabOffsetY = startY - rect.top\n\n    carryEl = document.createElement(\"div\")\n    carryEl.setAttribute(\"data-slot\", \"filters-drag-carry\")\n    carryEl.setAttribute(\"aria-hidden\", \"true\")\n    // `data-drop-invalid` rather than a toggled class name, so the style stays\n    // one static string Tailwind can see at build time.\n    //\n    // Muted and translucent, no border or shadow: the clone carries the row's\n    // own controls, and a box around them read as a card leaving the page. Only\n    // the invalid state marks the clone, since nothing else says the drop is\n    // dead, and it RINGS rather than going dashed: dashed is this builder's\n    // word for \"a row can land here\", and the clone is not one.\n    carryEl.className =\n      \"pointer-events-none fixed \" +\n      \"top-0 left-0 z-100 \" +\n      \"opacity-95 will-change-transform \" +\n      \"data-drop-invalid:ring-destructive/70 data-drop-invalid:ring-2 \" +\n      \"data-drop-invalid:opacity-60\"\n    // A bare anchor: the clip box below owns the size, and no overflow lets the\n    // badge overhang.\n    carryEl.style.position = \"fixed\"\n\n    const clone = source.cloneNode(true) as HTMLElement\n    // The source is faded while in flight; its copy must not inherit that.\n    delete clone.dataset.dragging\n    delete clone.dataset.dropNoop\n    delete clone.dataset.dropEdge\n    if (rect.width > 0) clone.style.width = `${rect.width}px`\n\n    /*\n      SANITIZED, because the clone lives on `<body>`: two elements would claim\n      one node id, `aria-hidden` leaves real buttons in the tab order and must\n      never wrap a focused one, and cloned ids make a `for` resolve to a copy.\n    */\n    const strip = (el: HTMLElement) => {\n      el.removeAttribute(\"id\")\n      el.removeAttribute(\"data-node-id\")\n      el.removeAttribute(\"data-filter-cell\")\n      if (el.dataset.slot === \"filter-row\") el.removeAttribute(\"data-slot\")\n      // `-1` rather than removed: the attribute is also how the roving scheme\n      // marks its cells, and a row copied mid-gesture has one cell at `0`.\n      el.setAttribute(\"tabindex\", \"-1\")\n    }\n    strip(clone)\n    for (const el of clone.querySelectorAll<HTMLElement>(\"*\")) strip(el)\n\n    /*\n      The CLIPPING box is the inner one: the carry is the badge's containing\n      block, so `overflow-hidden` there clipped the badge that overhangs it.\n    */\n    const clip = document.createElement(\"div\")\n    clip.className = \"bg-background overflow-hidden rounded-md\"\n    // Sized only when the rect is real: a document that is not being laid out\n    // measures zero, and a copy pinned to `0px` is invisible.\n    if (rect.width > 0) clip.style.width = `${rect.width}px`\n    if (rect.height > 0) clip.style.height = `${rect.height}px`\n    clip.appendChild(clone)\n    carryEl.appendChild(clip)\n\n    badgeEl = document.createElement(\"span\")\n    badgeEl.setAttribute(\"data-slot\", \"filters-drag-copy\")\n    badgeEl.className =\n      \"bg-primary text-primary-foreground absolute -end-1.5 -top-1.5 flex \" +\n      \"size-4 items-center justify-center rounded-full text-[10px] leading-none\"\n    badgeEl.textContent = \"+\"\n    // Legible BEFORE the release, or Alt is discoverable only by error.\n    badgeEl.hidden = !copy\n    carryEl.appendChild(badgeEl)\n\n    // <body>, not the panel: a transform or a `content-visibility` on a wrapper\n    // becomes the containing block for `position: fixed`, and the clone jumps.\n    document.body.appendChild(carryEl)\n    positionCarry(startX, startY)\n  }\n\n  const positionCarry = (x: number, y: number) => {\n    if (!carryEl) return\n    // THE GRAB OFFSET, not a fixed nudge: the grip sits at the row's trailing\n    // edge, so anchoring at the pointer hung the copy a row's width away.\n    carryEl.style.transform = `translate3d(${snapToPixel(x - grabOffsetX)}px, ${snapToPixel(y - grabOffsetY)}px, 0)`\n  }\n\n  // Two things decide the cursor and the RESOLUTION outranks Alt, which is why\n  // `none` is tested first: `copy` over nothing is still nothing.\n  const paintCursor = () => {\n    if (!active) return\n    document.body.style.cursor =\n      dropState === \"none\" ? \"no-drop\" : copy ? \"copy\" : \"grabbing\"\n  }\n\n  // Deliberately NOT guarded on `dropState === next`: the first resolution of a\n  // gesture is routinely `\"none\"`, which is also the initial value, so a guard\n  // left the first frame of a drag onto nothing wearing no mark at all.\n  const setDropState = (next: typeof dropState) => {\n    dropState = next\n    // On the SOURCE: \"it stays here\" is a statement about the row carried.\n    if (next === \"noop\") source.dataset.dropNoop = \"\"\n    else delete source.dataset.dropNoop\n    // And on the CARRY: over nothing there is no target left to mark.\n    if (carryEl) {\n      if (next === \"none\") carryEl.dataset.dropInvalid = \"\"\n      else delete carryEl.dataset.dropInvalid\n    }\n    paintCursor()\n  }\n\n  const setCopy = (next: boolean) => {\n    if (copy === next) return\n    copy = next\n    if (badgeEl) badgeEl.hidden = !next\n    paintCursor()\n    // Alt changes the ANSWER, not just the cursor: a release beside yourself is\n    // a no-op while moving and a duplicate in place while copying.\n    if (lastEvent) hitTest(lastEvent.clientX, lastEvent.clientY)\n  }\n\n  const hitTest = (x: number, y: number) => {\n    if (!surface) return\n    // One subtraction instead of a re-measure. Read off the ELEMENT every time:\n    // see `Surface.viewport`, a mirror misses the user's own scroll.\n    const scrolled = surface.viewport?.scrollTop ?? surface.startScrollTop\n    const drift = scrolled - surface.startScrollTop\n    const resolved = resolveFilterDrop(\n      surface.zones,\n      surface.rows,\n      x,\n      y + drift\n    )\n    const noop = isFilterDropNoop(resolved, origin, copy)\n    // A no-op commits as NOTHING, not as a move the tree would discard.\n    hit = noop ? null : resolved\n    paint(surface, hit)\n    setDropState(noop ? \"noop\" : hit ? \"ok\" : \"none\")\n  }\n\n  const autoScroll = (y: number) => {\n    if (rafScroll) cancelAnimationFrame(rafScroll)\n    rafScroll = 0\n    const viewport = surface?.viewport\n    const rect = surface?.viewportRect\n    if (!viewport || !rect) return\n\n    const edge = FILTER_DND_ACTIVATION.autoScrollEdgePx\n    const step = FILTER_DND_ACTIVATION.autoScrollMaxStepPx\n    let delta = 0\n    if (y >= rect.top && y < rect.top + edge) {\n      delta = -step * ((rect.top + edge - y) / edge)\n    } else if (y <= rect.bottom && y > rect.bottom - edge) {\n      delta = step * Math.min(1, (y - (rect.bottom - edge)) / edge)\n    }\n    if (delta === 0) return\n\n    const tick = () => {\n      // The read-back STOPS the loop: the browser clamps at the scroll extent,\n      // so a panel at its limit would keep asking for unusable frames.\n      const before = viewport.scrollTop\n      viewport.scrollTop = before + delta\n      if (viewport.scrollTop === before) return\n      if (lastEvent) hitTest(lastEvent.clientX, lastEvent.clientY)\n      rafScroll = requestAnimationFrame(tick)\n    }\n    rafScroll = requestAnimationFrame(tick)\n  }\n\n  /**\n   * A still pointer fires no `pointermove`, so a wheel mid-drag would leave the\n   * last answer painted while the rows slid out from under it. The overlap\n   * with the autoScroll tick is deliberate: this is arithmetic over boxes\n   * already measured, and one redundant pass per frame is cheaper than a rule\n   * about who owns the repaint.\n   */\n  const onViewportScroll = () => {\n    if (!active || !lastEvent) return\n    hitTest(lastEvent.clientX, lastEvent.clientY)\n  }\n\n  const activate = () => {\n    if (active) return\n    active = true\n    surface = collectSurface(root, source)\n\n    // Passive: nothing here calls `preventDefault`, and a non-passive listener\n    // on a scroller is a frame of jank per notch.\n    surface.viewport?.addEventListener(\"scroll\", onViewportScroll, {\n      passive: true,\n    })\n    source.dataset.dragging = \"\"\n    document.body.style.cursor = copy ? \"copy\" : \"grabbing\"\n    document.body.style.userSelect = \"none\"\n    createCarry()\n    // Armed with the GESTURE, not the press: a press that never travels far\n    // enough strands no overlay, no body style and no listener.\n    window.addEventListener(\"blur\", onWindowBlur)\n  }\n\n  // Idempotent. pointerup, pointercancel, Escape, window blur and the panel's\n  // own teardown can all race; whichever lands first wins and the rest no-op.\n  const cleanup = () => {\n    if (finished) return\n    finished = true\n    activeCancels.delete(cancel)\n    window.removeEventListener(\"pointermove\", onPointerMove)\n    window.removeEventListener(\"pointerup\", onPointerUp)\n    window.removeEventListener(\"pointercancel\", onPointerCancel)\n    window.removeEventListener(\"keydown\", onKeyDown, true)\n    window.removeEventListener(\"keyup\", onKeyUp, true)\n    window.removeEventListener(\"blur\", onWindowBlur)\n    surface?.viewport?.removeEventListener(\"scroll\", onViewportScroll)\n    if (touchTimer) clearTimeout(touchTimer)\n    if (rafScroll) cancelAnimationFrame(rafScroll)\n    if (surface) paint(surface, null)\n    delete source.dataset.dragging\n    delete source.dataset.dropNoop\n    carryEl?.remove()\n    carryEl = null\n    badgeEl = null\n    document.body.style.cursor = \"\"\n    document.body.style.userSelect = \"\"\n  }\n\n  /** A bare teardown: nothing is committed until release, so no snapshot. */\n  const cancel = () => {\n    if (active) lastDragEndedAt = performance.now()\n    cleanup()\n  }\n\n  const onWindowBlur = () => cancel()\n\n  const onKeyDown = (e: KeyboardEvent) => {\n    if (e.key === \"Escape\" && active) {\n      // Stopped, or the popover the builder may be living in closes underneath\n      // the gesture and takes the panel the drop was aimed at with it.\n      e.stopPropagation()\n      e.preventDefault()\n      cancel()\n      return\n    }\n    if (e.key === \"Alt\") setCopy(true)\n  }\n\n  // Alt tracked on its own keys too: reaching for the modifier without moving\n  // the mouse fires no pointermove, and the badge has to appear regardless.\n  const onKeyUp = (e: KeyboardEvent) => {\n    if (e.key === \"Alt\") setCopy(false)\n  }\n\n  const onPointerMove = (e: PointerEvent) => {\n    // A second finger must not drive or cancel the gesture this one started.\n    if (e.pointerId !== pointerId) return\n    lastEvent = e\n\n    if (!active) {\n      const distance = Math.hypot(e.clientX - startX, e.clientY - startY)\n      if (isTouch) {\n        // Past the tolerance the user is scrolling, so the press stays a scroll.\n        if (distance > FILTER_DND_ACTIVATION.touchTolerancePx) cancel()\n        return\n      }\n      if (distance < FILTER_DND_ACTIVATION.moveDistancePx) return\n      activate()\n    }\n\n    setCopy(e.altKey)\n    positionCarry(e.clientX, e.clientY)\n    hitTest(e.clientX, e.clientY)\n    autoScroll(e.clientY)\n  }\n\n  const onPointerUp = (e: PointerEvent) => {\n    if (e.pointerId !== pointerId) return\n    const landed = active ? hit : null\n    const wasCopy = copy\n    cleanup()\n    if (!active) return\n\n    lastDragEndedAt = performance.now()\n    // The trailing click belongs to the gesture, not to whatever it ended over.\n    window.addEventListener(\"click\", suppressTrailingClick, true)\n\n    if (!landed) return\n    options.onDrop(nodeId, {\n      parentId: landed.target.parentId,\n      index: landed.target.index,\n      copy: wasCopy,\n    })\n  }\n\n  const onPointerCancel = (e: PointerEvent) => {\n    if (e.pointerId !== pointerId) return\n    cancel()\n  }\n\n  window.addEventListener(\"pointermove\", onPointerMove)\n  window.addEventListener(\"pointerup\", onPointerUp)\n  window.addEventListener(\"pointercancel\", onPointerCancel)\n  window.addEventListener(\"keydown\", onKeyDown, true)\n  window.addEventListener(\"keyup\", onKeyUp, true)\n  activeCancels.add(cancel)\n\n  if (isTouch) {\n    touchTimer = setTimeout(() => {\n      activate()\n      if (lastEvent) {\n        positionCarry(lastEvent.clientX, lastEvent.clientY)\n        hitTest(lastEvent.clientX, lastEvent.clientY)\n      }\n    }, FILTER_DND_ACTIVATION.touchDelayMs)\n  }\n}\n\n/**\n * Only `onPointerDown`: the handle is a real button that Tab reaches, so it must\n * not also be `draggable` and race the browser's HTML5 drag, with its ghost, no\n * copy affordance and no way to report a drop into a nested target.\n */\nexport function useFilterRowDrag(options: FilterRowDragOptions) {\n  // Read at gesture time, not captured at wiring time, so the handler identity\n  // is stable and a memoized row never re-renders on a re-created callback.\n  const latest = React.useRef(options)\n  React.useEffect(() => {\n    latest.current = options\n  })\n\n  // A gesture outlives its row by design, but never the panel: its listeners\n  // are on `window` and its carry on `document.body`.\n  React.useEffect(() => cancelActiveFilterDrags, [])\n\n  return React.useCallback(\n    (nodeId: string) => ({\n      onPointerDown: (event: React.PointerEvent<HTMLElement>) => {\n        if (latest.current.disabled) return\n        // Primary button only: a right press strands the drag under a menu.\n        if (event.button !== 0) return\n        startDrag(event, nodeId, latest.current)\n      },\n    }),\n    []\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-dnd.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-draft.tsx",
      "content": "/**\n * filters-draft - adapted for tealmac UI from ReUI \"filters/filters-draft\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\nimport type {\n  FilterDraft,\n  FilterDraftStep,\n  FilterOperatorArity,\n} from \"@/components/reui/filters/filters-types\"\n\n/**\n * The filter builder's step machine. Pure: no React, Base UI or shadcn import,\n * so the whole create and amend flow is a table test in node with no DOM.\n *\n * Arity arrives ON THE ACTION, which keeps the reducer free of the schema index\n * while it still owns the branch that skips the value step. The shipped chrome\n * drives `openCreate`, browse, query, `selectField` and `close`; `openAmend`,\n * `selectOperator`, `setValue`, `commit`, `back` and `goto` are published\n * surface for a consumer composing their own panel.\n */\nexport type FilterDraftAction<V = unknown> =\n  | { type: \"openCreate\"; cascaderPath?: string[] }\n  | {\n      type: \"openAmend\"\n      ruleId: string\n      step: FilterDraftStep\n      path: string[]\n      operator: string | null\n      value: V | undefined\n      cascaderPath?: string[]\n    }\n  | { type: \"close\" }\n  /** Where the user is BROWSING, not the selected field's path. */\n  | { type: \"setCascaderPath\"; path: string[] }\n  | { type: \"setQuery\"; query: string }\n  | {\n      type: \"selectField\"\n      path: string[]\n      defaultOperator: string | null\n    }\n  | {\n      type: \"selectOperator\"\n      operator: string\n      arity: FilterOperatorArity\n      /** Carried across the operator change, already coerced. */\n      value: V | undefined\n    }\n  | { type: \"setValue\"; value: V | undefined }\n  | { type: \"commit\"; value?: V }\n  | { type: \"back\" }\n  | { type: \"goto\"; step: FilterDraftStep }\n\nexport function createFilterDraft<V = unknown>(\n  cascaderPath: string[] = []\n): FilterDraft<V> {\n  return {\n    step: \"field\",\n    status: \"editing\",\n    ruleId: null,\n    path: [],\n    cascaderPath,\n    operator: null,\n    value: undefined,\n    query: \"\",\n  }\n}\n\n/** null means Back closes the builder rather than stepping back. */\nfunction previousStep(step: FilterDraftStep): FilterDraftStep | null {\n  if (step === \"value\") return \"operator\"\n  if (step === \"operator\") return \"field\"\n  return null\n}\n\n/**\n * `null` is the closed state, not a separate boolean: `{ open, draft }` would\n * make \"open with no draft\" and \"closed but still holding one\" representable.\n */\nexport function filterDraftReducer<V = unknown>(\n  state: FilterDraft<V> | null,\n  action: FilterDraftAction<V>\n): FilterDraft<V> | null {\n  switch (action.type) {\n    case \"openCreate\":\n      return createFilterDraft<V>(action.cascaderPath ?? [])\n\n    case \"openAmend\":\n      return {\n        step: action.step,\n        status: \"editing\",\n        ruleId: action.ruleId,\n        path: action.path,\n        // Defaults the picker to the field's own level, so amend opens beside\n        // its siblings, not at the root. Callers may override.\n        cascaderPath: action.cascaderPath ?? action.path.slice(0, -1),\n        operator: action.operator,\n        value: action.value,\n        query: \"\",\n      }\n\n    case \"close\":\n      return null\n\n    case \"setCascaderPath\":\n      if (!state) return state\n      if (state.cascaderPath === action.path) return state\n      return { ...state, cascaderPath: action.path }\n\n    case \"setQuery\":\n      if (!state) return state\n      if (state.query === action.query) return state\n      return { ...state, query: action.query }\n\n    case \"selectField\": {\n      if (!state) return state\n      // Choosing a field COMMITS at once; the condition is picked on the chip,\n      // so the popover never holds a second and third step to walk.\n      return {\n        ...state,\n        path: action.path,\n        operator: action.defaultOperator,\n        status: \"ready\",\n        // A field change invalidates the value: \"Active\" means nothing once\n        // the field becomes \"Created at\".\n        value: undefined,\n        step: \"operator\",\n        query: \"\",\n      }\n    }\n\n    case \"selectOperator\": {\n      if (!state) return state\n      // arity \"none\" is the whole filter; a value step would be an empty panel.\n      if (action.arity === \"none\") {\n        return {\n          ...state,\n          operator: action.operator,\n          value: undefined,\n          status: \"ready\",\n          query: \"\",\n        }\n      }\n      return {\n        ...state,\n        operator: action.operator,\n        value: action.value,\n        step: \"value\",\n        status: \"editing\",\n        query: \"\",\n      }\n    }\n\n    case \"setValue\":\n      if (!state) return state\n      return { ...state, value: action.value }\n\n    case \"commit\":\n      if (!state) return state\n      return {\n        ...state,\n        value: action.value === undefined ? state.value : action.value,\n        status: \"ready\",\n      }\n\n    case \"back\": {\n      if (!state) return state\n      const step = previousStep(state.step)\n      if (!step) return null\n      return { ...state, step, status: \"editing\", query: \"\" }\n    }\n\n    case \"goto\":\n      if (!state) return state\n      if (state.step === action.step) return state\n      return { ...state, step: action.step, status: \"editing\", query: \"\" }\n\n    default:\n      return state\n  }\n}\n\n/**\n * A path is enough. Not an operator: the flow commits when the field is picked,\n * so `operator: \"\"` is a legitimate committed state. Not a value either, since\n * `arity: \"none\"` has none and an editor may commit `undefined` to clear.\n */\nexport function isFilterDraftCommittable<V>(\n  draft: FilterDraft<V> | null\n): draft is FilterDraft<V> {\n  return Boolean(draft && draft.path.length > 0)\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-draft.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-editors.tsx",
      "content": "/**\n * filters-editors - adapted for tealmac UI from ReUI \"filters/filters-editors\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n\"use client\"\n\nimport * as React from \"react\"\nimport { CheckIcon, XIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { ButtonGroup } from \"@/components/ui/button-group\"\nimport { Input } from \"@/components/ui/input\"\nimport {\n  Cascader,\n  CascaderEmpty,\n  CascaderList,\n  CascaderPanel,\n  CascaderStatus,\n} from \"@/components/reui/cascader/cascader\"\nimport type {\n  CascaderItemState,\n  CascaderProps,\n} from \"@/components/reui/cascader/cascader\"\nimport {\n  useCascaderActions,\n  useCascaderHighlight,\n} from \"@/components/reui/cascader/cascader-context\"\nimport { CascaderFooter } from \"@/components/reui/cascader/cascader-footer\"\nimport { CascaderItems } from \"@/components/reui/cascader/cascader-item\"\nimport {\n  CascaderInput,\n  CascaderNav,\n} from \"@/components/reui/cascader/cascader-nav\"\nimport type {\n  CascaderActionItem,\n  CascaderNode,\n} from \"@/components/reui/cascader/cascader-types\"\nimport {\n  FilterActionsContext,\n  filterControlSizes,\n  type FilterResolutionStore,\n} from \"@/components/reui/filters/filters-context\"\nimport {\n  applyFilterExclusiveSelection,\n  filterFilterOptions,\n  joinFilterPath,\n  normalizeFilterQuery,\n  warnFilterOnce,\n} from \"@/components/reui/filters/filters-lib\"\nimport type {\n  AnyFilterEditor,\n  FilterEditorProps,\n  FilterEditorRegistry,\n  FilterField,\n  FilterIndex,\n  FilterLabels,\n  FilterLoadResult,\n  FilterOperator,\n  FilterOption,\n  FilterOptionsState,\n} from \"@/components/reui/filters/filters-types\"\n\n/* -------------------------------------------------------------------------- */\n/*                              The options service                           */\n/* -------------------------------------------------------------------------- */\n\ninterface OptionsInternalState<O> {\n  items: FilterOption<O>[]\n  loading: boolean\n  error: boolean\n  hasMore: boolean\n  cursor?: string\n}\n\nconst IDLE: OptionsInternalState<never> = {\n  items: [],\n  loading: false,\n  error: false,\n  hasMore: false,\n}\n\n/** Stable no-op subscription, for a hook running outside a `Filters` root. */\nconst emptySubscribe = () => () => {}\nconst zeroVersion = () => 0\n\n/**\n * The joined path of a field, from the schema index. Keyed by PATH, not field\n * identity, so labels survive a schema rebuild; an unknown field uses its id.\n */\nfunction filterFieldKey<V, O>(\n  field: FilterField<V, O> | undefined,\n  index: FilterIndex | undefined\n): string | null {\n  if (!field) return null\n  if (index) {\n    for (const entry of index.all) {\n      if ((entry.field as unknown) === (field as unknown)) {\n        return joinFilterPath(entry.path)\n      }\n    }\n  }\n  return `#${field.id}`\n}\n\n/**\n * The shared option service every option-backed editor receives: debouncing,\n * aborting, cursor paging and value-to-label resolution. A deliberate fork of\n * the cascader's async machinery. Resolution is two-tier: a ref cache written\n * in an EFFECT, plus the root's `FilterResolutionStore`, without which a\n * `loadOptions`-only field showed its raw id once the menu closed.\n */\nexport function useFilterOptions<V, O>(\n  field: FilterField<V, O> | undefined,\n  enabled: boolean,\n  debounceMs = 250\n): FilterOptionsState<O> {\n  const [query, setQueryState] = React.useState(\"\")\n  const [state, setState] = React.useState<OptionsInternalState<O>>(\n    IDLE as OptionsInternalState<O>\n  )\n\n  const cache = React.useRef(new Map<string, FilterOption<O>>())\n  const requestId = React.useRef(0)\n  const abortRef = React.useRef<AbortController | null>(null)\n\n  // Read directly, so this degrades outside a `Filters` root instead of throwing.\n  const actionsContext = React.useContext(FilterActionsContext)\n  const shared: FilterResolutionStore | null =\n    actionsContext?.resolution ?? null\n  const sharedKey = filterFieldKey(field, actionsContext?.index)\n\n  // Re-render when a label lands ANYWHERE under this root, not just here.\n  React.useSyncExternalStore(\n    shared ? shared.subscribe : emptySubscribe,\n    shared ? shared.getVersion : zeroVersion,\n    shared ? shared.getVersion : zeroVersion\n  )\n\n  const staticOptions = field?.options\n  const loadOptions = field?.loadOptions\n  const isAsync = Boolean(loadOptions)\n\n  // Seeded in an effect, not during render, so the render stays pure.\n  React.useEffect(() => {\n    if (!staticOptions) return\n    for (const option of staticOptions) cache.current.set(option.value, option)\n    if (shared && sharedKey) shared.set(sharedKey, staticOptions)\n  }, [staticOptions, shared, sharedKey])\n\n  React.useEffect(() => {\n    for (const option of state.items) cache.current.set(option.value, option)\n    if (shared && sharedKey && state.items.length) {\n      shared.set(sharedKey, state.items)\n    }\n  }, [state.items, shared, sharedKey])\n\n  const run = React.useCallback(\n    async (nextQuery: string, cursor: string | undefined, append: boolean) => {\n      if (!loadOptions) return\n\n      abortRef.current?.abort()\n      const controller = new AbortController()\n      abortRef.current = controller\n      const id = ++requestId.current\n\n      setState((previous) => ({\n        ...previous,\n        loading: true,\n        error: false,\n        items: append ? previous.items : [],\n      }))\n\n      try {\n        const result = await loadOptions(nextQuery, {\n          signal: controller.signal,\n          cursor,\n        })\n        // A superseded request must not write; the id, not the abort, decides.\n        if (id !== requestId.current) return\n\n        const normalized: FilterLoadResult<O> = Array.isArray(result)\n          ? { items: result }\n          : result\n\n        setState((previous) => ({\n          items: append\n            ? [...previous.items, ...normalized.items]\n            : normalized.items,\n          loading: false,\n          error: false,\n          hasMore: normalized.hasMore ?? Boolean(normalized.nextCursor),\n          cursor: normalized.nextCursor,\n        }))\n      } catch (error) {\n        if (id !== requestId.current) return\n        if ((error as Error)?.name === \"AbortError\") return\n        setState((previous) => ({\n          ...previous,\n          loading: false,\n          error: true,\n          hasMore: false,\n        }))\n      }\n    },\n    [loadOptions]\n  )\n\n  React.useEffect(() => {\n    if (!enabled || !isAsync) return\n    const timer = setTimeout(\n      () => void run(query, undefined, false),\n      debounceMs\n    )\n    return () => clearTimeout(timer)\n  }, [enabled, isAsync, query, debounceMs, run])\n\n  React.useEffect(() => {\n    return () => abortRef.current?.abort()\n  }, [])\n\n  const normalizedQuery = normalizeFilterQuery(query)\n\n  // Async results are server-filtered; re-filtering hides what the label omits.\n  const items = React.useMemo(() => {\n    if (isAsync) return state.items\n    return filterFilterOptions(staticOptions ?? [], normalizedQuery)\n  }, [isAsync, state.items, staticOptions, normalizedQuery])\n\n  const setQuery = React.useCallback((next: string) => setQueryState(next), [])\n\n  const loadMore = React.useCallback(() => {\n    if (!state.hasMore || state.loading) return\n    void run(query, state.cursor, true)\n  }, [state.hasMore, state.loading, state.cursor, query, run])\n\n  const retry = React.useCallback(() => {\n    void run(query, undefined, false)\n  }, [query, run])\n\n  const resolve = React.useCallback(\n    (value: string) => {\n      // The ref cache cannot be the only tier: a ref write triggers no render,\n      // so the chip would paint the raw value and never repaint. The shared\n      // store holds other instances' pages and re-renders this one on a gain.\n      const declared = staticOptions?.find((option) => option.value === value)\n      if (declared) return declared\n      const fromShared =\n        shared && sharedKey ? shared.get(sharedKey, value) : undefined\n      if (fromShared) return fromShared as FilterOption<O>\n      return cache.current.get(value)\n    },\n    [staticOptions, shared, sharedKey]\n  )\n\n  return {\n    items,\n    loading: state.loading,\n    error: state.error,\n    hasMore: state.hasMore,\n    query,\n    setQuery,\n    loadMore,\n    retry,\n    resolve,\n  }\n}\n\n/**\n * Resolves committed values no loaded page covered, through `resolveValues`: a\n * restored saved view holds ids the loader never returned. The claim set marks\n * an omitted id asked, so only a REJECTED resolve lets a later mount retry.\n */\nexport function useFilterValueResolution<V, O>(\n  field: FilterField<V, O> | undefined,\n  values: readonly unknown[]\n): void {\n  const actionsContext = React.useContext(FilterActionsContext)\n  const shared: FilterResolutionStore | null =\n    actionsContext?.resolution ?? null\n  const sharedKey = filterFieldKey(field, actionsContext?.index)\n  const resolveValues = field?.resolveValues\n  const staticOptions = field?.options\n  // Keyed by CONTENT; NUL cannot occur inside a real stored value.\n  const valuesKey = values.map((entry) => String(entry)).join(\"\\u0000\")\n\n  React.useEffect(() => {\n    if (!resolveValues || !shared || !sharedKey || valuesKey === \"\") return\n    const missing = valuesKey.split(\"\\u0000\").filter((value) => {\n      if (staticOptions?.some((option) => option.value === value)) return false\n      return shared.get(sharedKey, value) === undefined\n    })\n    const wanted = shared.claim(sharedKey, missing)\n    if (wanted.length === 0) return\n\n    // No unmount guard: the store outlives the component.\n    void Promise.resolve(resolveValues(wanted)).then(\n      (options) => shared.set(sharedKey, options),\n      () => shared.release(sharedKey, wanted)\n    )\n  }, [resolveValues, shared, sharedKey, valuesKey, staticOptions])\n}\n\n/* -------------------------------------------------------------------------- */\n/*                               Shared chrome                                */\n/* -------------------------------------------------------------------------- */\n\n/**\n * The panel every editor renders into. A plain flex column, NOT a combobox: an\n * editor inside a Base UI composite would inherit its `aria-activedescendant`\n * and arrow keys, which is hostile to a colour picker or a slider.\n */\nfunction EditorPanel({\n  children,\n  className,\n}: {\n  children: React.ReactNode\n  className?: string\n}) {\n  return (\n    <div\n      data-slot=\"filter-editor\"\n      className={cn(\n        \"flex w-full flex-col gap-2 p-2\",\n        /* The list height cap as a VARIABLE, not the `maxHeight` prop, which\n           becomes an inline style no consumer class can beat. 16rem is the\n           256px the menu has always used. */\n        \"[--cascader-max-height:16rem]\",\n        className\n      )}\n    >\n      {children}\n    </div>\n  )\n}\n\nfunction EditorFooter({\n  onCancel,\n  onCommit,\n  labels,\n  host,\n}: Pick<FilterEditorProps, \"labels\" | \"host\"> & {\n  onCancel: () => void\n  onCommit: () => void\n}) {\n  // The ONE ladder, not a hardcoded rung: `size=\"sm\"` here measured 4px short\n  // of the bar's own controls at `size=\"default\"` in all eight styles.\n  const actions = React.useContext(FilterActionsContext)\n  const sizes = filterControlSizes({ size: actions?.size ?? \"default\" })\n\n  // The create host advances on commit and has Back; amend must offer discard.\n  if (host === \"create\") return null\n  return (\n    <div className=\"flex items-center justify-end gap-1.5 pt-1\">\n      <Button variant=\"ghost\" size={sizes.button} onClick={onCancel}>\n        {labels.discard}\n      </Button>\n      <Button size={sizes.button} onClick={onCommit}>\n        {labels.apply}\n      </Button>\n    </div>\n  )\n}\n\n/**\n * `w-full` because `ButtonGroup` is `w-fit`, which collapses inside this\n * fixed-width panel. Sera is an underline style, so its direct children flatten\n * to one bottom-only edge - `border-b-input`, not transparent, since the\n * buttons are the trailing edge and the rule would stop mid-panel.\n */\nconst EDITOR_FIELD_GROUP =\n  \"w-full style-sera:*:border-transparent style-sera:*:border-b-input\"\n\n/**\n * Confirm and cancel, an OUTLINE pair FUSED onto the field's trailing edge.\n * Returns a FRAGMENT: `ButtonGroup` fuses with selectors matching DIRECT\n * children only, so a wrapper div renders three separate boxes. `size=\"icon\"`\n * because every style's icon button at that size is exactly its input's height.\n */\nfunction EditorCommitButtons({\n  onCancel,\n  onCommit,\n  labels,\n}: Pick<FilterEditorProps, \"labels\"> & {\n  onCancel: () => void\n  onCommit: () => void\n}) {\n  return (\n    <>\n      <Button\n        type=\"button\"\n        variant=\"outline\"\n        size=\"icon\"\n        aria-label={labels.apply}\n        onClick={onCommit}\n      >\n        <CheckIcon aria-hidden=\"true\" />\n      </Button>\n      <Button\n        type=\"button\"\n        variant=\"outline\"\n        size=\"icon\"\n        aria-label={labels.discard}\n        onClick={onCancel}\n      >\n        <XIcon aria-hidden=\"true\" />\n      </Button>\n    </>\n  )\n}\n\nfunction useCommitKeys(commit: () => void, cancel: () => void) {\n  return React.useCallback(\n    (event: React.KeyboardEvent) => {\n      if (event.key === \"Enter\" && !event.nativeEvent.isComposing) {\n        event.preventDefault()\n        commit()\n        return\n      }\n      if (event.key === \"Escape\") {\n        event.preventDefault()\n        // Stop here so a surrounding dialog does not also close.\n        event.stopPropagation()\n        cancel()\n      }\n    },\n    [commit, cancel]\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                Text / number                               */\n/* -------------------------------------------------------------------------- */\n\nexport function FilterTextEditor<V, O>({\n  value,\n  onValueChange,\n  commit,\n  cancel,\n  autoFocusProps,\n  labels,\n  host,\n  field,\n}: FilterEditorProps<V, O>) {\n  const onKeyDown = useCommitKeys(() => commit(), cancel)\n  return (\n    // A width, not shrink-to-fit: the popover is `w-auto`, so an unsized box\n    // changes width between the hosts. `w-72` is measured - it holds about 23\n    // characters in sera and 27 in nova; `w-64` held about eighteen, too short\n    // for an email, and `w-80` was the widest control in a bar of compact\n    // chips. Capped at the viewport because `w-80` is 320px and a 360px phone\n    // has 40px to spare. A `w-*` on the field wins.\n    <EditorPanel\n      className={cn(\"w-72 max-w-[calc(100vw-2rem)] min-w-0\", field.className)}\n    >\n      <ButtonGroup className={EDITOR_FIELD_GROUP}>\n        <Input\n          {...autoFocusProps}\n          value={(value as string) ?? \"\"}\n          placeholder={field.placeholder ?? labels.valuePlaceholder}\n          aria-label={field.label}\n          onChange={(event) => onValueChange(event.target.value as V)}\n          onKeyDown={onKeyDown}\n        />\n        {/*\n          A lone input still belongs in the group: the per-style sheets re-round\n          the LAST child, so a group with nothing fused draws the bare field.\n        */}\n        {host === \"create\" ? null : (\n          <EditorCommitButtons\n            labels={labels}\n            onCancel={cancel}\n            onCommit={() => commit()}\n          />\n        )}\n      </ButtonGroup>\n    </EditorPanel>\n  )\n}\n\nexport function FilterNumberEditor<V, O>({\n  value,\n  onValueChange,\n  commit,\n  cancel,\n  autoFocusProps,\n  labels,\n  host,\n  field,\n}: FilterEditorProps<V, O>) {\n  const onKeyDown = useCommitKeys(() => commit(), cancel)\n  return (\n    // Deliberately not the text editor's `w-72`: number values are short by\n    // construction, and a wide box around \"42\" is the opposite defect.\n    <EditorPanel className={cn(\"w-56 min-w-0\", field.className)}>\n      <ButtonGroup className={EDITOR_FIELD_GROUP}>\n        <Input\n          {...autoFocusProps}\n          type=\"number\"\n          value={value === undefined || value === null ? \"\" : String(value)}\n          placeholder={field.placeholder}\n          aria-label={field.label}\n          onChange={(event) => {\n            const raw = event.target.value\n            onValueChange((raw === \"\" ? undefined : Number(raw)) as V)\n          }}\n          onKeyDown={onKeyDown}\n        />\n        {host === \"create\" ? null : (\n          <EditorCommitButtons\n            labels={labels}\n            onCancel={cancel}\n            onCommit={() => commit()}\n          />\n        )}\n      </ButtonGroup>\n    </EditorPanel>\n  )\n}\n\nexport function FilterRangeEditor<V, O>({\n  value,\n  onValueChange,\n  commit,\n  cancel,\n  autoFocusProps,\n  labels,\n  host,\n  field,\n}: FilterEditorProps<V, O>) {\n  const tuple = (Array.isArray(value) ? value : []) as unknown[]\n  const onKeyDown = useCommitKeys(() => commit(), cancel)\n\n  const update = (index: 0 | 1, raw: string) => {\n    const next = [tuple[0], tuple[1]]\n    next[index] = raw === \"\" ? undefined : Number(raw)\n    onValueChange(next as V)\n  }\n\n  return (\n    <EditorPanel>\n      <div className=\"flex items-center gap-1.5\">\n        <Input\n          {...autoFocusProps}\n          type=\"number\"\n          value={tuple[0] === undefined ? \"\" : String(tuple[0])}\n          aria-label={labels.rangeFrom(field.label)}\n          onChange={(event) => update(0, event.target.value)}\n          onKeyDown={onKeyDown}\n        />\n        <span className=\"text-muted-foreground text-xs\">\n          {labels.rangeSeparator}\n        </span>\n        <Input\n          type=\"number\"\n          value={tuple[1] === undefined ? \"\" : String(tuple[1])}\n          aria-label={labels.rangeTo(field.label)}\n          onChange={(event) => update(1, event.target.value)}\n          onKeyDown={onKeyDown}\n        />\n      </div>\n      <EditorFooter\n        host={host}\n        labels={labels}\n        onCancel={cancel}\n        onCommit={() => commit()}\n      />\n    </EditorPanel>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  The menu                                  */\n/* -------------------------------------------------------------------------- */\n\n/** One row. The shape both the operator menu and the option editors hand over. */\nexport interface FilterListItem {\n  value: string\n  label: string\n  icon?: React.ReactNode\n  description?: string\n  keywords?: string[]\n  disabled?: boolean\n  /**\n   * A None row, from `FilterOption.exclusive`. LAYOUT only: what a pick DOES is\n   * `applyFilterExclusiveSelection`, in the option editor's handler. A consumer\n   * composing `FilterMenu` into an editor of their own owns the same call.\n   */\n  exclusive?: boolean\n}\n\n/**\n * Beyond the cascader's own fields: one divider flag, on the first row of a\n * group that is not the first, because grouping happens out here. A separator\n * NODE would join the option ring, and `[data-selected] + :not([data-selected])`\n * reads the LIVE selection, so unticking a pinned row drew a second line.\n */\ninterface FilterMenuMeta {\n  divider?: boolean\n  /**\n   * Carries `FilterListItem.exclusive` down to the row. The rule above it is\n   * `aria-hidden`, so the row's accessible name is the only channel arriving\n   * before the press, and `renderItem` receives the node and nothing else.\n   *\n   * `[data-slot=filter-menu-exclusive-hint]` is also the handle a consumer\n   * styles the row through: the cascader's row element takes no attribute of\n   * ours, so `:has([data-slot=filter-menu-exclusive-hint])` selects it.\n   */\n  exclusive?: boolean\n}\n\n/** Joins a selection into one comparable key; NUL cannot occur in a value. */\nconst PIN_SEPARATOR = \"\\u0000\"\n\n/** A bound on a race: each attempt costs one task and stops on success. */\nconst MAX_PIN_RESTORE_ATTEMPTS = 4\n\ninterface PendingPinRestore {\n  /** The row the user was on when the rows moved. Tracked by VALUE, never index. */\n  value: string\n  /** The index it sat at, which is the half of the signature Base UI keeps. */\n  index: number\n  /** The order the rows landed in, so the target's new position is known. */\n  order: string[]\n  attempts: number\n}\n\n/**\n * Carries the HIGHLIGHT across a live re-pin. Base UI holds it as an INDEX and\n * a keyed reorder MOVES the DOM node rather than remounting it, so the index\n * map only rebuilds when the `MutationObserver` fires: until then, ticking a\n * row moves the highlight down one. So this ARMS in the layout effect, where\n * the map still reads the OLD order, and fires on the signature (SAME index,\n * DIFFERENT row) from a TASK, re-trying because the store event and the re-sort\n * are unordered. A synthetic `mousemove`, since Base UI exposes no setter.\n */\nfunction FilterMenuPinKeeper({\n  order,\n  items,\n}: {\n  order: string[]\n  /** The data the order was derived from, by identity. */\n  items: FilterListItem[]\n}) {\n  const { baseId } = useCascaderActions()\n  const highlight = useCascaderHighlight()\n  const previousRef = React.useRef<{\n    order: string[]\n    items: FilterListItem[]\n  } | null>(null)\n  const pendingRef = React.useRef<PendingPinRestore | null>(null)\n  const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n\n  // From the render: on the reordering commit a ref still holds the OLD row.\n  const highlightedValue = highlight.value\n  const highlightedIndex = highlight.index\n\n  const stop = React.useCallback(() => {\n    pendingRef.current = null\n    if (timerRef.current === null) return\n    clearTimeout(timerRef.current)\n    timerRef.current = null\n  }, [])\n\n  const startRestore = React.useCallback(() => {\n    const attempt = () => {\n      timerRef.current = null\n      const pending = pendingRef.current\n      if (!pending) return\n\n      const target = pending.order.indexOf(pending.value)\n      const rows = document\n        .getElementById(`${baseId}-column-0`)\n        ?.querySelectorAll<HTMLElement>('[data-slot=\"cascader-item\"]')\n      // A WINDOWED list renders a subset, so row N is not order[N]. Leave it.\n      if (target < 0 || !rows || rows.length !== pending.order.length) {\n        stop()\n        return\n      }\n\n      rows[target]?.dispatchEvent(\n        new MouseEvent(\"mousemove\", { bubbles: true })\n      )\n\n      pending.attempts += 1\n      if (pending.attempts >= MAX_PIN_RESTORE_ATTEMPTS) {\n        stop()\n        return\n      }\n      timerRef.current = setTimeout(attempt, 0)\n    }\n\n    timerRef.current = setTimeout(attempt, 0)\n  }, [baseId, stop])\n\n  // No dependency list: the arm must run on the commit that reorders the rows.\n  React.useLayoutEffect(() => {\n    const previous = previousRef.current\n    previousRef.current = { order, items }\n\n    if (!previous || previous.order === order) return\n    // New DATA (a page, a query) is Base UI's to highlight; only a re-pin is ours.\n    if (previous.items !== items) return\n    if (!highlightedValue) return\n    // Content, not identity: a re-pin can leave the rows in the same order.\n    if (isSameOrder(previous.order, order)) return\n\n    pendingRef.current = {\n      value: highlightedValue,\n      index: highlightedIndex,\n      order,\n      attempts: 0,\n    }\n  })\n\n  React.useEffect(() => {\n    const pending = pendingRef.current\n    if (!pending) return\n\n    // Back where it belongs, or moved by the user: either way the arm is spent.\n    if (\n      highlightedValue === pending.value ||\n      highlightedIndex !== pending.index\n    ) {\n      stop()\n      return\n    }\n    // Already chasing this one; a second chain would double every dispatch.\n    if (pending.attempts > 0 || timerRef.current !== null) return\n    startRestore()\n  }, [highlightedValue, highlightedIndex, startRestore, stop])\n\n  React.useEffect(() => stop, [stop])\n\n  return null\n}\n\n/** Element-wise, because the arrays are rebuilt on every selection change. */\nfunction isSameOrder(a: string[], b: string[]) {\n  if (a.length !== b.length) return false\n  for (let index = 0; index < a.length; index += 1) {\n    if (a[index] !== b[index]) return false\n  }\n  return true\n}\n\nexport interface FilterMenuProps {\n  items: FilterListItem[]\n  /** Committed values. Drives the check mark and the pinned group. */\n  selected: string[]\n  multiple?: boolean\n  /** Receives the FULL next selection, so no caller re-derives it. */\n  onSelectionChange: (values: string[]) => void\n  labels: FilterLabels\n  ariaLabel: string\n  searchPlaceholder?: string\n  /** Whether the search field is VISIBLE. It is always rendered regardless. */\n  searchable?: boolean\n  /**\n   * Viewport height before the list scrolls, in pixels. Omitted on purpose by\n   * the option editors: it becomes an inline style a consumer's `className`\n   * cannot outrank, so the panel publishes `--cascader-max-height` instead.\n   */\n  maxHeight?: number\n  /**\n   * Pin selected rows above the rest, with a full-bleed rule between them. Off\n   * by default; the option editors read `FilterField.pinSelected` per field.\n   */\n  pinSelected?: boolean\n  /**\n   * Order INSIDE each group, plus WHEN the partition is taken. Declaration\n   * order by default, so the partition is stable rather than a re-sort.\n   */\n  sortSelected?: \"none\" | \"label\" | \"snapshot\"\n  /** The caller already filtered `items`, so the cascader must not re-filter. */\n  preFiltered?: boolean\n  autoFocusProps?: FilterEditorProps[\"autoFocusProps\"]\n  /** Controlled query. Pair it with `onQueryChange` to filter outside. */\n  query?: string\n  onQueryChange?: (query: string) => void\n  state?: Pick<\n    FilterOptionsState<unknown>,\n    \"loading\" | \"error\" | \"hasMore\" | \"loadMore\" | \"retry\"\n  >\n}\n\n/**\n * One accessible list, shared by the operator menu and every option editor. It\n * is the CASCADER configured flat, not a list this file implements, which\n * brings the typeahead, RTL handling and live region with it. Only the pinning\n * and the paging affordance stay out here.\n */\nexport function FilterMenu({\n  items,\n  selected,\n  multiple = false,\n  onSelectionChange,\n  labels,\n  ariaLabel,\n  searchPlaceholder,\n  searchable = true,\n  maxHeight,\n  pinSelected = false,\n  sortSelected = \"none\",\n  preFiltered = false,\n  autoFocusProps,\n  query,\n  onQueryChange,\n  state,\n}: FilterMenuProps) {\n  /**\n   * The pin set as a KEY, not an array: `selected` is a fresh array on most\n   * renders, so a memo depending on it re-partitions every render.\n   */\n  const liveKey = pinSelected ? selected.join(PIN_SEPARATOR) : \"\"\n\n  /**\n   * The same set, frozen at OPEN, for `sortSelected: \"snapshot\"`. LIVE is the\n   * default: \"your picks, then the rest\" is about the CURRENT selection, and\n   * `FilterMenuPinKeeper` pays for rows moving under the pointer.\n   */\n  const [snapshotKey] = React.useState(() => liveKey)\n  // `pinSelected` re-checked here, not just through `liveKey`: `snapshotKey` is\n  // frozen at MOUNT, so a menu that lost the prop would keep partitioning.\n  const pinnedKey = !pinSelected\n    ? \"\"\n    : sortSelected === \"snapshot\"\n      ? snapshotKey\n      : liveKey\n\n  // Uncontrolled unless the caller owns the query, as an option service does.\n  const [ownQuery, setOwnQuery] = React.useState(\"\")\n  const currentQuery = query ?? ownQuery\n  const setQuery = onQueryChange ?? setOwnQuery\n\n  /**\n   * Memoized on the SELECTION, not the query: folding the query in re-sorted\n   * 4,000 rows on every keystroke, for a one pixel rule.\n   */\n  const partitioned = React.useMemo(() => {\n    const pinned = new Set(pinnedKey ? pinnedKey.split(PIN_SEPARATOR) : [])\n\n    /*\n      Exclusive rows come out BEFORE the pin partition; their position is fixed.\n      Pinning is by SELECTION, so a ticked None row would lift itself above the\n      very rule drawn to set it apart and drop back on untick. Grouping by ROLE\n      means the pinned group counts ordinary picks only, which is also why\n      picking None draws no pin rule: it clears every other pick.\n    */\n    const exclusive = items.filter((item) => item.exclusive)\n    const values = exclusive.length\n      ? items.filter((item) => !item.exclusive)\n      : items\n\n    const chosen = pinned.size\n      ? values.filter((item) => pinned.has(item.value))\n      : []\n    const rest = pinned.size\n      ? values.filter((item) => !pinned.has(item.value))\n      : values\n\n    // The SCHEMA's order inside each group unless the field asks otherwise:\n    // option order is usually semantic.\n    const ordered =\n      sortSelected === \"label\"\n        ? [\n            [...chosen].sort((a, b) => a.label.localeCompare(b.label)),\n            [...rest].sort((a, b) => a.label.localeCompare(b.label)),\n            [...exclusive].sort((a, b) => a.label.localeCompare(b.label)),\n          ]\n        : [chosen, rest, exclusive]\n\n    const rows = [...ordered[0], ...ordered[1], ...ordered[2]]\n\n    return {\n      chosenCount: chosen.length,\n      /** Index of the first exclusive row, or -1 when the list has none. */\n      exclusiveAt: exclusive.length ? rows.length - exclusive.length : -1,\n      // The render order alone, so a REORDER is an identity compare.\n      order: rows.map((item) => item.value),\n      nodes: rows.map<CascaderNode<FilterMenuMeta>>((item) => ({\n        value: item.value,\n        label: item.label,\n        icon: item.icon,\n        description: item.description,\n        keywords: item.keywords,\n        disabled: item.disabled,\n        // Only exclusive rows carry `data`, so the ordinary 4,000 keep theirs.\n        data: item.exclusive ? { exclusive: true } : undefined,\n      })),\n    }\n  }, [items, pinnedKey, sortSelected])\n\n  // No rule under a query: \"your picks, then the rest\" is about the WHOLE list.\n  const dividerAt =\n    partitioned.chosenCount && !currentQuery.trim()\n      ? partitioned.chosenCount\n      : -1\n\n  // Survives a search, unlike the pin rule: it is a fact about the row.\n  const exclusiveDividerAt = partitioned.exclusiveAt\n\n  const nodes = React.useMemo<CascaderNode<FilterMenuMeta>[]>(() => {\n    const total = partitioned.nodes.length\n    // Only a boundary with rows on BOTH sides is one: a rule on row 0 would\n    // be a line above the top of the list.\n    const marks = [dividerAt, exclusiveDividerAt].filter(\n      (index) => index > 0 && index < total\n    )\n    if (marks.length === 0) return partitioned.nodes\n    // Rows rewritten, not rebuilt: copying 4,000 objects would undo the split.\n    const next = partitioned.nodes.slice()\n    for (const index of marks) {\n      // MERGED, never replaced: the two boundaries usually fall on one row, and\n      // overwriting `data` dropped the flag the accessible name is built from.\n      next[index] = {\n        ...next[index],\n        data: { ...next[index].data, divider: true },\n      }\n    }\n    return next\n  }, [partitioned, dividerAt, exclusiveDividerAt])\n\n  const renderItem = React.useCallback(\n    (\n      node: CascaderNode<FilterMenuMeta>,\n      itemState: CascaderItemState<FilterMenuMeta>\n    ) => (\n      <>\n        {node.data?.divider ? (\n          <span\n            data-slot=\"filter-menu-divider\"\n            aria-hidden=\"true\"\n            /* Full bleed, over the per-style `--cascader-list-pad` the shell\n               publishes: a rule stopping at the row's inset box reads as a gap.\n               Centred in the 8px the row gives back above itself, not `top-0`. */\n            className=\"bg-border absolute inset-x-[calc(var(--cascader-list-pad,4px)*-1)] -top-1 h-px\"\n          />\n        ) : null}\n\n        {node.icon ? (\n          <span\n            data-slot=\"filter-menu-icon\"\n            className=\"text-muted-foreground flex shrink-0 items-center justify-center\"\n          >\n            {node.icon}\n          </span>\n        ) : null}\n\n        <span className=\"flex min-w-0 flex-1 flex-col items-start gap-0.5\">\n          <span className=\"w-full truncate text-start\">{node.label}</span>\n          {node.description ? (\n            <span className=\"text-muted-foreground w-full truncate text-start text-xs\">\n              {node.description}\n            </span>\n          ) : null}\n        </span>\n\n        {/*\n          What the aria-hidden rule says, for the people it does not reach.\n          Inside the option element so it joins the row's accessible NAME, not\n          an `aria-describedby`: a description is announced late or not at all,\n          and this has to arrive before the press. The cascader's `srDetails`\n          cannot either: `renderItem` replaces the row body. Empty copy renders\n          nothing, so `labels.exclusiveHint` of \"\" silences it.\n        */}\n        {node.data?.exclusive && labels.exclusiveHint ? (\n          <span data-slot=\"filter-menu-exclusive-hint\" className=\"sr-only\">\n            {`, ${labels.exclusiveHint}`}\n          </span>\n        ) : null}\n\n        {/* A check mark in both modes, never the cascader's default box. */}\n        {itemState.selected ? (\n          <span\n            data-slot=\"filter-menu-check\"\n            /* The gutter every style already reserves, on the cascader's own\n               logical inset. `end-*` rather than `right-2`, so RTL mirrors. */\n            className=\"style-vega:size-4 style-nova:size-4 style-maia:size-4 style-lyra:size-4 style-mira:size-3.5 style-luma:size-4 style-rhea:size-4 style-sera:size-4 pointer-events-none absolute end-[var(--cascader-row-inset,8px)]! flex items-center justify-center rtl:right-auto!\"\n          >\n            <CheckIcon /* Pinned on the svg AND its descendants: every style repaints\n                 icons in a highlighted row with `**:text-accent-foreground`. */\n              className=\"text-foreground! **:text-foreground!\"\n            />\n          </span>\n        ) : null}\n      </>\n    ),\n    [labels.exclusiveHint]\n  )\n\n  const cascaderLabels = React.useMemo(\n    () => ({\n      search: searchPlaceholder ?? labels.searchOptions,\n      empty: labels.empty,\n      loading: labels.loading,\n      loadingMore: labels.loadingMore,\n      loadMore: labels.loadMore,\n      error: labels.error,\n      retry: labels.retry,\n      // Named after the field, not the cascader's own \"Top level\" wording.\n      rootLevel: ariaLabel,\n      panelLabel: ariaLabel,\n      // Run FLAT, so the default hint would teach branch keys that do not exist.\n      keyboardHint: () => \"\",\n      // From `FilterLabels`, so the menu ships no English of its own.\n      resultsAnnouncement: labels.resultsAnnouncement,\n      actionsLabel: labels.actionsLabel,\n    }),\n    [labels, ariaLabel, searchPlaceholder]\n  )\n\n  /**\n   * Paging and retry in the pinned footer, never a row: a row would join the\n   * option ring, where arrows land on it and a query filters it away mid-page.\n   */\n  const actions = React.useMemo<CascaderActionItem[]>(() => {\n    if (state?.error) {\n      return [{ value: \"retry\", label: labels.retry, onSelect: state.retry }]\n    }\n    if (state?.hasMore) {\n      return [\n        {\n          value: \"load-more\",\n          label: state.loading ? labels.loadingMore : labels.loadMore,\n          disabled: state.loading,\n          onSelect: state.loadMore,\n        },\n      ]\n    }\n    return []\n  }, [state, labels])\n\n  const shared = {\n    // Inline and pinned open with a no-op handler, so the unconditional\n    // `setOpen(false)` of a single-select commit cannot dismiss the popover.\n    inline: true,\n    open: true,\n    onOpenChange: () => {},\n    items: nodes,\n    inputValue: currentQuery,\n    onInputValueChange: setQuery,\n    maxHeight,\n    renderItem,\n    labels: cascaderLabels,\n    actions,\n    // The option service is the ONE filter when it owns the query.\n    ...(preFiltered ? { filter: () => true } : null),\n  }\n\n  const cascaderProps: CascaderProps<FilterMenuMeta> = multiple\n    ? {\n        ...shared,\n        multiple: true,\n        value: selected,\n        onValueChange: (values: string[]) => onSelectionChange(values),\n      }\n    : {\n        ...shared,\n        value: selected[0] ?? \"\",\n        onValueChange: (value: string) =>\n          onSelectionChange(value ? [value] : []),\n      }\n\n  return (\n    <Cascader {...cascaderProps}>\n      <CascaderPanel>\n        {/*\n          `searchable: false` hides the FIELD, never removes it: the input owns\n          focus and `aria-activedescendant`, so a menu without one has no\n          keyboard. The class goes on the nav so the strip's border goes too.\n        */}\n        <CascaderNav\n          className={cn(\n            /* The nav's divider is `border-border/60` and the group separator\n               is a full-opacity `bg-border`; two strengths read as a mistake. */\n            \"border-border\",\n            !searchable && \"sr-only\"\n          )}\n        >\n          <CascaderInput\n            {...(autoFocusProps ?? {})}\n            placeholder={searchPlaceholder ?? labels.searchOptions}\n            aria-label={ariaLabel}\n          />\n        </CascaderNav>\n        <CascaderEmpty>\n          {state?.error\n            ? labels.error\n            : state?.loading\n              ? labels.loading\n              : labels.empty}\n        </CascaderEmpty>\n        {/*\n          Plain rows, DELIBERATELY not `CascaderVirtualItems`: windowing stands\n          `FilterMenuPinKeeper` down. The long lists are async and PAGE 25.\n        */}\n        <CascaderList\n          /**\n           * Real layout space around the group rule, which is absolutely\n           * positioned and adds no height. `renderItem` cannot reach the row's\n           * own box, and a spacer NODE would join the option ring.\n           *\n           * `:has()` is affordable here: scoped to this one list, a compound\n           * whose descendant exists on at most ONE row, and these menus render\n           * tens of rows rather than thousands.\n           */\n          className=\"[&>[data-slot=cascader-item]:has([data-slot=filter-menu-divider])]:mt-2\"\n        >\n          <CascaderItems />\n        </CascaderList>\n        <CascaderFooter />\n        <CascaderStatus />\n        {/*\n          Last, so its layout effect reads the reordered DOM after every row has\n          registered. Not mounted at all for a menu that cannot reorder.\n        */}\n        {pinSelected && sortSelected !== \"snapshot\" ? (\n          <FilterMenuPinKeeper order={partitioned.order} items={items} />\n        ) : null}\n      </CascaderPanel>\n    </Cascader>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                              Option based editors                          */\n/* -------------------------------------------------------------------------- */\n\nfunction OptionEditor<V, O>(\n  props: FilterEditorProps<V, O> & { multiple: boolean }\n) {\n  const {\n    multiple,\n    options,\n    labels,\n    autoFocusProps,\n    commit,\n    cancel,\n    onValueChange,\n    value,\n    field,\n  } = props\n\n  const selected = React.useMemo(() => {\n    if (value === undefined || value === null) return []\n    return (Array.isArray(value) ? value : [value]) as string[]\n  }, [value])\n\n  const announce = React.useContext(FilterActionsContext)?.announce\n\n  return (\n    /*\n      A DELIBERATELY narrow default: 12rem holds around 22 characters at every\n      style's row size. `field.className` lands LAST, so a consumer's `w-*` wins.\n    */\n    <EditorPanel className={cn(\"w-48 min-w-0 gap-0 p-0\", field.className)}>\n      <FilterMenu\n        items={options.items}\n        selected={selected}\n        multiple={multiple}\n        onSelectionChange={(raw) => {\n          /*\n            The ONE place the None rule is applied: every route into a selection\n            arrives here, so click and keyboard cannot disagree, and only the\n            editor can ANSWER it - `options.resolve` sees the schema and every\n            loaded page, where the menu holds only the rows on screen.\n          */\n          const values = applyFilterExclusiveSelection(raw, selected, (value) =>\n            Boolean(options.resolve(value)?.exclusive)\n          )\n\n          /*\n            Identity is the test: the rule hands back `raw` itself unless it\n            intervened. Announced because nothing else reports it: focus never\n            moved, and nobody is on the rows that lost their check marks.\n          */\n          if (values !== raw && announce) {\n            const arrived = values.find((entry) => !selected.includes(entry))\n            const cleared = raw.length - values.length\n            if (arrived !== undefined && cleared > 0) {\n              announce(\n                labels.exclusiveAnnouncement(\n                  options.resolve(arrived)?.label ?? arrived,\n                  cleared\n                )\n              )\n            }\n          } else if (values === raw && raw.length > 1) {\n            /*\n              The hole in the rule, made LOUD. An unresolvable value is treated\n              as ordinary and cannot be told from an id whose label has not\n              arrived, so this warns rather than acts. Needs a SEEN None row.\n            */\n            const hasNoneRow =\n              options.items.some((item) => item.exclusive) ||\n              Boolean(field.options?.some((option) => option.exclusive))\n            const unresolved = hasNoneRow\n              ? raw.find((entry) => options.resolve(entry) === undefined)\n              : undefined\n            if (unresolved !== undefined) {\n              warnFilterOnce(\n                `exclusive-unresolved:${field.id}`,\n                `field \"${field.id}\" has an exclusive option, but the value ` +\n                  `\"${unresolved}\" resolves to no option, so the None rule ` +\n                  `cannot tell whether it is the exclusive one and has left ` +\n                  `it in place. Declare the exclusive option in the field's ` +\n                  `\\`options\\` even when the rest of the list is async, or ` +\n                  `cover stored values with \\`resolveValues\\`.`\n              )\n            }\n          }\n\n          if (!multiple) {\n            const next = values[0]\n            // Base UI deselects the committed row; an empty filter is no gain.\n            if (next === undefined) {\n              cancel()\n              return\n            }\n            onValueChange(next as V)\n            commit(next as V)\n            return\n          }\n          onValueChange(values as V)\n          // Every toggle commits with the popover open: several picks, one gesture.\n          commit(values as V, { close: false })\n        }}\n        labels={labels}\n        ariaLabel={field.label}\n        searchable={field.searchable ?? true}\n        // Not a composed `Search ${label}...`: hardcoded English no `labels`\n        // override could reach, and lowercasing a label is locale-hostile.\n        searchPlaceholder={field.placeholder}\n        pinSelected={field.pinSelected ?? false}\n        sortSelected={field.sortSelected}\n        // `useFilterOptions` already applied the query, locally or server side.\n        preFiltered\n        query={options.query}\n        onQueryChange={options.setQuery}\n        state={options}\n        autoFocusProps={autoFocusProps}\n      />\n    </EditorPanel>\n  )\n}\n\nexport function FilterSelectEditor<V, O>(props: FilterEditorProps<V, O>) {\n  return <OptionEditor {...props} multiple={false} />\n}\n\nexport function FilterMultiSelectEditor<V, O>(props: FilterEditorProps<V, O>) {\n  return <OptionEditor {...props} multiple />\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Boolean                                  */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Module level, so the menu's index is not rebuilt on every render. Not in\n * `FilterLabels`: the chip's own display spells the same two words out.\n */\nconst BOOLEAN_ITEMS: FilterListItem[] = [\n  { value: \"true\", label: \"True\" },\n  { value: \"false\", label: \"False\" },\n]\n\nexport function FilterBooleanEditor<V, O>({\n  value,\n  onValueChange,\n  commit,\n  labels,\n  autoFocusProps,\n  field,\n}: FilterEditorProps<V, O>) {\n  return (\n    // Two words, and `field.className` lands last so a consumer's `w-*` wins.\n    <EditorPanel className={cn(\"w-40 min-w-0 gap-0 p-0\", field.className)}>\n      <FilterMenu\n        items={BOOLEAN_ITEMS}\n        selected={value === true ? [\"true\"] : value === false ? [\"false\"] : []}\n        onSelectionChange={(values) => {\n          /* Deselecting the committed row leaves nothing to filter on, so it is\n             a no-op rather than a commit of `false`. */\n          if (values.length === 0) return\n          const next = (values[0] === \"true\") as V\n          onValueChange(next)\n          commit(next)\n        }}\n        labels={labels}\n        ariaLabel={field.label}\n        /* Two rows: a search over them is more chrome than list, but the\n           field is still rendered, hidden, because it owns the keyboard. */\n        searchable={false}\n        autoFocusProps={autoFocusProps}\n      />\n    </EditorPanel>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Resolution                                */\n/* -------------------------------------------------------------------------- */\n\nexport type {\n  AnyFilterEditor,\n  FilterEditorRegistry,\n} from \"@/components/reui/filters/filters-types\"\n\nexport const DEFAULT_FILTER_EDITORS: FilterEditorRegistry = {\n  text: FilterTextEditor,\n  number: FilterNumberEditor,\n  range: FilterRangeEditor,\n  select: FilterSelectEditor,\n  multiselect: FilterMultiSelectEditor,\n  boolean: FilterBooleanEditor,\n}\n\n/**\n * Picks the editor for a (field, operator) pair: the field's own `editor`, then\n * the operator's ARITY, then the field's `type`. Arity outranks type because\n * \"between\" wants two boxes whatever the field said.\n */\nexport function resolveFilterEditor<V, O>(\n  field: FilterField<V, O>,\n  operator: FilterOperator | undefined,\n  editors: FilterEditorRegistry\n): AnyFilterEditor | undefined {\n  if (typeof field.editor === \"function\") {\n    // The one place a consumer's typed editor meets the erased registry.\n    return field.editor as unknown as AnyFilterEditor\n  }\n  if (typeof field.editor === \"string\") {\n    const named = editors[field.editor]\n    if (named) return named\n  }\n\n  const arity = operator?.arity ?? \"one\"\n  if (arity === \"none\") return undefined\n  if (arity === \"range\") return editors.range\n  if (arity === \"many\") {\n    // An option-backed field gets checkboxes; anything else receives an array.\n    if (field.options || field.loadOptions) return editors.multiselect\n  }\n\n  return editors[field.type ?? \"text\"] ?? editors.text\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-editors.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-i18n.tsx",
      "content": "/**\n * filters-i18n - adapted for tealmac UI from ReUI \"filters/filters-i18n\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\nimport type {\n  FilterDraftStep,\n  FilterIssue,\n  FilterIssueReason,\n  FilterLabels,\n} from \"@/components/reui/filters/filters-types\"\n\n/**\n * The shipped English copy. `stepAnnouncement` (consumer-composed create\n * wizard) and `showRecords` (a consumer's own panel heading) are unread by the\n * shipped chrome and kept on purpose; do not prune them as dead keys.\n */\nexport const DEFAULT_FILTER_LABELS: FilterLabels = {\n  addFilter: \"Add filter\",\n  advancedFilter: \"Advanced filter\",\n  showRecords: \"In this view, show records\",\n  builderEmpty: \"No filters yet\",\n  builderEmptyHint: \"Add a filter to narrow down what you see.\",\n  addCondition: \"Add filter\",\n  addConditionGroup: \"Add group\",\n  addToGroup: \"Add filter to this group\",\n  removeGroup: \"Remove group\",\n  wrapInGroup: \"Wrap in group\",\n  ungroup: \"Ungroup\",\n  moveToTopLevel: \"Move to top\",\n  moveToGroup: (position) => `Move to group ${position}`,\n  reorder: \"Reorder\",\n  reorderHint: \"Press Alt with Arrow Up or Arrow Down to reorder\",\n  groupAll: \"All of the following are true...\",\n  groupAny: \"Any of the following are true...\",\n  groupPlaceholder: \"Drag filters here\",\n  rowLabel: (condition, depth) => `${condition}, level ${depth}`,\n  groupLabel: (description, depth) => `${description} level ${depth}`,\n  groupAnnouncement: (added) => (added ? \"Group added\" : \"Group removed\"),\n  reorderAnnouncement: (label, position, total) =>\n    `${label} moved to position ${position} of ${total}`,\n  // Destination FIRST after the verb: it is the half a plain reorder cannot\n  // say and the half the user cannot see once the row has stopped moving.\n  // Position stays last, so this still ends on the \"of N\" a reorder ends on.\n  moveAnnouncement: (label, destination, position, total) =>\n    `${label} moved into ${destination}, position ${position} of ${total}`,\n  clearAll: \"Clear all\",\n  groupMenu: \"Group options\",\n  searchFields: \"Search attributes...\",\n  searchOperators: \"Search operators...\",\n  searchOptions: \"Search...\",\n  back: \"Back\",\n  clear: \"Clear\",\n  apply: \"Apply\",\n  discard: \"Discard changes\",\n  empty: \"No results\",\n  loading: \"Loading...\",\n  loadingMore: \"Loading more...\",\n  loadMore: \"Load more\",\n  error: \"Could not load\",\n  retry: \"Retry\",\n  where: \"Where\",\n  and: \"And\",\n  or: \"Or\",\n  combinator: \"Change combinator\",\n  // The word first: it is what the control SAYS and what a truncated pill\n  // stops showing. The action follows, so the name still names an action.\n  combinatorLabel: (word) => `${word}, change combinator`,\n  duplicate: \"Duplicate\",\n  negate: \"Negate\",\n  convertToAdvanced: \"Advanced editor\",\n  remove: \"Remove\",\n  chipMenu: (fieldLabel) => `${fieldLabel} filter options`,\n  filtersLabel: \"Filters\",\n  filterLabel: (condition) => condition,\n  readOnly: \"Read only. These filters cannot be changed.\",\n  pathSeparator: \" > \",\n  valuePlaceholder: \"enter text...\",\n  selectPlaceholder: \"Select...\",\n  noValue: \"no value\",\n  selectCondition: \"Select condition\",\n  incomplete: \"incomplete filter\",\n  branchAffordance: \"opens a list\",\n  exclusiveHint: \"cannot be combined with the other options\",\n  exclusiveAnnouncement: (label, cleared) =>\n    cleared === 1\n      ? `${label} selected. 1 other selection cleared.`\n      : `${label} selected. ${cleared} other selections cleared.`,\n  itemCount: (count) => `${count} items`,\n  fieldsLabel: \"Attributes\",\n  resultsAnnouncement: (count) =>\n    count === 1 ? \"1 result\" : `${count} results`,\n  actionsLabel: \"Actions\",\n  stepAnnouncement: (step, label) => {\n    if (step === \"field\") return `Choose an attribute. ${label}`\n    if (step === \"operator\") return `Choose a condition for ${label}`\n    return `Enter a value for ${label}`\n  },\n  countAnnouncement: (count) =>\n    count === 1 ? \"1 filter applied\" : `${count} filters applied`,\n  valueCount: (count) => `${count} selected`,\n  valueDetail: (summary, values) => `${summary}: ${values.join(\", \")}`,\n  valueRange: (from, to) => `${from} to ${to}`,\n  rangeFrom: (fieldLabel) => `${fieldLabel} from`,\n  rangeTo: (fieldLabel) => `${fieldLabel} to`,\n  rangeSeparator: \"to\",\n  negated: (operatorLabel) => `not ${operatorLabel}`,\n  issueOperator: \"Choose a condition\",\n  issueValue: \"Enter a value\",\n  issueRange: \"Enter both ends of the range\",\n  issueRangeOrder: \"The end of the range comes before its start\",\n  issueEmptyGroup: \"This group has no conditions yet\",\n  // \"Row\", not \"condition\": an empty GROUP is counted here too and a group is\n  // not a condition. Rule and group divs alike carry `data-slot=\"filter-row\"`.\n  issueSummary: (count) =>\n    count === 1 ? \"1 row needs attention\" : `${count} rows need attention`,\n}\n\n/**\n * Shallow merge over the defaults, like the cascader's. A deep merge would leak\n * the default back into a replaced function-valued label for the arguments the\n * consumer did not think about.\n */\nexport function resolveFilterLabels(\n  labels?: Partial<FilterLabels>\n): FilterLabels {\n  if (!labels) return DEFAULT_FILTER_LABELS\n  return { ...DEFAULT_FILTER_LABELS, ...labels }\n}\n\n/**\n * The sentence for one issue. Takes the ISSUE, not just the reason: a field's\n * `validate` supplies its own words, so `custom` has nothing to look up.\n */\nexport function filterIssueLabel(\n  issue: Pick<FilterIssue, \"reason\" | \"message\"> | FilterIssueReason,\n  labels: FilterLabels\n): string {\n  const reason = typeof issue === \"string\" ? issue : issue.reason\n  if (typeof issue !== \"string\" && issue.message) return issue.message\n  if (reason === \"missing-operator\") return labels.issueOperator\n  if (reason === \"incomplete-range\") return labels.issueRange\n  if (reason === \"reversed-range\") return labels.issueRangeOrder\n  if (reason === \"empty-group\") return labels.issueEmptyGroup\n  return labels.issueValue\n}\n\n/** The search placeholder for a step's panel. */\nexport function stepPlaceholder(\n  step: FilterDraftStep,\n  labels: FilterLabels\n): string {\n  if (step === \"field\") return labels.searchFields\n  if (step === \"operator\") return labels.searchOperators\n  return labels.searchOptions\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-i18n.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-lib.tsx",
      "content": "/**\n * filters-lib - adapted for tealmac UI from ReUI \"filters/filters-lib\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\nimport { collapseCascaderPath } from \"@/components/reui/cascader/cascader-lib\"\nimport type { CascaderCollapse } from \"@/components/reui/cascader/cascader-types\"\nimport type {\n  FilterField,\n  FilterIndex,\n  FilterOperator,\n  FilterOption,\n} from \"@/components/reui/filters/filters-types\"\n\n/* -------------------------------------------------------------------------- */\n/*                                    Menus                                   */\n/* -------------------------------------------------------------------------- */\n\n/**\n * One menu size for the chip's kebab and the builder's three menus, which draw\n * the same rows. `w-max` OVERRIDES the shadcn content width, which pins to the\n * anchor and hides horizontal overflow, so a menu hung off a 28px icon button\n * CUT every longer row. Floor 128px, down from 224px: the rows run about 130px,\n * and five of the eight styles already floor a dropdown there (luma, maia and\n * sera sit at 192px). The 24rem cap stops a pathological label pushing the menu\n * off the side of a phone. Past it a row truncates rather than wraps, since a\n * wrapped row changes HEIGHT and would slide the destructive row under the\n * pointer: `min-w-0` lets a row shrink below its content at all (a flex child's\n * floor is its content otherwise) and the label span carries `truncate`, see\n * `FILTER_MENU_LABEL_CLASS`.\n */\nexport const FILTER_MENU_CLASS =\n  \"w-max min-w-32 max-w-[min(24rem,calc(100vw-2rem))] [&_[data-slot=dropdown-menu-item]]:min-w-0\"\n\n/**\n * What a menu row's LABEL wears, and it has to be a real span: `text-overflow`\n * needs a block container, not the anonymous flex item a bare text child is.\n * `min-w-0` so the span can shrink below its own content.\n */\nexport const FILTER_MENU_LABEL_CLASS = \"min-w-0 truncate\"\n\n/**\n * The FIELD PICKER's panel, shared by the Add filter popover and the advanced\n * row's attribute cell so one schema is never drawn at two widths. `w-auto`\n * grows to the longest row, so the 224px floor (down from 256px) only decides\n * the reported case: a flat schema of short names in a mostly empty panel.\n * Measured: 224px still clears the search input, the breadcrumb and a leaf\n * row's icon-plus-label.\n */\nexport const FILTER_FIELD_PICKER_CLASS = \"w-auto min-w-56 p-0\"\n\n/* -------------------------------------------------------------------------- */\n/*                                    Paths                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Root key for `childrenOf`; a control char cannot collide with a field id. */\nexport const FILTER_ROOT_KEY = \"\\u0000root\"\n\n/** Separator between path segments in the flat map keys. */\nconst PATH_SEPARATOR = \"\\u0000\"\n\nexport function joinFilterPath(path: readonly string[]): string {\n  return path.join(PATH_SEPARATOR)\n}\n\nexport function splitFilterPath(key: string): string[] {\n  return key === \"\" ? [] : key.split(PATH_SEPARATOR)\n}\n\n/** The joined key of a path's parent, or `FILTER_ROOT_KEY` at the top level. */\nexport function parentFilterKey(path: readonly string[]): string {\n  return path.length <= 1 ? FILTER_ROOT_KEY : joinFilterPath(path.slice(0, -1))\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Signature                                 */\n/* -------------------------------------------------------------------------- */\n\n/**\n * A content hash of the schema, used to skip a rebuild. Identity alone is\n * useless: every block and example declares `fields` as an inline literal, so a\n * memo keyed on the array misses on every parent render. Render props (`icon`,\n * `renderValue`, a component-valued `editor`) are hashed by PRESENCE only,\n * because inline JSX recreates them: swapping one's body keeps serving the\n * previous field objects, so change a structural field or give `fields` a\n * stable identity.\n */\nexport function computeFilterSchemaSignature<V, O>(\n  fields: readonly FilterField<V, O>[]\n): string {\n  const parts: string[] = []\n\n  const walk = (list: readonly FilterField<V, O>[], depth: number) => {\n    for (const field of list) {\n      parts.push(\n        depth +\n          \":\" +\n          field.id +\n          \"|\" +\n          (field.label ?? \"\") +\n          \"|\" +\n          (field.type ?? \"\") +\n          \"|\" +\n          (field.defaultOperator ?? \"\") +\n          \"|\" +\n          (field.column ?? \"\") +\n          \"|\" +\n          (field.selectable ? \"1\" : \"0\") +\n          (field.disabled ? \"1\" : \"0\") +\n          (field.icon ? \"1\" : \"0\") +\n          (field.renderValue ? \"1\" : \"0\") +\n          (field.loadOptions ? \"1\" : \"0\") +\n          (field.resolveValues ? \"1\" : \"0\") +\n          \"|\" +\n          (typeof field.editor === \"string\"\n            ? field.editor\n            : field.editor\n              ? \"fn\"\n              : \"\") +\n          \"|\" +\n          (field.keywords?.join(\",\") ?? \"\") +\n          \"|\" +\n          (field.count ?? \"\") +\n          \"|\" +\n          // Options are part of the shape, and `exclusive` rides along: it\n          // decides what a pick DOES, so turning it on must force a rebuild.\n          (field.options\n            ? field.options\n                .map(\n                  (option) =>\n                    option.value +\n                    \"~\" +\n                    option.label +\n                    (option.exclusive ? \"~x\" : \"\")\n                )\n                .join(\",\")\n            : \"\") +\n          \"|\" +\n          (Array.isArray(field.operators)\n            ? field.operators.map((operator) => operator.value).join(\",\")\n            : field.operators\n              ? \"fn\"\n              : \"\")\n      )\n      if (field.fields?.length) walk(field.fields, depth + 1)\n    }\n  }\n\n  walk(fields, 0)\n  return parts.join(\"\\n\")\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Index                                   */\n/* -------------------------------------------------------------------------- */\n\nconst EMPTY_INDEX: FilterIndex<never, never> = {\n  byPath: new Map(),\n  childrenOf: new Map(),\n  parentOf: new Map(),\n  all: [],\n  roots: [],\n  signature: \"\",\n}\n\n/**\n * Normalizes a field schema into flat maps. When `previous`'s signature\n * matches, the PREVIOUS OBJECT is returned: an equal-but-new one would leave\n * every downstream memo missing exactly as often as before. Duplicate sibling\n * ids are ignored after the first, as the cascader does for node values, and\n * `findFilterSchemaIssues` reports them in development.\n */\nexport function buildFilterIndex<V = unknown, O = unknown>(\n  fields: readonly FilterField<V, O>[],\n  previous?: FilterIndex<V, O> | null,\n  /** A signature the caller already computed, to avoid walking twice. */\n  precomputedSignature?: string\n): FilterIndex<V, O> {\n  const signature = precomputedSignature ?? computeFilterSchemaSignature(fields)\n  if (previous && previous.signature === signature) return previous\n  if (fields.length === 0) {\n    return { ...(EMPTY_INDEX as unknown as FilterIndex<V, O>), signature }\n  }\n\n  const byPath = new Map<string, FilterField<V, O>>()\n  const childrenOf = new Map<string, FilterField<V, O>[]>()\n  const parentOf = new Map<string, string>()\n  const all: { field: FilterField<V, O>; path: string[] }[] = []\n  const roots: FilterField<V, O>[] = []\n\n  const walk = (\n    list: readonly FilterField<V, O>[],\n    parentPath: string[],\n    parentKey: string\n  ) => {\n    const accepted: FilterField<V, O>[] = []\n    const seen = new Set<string>()\n\n    for (const field of list) {\n      if (seen.has(field.id)) continue\n      seen.add(field.id)\n\n      const path = [...parentPath, field.id]\n      const key = joinFilterPath(path)\n      if (byPath.has(key)) continue\n\n      byPath.set(key, field)\n      parentOf.set(key, parentKey === FILTER_ROOT_KEY ? \"\" : parentKey)\n      all.push({ field, path })\n      accepted.push(field)\n\n      if (field.fields?.length) walk(field.fields, path, key)\n    }\n\n    childrenOf.set(parentKey, accepted)\n    if (parentKey === FILTER_ROOT_KEY) roots.push(...accepted)\n  }\n\n  walk(fields, [], FILTER_ROOT_KEY)\n\n  return { byPath, childrenOf, parentOf, all, roots, signature }\n}\n\nexport function getFilterField<V, O>(\n  index: FilterIndex<V, O>,\n  path: readonly string[]\n): FilterField<V, O> | undefined {\n  return index.byPath.get(joinFilterPath(path))\n}\n\n/** The ancestor chain for a path, root first and the field itself last. */\nexport function getFilterFieldChain<V, O>(\n  index: FilterIndex<V, O>,\n  path: readonly string[]\n): FilterField<V, O>[] {\n  const chain: FilterField<V, O>[] = []\n  for (let i = 1; i <= path.length; i++) {\n    const field = index.byPath.get(joinFilterPath(path.slice(0, i)))\n    if (!field) break\n    chain.push(field)\n  }\n  return chain\n}\n\n/** Child fields of a path. Pass an empty path for the root level. */\nexport function getFilterChildren<V, O>(\n  index: FilterIndex<V, O>,\n  path: readonly string[]\n): FilterField<V, O>[] {\n  const key = path.length === 0 ? FILTER_ROOT_KEY : joinFilterPath(path)\n  return index.childrenOf.get(key) ?? []\n}\n\nexport function isFilterBranch<V, O>(field: FilterField<V, O>): boolean {\n  return Boolean(field.fields?.length)\n}\n\n/**\n * Whether a field DECLARES itself filterable on: leaves always, a branch only\n * with `selectable`. The shipped pickers ignore it, see `isFilterFieldPickable`.\n */\nexport function isFilterFieldSelectable<V, O>(\n  field: FilterField<V, O>\n): boolean {\n  if (field.disabled) return false\n  return isFilterBranch(field) ? Boolean(field.selectable) : true\n}\n\n/**\n * Whether the SHIPPED pickers may commit a field: leaves only. A row that both\n * drills in and commits cannot disambiguate a click - its chevron and child\n * count promise \"opens a list\", so the press that opened it also filtered on\n * the parent and dismissed the picker. `selectable` stays honoured by\n * `isFilterFieldSelectable` for a chrome that separates the two.\n */\nexport function isFilterFieldPickable<V, O>(field: FilterField<V, O>): boolean {\n  if (field.disabled) return false\n  return !isFilterBranch(field)\n}\n\n/** Trailing count for a branch row. */\nexport function getFilterFieldCount<V, O>(field: FilterField<V, O>): number {\n  return field.count ?? field.fields?.length ?? 0\n}\n\n/** Renders a path as \"Name > First\" using the caller's separator. */\nexport function formatFilterPath<V, O>(\n  index: FilterIndex<V, O>,\n  path: readonly string[],\n  separator: string\n): string {\n  const chain = getFilterFieldChain(index, path)\n  if (chain.length === 0) return path.join(separator)\n  return chain.map((field) => field.label).join(separator)\n}\n\n/** How a path is shortened; the cascader's own union, so the two cannot drift. */\nexport type FilterPathCollapse = CascaderCollapse\n\nexport type FilterPathSegment<V = unknown, O = unknown> =\n  | { type: \"field\"; field: FilterField<V, O> }\n  /** The run that was elided, kept so a host can surface it. */\n  | { type: \"ellipsis\"; hidden: FilterField<V, O>[] }\n\n/**\n * Shortens an ancestor chain to at most `maxSegments` names, on the cascader's\n * arithmetic so the chip's path and the builder's attribute cell cannot round\n * differently. The adapter is POSITIONAL because a `FilterField`'s `id` is\n * unique only among its siblings, so the index is the only key that survives a\n * collapser keyed on `value`. Default `\"none\"`: no upgrade shortens a path.\n */\nexport function collapseFilterPath<V, O>(\n  chain: readonly FilterField<V, O>[],\n  options: { maxSegments?: number; collapse?: FilterPathCollapse } = {}\n): FilterPathSegment<V, O>[] {\n  const segments = collapseCascaderPath(\n    chain.map((field, index) => ({ value: String(index), label: field.label })),\n    { maxSegments: options.maxSegments, collapse: options.collapse ?? \"none\" }\n  )\n  return segments.map((segment) =>\n    segment.type === \"node\"\n      ? { type: \"field\" as const, field: chain[Number(segment.node.value)] }\n      : {\n          type: \"ellipsis\" as const,\n          hidden: segment.hidden.map((node) => chain[Number(node.value)]),\n        }\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                 Combinator                                 */\n/* -------------------------------------------------------------------------- */\n\nexport type FilterCombinatorSlot = \"where\" | \"toggle\" | \"echo\"\n\n/**\n * Which of the three forms the combinator slot before rule `index` takes. A\n * group has exactly ONE combinator, so only one slot may be interactive: three\n * editable \"and\"s down a column would imply three independent choices.\n */\nexport function filterCombinatorSlot(index: number): FilterCombinatorSlot {\n  if (index === 0) return \"where\"\n  return index === 1 ? \"toggle\" : \"echo\"\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Matching                                 */\n/* -------------------------------------------------------------------------- */\n\n/** `toLocaleLowerCase`, so Turkish dotted and dotless i fold as a reader expects. */\nexport function foldFilterText(text: string): string {\n  return text.toLocaleLowerCase()\n}\n\nexport function normalizeFilterQuery(query: string): string {\n  return foldFilterText(query.trim())\n}\n\n/** Whether a field matches a normalized query, by label or keywords. */\nexport function matchesFilterQuery<V, O>(\n  field: FilterField<V, O>,\n  normalizedQuery: string\n): boolean {\n  if (normalizedQuery === \"\") return true\n  if (foldFilterText(field.label).includes(normalizedQuery)) return true\n  if (field.keywords) {\n    for (const keyword of field.keywords) {\n      if (foldFilterText(keyword).includes(normalizedQuery)) return true\n    }\n  }\n  return false\n}\n\n/**\n * Filters one level, preserving input order. Unused here like\n * `searchFilterDeep`: kept so a consumer's own picker need not re-implement the\n * fold and the keyword matching.\n */\nexport function filterFilterLevel<V, O>(\n  fields: readonly FilterField<V, O>[],\n  normalizedQuery: string\n): FilterField<V, O>[] {\n  if (normalizedQuery === \"\") return fields as FilterField<V, O>[]\n  return fields.filter((field) => matchesFilterQuery(field, normalizedQuery))\n}\n\n/**\n * Searches every SELECTABLE field at any depth, because a result the user\n * cannot pick is a dead end. Unused here - the shipped picker is the cascader\n * and delegates deep search to it - but it keeps a consumer's own picker from\n * re-implementing the fold, the keyword matching and the selectable rule.\n */\nexport function searchFilterDeep<V, O>(\n  index: FilterIndex<V, O>,\n  normalizedQuery: string,\n  limit = 200\n): { field: FilterField<V, O>; path: string[] }[] {\n  if (normalizedQuery === \"\") return []\n  const results: { field: FilterField<V, O>; path: string[] }[] = []\n  for (const entry of index.all) {\n    if (results.length >= limit) break\n    if (!isFilterFieldSelectable(entry.field)) continue\n    if (matchesFilterQuery(entry.field, normalizedQuery)) results.push(entry)\n  }\n  return results\n}\n\n/** Filters an option list by a normalized query, by label or keywords. */\nexport function filterFilterOptions<O>(\n  options: readonly FilterOption<O>[],\n  normalizedQuery: string\n): FilterOption<O>[] {\n  if (normalizedQuery === \"\") return options as FilterOption<O>[]\n  return options.filter((option) => {\n    if (foldFilterText(option.label).includes(normalizedQuery)) return true\n    if (option.keywords) {\n      for (const keyword of option.keywords) {\n        if (foldFilterText(keyword).includes(normalizedQuery)) return true\n      }\n    }\n    return false\n  })\n}\n\n/* -------------------------------------------------------------------------- */\n/*                              Exclusive options                             */\n/* -------------------------------------------------------------------------- */\n\n/**\n * The None rule, as pure algebra over two selections: pick the `exclusive`\n * option and it is the only pick, pick anything else and it goes. Written\n * against the DELTA, not the result, which is what makes it total: an empty\n * delta is a removal, including UNTICKING the exclusive row; an exclusive\n * arrival is the whole answer; an ordinary arrival drops every exclusive value,\n * restored ones included; both at once gives it to the LAST exclusive.\n * `isExclusive` is a lookup, not an array, because a query hiding the None row\n * while it stays SELECTED would answer \"not exclusive\" for the value the click\n * must clear. Never applied on read - a saved view is the consumer's data - so\n * it heals on the first ordinary pick, and only while `isExclusive` can ANSWER:\n * a None row on a `loadOptions` field belongs in the static `options`.\n */\nexport function applyFilterExclusiveSelection(\n  next: readonly string[],\n  previous: readonly string[],\n  isExclusive: (value: string) => boolean\n): string[] {\n  const held = new Set(previous)\n  const added = next.filter((value) => !held.has(value))\n  if (added.length === 0) return next as string[]\n\n  let arrived: string | null = null\n  for (const value of added) {\n    if (isExclusive(value)) arrived = value\n  }\n  if (arrived !== null) return [arrived]\n\n  const kept = next.filter((value) => !isExclusive(value))\n  // The same array when nothing was exclusive, which is nearly every call: a\n  // fresh one would commit a new value on every toggle of an ordinary row.\n  return kept.length === next.length ? (next as string[]) : kept\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                     Ids                                    */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Builds a deterministic id generator. `Date.now()` and `Math.random()`, as the\n * old `createFilter` used, give the server and the client different ids for the\n * same query, so any page shipping default filters hydrated mismatched.\n */\nexport function createFilterIdFactory(seed: string): () => string {\n  let counter = 0\n  return () => {\n    counter += 1\n    return `${seed}${counter}`\n  }\n}\n\n/* -------------------------------------------------------------------------- */\n/*                              Development checks                            */\n/* -------------------------------------------------------------------------- */\n\nconst warned = new Set<string>()\n\n/** Warns once per key. Never throws, and is a no-op in production. */\nexport function warnFilterOnce(key: string, message: string): void {\n  if (process.env.NODE_ENV === \"production\") return\n  if (warned.has(key)) return\n  warned.add(key)\n  console.warn(`[filters] ${message}`)\n}\n\n/** Clears the warn-once memory. For tests. */\nexport function resetFilterWarnings(): void {\n  warned.clear()\n}\n\nexport interface FilterSchemaIssues {\n  /** Ids that are empty, or that collide with a sibling. */\n  duplicatePaths: string[]\n  emptyIds: string[]\n  /** Branches that declare `selectable` but hold no children. */\n  emptyBranches: string[]\n  /** Fields whose `defaultOperator` is not in their operator list. */\n  unknownDefaultOperators: string[]\n}\n\n/** Reported, never thrown: a bad schema must degrade, not blank the page. */\nexport function findFilterSchemaIssues<V, O>(\n  fields: readonly FilterField<V, O>[],\n  resolveOperators: (field: FilterField<V, O>) => FilterOperator[]\n): FilterSchemaIssues {\n  const duplicatePaths: string[] = []\n  const emptyIds: string[] = []\n  const emptyBranches: string[] = []\n  const unknownDefaultOperators: string[] = []\n\n  const walk = (list: readonly FilterField<V, O>[], parentPath: string[]) => {\n    const seen = new Set<string>()\n    for (const field of list) {\n      const label = [...parentPath, field.id].join(\".\")\n      if (!field.id) emptyIds.push(label)\n      else if (seen.has(field.id)) duplicatePaths.push(label)\n      seen.add(field.id)\n\n      if (field.selectable && field.fields && field.fields.length === 0) {\n        emptyBranches.push(label)\n      }\n\n      if (field.defaultOperator) {\n        const operators = resolveOperators(field)\n        if (!operators.some((op) => op.value === field.defaultOperator)) {\n          unknownDefaultOperators.push(`${label} -> ${field.defaultOperator}`)\n        }\n      }\n\n      if (field.fields?.length) walk(field.fields, [...parentPath, field.id])\n    }\n  }\n\n  walk(fields, [])\n  return { duplicatePaths, emptyIds, emptyBranches, unknownDefaultOperators }\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-lib.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-operators.tsx",
      "content": "/**\n * filters-operators - adapted for tealmac UI from ReUI \"filters/filters-operators\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\nimport type {\n  FilterField,\n  FilterOperator,\n  FilterValueType,\n} from \"@/components/reui/filters/filters-types\"\n\n/**\n * Every operator label, keyed by value. Split from `FilterLabels`: operator\n * wording is reworded per domain, chrome copy is translated once per app.\n */\nexport type FilterOperatorLabels = Record<string, string>\n\nexport const DEFAULT_FILTER_OPERATOR_LABELS: FilterOperatorLabels = {\n  contains: \"contains\",\n  not_contains: \"does not contain\",\n  starts_with: \"starts with\",\n  ends_with: \"ends with\",\n  is: \"is\",\n  is_not: \"is not\",\n  is_any_of: \"is any of\",\n  is_none_of: \"is none of\",\n  has_any_of: \"has any of\",\n  has_all_of: \"has all of\",\n  has_none_of: \"has none of\",\n  eq: \"equals\",\n  neq: \"does not equal\",\n  gt: \"is greater than\",\n  gte: \"is greater than or equal to\",\n  lt: \"is less than\",\n  lte: \"is less than or equal to\",\n  between: \"is between\",\n  not_between: \"is not between\",\n  is_before: \"is before\",\n  is_after: \"is after\",\n  is_on_or_before: \"is on or before\",\n  is_on_or_after: \"is on or after\",\n  empty: \"is empty\",\n  not_empty: \"is not empty\",\n}\n\n/**\n * Operator catalog per value type: value, arity, inverse, labels resolved at\n * build time so translating one operator never restates the catalog. `arity`\n * of \"none\" drops the chip's value segment and the wizard's value step, in a\n * consumer's own `operators` array as much as in this catalog.\n */\nconst CATALOG: Record<\n  FilterValueType,\n  { value: string; arity?: FilterOperator[\"arity\"]; inverse?: string }[]\n> = {\n  text: [\n    { value: \"contains\", inverse: \"not_contains\" },\n    { value: \"not_contains\", inverse: \"contains\" },\n    { value: \"starts_with\" },\n    { value: \"ends_with\" },\n    { value: \"is\", inverse: \"is_not\" },\n    { value: \"is_not\", inverse: \"is\" },\n    { value: \"empty\", arity: \"none\", inverse: \"not_empty\" },\n    { value: \"not_empty\", arity: \"none\", inverse: \"empty\" },\n  ],\n  number: [\n    { value: \"eq\", inverse: \"neq\" },\n    { value: \"neq\", inverse: \"eq\" },\n    { value: \"gt\", inverse: \"lte\" },\n    { value: \"gte\", inverse: \"lt\" },\n    { value: \"lt\", inverse: \"gte\" },\n    { value: \"lte\", inverse: \"gt\" },\n    { value: \"between\", arity: \"range\", inverse: \"not_between\" },\n    { value: \"not_between\", arity: \"range\", inverse: \"between\" },\n    { value: \"empty\", arity: \"none\", inverse: \"not_empty\" },\n    { value: \"not_empty\", arity: \"none\", inverse: \"empty\" },\n  ],\n  range: [\n    { value: \"between\", arity: \"range\", inverse: \"not_between\" },\n    { value: \"not_between\", arity: \"range\", inverse: \"between\" },\n    { value: \"empty\", arity: \"none\", inverse: \"not_empty\" },\n    { value: \"not_empty\", arity: \"none\", inverse: \"empty\" },\n  ],\n  select: [\n    { value: \"is\", inverse: \"is_not\" },\n    { value: \"is_not\", inverse: \"is\" },\n    { value: \"is_any_of\", arity: \"many\", inverse: \"is_none_of\" },\n    { value: \"is_none_of\", arity: \"many\", inverse: \"is_any_of\" },\n    { value: \"empty\", arity: \"none\", inverse: \"not_empty\" },\n    { value: \"not_empty\", arity: \"none\", inverse: \"empty\" },\n  ],\n  multiselect: [\n    { value: \"has_any_of\", arity: \"many\", inverse: \"has_none_of\" },\n    { value: \"has_all_of\", arity: \"many\" },\n    { value: \"has_none_of\", arity: \"many\", inverse: \"has_any_of\" },\n    { value: \"empty\", arity: \"none\", inverse: \"not_empty\" },\n    { value: \"not_empty\", arity: \"none\", inverse: \"empty\" },\n  ],\n  boolean: [\n    { value: \"is\", inverse: \"is_not\" },\n    { value: \"is_not\", inverse: \"is\" },\n    { value: \"empty\", arity: \"none\", inverse: \"not_empty\" },\n    { value: \"not_empty\", arity: \"none\", inverse: \"empty\" },\n  ],\n}\n\nexport const DEFAULT_FILTER_VALUE_TYPE: FilterValueType = \"text\"\n\n/**\n * Builds the operator catalog for one set of labels. Callers memoize on the\n * label object: the old primitive built its equivalent inside\n * `getOperatorsForField`, keyed on a `values` array that was fresh after every\n * filter update, so every miss reallocated four arrays of 27 objects each.\n */\nexport function createFilterOperators(\n  labels: FilterOperatorLabels\n): Record<FilterValueType, FilterOperator[]> {\n  const built = {} as Record<FilterValueType, FilterOperator[]>\n  for (const type of Object.keys(CATALOG) as FilterValueType[]) {\n    built[type] = CATALOG[type].map((entry) => ({\n      value: entry.value,\n      label: labels[entry.value] ?? entry.value,\n      arity: entry.arity ?? \"one\",\n      inverse: entry.inverse,\n    }))\n  }\n  return built\n}\n\nexport const DEFAULT_FILTER_OPERATORS: Record<\n  FilterValueType,\n  FilterOperator[]\n> = createFilterOperators(DEFAULT_FILTER_OPERATOR_LABELS)\n\n/**\n * The operators for a field: its own `operators` wins, array or function,\n * otherwise the catalog entry for its `type`. No implicit select to multiselect\n * promotion by selection count: that changed the list as the user picked.\n */\nexport function resolveFilterOperators<V, O>(\n  field: FilterField<V, O>,\n  catalog: Record<FilterValueType, FilterOperator[]> = DEFAULT_FILTER_OPERATORS\n): FilterOperator[] {\n  if (typeof field.operators === \"function\") return field.operators(field)\n  if (field.operators) return field.operators\n  return catalog[field.type ?? DEFAULT_FILTER_VALUE_TYPE] ?? catalog.text\n}\n\nexport function visibleFilterOperators(\n  operators: readonly FilterOperator[]\n): FilterOperator[] {\n  return operators.filter((operator) => !operator.hidden)\n}\n\nexport function getFilterOperator(\n  operators: readonly FilterOperator[],\n  value: string | null | undefined\n): FilterOperator | undefined {\n  if (!value) return undefined\n  return operators.find((operator) => operator.value === value)\n}\n\nexport function getFilterArity(\n  operator: FilterOperator | undefined\n): FilterOperator[\"arity\"] {\n  return operator?.arity ?? \"one\"\n}\n\nexport function operatorTakesValue(\n  operator: FilterOperator | undefined\n): boolean {\n  return getFilterArity(operator) !== \"none\"\n}\n\n/**\n * The operator a field starts with: `defaultOperator` when it names one the\n * field offers, otherwise the first visible operator. Falling back rather than\n * trusting the schema keeps the rule out of a state its own list cannot show.\n */\nexport function getDefaultFilterOperator<V, O>(\n  field: FilterField<V, O>,\n  operators: readonly FilterOperator[]\n): string | null {\n  if (field.defaultOperator) {\n    const named = getFilterOperator(operators, field.defaultOperator)\n    if (named) return named.value\n  }\n  const visible = visibleFilterOperators(operators)\n  return visible[0]?.value ?? operators[0]?.value ?? null\n}\n\n/**\n * Negating a rule: swap to the declared `inverse` so the chip reads \"does not\n * contain\", else toggle `negated` so Negate still works without an inverse.\n */\nexport function negateFilterOperator(\n  operator: FilterOperator | undefined,\n  operators: readonly FilterOperator[],\n  negated: boolean | undefined\n): { operator: string | null; negated: boolean } {\n  if (operator?.inverse) {\n    const inverse = getFilterOperator(operators, operator.inverse)\n    if (inverse) return { operator: inverse.value, negated: Boolean(negated) }\n  }\n  return { operator: operator?.value ?? null, negated: !negated }\n}\n\n/**\n * Reshapes a value when arity changes: widening \"is\" to \"is any of\" keeps what\n * the user picked, narrowing keeps the first of them, `\"none\"` always drops it.\n */\nexport function coerceFilterValue(\n  value: unknown,\n  from: FilterOperator | undefined,\n  to: FilterOperator | undefined\n): unknown {\n  const nextArity = getFilterArity(to)\n  if (nextArity === \"none\") return undefined\n  if (value === undefined || value === null) return value\n\n  const previousArity = getFilterArity(from)\n  if (previousArity === nextArity) return value\n\n  const asArray = Array.isArray(value) ? value : [value]\n\n  if (nextArity === \"many\") return asArray\n  if (nextArity === \"one\") return asArray[0]\n  if (nextArity === \"range\") {\n    return [asArray[0], asArray[1]] as [unknown, unknown]\n  }\n  return value\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-operators.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-query.tsx",
      "content": "/**\n * filters-query - adapted for tealmac UI from ReUI \"filters/filters-query\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\nimport type {\n  FilterCombinator,\n  FilterGroupNode,\n  FilterIssue,\n  FilterNode,\n  FilterOperator,\n  FilterQuery,\n  FilterRule,\n} from \"@/components/reui/filters/filters-types\"\n\nexport function isFilterRule<V>(node: FilterNode<V>): node is FilterRule<V> {\n  return node.type === \"rule\"\n}\n\nexport function isFilterGroup<V>(\n  node: FilterNode<V>\n): node is FilterGroupNode<V> {\n  return node.type === \"group\"\n}\n\n/**\n * A rule. `id` is passed in, never generated here: a non-deterministic value in\n * a pure function broke hydration. Callers use `createFilterIdFactory`.\n */\nexport function createFilterRule<V = unknown>(input: {\n  id: string\n  path: string[]\n  operator: string\n  value?: V\n  negated?: boolean\n}): FilterRule<V> {\n  const rule: FilterRule<V> = {\n    id: input.id,\n    type: \"rule\",\n    path: input.path,\n    operator: input.operator,\n    value: input.value,\n  }\n  if (input.negated) rule.negated = true\n  return rule\n}\n\nexport function createFilterGroup<V = unknown>(input: {\n  id: string\n  combinator?: FilterCombinator\n  rules?: FilterNode<V>[]\n}): FilterGroupNode<V> {\n  return {\n    id: input.id,\n    type: \"group\",\n    combinator: input.combinator ?? \"and\",\n    rules: input.rules ?? [],\n  }\n}\n\n/** An empty query. The root is always a group, never a bare array. */\nexport function createFilterQuery<V = unknown>(\n  rules: FilterNode<V>[] = [],\n  combinator: FilterCombinator = \"and\",\n  id = \"root\"\n): FilterQuery<V> {\n  return { id, type: \"group\", combinator, rules }\n}\n\n/** Every rule in the tree, depth first. Groups are flattened away. */\nexport function flattenFilterRules<V>(query: FilterQuery<V>): FilterRule<V>[] {\n  const out: FilterRule<V>[] = []\n  const walk = (node: FilterNode<V>) => {\n    if (isFilterRule(node)) {\n      out.push(node)\n      return\n    }\n    for (const child of node.rules) walk(child)\n  }\n  walk(query)\n  return out\n}\n\n/**\n * One rule, flattened for a predicate. `values` is always an array even though\n * `FilterRule.value` is singular, so no caller re-derives arity.\n */\nexport interface FilterCondition {\n  /** Full field path, `[\"name\", \"first\"]`. */\n  path: string[]\n  /** First path segment, for the common flat-schema case. */\n  field: string\n  operator: string\n  /** `[]` for an operator that takes no value. */\n  values: unknown[]\n  negated: boolean\n}\n\n/**\n * Whether a rule says anything yet. A rule exists as soon as an attribute is\n * picked, so `operator: \"\"` is a real state: `flattenFilterConditions` leaves\n * it out, `countFilterRules` still counts it, and `collectFilterIssues` reports\n * it as `missing-operator`.\n */\nexport function isFilterRuleComplete<V>(rule: FilterRule<V>): boolean {\n  return rule.operator !== \"\"\n}\n\n/**\n * Flattens a query to conditions. Lossy: safe only when the query is flat or\n * every group shares the root's combinator. Read `query.combinator` and walk\n * the tree yourself for anything else. Incomplete rules are left out.\n */\nexport function flattenFilterConditions<V>(\n  query: FilterQuery<V>\n): FilterCondition[] {\n  return flattenFilterRules(query)\n    .filter(isFilterRuleComplete)\n    .map((rule) => ({\n      path: rule.path,\n      field: rule.path[0],\n      operator: rule.operator,\n      values:\n        rule.value === undefined || rule.value === null\n          ? []\n          : Array.isArray(rule.value)\n            ? (rule.value as unknown[])\n            : [rule.value],\n      negated: Boolean(rule.negated),\n    }))\n}\n\n/** How many rules the query holds, at any depth. */\nexport function countFilterRules<V>(query: FilterQuery<V>): number {\n  let count = 0\n  const walk = (node: FilterNode<V>) => {\n    if (isFilterRule(node)) {\n      count += 1\n      return\n    }\n    for (const child of node.rules) walk(child)\n  }\n  walk(query)\n  return count\n}\n\n/** Whether the query would match everything. */\nexport function isFilterQueryEmpty<V>(query: FilterQuery<V>): boolean {\n  return countFilterRules(query) === 0\n}\n\n/**\n * How an arity is answered for one rule. The caller resolves it, since arity\n * lives on the FIELD's operator list. `null` is a rule it cannot judge.\n */\nexport type FilterArityResolver<V> = (\n  rule: FilterRule<V>\n) => FilterOperator[\"arity\"] | null\n\n/** Runs a field's own `validate`. A resolver like `arityOf`: no schema here. */\nexport type FilterValidateResolver<V> = (\n  rule: FilterRule<V>\n) => string | null | undefined | false\n\n/** A value slot the user has not filled in. `false` and `0` are values. */\nfunction isBlankFilterValue(value: unknown): boolean {\n  return value === undefined || value === null || value === \"\"\n}\n\n/**\n * Compares two range bounds, or gives up. Numbers, dates and ISO strings only:\n * inventing an order for a range of colour names would flag a correct filter as\n * reversed. `Date.parse` must parse BOTH strings before they are compared.\n */\nfunction compareFilterBounds(from: unknown, to: unknown): number | null {\n  if (typeof from === \"number\" && typeof to === \"number\") {\n    return Number.isNaN(from) || Number.isNaN(to) ? null : from - to\n  }\n  if (from instanceof Date && to instanceof Date) {\n    const a = from.getTime()\n    const b = to.getTime()\n    return Number.isNaN(a) || Number.isNaN(b) ? null : a - b\n  }\n  if (typeof from === \"string\" && typeof to === \"string\") {\n    const a = Date.parse(from)\n    const b = Date.parse(to)\n    return Number.isNaN(a) || Number.isNaN(b) ? null : a - b\n  }\n  return null\n}\n\n/**\n * Every reason a query cannot be run as written, in document order: the five\n * ways this builder can hold a condition that SILENTLY does the wrong thing.\n * `missing-operator` and `empty-group` carry no predicate and are dropped by\n * `flattenFilterConditions`; `missing-value` reaches the consumer with a\n * `values` array that is empty or all blank, which most backends read as\n * \"match nothing\"; `incomplete-range` is the same for a range and often\n * arrives with one bound FILLED, so an emptiness check will not catch it;\n * `reversed-range` is legal and matches nothing anywhere. A group of exactly\n * ONE node is NOT an issue (it is what \"Convert to group\" produces), and the\n * root is exempt from `empty-group`.\n */\nexport function collectFilterIssues<V>(\n  query: FilterQuery<V>,\n  arityOf: FilterArityResolver<V>,\n  validateOf?: FilterValidateResolver<V>\n): FilterIssue[] {\n  const issues: FilterIssue[] = []\n\n  const visit = (group: FilterGroupNode<V>, isRoot: boolean) => {\n    if (!isRoot && group.rules.length === 0) {\n      issues.push({\n        nodeId: group.id,\n        column: \"group\",\n        reason: \"empty-group\",\n      })\n    }\n\n    for (const child of group.rules) {\n      if (isFilterGroup(child)) {\n        visit(child, false)\n        continue\n      }\n      // Asked FIRST: `null` means the caller cannot judge this rule at all, so\n      // even `missing-operator` would point at a control that is not on screen.\n      const arity = arityOf(child)\n      if (arity === null) continue\n\n      if (!isFilterRuleComplete(child)) {\n        issues.push({\n          nodeId: child.id,\n          column: \"operator\",\n          reason: \"missing-operator\",\n        })\n        continue\n      }\n\n      if (arity === \"none\") continue\n\n      const values =\n        child.value === undefined || child.value === null\n          ? []\n          : Array.isArray(child.value)\n            ? (child.value as unknown[])\n            : [child.value]\n\n      if (arity === \"range\") {\n        if (\n          values.length < 2 ||\n          isBlankFilterValue(values[0]) ||\n          isBlankFilterValue(values[1])\n        ) {\n          issues.push({\n            nodeId: child.id,\n            column: \"value\",\n            reason: \"incomplete-range\",\n          })\n          continue\n        }\n        const order = compareFilterBounds(values[0], values[1])\n        if (order !== null && order > 0) {\n          issues.push({\n            nodeId: child.id,\n            column: \"value\",\n            reason: \"reversed-range\",\n          })\n        }\n        continue\n      }\n\n      // `many` and `one` collapse here: both are unsatisfied by an empty list,\n      // and `one` normalises to a single-element list above.\n      if (values.length === 0 || values.every(isBlankFilterValue)) {\n        issues.push({\n          nodeId: child.id,\n          column: \"value\",\n          reason: \"missing-value\",\n        })\n        continue\n      }\n\n      // LAST, and only on a rule the primitive is already happy with: stacking\n      // a second message on one cell breaks the one-issue-per-node shape.\n      const message = validateOf?.(child)\n      if (message) {\n        issues.push({\n          nodeId: child.id,\n          column: \"value\",\n          reason: \"custom\",\n          message,\n        })\n      }\n    }\n  }\n\n  visit(query, true)\n  return issues\n}\n\n/** Locates a node and its parent. Returns null when the id is unknown. */\nexport function findFilterNode<V>(\n  query: FilterQuery<V>,\n  id: string\n): {\n  node: FilterNode<V>\n  parent: FilterGroupNode<V> | null\n  index: number\n} | null {\n  if (query.id === id) return { node: query, parent: null, index: -1 }\n\n  const walk = (\n    group: FilterGroupNode<V>\n  ): {\n    node: FilterNode<V>\n    parent: FilterGroupNode<V>\n    index: number\n  } | null => {\n    for (let i = 0; i < group.rules.length; i++) {\n      const child = group.rules[i]\n      if (child.id === id) return { node: child, parent: group, index: i }\n      if (isFilterGroup(child)) {\n        const found = walk(child)\n        if (found) return found\n      }\n    }\n    return null\n  }\n\n  return walk(query)\n}\n\n/** The rule with this id, or null when the id names a group or is unknown. */\nexport function findFilterRule<V>(\n  query: FilterQuery<V>,\n  id: string\n): FilterRule<V> | null {\n  const found = findFilterNode(query, id)\n  if (!found || !isFilterRule(found.node)) return null\n  return found.node\n}\n\n/**\n * Rebuilds the tree, applying `transform` to the group holding `id`. An\n * unchanged subtree comes back BY IDENTITY, so `React.memo` holds for all but\n * the moved chip. Tests assert it with `toBe`. `removeFilterNode` and\n * `detachFilterNode` drop children rather than replace a group, so they\n * hand-roll the same identity-preserving walk.\n */\nfunction rewriteGroup<V>(\n  group: FilterGroupNode<V>,\n  shouldRewrite: (group: FilterGroupNode<V>) => boolean,\n  transform: (group: FilterGroupNode<V>) => FilterGroupNode<V>\n): FilterGroupNode<V> {\n  if (shouldRewrite(group)) return transform(group)\n\n  let changed = false\n  const rules = group.rules.map((child) => {\n    if (!isFilterGroup(child)) return child\n    const next = rewriteGroup(child, shouldRewrite, transform)\n    if (next !== child) changed = true\n    return next\n  })\n\n  return changed ? { ...group, rules } : group\n}\n\n/** Replaces a rule's fields. Unknown ids return the query unchanged. */\nexport function updateFilterRule<V>(\n  query: FilterQuery<V>,\n  id: string,\n  updates: Partial<Omit<FilterRule<V>, \"id\" | \"type\">>\n): FilterQuery<V> {\n  return rewriteGroup(\n    query,\n    (group) =>\n      group.rules.some((child) => child.id === id && isFilterRule(child)),\n    (group) => ({\n      ...group,\n      rules: group.rules.map((child) =>\n        child.id === id && isFilterRule(child)\n          ? { ...child, ...updates }\n          : child\n      ),\n    })\n  ) as FilterQuery<V>\n}\n\n/**\n * Removes a node, plus any group it empties, all the way up (not the root): an\n * empty group is invisible in the flat UI yet still compiles to parentheses.\n */\nexport function removeFilterNode<V>(\n  query: FilterQuery<V>,\n  id: string\n): FilterQuery<V> {\n  const prune = (group: FilterGroupNode<V>): FilterGroupNode<V> => {\n    let changed = false\n    const rules: FilterNode<V>[] = []\n\n    for (const child of group.rules) {\n      if (child.id === id) {\n        changed = true\n        continue\n      }\n      if (isFilterGroup(child)) {\n        const next = prune(child)\n        if (next !== child) changed = true\n        if (next.rules.length === 0) continue\n        rules.push(next)\n        continue\n      }\n      rules.push(child)\n    }\n\n    return changed ? { ...group, rules } : group\n  }\n\n  return prune(query) as FilterQuery<V>\n}\n\n/** Appends a node to a group, defaulting to the root. */\nexport function insertFilterNode<V>(\n  query: FilterQuery<V>,\n  node: FilterNode<V>,\n  parentId?: string,\n  index?: number\n): FilterQuery<V> {\n  const targetId = parentId ?? query.id\n  return rewriteGroup(\n    query,\n    (group) => group.id === targetId,\n    (group) => {\n      const rules = [...group.rules]\n      const at =\n        index === undefined\n          ? rules.length\n          : Math.max(0, Math.min(index, rules.length))\n      rules.splice(at, 0, node)\n      return { ...group, rules }\n    }\n  ) as FilterQuery<V>\n}\n\n/**\n * A deep copy under fresh ids, the whole way down: children keeping their old\n * ids would give two live nodes one id, and every lookup here is by id.\n */\nfunction cloneFilterNode<V>(\n  node: FilterNode<V>,\n  nextId: () => string\n): FilterNode<V> {\n  return isFilterRule(node)\n    ? { ...node, id: nextId() }\n    : {\n        ...node,\n        id: nextId(),\n        rules: node.rules.map((child) => cloneFilterNode(child, nextId)),\n      }\n}\n\n/** Copies a node in beside the original. */\nexport function duplicateFilterNode<V>(\n  query: FilterQuery<V>,\n  id: string,\n  nextId: () => string\n): FilterQuery<V> {\n  const found = findFilterNode(query, id)\n  if (!found || !found.parent) return query\n\n  return insertFilterNode(\n    query,\n    cloneFilterNode(found.node, nextId),\n    found.parent.id,\n    found.index + 1\n  )\n}\n\nexport function setFilterCombinator<V>(\n  query: FilterQuery<V>,\n  groupId: string,\n  combinator: FilterCombinator\n): FilterQuery<V> {\n  return rewriteGroup(\n    query,\n    (group) => group.id === groupId,\n    (group) =>\n      group.combinator === combinator ? group : { ...group, combinator }\n  ) as FilterQuery<V>\n}\n\nexport function toggleFilterCombinator<V>(\n  query: FilterQuery<V>,\n  groupId: string\n): FilterQuery<V> {\n  const found = findFilterNode(query, groupId)\n  if (!found || !isFilterGroup(found.node)) return query\n  return setFilterCombinator(\n    query,\n    groupId,\n    found.node.combinator === \"and\" ? \"or\" : \"and\"\n  )\n}\n\n/** Moves a node within its own group. Out of range moves are no-ops. */\nexport function moveFilterNode<V>(\n  query: FilterQuery<V>,\n  id: string,\n  delta: number\n): FilterQuery<V> {\n  const found = findFilterNode(query, id)\n  if (!found || !found.parent) return query\n\n  const from = found.index\n  const to = from + delta\n  if (to < 0 || to >= found.parent.rules.length || delta === 0) return query\n\n  return rewriteGroup(\n    query,\n    (group) => group.id === found.parent!.id,\n    (group) => {\n      const rules = [...group.rules]\n      const [moved] = rules.splice(from, 1)\n      rules.splice(to, 0, moved)\n      return { ...group, rules }\n    }\n  ) as FilterQuery<V>\n}\n\n/** Whether `id` names `node` itself or anything beneath it. */\nfunction containsFilterNode<V>(node: FilterNode<V>, id: string): boolean {\n  if (node.id === id) return true\n  if (isFilterRule(node)) return false\n  return node.rules.some((child) => containsFilterNode(child, id))\n}\n\n/**\n * Removes a node WITHOUT pruning what it empties. A move cannot reuse\n * `removeFilterNode`: it would delete the group the drop is aimed at.\n */\nfunction detachFilterNode<V>(\n  group: FilterGroupNode<V>,\n  id: string\n): FilterGroupNode<V> {\n  let changed = false\n  const rules: FilterNode<V>[] = []\n\n  for (const child of group.rules) {\n    if (child.id === id) {\n      changed = true\n      continue\n    }\n    if (isFilterGroup(child)) {\n      const next = detachFilterNode(child, id)\n      if (next !== child) changed = true\n      rules.push(next)\n      continue\n    }\n    rules.push(child)\n  }\n\n  return changed ? { ...group, rules } : group\n}\n\n/**\n * Moves a node into another group, at an index: the cross-parent form of\n * `moveFilterNode`, which only reorders within one parent. Refuses a group into\n * itself or a descendant, which would leave a cycle, and refuses the root.\n */\nexport function moveFilterNodeTo<V>(\n  query: FilterQuery<V>,\n  id: string,\n  parentId: string,\n  index: number\n): FilterQuery<V> {\n  const found = findFilterNode(query, id)\n  if (!found || !found.parent) return query\n  if (containsFilterNode(found.node, parentId)) return query\n\n  const destination = findFilterNode(query, parentId)\n  if (!destination || !isFilterGroup(destination.node)) return query\n\n  // Within one parent the node's own slot disappears when it detaches, so\n  // indexes after it shift down by one: without this a drag down is a no-op.\n  const sameParent = found.parent.id === parentId\n  const target = sameParent && found.index < index ? index - 1 : index\n  if (sameParent && target === found.index) return query\n\n  return insertFilterNode(\n    detachFilterNode(query, id),\n    found.node,\n    parentId,\n    target\n  )\n}\n\n/**\n * Copies a node into a group at a position: the Alt path of the drag layer. Not\n * `duplicateFilterNode` then `moveFilterNodeTo`, which emits two queries for one\n * gesture and needs the id the first step minted and never returned. The clone\n * is taken BEFORE the insert, so copying a group into itself stays finite.\n */\nexport function copyFilterNodeTo<V>(\n  query: FilterQuery<V>,\n  id: string,\n  parentId: string,\n  index: number,\n  nextId: () => string\n): FilterQuery<V> {\n  const found = findFilterNode(query, id)\n  if (!found || !found.parent) return query\n\n  const destination = findFilterNode(query, parentId)\n  if (!destination || !isFilterGroup(destination.node)) return query\n\n  return insertFilterNode(\n    query,\n    cloneFilterNode(found.node, nextId),\n    parentId,\n    index\n  )\n}\n\n/**\n * Wraps a node in a new group: the \"Wrap in condition group\" action, and the\n * keyboard path to nesting for a user who cannot drag.\n */\nexport function wrapFilterNodeInGroup<V>(\n  query: FilterQuery<V>,\n  id: string,\n  groupId: string,\n  combinator: FilterCombinator = \"or\"\n): FilterQuery<V> {\n  const found = findFilterNode(query, id)\n  if (!found || !found.parent) return query\n\n  return rewriteGroup(\n    query,\n    (group) => group.id === found.parent!.id,\n    (group) => ({\n      ...group,\n      rules: group.rules.map((child) =>\n        child.id === id\n          ? createFilterGroup<V>({ id: groupId, combinator, rules: [child] })\n          : child\n      ),\n    })\n  ) as FilterQuery<V>\n}\n\n/**\n * Dissolves a group into its parent, splicing its rules in at the position the\n * group held so wrap and unwrap round-trip. The root, a rule id and an unknown\n * id each return the query unchanged.\n */\nexport function unwrapFilterGroup<V>(\n  query: FilterQuery<V>,\n  groupId: string\n): FilterQuery<V> {\n  if (query.id === groupId) return query\n  const found = findFilterNode(query, groupId)\n  if (!found || !found.parent || !isFilterGroup(found.node)) return query\n\n  const dissolved = found.node\n  return rewriteGroup(\n    query,\n    (group) => group.id === found.parent!.id,\n    (group) => {\n      const rules = [...group.rules]\n      rules.splice(found.index, 1, ...dissolved.rules)\n      return { ...group, rules }\n    }\n  ) as FilterQuery<V>\n}\n\n/** Empties the query, keeping the root's identity fields. */\nexport function clearFilterQuery<V>(query: FilterQuery<V>): FilterQuery<V> {\n  return query.rules.length === 0 ? query : { ...query, rules: [] }\n}\n\n/**\n * Drops empty groups and collapses a group whose only child is a group. Not\n * automatic: a user mid-edit may hold an almost-empty group. Call on persist.\n */\nexport function pruneFilterQuery<V>(query: FilterQuery<V>): FilterQuery<V> {\n  const prune = (node: FilterNode<V>): FilterNode<V> | null => {\n    if (isFilterRule(node)) return node\n\n    const rules: FilterNode<V>[] = []\n    for (const child of node.rules) {\n      const next = prune(child)\n      if (next) rules.push(next)\n    }\n\n    if (rules.length === 0) return null\n    if (rules.length === 1 && isFilterGroup(rules[0])) return rules[0]\n    return { ...node, rules }\n  }\n\n  const rules: FilterNode<V>[] = []\n  for (const child of query.rules) {\n    const next = prune(child)\n    if (next) rules.push(next)\n  }\n  return { ...query, rules }\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-query.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters-types.tsx",
      "content": "/**\n * filters-types - adapted for tealmac UI from ReUI \"filters/filters-types\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n// Title: Filters\n// Description: Stepped filter builder with nested fields, popover value editors and a boolean query tree.\n\nimport type * as React from \"react\"\n\n/* -------------------------------------------------------------------------- */\n/*                                 Query tree                                 */\n/* -------------------------------------------------------------------------- */\n\nexport type FilterCombinator = \"and\" | \"or\"\n\n/**\n * One condition. `path` maps one to one onto the cascader's `details.path`, so\n * a field selection commits untranslated. `value` is SINGULAR and the\n * operator's `arity` decides its shape: `\"many\"` holds an array, `\"range\"` a\n * tuple, `\"none\"` undefined.\n */\nexport interface FilterRule<V = unknown> {\n  id: string\n  type: \"rule\"\n  /** Field path, root first. `[\"name\", \"first\"]` for a nested attribute. */\n  path: string[]\n  operator: string\n  value: V | undefined\n  /** Flips the meaning in place. Set by Negate when there is no `inverse`. */\n  negated?: boolean\n}\n\n/** Rules under one combinator; nests, so nesting is never a later break. */\nexport interface FilterGroupNode<V = unknown> {\n  id: string\n  type: \"group\"\n  combinator: FilterCombinator\n  rules: FilterNode<V>[]\n}\n\nexport type FilterNode<V = unknown> = FilterRule<V> | FilterGroupNode<V>\n\n/** A whole query. Always a group, so flat and nested are one code path. */\nexport type FilterQuery<V = unknown> = FilterGroupNode<V>\n\nexport type FilterChangeReason =\n  | \"add\"\n  | \"update\"\n  | \"remove\"\n  | \"duplicate\"\n  | \"negate\"\n  | \"reorder\"\n  | \"combinator\"\n  | \"clear\"\n\n/** Second argument to `onQueryChange`, so nobody has to diff two trees. */\nexport interface FilterChangeDetails<V = unknown, O = unknown> {\n  reason: FilterChangeReason\n  /** The rule that changed, or null for whole-query changes like `clear`. */\n  rule: FilterRule<V> | null\n  /** The field the rule points at, resolved. Null when the path is unknown. */\n  field: FilterField<V, O> | null\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Operators                                 */\n/* -------------------------------------------------------------------------- */\n\n/**\n * How many values an operator takes. Answers \"does this need a value editor\"\n * for every operator, a consumer's own included, in place of the hardcoded\n * `operator === \"empty\"` checks it replaced.\n */\nexport type FilterOperatorArity = \"none\" | \"one\" | \"many\" | \"range\"\n\nexport interface FilterOperator {\n  value: string\n  label: string\n  /** Defaults to `\"one\"`. */\n  arity?: FilterOperatorArity\n  /** The opposite operator. Negate flips to it, else sets `rule.negated`. */\n  inverse?: string\n  /** Hidden from the operator list but still valid in a restored query. */\n  hidden?: boolean\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Fields                                   */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Which built-in editor a field uses by DEFAULT: `editor` overrides it, and an\n * operator may override both. No date type on purpose - every product wants a\n * different date control, and a built-in one would add a calendar dependency to\n * every install, so a date ships as an `editor`.\n */\nexport type FilterValueType =\n  \"text\" | \"number\" | \"range\" | \"select\" | \"multiselect\" | \"boolean\"\n\nexport interface FilterOption<O = unknown> {\n  value: string\n  label: string\n  icon?: React.ReactNode\n  description?: string\n  keywords?: string[]\n  disabled?: boolean\n  /**\n   * The row that means NONE OF THE ABOVE: Unassigned, No label, No due date.\n   * Picking it clears every other pick and picking anything else clears it, and\n   * it is drawn apart under a rule of its own, because a list that wipes a\n   * selection must not look like one that does not; hide that line with\n   * `\"[&_[data-slot=filter-menu-divider]]:hidden\"`. Applied under EVERY\n   * operator, negative ones included. The value must be RESOLVABLE, since the\n   * rule runs through the option service: an option that exists only in an\n   * unfetched `loadOptions` page is invisible to it.\n   */\n  exclusive?: boolean\n  /** Arbitrary payload, carried untouched through every render callback. */\n  data?: O\n}\n\nexport interface FilterLoadContext {\n  /** Aborted when the query changes, the editor closes, or a load supersedes. */\n  signal: AbortSignal\n  cursor?: string\n}\n\n/** Result of `loadOptions`, or a bare array. Shape-locked to the cascader. */\nexport interface FilterLoadResult<O = unknown> {\n  items: FilterOption<O>[]\n  nextCursor?: string\n  /** Defaults to whether `nextCursor` was supplied. */\n  hasMore?: boolean\n}\n\n/** A field, or a branch. A group is a field with `fields`, not `selectable`. */\nexport interface FilterField<V = unknown, O = unknown> {\n  /** Stable id. Unique among its siblings; the full path must be unique. */\n  id: string\n  label: string\n  icon?: React.ReactNode\n  description?: string\n  keywords?: string[]\n  /** Trailing count. Defaults to known children; set it when they are lazy. */\n  count?: number\n  fields?: FilterField<V, O>[]\n  /** Whether a BRANCH is itself filterable. Leaves always are. */\n  selectable?: boolean\n  disabled?: boolean\n\n  type?: FilterValueType\n  options?: FilterOption<O>[]\n  /** Async options, paged via `cursor`. Any `options` also seed the cache. */\n  loadOptions?: (\n    query: string,\n    context: FilterLoadContext\n  ) => FilterOption<O>[] | Promise<FilterOption<O>[] | FilterLoadResult<O>>\n  /** Resolves stored values the loader never returned, for restored chips. */\n  resolveValues?: (\n    values: string[]\n  ) => FilterOption<O>[] | Promise<FilterOption<O>[]>\n\n  /** Operators for this field. Falls back to the catalog for its `type`. */\n  operators?:\n    FilterOperator[] | ((field: FilterField<V, O>) => FilterOperator[])\n  /**\n   * The operator this field FALLS BACK to, not a way to preselect one. Both\n   * create paths deliberately start a rule on `operator: \"\"` so the condition\n   * menu opens with nothing chosen, so this is read when an existing rule\n   * changes field, and it is the value `FilterFieldPicker` hands to `onSelect`.\n   * Ignored, with a dev warning, when it names an operator the field does not\n   * offer; the first visible operator wins instead.\n   */\n  defaultOperator?: string\n\n  /** Overrides the editor chosen from `type`. See `FilterEditorProps`. */\n  editor?: FilterEditorRef<V, O>\n  renderValue?: (context: FilterValueDisplayContext<V, O>) => React.ReactNode\n  /** The value as PLAIN TEXT for a11y; the default is `String(value)`. */\n  valueText?: (context: FilterValueDisplayContext<V, O>) => string\n\n  /** Placeholder for the value editor's input, or an option list's search. */\n  placeholder?: string\n  /** SHOWS the search box (default true). Off keeps it, hidden: it owns focus. */\n  searchable?: boolean\n  /**\n   * Whether an option-backed editor STACKS the picks at the top of its list.\n   * Off by default, because a short closed list is read as a whole and lifting\n   * a row out of a memorised order costs more than it buys. The partition is\n   * taken LIVE unless `sortSelected: \"snapshot\"`, so ticking a row moves the\n   * rows below it and the highlight is carried across by VALUE. Exclusive\n   * options never join the stack; they are grouped by ROLE.\n   */\n  pinSelected?: boolean\n  /**\n   * How an option list is ordered INSIDE each group, plus WHEN the partition is\n   * taken under `pinSelected`. With pinning off there is no partition, so\n   * `\"snapshot\"` is the same thing as `\"none\"`.\n   *\n   * - `\"none\"` (default) keeps declaration order. Not alphabetical, because\n   *   option order is usually semantic (To do, In progress, Done).\n   * - `\"label\"` sorts with `localeCompare`, so \"Ålesund\" files next to\n   *   \"Alesund\" rather than after \"Zurich\".\n   * - `\"snapshot\"` keeps declaration order too, and freezes the partition as\n   *   the menu opened it: a steady pointer target where the other two re-pin\n   *   live.\n   */\n  sortSelected?: \"none\" | \"label\" | \"snapshot\"\n  /**\n   * This field's own validity check. Return a MESSAGE to mark the value cell\n   * invalid, or `null` / `undefined` / `false` when the value is fine. A string\n   * rather than a schema object keeps the primitive library-agnostic.\n   *\n   * ORDER MATTERS: the built-in checks run first and this runs only when they\n   * pass, so a validator never re-answers \"is there a value at all\". Not called\n   * for a valueless operator, nor for a rule whose field the schema no longer\n   * has, and shown only once the user has committed a value to that rule.\n   */\n  validate?: (\n    context: FilterValidateContext<V, O>\n  ) => string | null | undefined | false\n  /**\n   * Reaches the value editor's PANEL. Merged last through tailwind-merge, so a\n   * `w-*` here beats the default rather than losing to it on source order.\n   *\n   * HEIGHT IS A VARIABLE, NOT A UTILITY: a `max-h-*` here bounds the PANEL and\n   * does nothing to the list inside it, which owns its own `max-height`. Write\n   * `--cascader-max-height: 28rem` as an arbitrary property instead; the cap is\n   * the SMALLER of that and the space the popup has.\n   */\n  className?: string\n\n  /** The storage column when it differs from the UI path. Never read here. */\n  column?: string\n  data?: unknown\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Editors                                  */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Where an editor renders. The SAME component serves both: `\"create\"` is the\n * wizard step, which has Back and advances on commit, `\"amend\"` the\n * chip-anchored popover, which offers Discard instead.\n */\nexport type FilterEditorHost = \"create\" | \"amend\"\n\nexport interface FilterOptionsState<O = unknown> {\n  items: FilterOption<O>[]\n  loading: boolean\n  error: boolean\n  hasMore: boolean\n  /** Current search text. Debounced before it reaches `loadOptions`. */\n  query: string\n  setQuery: (query: string) => void\n  loadMore: () => void\n  retry: () => void\n  /** Resolves a stored value to its option, from cache when possible. */\n  resolve: (value: string) => FilterOption<O> | undefined\n}\n\nexport interface FilterCommitOptions {\n  /** Dismiss the host after writing. Defaults to true. */\n  close?: boolean\n}\n\nexport interface FilterEditorProps<V = unknown, O = unknown> {\n  field: FilterField<V, O>\n  operator: FilterOperator\n  /** The DRAFT value. An editor edits a draft; the host commits it. */\n  value: V | undefined\n  onValueChange: (value: V | undefined) => void\n  host: FilterEditorHost\n  /**\n   * Spread onto whichever element should take focus, so no editor reaches for\n   * `setTimeout`. A CALLBACK ref at `HTMLElement` is the one shape assignable\n   * to every element's own ref prop, so it spreads onto an input, a slider or a\n   * button without a cast.\n   */\n  autoFocusProps: {\n    ref: React.RefCallback<HTMLElement>\n    autoFocus: boolean\n  }\n  /** Accept the draft. `{ close: false }` writes through without dismissing. */\n  commit: (value?: V, options?: FilterCommitOptions) => void\n  cancel: () => void\n  /** Step back. Only meaningful when `host === \"create\"`. */\n  back: () => void\n  options: FilterOptionsState<O>\n  labels: FilterLabels\n}\n\nexport type FilterEditor<V = unknown, O = unknown> = React.ComponentType<\n  FilterEditorProps<V, O>\n>\n\n/**\n * An editor with its generics erased, for the registry. `unknown` rather than\n * `never`: props are contravariant, so a `FilterEditor<never, never>` registry\n * accepts nothing at all. The single widening cast happens where it renders.\n */\nexport type AnyFilterEditor = React.ComponentType<\n  FilterEditorProps<unknown, unknown>\n>\n\nexport type FilterEditorRegistry = Record<string, AnyFilterEditor>\n\n/**\n * A registered editor's name, or a component. The `any` arm lets a CONCRETE\n * editor sit on an unknown-typed field without a cast: props are contravariant,\n * so `FilterEditor<DateValue>` is not a `FilterEditor<unknown>`. The widening\n * happens once, inside `resolveFilterEditor`.\n */\nexport type FilterEditorRef<V = unknown, O = unknown> =\n  | string\n  | FilterEditor<V, O>\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  | FilterEditor<any, any>\n\n/** Context for a custom builder empty state. Its actions ARE the footer's. */\nexport interface FilterEmptyStateContext {\n  labels: FilterLabels\n  /** The bar is locked. A custom state should not offer an action here. */\n  readOnly: boolean\n  /** Which box the builder is in, for a state that wants to be denser inline. */\n  mode: \"popover\" | \"inline\"\n  /** Appends a condition and opens its attribute picker. */\n  addFilter: () => void\n  addGroup: () => void\n}\n\nexport interface FilterValueDisplayContext<V = unknown, O = unknown> {\n  value: V | undefined\n  /** `value` normalised to an array, so callbacks never re-derive it. */\n  values: unknown[]\n  field: FilterField<V, O>\n  operator: FilterOperator\n  /** Options already resolved for `value`, when the field is option-backed. */\n  options: FilterOption<O>[]\n  labels: FilterLabels\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Index                                    */\n/* -------------------------------------------------------------------------- */\n\n/** Normalized schema, keyed by SIGNATURE: call sites inline the array. */\nexport interface FilterIndex<V = unknown, O = unknown> {\n  /** Every field by its joined path, `\"name.first\"`. */\n  byPath: Map<string, FilterField<V, O>>\n  /** Child fields by parent path. Root fields are keyed by `FILTER_ROOT_KEY`. */\n  childrenOf: Map<string, FilterField<V, O>[]>\n  /** Parent path by path. Empty string for a root field. */\n  parentOf: Map<string, string>\n  /** Every field in stable, depth-first order. Deep search walks it, and the\n   * builder seeds a new row from the FIRST pickable entry, so order is load\n   * bearing, not incidental. */\n  all: { field: FilterField<V, O>; path: string[] }[]\n  /** Top level fields, in input order. */\n  roots: FilterField<V, O>[]\n  /** Content hash; equal schemas share one, so a rebuild reuses the index. */\n  signature: string\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Draft                                   */\n/* -------------------------------------------------------------------------- */\n\nexport type FilterDraftStep = \"field\" | \"operator\" | \"value\"\n\n/**\n * The in-flight filter. `cascaderPath` is kept SEPARATE from `path`: `path` is\n * what the user chose, `cascaderPath` is where they were browsing when they\n * chose it, and Back has to return there. Deriving it from `path` breaks the\n * moment a deep search jumps across the tree.\n */\nexport interface FilterDraft<V = unknown> {\n  step: FilterDraftStep\n  /** `\"ready\"` = complete: the host writes it into the query and closes. The\n   * pure reducer decides that, not a click handler. */\n  status: \"editing\" | \"ready\"\n  /** Set when amending an existing rule, null when creating a new one. */\n  ruleId: string | null\n  /** The chosen field path. Empty until the field step commits. */\n  path: string[]\n  cascaderPath: string[]\n  operator: string | null\n  value: V | undefined\n  query: string\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Labels                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Every user facing string. `stepAnnouncement` alone is headless-only. */\nexport interface FilterLabels {\n  addFilter: string\n  advancedFilter: string\n  /** The line above the builder's rows, \"In this view, show records\". */\n  showRecords: string\n  /** Empty-state title. The HINT below is withheld from a read-only bar. */\n  builderEmpty: string\n  builderEmptyHint: string\n  /** Appends a condition to the root group, from the builder's footer. */\n  addCondition: string\n  addConditionGroup: string\n  /** A group's own add button: the only keyboard route into a nested group. It\n   * NAMES a button that shows `addCondition`, so a translation must contain\n   * that string, which is what WCAG Label in Name asks for. */\n  addToGroup: string\n  removeGroup: string\n  wrapInGroup: string\n  /** Dissolves a group into its parent. The inverse of `wrapInGroup`. */\n  ungroup: string\n  /** Moves a condition to the root group. The keyboard path to that drag. */\n  moveToTopLevel: string\n  /** Groups have no names, so they are numbered in document order, one-based. */\n  moveToGroup: (position: number) => string\n  /** Accessible name of a row's or a group's drag handle. */\n  reorder: string\n  /** Description on the drag handle, teaching the Alt+Arrow keyboard model. */\n  reorderHint: string\n  groupAll: string\n  groupAny: string\n  groupPlaceholder: string\n  /** Names a builder row. Depth is in it: indentation is invisible to AT. */\n  rowLabel: (condition: string, depth: number) => string\n  groupLabel: (description: string, depth: number) => string\n  groupAnnouncement: (added: boolean) => string\n  /** Alt+Arrow is otherwise silent. The total says whether this is the end. */\n  reorderAnnouncement: (\n    label: string,\n    position: number,\n    total: number\n  ) => string\n  /** A cross-PARENT move; a plain reorder announcement cannot be told apart.\n   * `destination` is the group's own headline, or the bar's label at the top\n   * level. */\n  moveAnnouncement: (\n    label: string,\n    destination: string,\n    position: number,\n    total: number\n  ) => string\n  clearAll: string\n  /** Names a group's menu; distinct from `chipMenu`, which is per-rule. */\n  groupMenu: string\n  searchFields: string\n  searchOperators: string\n  searchOptions: string\n  back: string\n  clear: string\n  apply: string\n  discard: string\n  empty: string\n  loading: string\n  loadingMore: string\n  loadMore: string\n  error: string\n  retry: string\n  /** Leading word before the first chip, where a combinator would otherwise go. */\n  where: string\n  and: string\n  or: string\n  /** Accessible name of the combinator toggle between two chips. */\n  combinator: string\n  /** Builder combinator toggle. English \"and\" wants 58.72px of a 64px track,\n   * so the name must CONTAIN the word: truncated, the pill shows \"a...\". */\n  combinatorLabel: (word: string) => string\n  duplicate: string\n  negate: string\n  /** Chip kebab's route into the builder. Needs `onConvertToAdvanced`. */\n  convertToAdvanced: string\n  remove: string\n  /** Names a chip's menu button. The builder's row menu reads the same key. */\n  chipMenu: (fieldLabel: string) => string\n  filtersLabel: string\n  filterLabel: (condition: string) => string\n  /** Prose, not ARIA: `aria-readonly` is invalid on toolbar, group and button. */\n  readOnly: string\n  /** Joins ancestors in a nested field path, \"Name > First\", for the names\n   * `formatFilterPath` builds. The chip draws a decorative chevron instead. */\n  pathSeparator: string\n  valuePlaceholder: string\n  /** Empty word for an OPTION value; `placeholder` is the search prompt. */\n  selectPlaceholder: string\n  /** Spoken for an empty value: \"contains enter text...\" is not a name. */\n  noValue: string\n  /** Shown in the operator segment before a condition has been chosen. */\n  selectCondition: string\n  /** Appended to a chip with no condition, matching the dashed outline. */\n  incomplete: string\n  /** Appended to a branch row's accessible name in the field picker. */\n  branchAffordance: string\n  /** A FRAGMENT, appended after a comma to an exclusive row's accessible name.\n   * Warns before the press; `exclusiveAnnouncement` is the receipt after. */\n  exclusiveHint: string\n  /** The clearing moves nothing on screen, so it is otherwise silent. */\n  exclusiveAnnouncement: (label: string, cleared: number) => string\n  itemCount: (count: number) => string\n  fieldsLabel: string\n  /** Live-region text after a query narrows an option list or the picker. */\n  resultsAnnouncement: (count: number) => string\n  /** Accessible name of an option menu's footer (Load more, Retry). */\n  actionsLabel: string\n  /** For a CONSUMER-composed wizard; the shipped flow announces counts. */\n  stepAnnouncement: (step: FilterDraftStep, label: string) => string\n  countAnnouncement: (count: number) => string\n  valueCount: (count: number) => string\n  /** Spells out the list behind the `valueCount` summary, and contains it. */\n  valueDetail: (summary: string, values: string[]) => string\n  valueRange: (from: string, to: string) => string\n  rangeFrom: (fieldLabel: string) => string\n  rangeTo: (fieldLabel: string) => string\n  rangeSeparator: string\n  /** Rendered for a `negated` rule, wrapping the operator label. */\n  negated: (operatorLabel: string) => string\n  /** Guidance (\"Choose a condition\"), not diagnosis: shown three ways over. */\n  issueOperator: string\n  issueValue: string\n  issueRange: string\n  issueRangeOrder: string\n  issueEmptyGroup: string\n  /** The roll-up, and the name of the button that jumps to the first issue. */\n  issueSummary: (count: number) => string\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                 Validation                                 */\n/* -------------------------------------------------------------------------- */\n\n/** Why a node cannot run as written. `collectFilterIssues` produces these. */\nexport type FilterIssueReason =\n  | \"missing-operator\"\n  | \"missing-value\"\n  | \"incomplete-range\"\n  | \"reversed-range\"\n  | \"empty-group\"\n  /** The one reason whose message is the validator's, not `FilterLabels`. */\n  | \"custom\"\n\nexport interface FilterIssue {\n  nodeId: string\n  /** WHICH cell to mark. Two reasons share the value cell; groups have none. */\n  column: \"operator\" | \"value\" | \"group\"\n  reason: FilterIssueReason\n  /** Set only for `reason: \"custom\"`; the rest look up `FilterLabels`. */\n  message?: string\n}\n\n/**\n * What a field's `validate` is handed. Mirrors `FilterValueDisplayContext`.\n * SYNCHRONOUS: issues are collected in a pure memo pass, so a check that has to\n * hit a server belongs in the consumer's own submit path.\n */\nexport interface FilterValidateContext<V = unknown, O = unknown> {\n  value: V | undefined\n  values: unknown[]\n  field: FilterField<V, O>\n  operator: FilterOperator\n  /** How many values this operator takes, already resolved. */\n  arity: FilterOperatorArity\n  rule: FilterRule<V>\n  labels: FilterLabels\n}\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters-types.tsx"
    },
    {
      "path": "registry/tealmac/reui-filters/filters.tsx",
      "content": "/**\n * filters - adapted for tealmac UI from ReUI \"filters/filters\"\n * (https://github.com/keenthemes/reui), MIT License, Copyright (c) 2025\n * Keenthemes Inc. The full licence text is in THIRD_PARTY_NOTICES.md.\n * Changes: tealmac UI import paths, lucide icons instead of the icon-library\n * placeholder, @radix-ui/react-slot, and theme tokens.\n */\n\"use client\"\n\nimport * as React from \"react\"\nimport { cva } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { FiltersAdvanced } from \"@/components/reui/filters/filters-advanced\"\nimport { FiltersBuilder } from \"@/components/reui/filters/filters-builder\"\nimport { FilterChip } from \"@/components/reui/filters/filters-chip\"\nimport {\n  createFilterFocusStore,\n  createFilterResolutionStore,\n  createFilterRowStateStore,\n  FilterActionsContext,\n  filterControlSizes,\n  FilterFocusContext,\n  filterReadOnlyProps,\n  FilterRenderContext,\n  FilterRowStateProvider,\n  FilterStateContext,\n  isFilterLocked,\n  useFilterActions,\n  useFilterFocusStore,\n  useFilterState,\n  type FilterActionsContextValue,\n} from \"@/components/reui/filters/filters-context\"\nimport {\n  filterDraftReducer,\n  isFilterDraftCommittable,\n  type FilterDraftAction,\n} from \"@/components/reui/filters/filters-draft\"\nimport {\n  DEFAULT_FILTER_EDITORS,\n  resolveFilterEditor,\n  type FilterEditorRegistry,\n} from \"@/components/reui/filters/filters-editors\"\nimport { resolveFilterLabels } from \"@/components/reui/filters/filters-i18n\"\nimport {\n  buildFilterIndex,\n  computeFilterSchemaSignature,\n  createFilterIdFactory,\n  findFilterSchemaIssues,\n  formatFilterPath,\n  getFilterField,\n  warnFilterOnce,\n  type FilterPathCollapse,\n} from \"@/components/reui/filters/filters-lib\"\nimport {\n  createFilterOperators,\n  DEFAULT_FILTER_OPERATOR_LABELS,\n  DEFAULT_FILTER_OPERATORS,\n  getFilterOperator,\n  negateFilterOperator,\n  operatorTakesValue,\n  resolveFilterOperators,\n  type FilterOperatorLabels,\n} from \"@/components/reui/filters/filters-operators\"\nimport {\n  clearFilterQuery,\n  copyFilterNodeTo,\n  countFilterRules,\n  createFilterGroup,\n  createFilterQuery,\n  createFilterRule,\n  duplicateFilterNode,\n  findFilterNode,\n  findFilterRule,\n  flattenFilterRules,\n  insertFilterNode,\n  isFilterRule,\n  moveFilterNode,\n  moveFilterNodeTo,\n  removeFilterNode,\n  setFilterCombinator,\n  toggleFilterCombinator,\n  unwrapFilterGroup,\n  updateFilterRule,\n  wrapFilterNodeInGroup,\n} from \"@/components/reui/filters/filters-query\"\nimport type {\n  FilterChangeDetails,\n  FilterCombinator,\n  FilterDraft,\n  FilterDraftStep,\n  FilterEditor,\n  FilterEmptyStateContext,\n  FilterField,\n  FilterLabels,\n  FilterQuery,\n  FilterRule,\n  FilterValueDisplayContext,\n} from \"@/components/reui/filters/filters-types\"\n\n/* -------------------------------------------------------------------------- */\n/*                                  Variants                                  */\n/* -------------------------------------------------------------------------- */\n\nconst filtersBarVariants = cva(\"flex flex-wrap items-center\", {\n  variants: {\n    // The rungs `FILTER_CONTROL_SIZES` holds, fed the RESOLVED rung at both\n    // call sites, which is what keeps the two ladders in step: a cva default\n    // only applies to a value nobody passed, so a raw `\"lg\"` reaching here\n    // would leave the bar with no gap at all.\n    size: {\n      sm: \"gap-1.5\",\n      default: \"gap-2\",\n    },\n  },\n  defaultVariants: { size: \"default\" },\n})\n\n/* -------------------------------------------------------------------------- */\n/*                                 Controllable                               */\n/* -------------------------------------------------------------------------- */\n\nfunction useControllableQuery<V, O>(\n  controlled: FilterQuery<V> | undefined,\n  uncontrolledDefault: FilterQuery<V> | undefined,\n  onChange:\n    | ((query: FilterQuery<V>, details: FilterChangeDetails<V, O>) => void)\n    | undefined\n) {\n  const isControlled = controlled !== undefined\n  const [internal, setInternal] = React.useState<FilterQuery<V>>(\n    () => uncontrolledDefault ?? createFilterQuery<V>()\n  )\n\n  const query = isControlled ? controlled : internal\n  const queryRef = React.useRef(query)\n  React.useEffect(() => {\n    queryRef.current = query\n  })\n\n  const setQuery = React.useCallback(\n    (next: FilterQuery<V>, details: FilterChangeDetails<V, O>) => {\n      if (next === queryRef.current) return\n      queryRef.current = next\n      if (!isControlled) setInternal(next)\n      onChange?.(next, details)\n    },\n    [isControlled, onChange]\n  )\n\n  return { query, queryRef, setQuery }\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Root                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface FiltersProps<V = unknown, O = unknown> {\n  /** The field schema. Nested via each field's own `fields`. */\n  fields: FilterField<V, O>[]\n\n  query?: FilterQuery<V>\n  defaultQuery?: FilterQuery<V>\n  onQueryChange?: (\n    query: FilterQuery<V>,\n    details: FilterChangeDetails<V, O>\n  ) => void\n\n  labels?: Partial<FilterLabels>\n  /** Operator wording, overridden independently of the chrome copy. */\n  operatorLabels?: FilterOperatorLabels\n  /** Extra or replacement value editors, resolved by a field's `editor` name. */\n  editors?: FilterEditorRegistry\n\n  /**\n   * Which chrome draws the query. `\"basic\"` is the flat chip row, joined by an\n   * implicit AND and drawing no combinator, because a chip row has nowhere to\n   * put a parenthesis, and it draws a nested rule at any depth as a flat chip.\n   */\n  variant?: \"basic\" | \"advanced\"\n  /** Where the advanced builder lives. `\"inline\"` renders the panel in place. */\n  advancedMode?: \"popover\" | \"inline\"\n  /**\n   * Where the panel sits against its trigger. Stating it settles a twin split:\n   * on overflow Base UI flips edges, Radix only shifts along the axis.\n   */\n  advancedAlign?: \"start\" | \"center\" | \"end\"\n  /**\n   * Whether the advanced builder's rows can be REORDERED. Off by default: a\n   * move changes nothing about what the query MEANS, and costs a grip on every\n   * row plus a gesture a touch screen starts by accident. On, drag and\n   * Alt+Arrow move any row but the lone root.\n   */\n  reorderable?: boolean\n\n  /**\n   * The density of the whole bar, chips included. TWO RUNGS and no `lg`,\n   * resolved through `filterControlSizes` to whatever the ACTIVE STYLE calls\n   * that rung (nova 7/8, sera 9/10, mira 6/7, maia and luma 8/9, lyra and rhea\n   * 7/8, vega 8/9). Chips need no `ButtonGroup` variant: `items-stretch` gives\n   * the pill the height of its one definite-height child, the kebab.\n   */\n  size?: \"sm\" | \"default\"\n  disabled?: boolean\n  readOnly?: boolean\n\n  /**\n   * ONE VETO POINT for every change the BAR makes to the query, and only those.\n   * Return `false` to refuse; anything else commits, and `details.reason` names\n   * the action. One hook and not fourteen because every write goes through\n   * `emit`: the Delete key, Alt+Arrow and a drag alike. It can only refuse, and\n   * it sits BEHIND the lock, so a locked bar never asks it. Returning a\n   * REPLACEMENT tree was rejected: the announcement is already computed from\n   * the proposed tree, so the bar would say one thing and commit another.\n   */\n  onBeforeQueryChange?: (\n    query: FilterQuery<V>,\n    details: FilterChangeDetails<V, O>\n  ) => boolean | void\n\n  /**\n   * Offers \"Convert to advanced filter\" in every chip's kebab; its presence IS\n   * the switch, since `variant` belongs to the consumer. Not drawn in advanced.\n   */\n  onConvertToAdvanced?: () => void\n\n  /**\n   * Classes for the dropdown MENUS and the field PICKER panel, one prop each\n   * rather than one per mount point. Merged after the default, so `w-*` wins.\n   */\n  menuClassName?: string\n  fieldPickerClassName?: string\n\n  /**\n   * How a NESTED attribute path is shortened when too deep to read. `\"none\"` is\n   * the default, so an upgrade changes nothing under a consumer; the collapser\n   * is the cascader's, and the full path survives as the accessible NAME.\n   */\n  pathCollapse?: FilterPathCollapse\n  /**\n   * How many names survive the collapse, the elided run not counted. Inert\n   * while `pathCollapse` is `\"none\"`. Three is the cascader's own default.\n   */\n  maxPathSegments?: number\n\n  /** Replaces the default Add filter button. */\n  trigger?: React.ReactNode\n  /** Renders a Clear button once the query holds anything. */\n  showClear?: boolean\n\n  renderValue?: (context: FilterValueDisplayContext<V, O>) => React.ReactNode\n  renderChip?: (rule: FilterRule<V>) => React.ReactNode\n  /**\n   * Replaces the advanced builder's empty state, which exists at all because a\n   * builder with no rows is a footer floating in blank space. `null` for none.\n   */\n  renderEmpty?: (context: FilterEmptyStateContext) => React.ReactNode\n\n  className?: string\n  children?: React.ReactNode\n}\n\nexport function Filters<V = unknown, O = unknown>({\n  fields,\n  query: controlledQuery,\n  defaultQuery,\n  onQueryChange,\n  labels: labelsProp,\n  operatorLabels: operatorLabelsProp,\n  editors: editorsProp,\n  variant = \"basic\",\n  advancedMode = \"popover\",\n  advancedAlign = \"start\",\n  reorderable = false,\n  size = \"default\",\n  disabled = false,\n  readOnly = false,\n  onBeforeQueryChange,\n  onConvertToAdvanced,\n  menuClassName,\n  fieldPickerClassName,\n  pathCollapse = \"none\",\n  maxPathSegments = 3,\n  trigger,\n  showClear = false,\n  renderValue,\n  renderChip,\n  renderEmpty,\n  className,\n  children,\n}: FiltersProps<V, O>) {\n  const { query, queryRef, setQuery } = useControllableQuery<V, O>(\n    controlledQuery,\n    defaultQuery,\n    onQueryChange\n  )\n\n  const [draft, dispatchDraftRaw] = React.useReducer(\n    filterDraftReducer<V>,\n    null as FilterDraft<V> | null\n  )\n  // Text AND a counter: `aria-live` fires on a DOM mutation and React writes\n  // nothing when the string is already there, so a repeat was silent. Measured\n  // with a MutationObserver: \"Group added\" three times, one mutation.\n  const [announced, setAnnounced] = React.useState({ seq: 0, text: \"\" })\n  const announcement = announced.text\n  const setAnnouncement = React.useCallback((text: string) => {\n    setAnnounced((prev) => ({ seq: prev.seq + 1, text }))\n  }, [])\n\n  // Seeded from useId: ids from Date.now() plus Math.random() broke hydration.\n  const idSeed = React.useId()\n  const nextId = React.useMemo(\n    () => createFilterIdFactory(`${idSeed}f`),\n    [idSeed]\n  )\n\n  const focusStore = React.useMemo(() => createFilterFocusStore(), [])\n  const rowStateStore = React.useMemo(() => createFilterRowStateStore(), [])\n  // One per root: the value-to-label store every `useFilterOptions` shares.\n  const resolutionStore = React.useMemo(() => createFilterResolutionStore(), [])\n\n  /* -------------------------------- derived ------------------------------- */\n\n  // `fields` is an inline literal at every real call site, so the CHEAP walk\n  // runs every render and the EXPENSIVE index memoizes on its result. Not a\n  // ref caching the previous index: writing a ref during render is the\n  // impurity this rewrite removed, and it misbehaves under StrictMode.\n  const signature = computeFilterSchemaSignature(fields)\n  const index = React.useMemo(\n    () => buildFilterIndex<V, O>(fields, null, signature),\n    // Not `fields`: its identity changes every render at every real call site.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [signature]\n  )\n\n  const labels = React.useMemo(\n    () => resolveFilterLabels(labelsProp),\n    [labelsProp]\n  )\n\n  const operatorCatalog = React.useMemo(() => {\n    if (!operatorLabelsProp) return DEFAULT_FILTER_OPERATORS\n    return createFilterOperators({\n      ...DEFAULT_FILTER_OPERATOR_LABELS,\n      ...operatorLabelsProp,\n    })\n  }, [operatorLabelsProp])\n\n  const editors = React.useMemo(\n    () => ({ ...DEFAULT_FILTER_EDITORS, ...editorsProp }),\n    [editorsProp]\n  )\n\n  const resolveOperators = React.useCallback(\n    (field: FilterField<V, O>) =>\n      resolveFilterOperators(field, operatorCatalog),\n    [operatorCatalog]\n  )\n\n  const ruleCount = React.useMemo(() => countFilterRules(query), [query])\n\n  /* --------------------------- latest-props ref --------------------------- */\n\n  const latest = React.useRef({\n    index,\n    labels,\n    operatorCatalog,\n    resolveOperators,\n    draft,\n    nextId,\n    setQuery,\n    queryRef,\n    disabled,\n    readOnly,\n    onBeforeQueryChange,\n  })\n  React.useEffect(() => {\n    latest.current = {\n      index,\n      labels,\n      operatorCatalog,\n      resolveOperators,\n      draft,\n      nextId,\n      setQuery,\n      queryRef,\n      disabled,\n      readOnly,\n      onBeforeQueryChange,\n    }\n  })\n\n  /* -------------------------------- actions ------------------------------- */\n\n  // Every mutator below reads state through `latest`, so no keystroke rebuilds\n  // one. The lock flags are the ONE exception, for the reason on `locked`.\n\n  /**\n   * THE MUTATION BOUNDARY, asked here and not at the nine buttons, because the\n   * routes into a query are not only buttons. It needs BOTH the closure and\n   * the ref: `latest` is written in a passive effect and effects run\n   * child-first, so a consumer effect in the commit that turns `readOnly` on\n   * runs BEFORE the ref learns of it, while the ref is what a stale handler\n   * reads afterwards.\n   */\n  const locked = React.useCallback(\n    () => disabled || readOnly || isFilterLocked(latest.current),\n    [disabled, readOnly]\n  )\n\n  // Reports whether the write LANDED: `onBeforeQueryChange` is discoverable\n  // only here, and a vetoed remove that still announced a count would lie.\n  const emit = React.useCallback(\n    (\n      next: FilterQuery<V>,\n      reason: FilterChangeDetails<V, O>[\"reason\"],\n      rule: FilterRule<V> | null\n    ): boolean => {\n      // The backstop, redundant with each mutator's own early return, and\n      // FIRST, so the consumer hook cannot approve what the lock refused.\n      if (locked()) return false\n      const field = rule\n        ? (getFilterField(latest.current.index, rule.path) ?? null)\n        : null\n      const details: FilterChangeDetails<V, O> = { reason, rule, field }\n      // Strictly `false`, so a handler that forgets to return is not a veto.\n      if (latest.current.onBeforeQueryChange?.(next, details) === false) {\n        return false\n      }\n      latest.current.setQuery(next, details)\n      return true\n    },\n    [locked]\n  )\n\n  /**\n   * Drops the roving tab stop when the node holding it no longer exists: a cell\n   * claims it when the store names it, and the \"row one takes it\" fallback\n   * fires only when the store is EMPTY, so a deleted id left twenty cells at\n   * `tabindex=\"-1\"` with focus on the BODY. Keyed on the committed `query`, so\n   * a consumer's Reset or saved-view load is repaired too: add a condition,\n   * press Reset, and 25 cells stayed untabbable in both twins.\n   */\n  React.useEffect(() => {\n    const { id } = focusStore.getSnapshot()\n    if (!id || findFilterNode(query, id)) return\n    focusStore.set({ id: null, segment: null, autoOpen: false })\n  }, [query, focusStore])\n\n  const addRule = React.useCallback(\n    (rule: FilterRule<V>, parentId?: string) => {\n      if (locked()) return\n      const next = insertFilterNode(\n        latest.current.queryRef.current,\n        rule,\n        parentId\n      )\n      if (!emit(next, \"add\", rule)) return\n      setAnnouncement(\n        latest.current.labels.countAnnouncement(countFilterRules(next))\n      )\n    },\n    [emit, locked, setAnnouncement]\n  )\n\n  const addGroup = React.useCallback(\n    (parentId?: string, combinator: FilterCombinator = \"or\") => {\n      // Before `nextId`, so a LOCKED bar cannot drift the SSR-seeded sequence.\n      if (locked()) return \"\"\n      const id = latest.current.nextId()\n      // `or` by default: `a AND (b AND c)` is just `a AND b AND c`.\n      const next = insertFilterNode(\n        latest.current.queryRef.current,\n        createFilterGroup<V>({ id, combinator }),\n        parentId\n      )\n      // `\"\"` on a veto: every caller moves focus onto the id it gets back, and\n      // focusing a group that was never created strands the tab stop. The id\n      // is already burnt, deliberately: a veto is a client-time decision the\n      // server never took part in.\n      if (!emit(next, \"add\", null)) return \"\"\n      setAnnouncement(latest.current.labels.groupAnnouncement(true))\n      return id\n    },\n    [emit, locked, setAnnouncement]\n  )\n\n  const updateRule = React.useCallback(\n    (id: string, updates: Partial<Omit<FilterRule<V>, \"id\" | \"type\">>) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = updateFilterRule(current, id, updates)\n      if (next === current) return\n      // THE VALUE, not the field or the operator: picking an attribute leaves\n      // the value empty, so arming there reddens the flow the primitive itself\n      // walks a user through. A field re-pick sends `value: undefined` in the\n      // SAME patch, so `path` and not the presence of `value` tells the two\n      // apart. Clearing a typed value still arms it: no `path` in that patch.\n      if (\"path\" in updates) rowStateStore.unmark(id)\n      else if (\"value\" in updates) rowStateStore.mark(id)\n      emit(next, \"update\", findFilterRule(next, id))\n    },\n    [emit, locked, rowStateStore]\n  )\n\n  const removeNode = React.useCallback(\n    (id: string) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const removed = findFilterRule(current, id)\n      const next = removeFilterNode(current, id)\n      if (next === current) return\n      if (!emit(next, \"remove\", removed)) return\n      // A rule removal reports the COUNT; a group has no rule to report and\n      // takes an unknown number of conditions with it, so it says so instead.\n      setAnnouncement(\n        removed\n          ? latest.current.labels.countAnnouncement(countFilterRules(next))\n          : latest.current.labels.groupAnnouncement(false)\n      )\n    },\n    [emit, locked, setAnnouncement]\n  )\n\n  const duplicateNode = React.useCallback(\n    (id: string) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = duplicateFilterNode(current, id, latest.current.nextId)\n      if (next === current) return\n      if (!emit(next, \"duplicate\", findFilterRule(current, id))) return\n      // The count, not \"duplicated\": a GROUP adds an unknown number of rows.\n      setAnnouncement(\n        latest.current.labels.countAnnouncement(countFilterRules(next))\n      )\n    },\n    [emit, locked, setAnnouncement]\n  )\n\n  const negateRule = React.useCallback(\n    (id: string) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const rule = findFilterRule(current, id)\n      if (!rule) return\n      const field = getFilterField(latest.current.index, rule.path)\n      if (!field) return\n      const operators = latest.current.resolveOperators(field)\n      const flipped = negateFilterOperator(\n        getFilterOperator(operators, rule.operator),\n        operators,\n        rule.negated\n      )\n      const next = updateFilterRule(current, id, {\n        operator: flipped.operator ?? rule.operator,\n        negated: flipped.negated || undefined,\n      })\n      emit(next, \"negate\", findFilterRule(next, id))\n    },\n    [emit, locked]\n  )\n\n  // Says where a node LANDED, the one mutator a screen reader hears nothing\n  // else about: focus stays on the handle and the name does not change. Reads\n  // the tree AFTER the move: the position and sibling count announced are the\n  // ones the user has just arrived at.\n  const announceReorder = React.useCallback(\n    (next: FilterQuery<V>, id: string, fromParentId: string | null) => {\n      const found = findFilterNode(next, id)\n      if (!found || !found.parent) return\n      const label = isFilterRule(found.node)\n        ? formatFilterPath(\n            latest.current.index,\n            found.node.path,\n            latest.current.labels.pathSeparator\n          )\n        : found.node.combinator === \"and\"\n          ? latest.current.labels.groupAll\n          : latest.current.labels.groupAny\n      const position = found.index + 1\n      const total = found.parent.rules.length\n\n      // A move that changed the node's CONTAINER is a different event, named by\n      // the group's own headline, or the bar's label at the top level.\n      if (fromParentId && fromParentId !== found.parent.id) {\n        const destination =\n          found.parent.id === next.id\n            ? latest.current.labels.filtersLabel\n            : found.parent.combinator === \"and\"\n              ? latest.current.labels.groupAll\n              : latest.current.labels.groupAny\n        setAnnouncement(\n          latest.current.labels.moveAnnouncement(\n            label,\n            destination,\n            position,\n            total\n          )\n        )\n        return\n      }\n\n      setAnnouncement(\n        latest.current.labels.reorderAnnouncement(label, position, total)\n      )\n    },\n    [setAnnouncement]\n  )\n\n  const moveNode = React.useCallback(\n    (id: string, delta: number) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = moveFilterNode(current, id, delta)\n      if (next === current) return\n      if (!emit(next, \"reorder\", findFilterRule(next, id))) return\n      // Within the owning group by construction, so there is no destination.\n      announceReorder(next, id, null)\n    },\n    [emit, announceReorder, locked]\n  )\n\n  // Also the drag layer's drop commit, so a drag and Alt+Arrow say the same.\n  const moveNodeTo = React.useCallback(\n    (id: string, parentId: string, index: number) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      // BEFORE the move: the only place the old parent still exists.\n      const fromParentId = findFilterNode(current, id)?.parent?.id ?? null\n      const next = moveFilterNodeTo(current, id, parentId, index)\n      if (next === current) return\n      if (!emit(next, \"reorder\", findFilterRule(next, id))) return\n      announceReorder(next, id, fromParentId)\n    },\n    [emit, announceReorder, locked]\n  )\n\n  const copyNodeTo = React.useCallback(\n    (id: string, parentId: string, index: number) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = copyFilterNodeTo(\n        current,\n        id,\n        parentId,\n        index,\n        latest.current.nextId\n      )\n      if (next === current) return\n      if (!emit(next, \"duplicate\", findFilterRule(current, id))) return\n      // The count again: an Alt-drag of a GROUP adds an unknown number of rows.\n      setAnnouncement(\n        latest.current.labels.countAnnouncement(countFilterRules(next))\n      )\n    },\n    [emit, locked, setAnnouncement]\n  )\n\n  const wrapNodeInGroup = React.useCallback(\n    (id: string, combinator: FilterCombinator = \"or\") => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = wrapFilterNodeInGroup(\n        current,\n        id,\n        latest.current.nextId(),\n        combinator\n      )\n      if (next === current) return\n      if (!emit(next, \"add\", findFilterRule(next, id))) return\n      setAnnouncement(latest.current.labels.groupAnnouncement(true))\n    },\n    [emit, locked, setAnnouncement]\n  )\n\n  const unwrapGroup = React.useCallback(\n    (groupId: string) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = unwrapFilterGroup(current, groupId)\n      if (next === current) return\n      // The conditions survive in place, so the count has not changed.\n      if (!emit(next, \"remove\", null)) return\n      setAnnouncement(latest.current.labels.groupAnnouncement(false))\n    },\n    [emit, locked, setAnnouncement]\n  )\n\n  // What a combinator change SOUNDS like: the pill's name changes with it, but\n  // a name change on the FOCUSED element is not re-announced by NVDA or JAWS.\n  // The group's own headline, not the bare word: it says what the query MEANS\n  // now, which is the thing that changed.\n  const announceCombinator = React.useCallback(\n    (combinator: FilterCombinator) => {\n      setAnnouncement(\n        combinator === \"and\"\n          ? latest.current.labels.groupAll\n          : latest.current.labels.groupAny\n      )\n    },\n    [setAnnouncement]\n  )\n\n  const setCombinatorAction = React.useCallback(\n    (groupId: string, combinator: FilterCombinator) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = setFilterCombinator(current, groupId, combinator)\n      if (next === current) return\n      if (!emit(next, \"combinator\", null)) return\n      announceCombinator(combinator)\n    },\n    [emit, locked, announceCombinator]\n  )\n\n  const toggleCombinatorAction = React.useCallback(\n    (groupId: string) => {\n      if (locked()) return\n      const current = latest.current.queryRef.current\n      const next = toggleFilterCombinator(current, groupId)\n      if (next === current) return\n      if (!emit(next, \"combinator\", null)) return\n      // Read off the COMMITTED tree, so the sentence cannot disagree with it.\n      const group = findFilterNode(next, groupId)?.node\n      if (group && !isFilterRule(group)) announceCombinator(group.combinator)\n    },\n    [emit, locked, announceCombinator]\n  )\n\n  const clearQueryAction = React.useCallback(() => {\n    if (locked()) return\n    const current = latest.current.queryRef.current\n    const next = clearFilterQuery(current)\n    if (next === current) return\n    if (!emit(next, \"clear\", null)) return\n    setAnnouncement(latest.current.labels.countAnnouncement(0))\n  }, [emit, locked, setAnnouncement])\n\n  // The live region, opened to the chrome inside the bar. The setter itself is\n  // not published: it is a channel anything could write anything to.\n  const announce = React.useCallback(\n    (message: string) => {\n      if (!message) return\n      setAnnouncement(message)\n    },\n    [setAnnouncement]\n  )\n\n  // A draft is a MUTATION in progress, so it locks with the rest, except\n  // `close`: a panel open when the bar turned read only must still dismiss.\n  const dispatchDraft = React.useCallback(\n    (action: FilterDraftAction<V>) => {\n      if (action.type !== \"close\" && locked()) return\n      dispatchDraftRaw(action)\n    },\n    [locked]\n  )\n\n  const openCreate = React.useCallback(() => {\n    if (locked()) return\n    dispatchDraftRaw({ type: \"openCreate\" })\n  }, [locked])\n\n  const openAmend = React.useCallback(\n    (id: string, step: FilterDraftStep) => {\n      if (locked()) return\n      const rule = findFilterRule(latest.current.queryRef.current, id)\n      if (!rule) return\n      dispatchDraftRaw({\n        type: \"openAmend\",\n        ruleId: id,\n        step,\n        path: rule.path,\n        operator: rule.operator,\n        value: rule.value,\n      })\n    },\n    [locked]\n  )\n\n  const closeDraft = React.useCallback(\n    () => dispatchDraftRaw({ type: \"close\" }),\n    []\n  )\n\n  const getQuery = React.useCallback(() => latest.current.queryRef.current, [])\n  const getDraft = React.useCallback(() => latest.current.draft, [])\n\n  /* ------------------------- draft -> query commit ------------------------ */\n\n  // The draft becomes a rule exactly once, when the reducer says it is ready.\n  // Here rather than in each click handler, which is what lets the \"arity none\n  // skips the value step\" branch live in the pure reducer.\n  React.useEffect(() => {\n    if (!draft || draft.status !== \"ready\") return\n    if (!isFilterDraftCommittable(draft)) return\n\n    if (draft.ruleId) {\n      updateRule(draft.ruleId, {\n        path: draft.path,\n        operator: draft.operator ?? \"\",\n        value: draft.value,\n      })\n    } else if (!locked()) {\n      // Asked here too: this branch burns an id and points the focus store at\n      // it, and a store naming a chip that never existed eats the tab stop.\n      const id = nextId()\n      addRule(\n        createFilterRule<V>({\n          id,\n          path: draft.path,\n          // Empty on purpose: the chip renders \"Select condition\" and opens.\n          operator: \"\",\n          value: undefined,\n        })\n      )\n      focusStore.set({ id, segment: \"operator\", autoOpen: true })\n    }\n    dispatchDraftRaw({ type: \"close\" })\n  }, [draft, addRule, updateRule, nextId, focusStore, locked])\n\n  /* ---------------------------- dev diagnostics --------------------------- */\n\n  React.useEffect(() => {\n    if (process.env.NODE_ENV === \"production\") return\n    const issues = findFilterSchemaIssues(fields, (field) =>\n      resolveFilterOperators(field, operatorCatalog)\n    )\n    if (issues.duplicatePaths.length) {\n      warnFilterOnce(\n        `dup:${issues.duplicatePaths.join(\",\")}`,\n        `duplicate sibling field ids are ignored after the first: ${issues.duplicatePaths.join(\", \")}`\n      )\n    }\n    if (issues.emptyIds.length) {\n      warnFilterOnce(\"empty-id\", \"every field needs a non-empty id\")\n    }\n    if (issues.unknownDefaultOperators.length) {\n      warnFilterOnce(\n        `op:${issues.unknownDefaultOperators.join(\",\")}`,\n        `defaultOperator names an operator the field does not offer: ${issues.unknownDefaultOperators.join(\", \")}`\n      )\n    }\n  }, [fields, operatorCatalog])\n\n  /* ------------------------------- contexts ------------------------------- */\n\n  const actions = React.useMemo<FilterActionsContextValue<V, O>>(\n    () => ({\n      index,\n      labels,\n      operatorCatalog,\n      editors,\n      size,\n      disabled,\n      readOnly,\n      variant,\n      menuClassName,\n      fieldPickerClassName,\n      convertToAdvanced: onConvertToAdvanced,\n      pathCollapse,\n      maxPathSegments,\n      resolveOperators,\n      // The same lookup the chrome uses, so a headless consumer can ask it too.\n      resolveEditor: (field, operator) =>\n        resolveFilterEditor(field, operator, editors) as\n          FilterEditor<V, O> | undefined,\n      resolution: resolutionStore,\n      addRule,\n      addGroup,\n      updateRule,\n      removeNode,\n      duplicateNode,\n      negateRule,\n      moveNode,\n      moveNodeTo,\n      copyNodeTo,\n      wrapNodeInGroup,\n      unwrapGroup,\n      setCombinator: setCombinatorAction,\n      toggleCombinator: toggleCombinatorAction,\n      clearQuery: clearQueryAction,\n      openCreate,\n      openAmend,\n      closeDraft,\n      dispatchDraft,\n      announce,\n      getQuery,\n      getDraft,\n      nextId,\n    }),\n    // Every input is memoized and every action `[]`-stable, so this\n    // republishes on a real schema or config change, never on a keystroke.\n    [\n      index,\n      labels,\n      operatorCatalog,\n      editors,\n      size,\n      disabled,\n      readOnly,\n      variant,\n      menuClassName,\n      fieldPickerClassName,\n      onConvertToAdvanced,\n      pathCollapse,\n      maxPathSegments,\n      resolveOperators,\n      resolutionStore,\n      addRule,\n      addGroup,\n      updateRule,\n      removeNode,\n      duplicateNode,\n      negateRule,\n      moveNode,\n      moveNodeTo,\n      copyNodeTo,\n      wrapNodeInGroup,\n      unwrapGroup,\n      setCombinatorAction,\n      toggleCombinatorAction,\n      clearQueryAction,\n      openCreate,\n      openAmend,\n      closeDraft,\n      dispatchDraft,\n      announce,\n      getQuery,\n      getDraft,\n      nextId,\n    ]\n  )\n\n  const state = React.useMemo(\n    () => ({\n      query,\n      draft,\n      ruleCount,\n      announcement,\n      announcementSeq: announced.seq,\n    }),\n    [query, draft, ruleCount, announcement, announced.seq]\n  )\n\n  const renderContext = React.useMemo(\n    () => ({ renderValue, renderChip, renderEmpty }),\n    [renderValue, renderChip, renderEmpty]\n  )\n\n  return (\n    <FilterActionsContext.Provider\n      value={actions as unknown as FilterActionsContextValue}\n    >\n      <FilterStateContext.Provider value={state as never}>\n        <FilterRenderContext.Provider value={renderContext as never}>\n          <FilterRowStateProvider value={rowStateStore}>\n            <FilterFocusContext.Provider value={focusStore}>\n              {children ??\n                (variant === \"advanced\" ? (\n                  <FiltersAdvanced<V, O>\n                    mode={advancedMode}\n                    align={advancedAlign}\n                    trigger={trigger}\n                    reorderable={reorderable}\n                    className={className}\n                  />\n                ) : (\n                  <FiltersRow\n                    trigger={trigger}\n                    showClear={showClear}\n                    className={className}\n                  />\n                ))}\n            </FilterFocusContext.Provider>\n          </FilterRowStateProvider>\n        </FilterRenderContext.Provider>\n      </FilterStateContext.Provider>\n    </FilterActionsContext.Provider>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Row                                     */\n/* -------------------------------------------------------------------------- */\n\nexport interface FiltersRowProps {\n  trigger?: React.ReactNode\n  showClear?: boolean\n  className?: string\n}\n\n/**\n * The chip row: a toolbar with a roving tabindex, where the predecessor made\n * every segment of every chip its own tab stop. There is NO combinator here,\n * because a chip row can draw a word between two pills but not a parenthesis.\n */\nexport function FiltersRow({ trigger, showClear, className }: FiltersRowProps) {\n  const actions = useFilterActions()\n  const sizes = filterControlSizes(actions)\n  const { query, ruleCount, announcement, announcementSeq } = useFilterState()\n  const focusStore = useFilterFocusStore()\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  // The keys consult this even though the actions already refuse: an ungated\n  // Enter would ARM `autoOpen` for a popover that then refuses to open. Gated\n  // per branch, never at the top of `onKeyDown`: the arrows, Home and End are\n  // how a read-only bar is read.\n  const locked = isFilterLocked(actions)\n\n  // Flattened, not `query.rules.filter(isFilterRule)`: a query built in the\n  // advanced builder would otherwise hide nested conditions that still filter.\n  const rules = React.useMemo(() => flattenFilterRules(query), [query])\n\n  const chips = () =>\n    Array.from(\n      rootRef.current?.querySelectorAll<HTMLElement>(\n        '[data-slot=\"filter-chip\"]'\n      ) ?? []\n    )\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const target = (event.target as HTMLElement).closest<HTMLElement>(\n      '[data-slot=\"filter-chip\"]'\n    )\n    if (!target) return\n    // A key pressed inside an open popover belongs to that popover.\n    if (event.target !== target) return\n\n    const all = chips()\n    const current = all.indexOf(target)\n    if (current === -1) return\n\n    const rtl = getComputedStyle(target).direction === \"rtl\"\n    const forward = rtl ? \"ArrowLeft\" : \"ArrowRight\"\n    const backward = rtl ? \"ArrowRight\" : \"ArrowLeft\"\n\n    const focusAt = (index: number) => {\n      const next = all[Math.max(0, Math.min(index, all.length - 1))]\n      if (!next) return\n      event.preventDefault()\n      next.focus()\n    }\n\n    const ruleId = target.dataset.ruleId\n    if (!ruleId) return\n\n    if (event.altKey && (event.key === forward || event.key === backward)) {\n      if (locked) return\n      event.preventDefault()\n      actions.moveNode(ruleId, event.key === forward ? 1 : -1)\n      return\n    }\n    if (event.key === forward) return focusAt(current + 1)\n    if (event.key === backward) return focusAt(current - 1)\n    if (event.key === \"Home\") return focusAt(0)\n    if (event.key === \"End\") return focusAt(all.length - 1)\n\n    if (event.key === \"Backspace\" || event.key === \"Delete\") {\n      if (locked) return\n      event.preventDefault()\n      actions.removeNode(ruleId)\n      // The neighbour taking this chip's place, so a run of deletes keeps focus.\n      requestAnimationFrame(() => {\n        const remaining = chips()\n        remaining[Math.min(current, remaining.length - 1)]?.focus()\n      })\n      return\n    }\n\n    if (event.key === \"Enter\" || event.key === \" \") {\n      if (locked) return\n      event.preventDefault()\n      // Enter RESUMES the chip: the attribute segment is display only, so the\n      // target is whichever step the flow has not reached, never nothing.\n      const rule = findFilterRule(actions.getQuery(), ruleId)\n      if (!rule) return\n      const field = getFilterField(actions.index, rule.path)\n      // No popover to open, so autoOpen would sit armed until another chip\n      // spent it. The chip stays reachable and Delete still removes it.\n      if (!field) return\n      const operator = getFilterOperator(\n        actions.resolveOperators(field),\n        rule.operator\n      )\n      const segment =\n        rule.operator && operatorTakesValue(operator) ? \"value\" : \"operator\"\n      focusStore.set({ id: ruleId, segment, autoOpen: true })\n    }\n  }\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"filters\"\n      data-empty={rules.length === 0 || undefined}\n      /* A presence hook, so a consumer can tint the whole read-only bar. */\n      data-readonly={actions.readOnly || undefined}\n      className={cn(\n        /* `sizes.button` and not `actions.size`: the gap ladder and the control\n           ladder must answer for the same rung, normalized in one place. */\n        filtersBarVariants({ size: sizes.button }),\n        /* An empty toolbar is still a flex child, so it took a gap with no\n           width. The gap goes, not the toolbar, which owns the row's name. */\n        rules.length === 0 && \"gap-0\",\n        className\n      )}\n    >\n      <div\n        role=\"toolbar\"\n        aria-label={actions.labels.filtersLabel}\n        aria-orientation=\"horizontal\"\n        /* `role=toolbar` disallows `aria-readonly`, and `aria-disabled` would\n           deny arrowing; a description is legal here and spoken on entry. */\n        {...(actions.readOnly\n          ? { \"aria-description\": actions.labels.readOnly }\n          : null)}\n        className={cn(filtersBarVariants({ size: sizes.button }))}\n        onKeyDown={onKeyDown}\n      >\n        {rules.map((rule, index) => (\n          <FilterChip key={rule.id} rule={rule} index={index} />\n        ))}\n      </div>\n\n      <FiltersBuilder trigger={trigger} />\n\n      {showClear && ruleCount > 0 ? (\n        // `ms-auto` and not `ml-auto`, so Clear stays on the trailing edge\n        // under RTL, where the whole bar mirrors.\n        <Button\n          variant=\"outline\"\n          /* The same rung as the Add filter trigger beside it. */\n          size={sizes.button}\n          className=\"ms-auto\"\n          /* `disabled` for the hard flag, `aria-disabled` for the soft one, so\n             a read-only Clear keeps its tab stop and can still be found. */\n          disabled={actions.disabled}\n          {...filterReadOnlyProps(actions)}\n          onClick={() => actions.clearQuery()}\n        >\n          {actions.labels.clear}\n        </Button>\n      ) : null}\n\n      {/* Keyed on the sequence, so the same sentence twice is two\n          announcements (see `announced` for the measurement). A replaced live\n          element stops being watched. */}\n      <div aria-live=\"polite\" role=\"status\" className=\"sr-only\">\n        <span key={announcementSeq}>{announcement}</span>\n      </div>\n    </div>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Exports                                  */\n/* -------------------------------------------------------------------------- */\n\n// The full pure READ surface, so one import reaches everything a predicate, a\n// saved view or a backend query needs. It stops at the query TREE and compiles\n// nothing: `flattenFilterConditions` is the hand-off a server compiles from.\n// No SQL emitter, because a server has to re-validate anything a browser sends\n// and should compile from the tree rather than parse a client's string. SQL is\n// one target of that hand-off beside Prisma, Drizzle, a REST query string and\n// Elasticsearch.\nexport {\n  // The panel does not DRAW the built-in reasons, so this is the only way to\n  // surface \"missing value\", \"empty group\" and the rest.\n  collectFilterIssues,\n  copyFilterNodeTo,\n  createFilterGroup,\n  createFilterQuery,\n  createFilterRule,\n  countFilterRules,\n  flattenFilterConditions,\n  flattenFilterRules,\n  isFilterQueryEmpty,\n  isFilterRuleComplete,\n  moveFilterNodeTo,\n  pruneFilterQuery,\n  unwrapFilterGroup,\n  wrapFilterNodeInGroup,\n} from \"@/components/reui/filters/filters-query\"\n\n// The two resolver signatures `collectFilterIssues` takes.\nexport type {\n  FilterArityResolver,\n  FilterValidateResolver,\n} from \"@/components/reui/filters/filters-query\"\n\nexport {\n  // The read-only contract: the gate, and the props a mutating control wears.\n  filterReadOnlyProps,\n  isFilterLocked,\n  useFilterActions,\n  useFilterState,\n  useFilterFocus,\n  // What a custom chip needs to rebuild the roving scheme `renderChip` drops.\n  useFilterChipAutoOpen,\n  useFilterChipFocused,\n  useFilterFocusEmpty,\n  useFilterFocusStore,\n  useFilterRender,\n  useFilterSegmentFocus,\n} from \"@/components/reui/filters/filters-context\"\n\nexport {\n  FilterChip,\n  FilterOperatorPopover,\n  FilterRuleMenuItems,\n  FilterValuePopover,\n  useFilterRuleDisplay,\n} from \"@/components/reui/filters/filters-chip\"\nexport {\n  FiltersAdvanced,\n  FiltersAdvancedPanel,\n  FilterAdvancedRow,\n} from \"@/components/reui/filters/filters-advanced\"\nexport {\n  FiltersBuilder,\n  FilterFieldPicker,\n} from \"@/components/reui/filters/filters-builder\"\nexport { DEFAULT_FILTER_LABELS } from \"@/components/reui/filters/filters-i18n\"\nexport {\n  DEFAULT_FILTER_OPERATORS,\n  DEFAULT_FILTER_OPERATOR_LABELS,\n} from \"@/components/reui/filters/filters-operators\"\nexport {\n  DEFAULT_FILTER_EDITORS,\n  useFilterOptions,\n  useFilterValueResolution,\n} from \"@/components/reui/filters/filters-editors\"\n\nexport type * from \"@/components/reui/filters/filters-types\"\n",
      "type": "registry:ui",
      "target": "components/reui/filters/filters.tsx"
    }
  ],
  "type": "registry:ui"
}