# Animated Filter for UI SDK (/docs/components/filter)

The faceted filter of a data table's toolbar: a dashed chip that opens a searchable list of values with counts, built on UI SDK's combobox. Chosen values arrive in the chip as badges one after another while the chip widens around them on a spring, counts roll, and a bar of filters slides its Reset in while any is active.

<ComponentPreview slug="filter" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport { CircleCheck, CircleDashed, CircleX, Clock, Globe, Store, Truck } from \&#x22;lucide-react\&#x22;\nimport * as React from \&#x22;react\&#x22;\n\nimport { Filter, FilterBar, FilterBarReset, type FilterItem } from \&#x22;@/components/keyframery/filter\&#x22;\n\ntype Order = { id: string; customer: string; total: string; status: string; channel: string; fulfilment: string }\n\nconst orders: Order[] = [\n  { id: \&#x22;#1048\&#x22;, customer: \&#x22;Maya Okafor\&#x22;, total: \&#x22;$184.00\&#x22;, status: \&#x22;paid\&#x22;, channel: \&#x22;online\&#x22;, fulfilment: \&#x22;shipped\&#x22; },\n  { id: \&#x22;#1047\&#x22;, customer: \&#x22;Jonas Berg\&#x22;, total: \&#x22;$62.50\&#x22;, status: \&#x22;pending\&#x22;, channel: \&#x22;pos\&#x22;, fulfilment: \&#x22;unfulfilled\&#x22; },\n  { id: \&#x22;#1046\&#x22;, customer: \&#x22;Priya Nair\&#x22;, total: \&#x22;$310.20\&#x22;, status: \&#x22;paid\&#x22;, channel: \&#x22;online\&#x22;, fulfilment: \&#x22;unfulfilled\&#x22; },\n  { id: \&#x22;#1045\&#x22;, customer: \&#x22;Leo Martin\&#x22;, total: \&#x22;$48.00\&#x22;, status: \&#x22;refunded\&#x22;, channel: \&#x22;online\&#x22;, fulfilment: \&#x22;shipped\&#x22; },\n  { id: \&#x22;#1044\&#x22;, customer: \&#x22;Ana Ruiz\&#x22;, total: \&#x22;$129.90\&#x22;, status: \&#x22;paid\&#x22;, channel: \&#x22;wholesale\&#x22;, fulfilment: \&#x22;shipped\&#x22; },\n  { id: \&#x22;#1043\&#x22;, customer: \&#x22;Sam Carter\&#x22;, total: \&#x22;$75.00\&#x22;, status: \&#x22;failed\&#x22;, channel: \&#x22;online\&#x22;, fulfilment: \&#x22;unfulfilled\&#x22; },\n  { id: \&#x22;#1042\&#x22;, customer: \&#x22;Hana Sato\&#x22;, total: \&#x22;$212.40\&#x22;, status: \&#x22;pending\&#x22;, channel: \&#x22;online\&#x22;, fulfilment: \&#x22;unfulfilled\&#x22; },\n  { id: \&#x22;#1041\&#x22;, customer: \&#x22;Owen Price\&#x22;, total: \&#x22;$96.10\&#x22;, status: \&#x22;paid\&#x22;, channel: \&#x22;pos\&#x22;, fulfilment: \&#x22;shipped\&#x22; },\n  { id: \&#x22;#1040\&#x22;, customer: \&#x22;Ines Costa\&#x22;, total: \&#x22;$58.00\&#x22;, status: \&#x22;paid\&#x22;, channel: \&#x22;online\&#x22;, fulfilment: \&#x22;shipped\&#x22; },\n]\n\nconst icon = { size: 14, strokeWidth: 1.75 }\n\nconst facets = [\n  {\n    key: \&#x22;status\&#x22;,\n    label: \&#x22;Status\&#x22;,\n    options: [\n      { value: \&#x22;paid\&#x22;, label: \&#x22;Paid\&#x22;, icon: <CircleCheck {...icon} /> },\n      { value: \&#x22;pending\&#x22;, label: \&#x22;Pending\&#x22;, icon: <Clock {...icon} /> },\n      { value: \&#x22;refunded\&#x22;, label: \&#x22;Refunded\&#x22;, icon: <CircleDashed {...icon} /> },\n      { value: \&#x22;failed\&#x22;, label: \&#x22;Failed\&#x22;, icon: <CircleX {...icon} /> },\n    ],\n  },\n  {\n    key: \&#x22;channel\&#x22;,\n    label: \&#x22;Channel\&#x22;,\n    options: [\n      { value: \&#x22;online\&#x22;, label: \&#x22;Online store\&#x22;, icon: <Globe {...icon} /> },\n      { value: \&#x22;pos\&#x22;, label: \&#x22;In person\&#x22;, icon: <Store {...icon} /> },\n      { value: \&#x22;wholesale\&#x22;, label: \&#x22;Wholesale\&#x22;, icon: <Truck {...icon} /> },\n    ],\n  },\n  {\n    key: \&#x22;fulfilment\&#x22;,\n    label: \&#x22;Fulfilment\&#x22;,\n    options: [\n      { value: \&#x22;unfulfilled\&#x22;, label: \&#x22;Unfulfilled\&#x22; },\n      { value: \&#x22;shipped\&#x22;, label: \&#x22;Shipped\&#x22; },\n    ],\n  },\n] as const\n\ntype Key = (typeof facets)[number][\&#x22;key\&#x22;]\n\nconst statusLabel: Record<string, string> = { paid: \&#x22;Paid\&#x22;, pending: \&#x22;Pending\&#x22;, refunded: \&#x22;Refunded\&#x22;, failed: \&#x22;Failed\&#x22; }\n\nexport default function FilterDemo({\n  label = \&#x22;Status\&#x22;,\n  multiple = true,\n  filters = 3,\n  maxBadges = 2,\n  counts = true,\n  icons = true,\n  search = true,\n  reset = true,\n  height = 32,\n  radius = 9,\n  listWidth = 240,\n  border = \&#x22;\&#x22;,\n  accent = \&#x22;\&#x22;,\n  badge = \&#x22;\&#x22;,\n  face = \&#x22;\&#x22;,\n}: {\n  label?: string\n  multiple?: boolean\n  filters?: number\n  maxBadges?: number\n  counts?: boolean\n  icons?: boolean\n  search?: boolean\n  reset?: boolean\n  height?: number\n  radius?: number\n  listWidth?: number\n  border?: string\n  accent?: string\n  badge?: string\n  face?: string\n}) {\n  const [chosen, setChosen] = React.useState<Record<Key, string[]>>({ status: [], channel: [], fulfilment: [] })\n\n  const matches = (order: Order, except?: Key) =>\n    (Object.keys(chosen) as Key[]).every((key) => key === except || !chosen[key].length || chosen[key].includes(order[key]))\n  const rows = orders.filter((order) => matches(order))\n\n  const style = {\n    \&#x22;--filter-height\&#x22;: `${height}px`,\n    \&#x22;--filter-radius\&#x22;: `${radius}px`,\n    \&#x22;--filter-list-width\&#x22;: `${listWidth}px`,\n    ...(border ? { \&#x22;--filter-border\&#x22;: border } : null),\n    ...(accent ? { \&#x22;--filter-accent\&#x22;: accent } : null),\n    ...(badge ? { \&#x22;--filter-badge\&#x22;: badge } : null),\n    ...(face ? { \&#x22;--filter-face\&#x22;: face } : null),\n  } as React.CSSProperties\n\n  return (\n    <div\n      style={style}\n      className=\&#x22;@container w-full max-w-[600px] overflow-hidden rounded-[16px] bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.12)] dark:bg-card dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07)]\&#x22;\n    >\n      <div className=\&#x22;flex items-baseline justify-between px-4 pt-4 pb-3\&#x22;>\n        <div className=\&#x22;text-[15px] font-semibold tracking-tight\&#x22;>Orders</div>\n        <div className=\&#x22;text-[12px] text-muted-foreground tabular-nums\&#x22;>\n          {rows.length} of {orders.length}\n        </div>\n      </div>\n      <div className=\&#x22;px-4 pb-3\&#x22;>\n        <FilterBar>\n          {facets.slice(0, filters).map((facet, index) => {\n            const options: FilterItem[] = facet.options.map((option) => ({\n              value: option.value,\n              label: option.label,\n              icon: icons && \&#x22;icon\&#x22; in option ? option.icon : undefined,\n              count: counts ? orders.filter((order) => matches(order, facet.key) && order[facet.key] === option.value).length : undefined,\n            }))\n            return (\n              <Filter\n                key={facet.key}\n                label={index === 0 ? label : facet.label}\n                options={options}\n                multiple={index === 0 ? multiple : facet.key !== \&#x22;fulfilment\&#x22;}\n                maxBadges={maxBadges}\n                hideSearch={!search}\n                value={chosen[facet.key]}\n                onValueChange={(value) => setChosen((now) => ({ ...now, [facet.key]: value }))}\n              />\n            )\n          })}\n          {reset && <FilterBarReset />}\n        </FilterBar>\n      </div>\n      <ul className=\&#x22;border-t border-border\&#x22;>\n        {rows.slice(0, 5).map((order) => (\n          <li key={order.id} className=\&#x22;grid grid-cols-[3.25rem_1fr_auto] items-center @md:grid-cols-[3.5rem_1fr_auto_5rem] gap-3 border-b border-border/70 px-4 py-2.5 text-[13px] last:border-b-0\&#x22;>\n            <span className=\&#x22;font-mono text-[12px] text-muted-foreground\&#x22;>{order.id}</span>\n            <span className=\&#x22;truncate font-medium\&#x22;>{order.customer}</span>\n            <span className=\&#x22;hidden text-[12px] text-muted-foreground @md:block\&#x22;>{statusLabel[order.status]}</span>\n            <span className=\&#x22;text-right tabular-nums\&#x22;>{order.total}</span>\n          </li>\n        ))}\n        {rows.length === 0 && <li className=\&#x22;px-4 py-8 text-center text-[13px] text-muted-foreground\&#x22;>No orders match these filters.</li>}\n      </ul>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;label&#x22;:[2610,2618],&#x22;multiple&#x22;:[2633,2637],&#x22;filters&#x22;:[2651,2652],&#x22;maxBadges&#x22;:[2668,2669],&#x22;counts&#x22;:[2682,2686],&#x22;icons&#x22;:[2698,2702],&#x22;search&#x22;:[2715,2719],&#x22;reset&#x22;:[2731,2735],&#x22;height&#x22;:[2748,2750],&#x22;radius&#x22;:[2763,2764],&#x22;listWidth&#x22;:[2780,2783],&#x22;border&#x22;:[2796,2798],&#x22;accent&#x22;:[2811,2813],&#x22;badge&#x22;:[2825,2827],&#x22;face&#x22;:[2838,2840]},&#x22;root&#x22;:[3867,6353],&#x22;importOffset&#x22;:239}" />

## Installation [#installation]

**CLI**

```bash
npx shadcn@latest add @keyframery/filter
```

This adds `components/keyframery/filter.tsx` and its primitive to your project, and installs UI SDK, along with [combobox](/docs/components/combobox), [badge](/docs/components/badge), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.9 @ui-sdk/react@0.1.0-beta.9 lucide-react clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"springy"` (the default), `"calm"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [combobox](/docs/components/combobox), [badge](/docs/components/badge) the same way first.

**Copy the component**

**components/keyframery/filter.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/filter"

/* Styled faceted filter: the animated primitive plus the Keyframery look. A chip with a dashed
   outline that names a column; its list is searchable, every option has a box, an optional icon and
   a count; what is chosen shows in the chip as small badges after a hairline.

   `Filter` with no children renders the whole thing from `options`. Pass children to compose the
   parts yourself (`FilterTrigger`, `FilterContent`, `FilterOption`, …).

   Theming: set these CSS variables on a filter, a bar or anything around them. Each falls back to
   the theme's own token, so nothing changes until you set one.
     --filter-face     the chip's surface while hovered or open, and the list's sheet  (default: --popover)
     --filter-ink      the chip's label and the options                               (default: --foreground)
     --filter-border   the chip's dashed outline                                      (default: --border)
     --filter-accent   a checked option's box                                         (default: --primary)
     --filter-badge    the chosen values' badges                                      (default: --secondary)
     --filter-radius   the chip's corners                                             (default: 9px)
     --filter-height   the chip's height                                              (default: 2rem) */

import { Check, CirclePlus, Search, X } from "lucide-react"
import * as React from "react"

import { Badge, Roll } from "@/components/keyframery/badge"
import {
  Filter as FilterPrimitive,
  FilterBar as FilterBarPrimitive,
  FilterBarReset as FilterBarResetPrimitive,
  FilterClear as FilterClearPrimitive,
  FilterContent as FilterContentPrimitive,
  FilterEmpty as FilterEmptyPrimitive,
  FilterInput as FilterInputPrimitive,
  FilterList as FilterListPrimitive,
  FilterOption as FilterOptionPrimitive,
  type FilterOptionData,
  FilterOptionIndicator as FilterOptionIndicatorPrimitive,
  FilterSeparator as FilterSeparatorPrimitive,
  FilterTrigger as FilterTriggerPrimitive,
  FilterValues as FilterValuesPrimitive,
} from "@/components/keyframery/primitives/filter"
import { Speed, type SpeedProps, useSpeedStyle } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* One size and one stroke for every icon in the filter. */
const icon = { size: 14, strokeWidth: 1.75, "aria-hidden": true } as const

/* UI SDK parts take a class name or a function of the part's state. Keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/** An option, with an icon if you like. */
type FilterItem = FilterOptionData & { icon?: React.ReactNode }

function FilterTrigger({ className, ...props }: React.ComponentProps<typeof FilterTriggerPrimitive>) {
  return (
    <FilterTriggerPrimitive
      className={withClass(
        cn(
          "inline-flex h-[var(--filter-height,2rem)] shrink-0 cursor-pointer items-center rounded-[var(--filter-radius,9px)] pr-1.5 pl-2.5 text-[13px] leading-none font-medium whitespace-nowrap text-[color:var(--filter-ink,var(--foreground))] outline-none select-none",
          "border border-dashed border-[color:var(--filter-border,var(--border))] bg-transparent",
          "[&>svg]:mr-1.5 [&>svg]:shrink-0 [&>svg]:text-muted-foreground",
          "hover:border-[color:color-mix(in_oklab,var(--filter-border,var(--border)),var(--foreground)_18%)] hover:bg-[color-mix(in_oklab,var(--filter-ink,var(--foreground))_4%,transparent)]",
          "data-open:border-solid data-open:bg-[var(--filter-face,var(--popover))] data-open:shadow-[0_1px_2px_rgb(0_0_0/0.06)] dark:data-open:bg-accent",
          "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
          "data-disabled:pointer-events-none data-disabled:opacity-50",
          /* Without values the label keeps an even right inset. */
          "has-[[data-slot=filter-values][data-empty]]:pr-2.5",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The chosen values: a hairline, then up to `max` badges, else "3 selected" with the number rolling.
   In a narrow bar (under 28rem) only the number shows. */
function FilterValues({ max = 2, className, ...props }: Omit<React.ComponentProps<typeof FilterValuesPrimitive>, "children"> & { max?: number }) {
  return (
    <FilterValuesPrimitive className={className} {...props}>
      {(state) =>
        state.count === 0
          ? null
          : [
              <span key="rule" className="mx-2 h-4 w-px bg-border" />,
              <Badge
                key="count"
                variant="secondary"
                count={state.count}
                className={cn(
                  "h-5 rounded-[5px] bg-[var(--filter-badge,var(--secondary))] px-1.5 font-medium",
                  state.count > max ? "inline-flex" : "hidden @max-md/filter-bar:inline-flex",
                )}
              >
                {state.count > max ? "selected" : null}
              </Badge>,
              ...(state.count > max
                ? []
                : state.chosen.map((label, index) => (
                    <Badge
                      key={state.value[index]}
                      variant="secondary"
                      className="ml-1 h-5 rounded-[5px] bg-[var(--filter-badge,var(--secondary))] px-1.5 font-medium first-of-type:ml-0 @max-md/filter-bar:hidden"
                    >
                      {label}
                    </Badge>
                  ))),
            ]
      }
    </FilterValuesPrimitive>
  )
}

function FilterContent({ className, children, sideOffset = 6, style, ...props }: React.ComponentProps<typeof FilterContentPrimitive>) {
  return (
    <FilterContentPrimitive
      sideOffset={sideOffset}
      className={withClass(
        cn(
          "group/content flex w-[var(--filter-list-width,15rem)] flex-col overflow-hidden rounded-[14px] bg-[var(--filter-face,var(--popover))] text-[color:var(--filter-ink,var(--popover-foreground))] outline-none",
          "[--list-height:var(--available-height)]",
          "shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_2px_6px_-2px_rgb(0_0_0/0.08),0_12px_32px_-8px_rgb(0_0_0/0.18)]",
          "dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08),0_12px_32px_-8px_rgb(0_0_0/0.7)]",
        ),
        className,
      )}
      style={useSpeedStyle(style)}
      {...props}
    >
      {children}
    </FilterContentPrimitive>
  )
}

/* The search field: a magnifier and bare text over a hairline. */
function FilterInput({ className, ...props }: React.ComponentProps<typeof FilterInputPrimitive>) {
  return (
    <div data-slot="filter-search" className="flex h-10 shrink-0 items-center gap-2 border-b border-border px-3 text-muted-foreground">
      <Search {...icon} />
      <FilterInputPrimitive
        className={withClass(
          "h-full min-w-0 flex-1 bg-transparent text-[13px] text-[color:var(--filter-ink,var(--foreground))] outline-none placeholder:text-muted-foreground",
          className,
        )}
        {...props}
      />
    </div>
  )
}

function FilterList({ className, ...props }: React.ComponentProps<typeof FilterListPrimitive>) {
  return (
    <FilterListPrimitive
      className={withClass(
        cn(
          "max-h-[min(calc(var(--list-height,100vh)-56px),17rem)] scroll-py-1.5 overflow-y-auto overscroll-contain p-1.5 outline-none",
          "group-has-[[data-slot=combobox-empty][data-empty]]/content:hidden",
          "before:rounded-[8px] before:bg-accent",
        ),
        className,
      )}
      {...props}
    />
  )
}

const row =
  "group/item relative flex min-h-8 cursor-default items-center gap-2.5 rounded-[8px] px-2 py-1.5 text-[13px] leading-[1.3] outline-none select-none data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-40"

/* A box that fills and draws its check when the option is chosen. */
function FilterOptionIndicator({ className, keepMounted = true, ...props }: React.ComponentProps<typeof FilterOptionIndicatorPrimitive>) {
  return (
    <FilterOptionIndicatorPrimitive
      keepMounted={keepMounted}
      className={withClass(
        cn(
          "grid size-4 shrink-0 place-items-center rounded-[5px] text-transparent",
          "shadow-[inset_0_0_0_1px_rgb(0_0_0/0.18)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.2)]",
          "transition-[background-color,box-shadow,scale] duration-[calc(320ms*var(--kf-speed,1))] ease-pop",
          "data-selected:bg-[var(--filter-accent,var(--primary))] data-selected:text-primary-foreground data-selected:shadow-[inset_0_0_0_1px_var(--filter-accent,var(--primary))]",
          "group-active/item:scale-[0.88]",
          "[&_path]:[stroke-dasharray:1_2] [&_path]:[stroke-dashoffset:1.2] [&_path]:transition-[stroke-dashoffset] [&_path]:delay-[calc(60ms*var(--kf-speed,1))] [&_path]:duration-[calc(260ms*var(--kf-speed,1))] [&_path]:ease-house",
          "data-selected:[&_path]:[stroke-dashoffset:0] group-data-starting-style/content:[&_path]:[stroke-dashoffset:1.2]!",
          "motion-reduce:transition-none! motion-reduce:[&_path]:transition-none!",
        ),
        className,
      )}
      {...props}
    >
      <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m3.5 8.5 3 3 6-7" pathLength={1} />
      </svg>
    </FilterOptionIndicatorPrimitive>
  )
}

/* One option: box, icon, label and a count at the end that rolls when it changes. */
function FilterOption({
  className,
  icon: optionIcon,
  count,
  children,
  ...props
}: React.ComponentProps<typeof FilterOptionPrimitive> & { icon?: React.ReactNode; count?: number }) {
  return (
    <FilterOptionPrimitive className={withClass(row, className)} {...props}>
      {(state) => (
        <>
          <FilterOptionIndicator />
          {optionIcon && <span className="grid size-4 shrink-0 place-items-center text-muted-foreground [&_svg]:size-3.5">{optionIcon}</span>}
          <span className="min-w-0 flex-1 truncate">{typeof children === "function" ? children(state) : children}</span>
          {count !== undefined && (
            <span className="ml-auto pl-2 font-mono text-[12px] text-muted-foreground tabular-nums">
              <Roll text={String(count)} />
              <span className="sr-only">{count}</span>
            </span>
          )}
        </>
      )}
    </FilterOptionPrimitive>
  )
}

function FilterSeparator({ className, ...props }: React.ComponentProps<typeof FilterSeparatorPrimitive>) {
  return <FilterSeparatorPrimitive className={withClass("-mx-1.5 my-1.5 h-px bg-border", className)} {...props} />
}

/* "Clear filter", centred under a hairline. */
function FilterClear({ className, ...props }: React.ComponentProps<typeof FilterClearPrimitive>) {
  return <FilterClearPrimitive className={withClass(cn(row, "justify-center font-medium"), className)} {...props} />
}

function FilterEmpty({ className, ...props }: React.ComponentProps<typeof FilterEmptyPrimitive>) {
  return (
    <FilterEmptyPrimitive
      className={withClass("hidden px-3 py-6 text-center text-[13px] text-muted-foreground data-empty:block", className)}
      {...props}
    />
  )
}

type FilterProps = Omit<React.ComponentProps<typeof FilterPrimitive>, "options"> &
  SpeedProps & {
    /** The values to choose from, each with an optional `icon` and `count`. */
    options?: readonly FilterItem[]
    /** How many chosen values show as badges before they read "3 selected". */
    maxBadges?: number
    /** The search field's placeholder. Defaults to the label. */
    placeholder?: string
    /** What the list says when nothing matches. */
    emptyText?: string
    /** Leaves out the search field. */
    hideSearch?: boolean
  }

/* With no children, the whole filter from `options`: chip, list, counts and the clear row. */
function Filter({ speed, options, maxBadges = 2, placeholder, emptyText = "No results.", hideSearch = false, label, className, children, ...props }: FilterProps) {
  return (
    <Speed speed={speed}>
      <FilterPrimitive label={label} options={options} className={withClass("inline-flex", className)} {...props}>
        {children ?? (
          <>
            <FilterTrigger>
              <CirclePlus {...icon} />
              {label}
              <FilterValues max={maxBadges} />
            </FilterTrigger>
            <FilterContent>
              {!hideSearch && <FilterInput placeholder={placeholder ?? label} />}
              <FilterEmpty>{emptyText}</FilterEmpty>
              <FilterList>
                {(options ?? []).map((option) => (
                  <FilterOption key={option.value} data-value={option.value} value={option.value} label={option.label} disabled={option.disabled} icon={option.icon} count={option.count}>
                    {option.label}
                  </FilterOption>
                ))}
                <FilterClearRow />
              </FilterList>
            </FilterContent>
          </>
        )}
      </FilterPrimitive>
    </Speed>
  )
}

/* The clear row with the hairline above it; both leave together. */
function FilterClearRow() {
  return (
    <>
      <FilterSeparator className="hidden has-[+[data-slot=combobox-item]]:block" />
      <FilterClear />
    </>
  )
}

/* The toolbar row. Wraps at phone width, and is the container the chips read their width from. */
function FilterBar({ className, ...props }: React.ComponentProps<typeof FilterBarPrimitive>) {
  return <FilterBarPrimitive className={withClass("@container/filter-bar flex w-full flex-wrap items-center gap-2", className)} {...props} />
}

function FilterBarReset({ className, children, ...props }: React.ComponentProps<typeof FilterBarResetPrimitive>) {
  return (
    <FilterBarResetPrimitive
      className={withClass(
        "inline-flex h-[var(--filter-height,2rem)] cursor-pointer items-center gap-1.5 rounded-[var(--filter-radius,9px)] px-2.5 text-[13px] leading-none font-medium text-muted-foreground outline-none hover:bg-[color-mix(in_oklab,var(--foreground)_5%,transparent)] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
        className,
      )}
      {...props}
    >
      {children ?? (
        <>
          Reset
          <X {...icon} />
        </>
      )}
    </FilterBarResetPrimitive>
  )
}

export {
  Filter,
  FilterBar,
  FilterBarReset,
  FilterClear,
  FilterContent,
  FilterEmpty,
  FilterInput,
  FilterList,
  FilterOption,
  FilterOptionIndicator,
  FilterSeparator,
  FilterTrigger,
  FilterValues,
  type FilterItem,
}
```

**components/keyframery/primitives/filter.tsx**

```tsx
"use client"

/* Animated faceted filter, on UI SDK's core. UI SDK ships no filter, so its state is defined in
   `@/components/core/filter` with `definePrimitive`, and its list is UI SDK's combobox (multiple,
   with the search field inside the popup), controlled from that state. This file adds motion only.
   Colours, radii, shadows and spacing stay yours.

   - Unfold: the list grows out of its chip (the combobox's own motion), its rows Cascade in and one
     highlight Glides between them.
   - Widen: the chosen values sit in a box whose width follows what it holds on a spring, so the chip
     widens and narrows around new badges without stretching its text.
   - Cascade: badges arrive one after another, each popping in from a smaller, blurred start.
   - Roll: "3 selected" and the option counts are rolling digits (use `Roll` from the badge).
   - The bar's reset button slides in from the left while any filter is active, and out again. */

import type { StateOf } from "@ui-sdk/core"
import { createParts, type PartProps, usePart, usePrimitive, type PrimitiveHandle } from "@ui-sdk/react/primitive"
import * as React from "react"

import { FILTER_CLEAR, filter, filterBar, type FilterOptions, type FilterState, filterValues } from "@/components/keyframery/core/filter-core"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxList,
  type ComboboxProps,
  ComboboxSeparator,
  ComboboxTrigger,
} from "@/components/keyframery/primitives/combobox"
import { cn } from "@/lib/utils"

/* UI SDK parts take a class name or a function of the part's state. Keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* The instance, and the chip the list opens from, shared with the parts inside (the content renders
   in a portal, so it anchors to the chip through this). */
type FilterContextValue = {
  handle: PrimitiveHandle<typeof filter>
  anchor: HTMLElement | null
  setAnchor: (el: HTMLElement | null) => void
}
const FilterContext = React.createContext<FilterContextValue | null>(null)

function useFilter(part: string) {
  const context = React.use(FilterContext)
  if (!context) throw new Error(`${part} must be inside a Filter.`)
  return context
}

type FilterProps = FilterOptions &
  Omit<PartProps<"div", StateOf<typeof filter, "root">>, "defaultValue"> & {
    /** Passed to the combobox inside, like `loop` or `autoHighlight`. */
    comboboxProps?: Omit<ComboboxProps<string, true>, "value" | "defaultValue" | "onValueChange" | "open" | "onOpenChange" | "query" | "onQueryChange" | "multiple">
  }

/* The filter: its root and the combobox it controls. Put a `FilterTrigger` and a `FilterContent` inside. */
function Filter({
  label,
  options,
  value,
  defaultValue,
  onValueChange,
  multiple,
  open,
  defaultOpen,
  onOpenChange,
  comboboxProps,
  children,
  ...props
}: FilterProps) {
  const handle = usePrimitive(filter, { label, options, value, defaultValue, onValueChange, multiple, open, defaultOpen, onOpenChange })
  const [anchor, setAnchor] = React.useState<HTMLElement | null>(null)
  const labelOf = React.useCallback(
    (entry: string) => handle.state.options.find((option) => option.value === entry)?.label ?? entry,
    [handle],
  )
  const root = usePart(
    handle,
    "root",
    {},
    {
      ...props,
      children: (state) => (
        <Combobox<string, true>
          multiple
          loop
          autoHighlight
          itemToLabel={labelOf}
          {...comboboxProps}
          value={state.value}
          onValueChange={(next, details) => handle.api.choose(next, details)}
          open={state.open}
          onOpenChange={(next, details) => handle.api.setOpen(next, details)}
          query={state.query}
          onQueryChange={(next) => handle.api.search(next)}
          onOpenChangeComplete={(isOpen) => {
            comboboxProps?.onOpenChangeComplete?.(isOpen)
            /* Back to the chip, unless focus already went somewhere else on purpose. */
            const active = document.activeElement
            if (!isOpen && (!active || active === document.body)) anchor?.focus()
          }}
        >
          {typeof children === "function" ? children(state) : children}
        </Combobox>
      ),
    },
    "div",
  )
  return <FilterContext value={{ handle, anchor, setAnchor }}>{root}</FilterContext>
}

const press = "transition-[scale,background-color,box-shadow,color] duration-[calc(200ms*var(--kf-speed,1))] ease-pop active:scale-[0.96] motion-reduce:transition-none!"

/* The chip. A button that opens the list. */
function FilterTrigger({ className, ...props }: React.ComponentProps<typeof ComboboxTrigger>) {
  const { setAnchor } = useFilter("FilterTrigger")
  /* The filter around it is what agents use (`setValue`, `toggle`, `clear`); the combobox inside
     would only repeat it under the same name. */
  return <ComboboxTrigger ref={setAnchor} data-agent-hidden="" className={withClass(press, className)} {...props} />
}

/* The filter's state, kept current in parts the root's render doesn't reach (children passed in
   once, like the chip's contents). */
function useFilterState(part: string) {
  const { instance } = useFilter(part).handle
  return React.useSyncExternalStore(
    instance.subscribe,
    () => instance.get() as FilterState,
    () => instance.get() as FilterState,
  )
}

/* The chosen values inside the chip. Its children (a function of the chosen values) are laid in a
   row whose width the box follows on a spring; each child pops in, one after another. A visually
   hidden summary (", 2 selected: Paid, Pending") gives the chip's accessible name the same news. */
function FilterValues({
  className,
  innerClassName,
  children,
  ...props
}: PartProps<"span", StateOf<typeof filterValues, "root">> & {
  /** Classes for the row inside, which is measured. */
  innerClassName?: string
}) {
  const { value, chosen } = useFilterState("FilterValues")
  const handle = usePrimitive(filterValues, { value, chosen })
  return usePart(
    handle,
    "root",
    {},
    {
      ...props,
      className: withClass(
        cn(
          "relative inline-flex shrink-0 overflow-hidden w-(--filter-values-width,auto)",
          "transition-[width,opacity] duration-[calc(460ms*var(--kf-speed,1))] ease-spring data-empty:opacity-0 data-empty:duration-[calc(260ms*var(--kf-speed,1))] data-empty:ease-house",
          "motion-reduce:transition-none!",
        ),
        className,
      ),
      children: (state) => (
        <>
          <span className="sr-only">{state.summary}</span>
          <span
            data-filter-values-row=""
            aria-hidden="true"
            className={cn(
              "inline-flex w-max shrink-0 items-center",
              "[&>*]:transition-[opacity,scale,filter] [&>*]:duration-[calc(420ms*var(--kf-speed,1))] [&>*]:ease-pop",
              "[&>*]:starting:scale-[0.6] [&>*]:starting:opacity-0 [&>*]:starting:blur-[3px]",
              "[&>*]:[transition-delay:calc((min(sibling-index(),6)-1)*calc(70ms*var(--kf-speed,1)))]",
              "motion-reduce:[&>*]:transition-none!",
              innerClassName,
            )}
          >
            {typeof children === "function" ? children(state) : children}
          </span>
        </>
      ),
    },
    "span",
  )
}

/* The popup, anchored to the chip, so it unfolds out of it. */
function FilterContent({ align = "start", ...props }: React.ComponentProps<typeof ComboboxContent>) {
  const { anchor } = useFilter("FilterContent")
  return <ComboboxContent anchor={anchor} align={align} {...props} />
}

/* The search field at the top of the list. Takes focus when the list opens. */
function FilterInput({ autoFocus = true, ...props }: React.ComponentProps<typeof ComboboxInput>) {
  const { handle } = useFilter("FilterInput")
  return <ComboboxInput autoFocus={autoFocus} aria-label={props["aria-label"] ?? `Search ${handle.state.label}`} {...props} />
}

const FilterList = ComboboxList
const FilterEmpty = ComboboxEmpty
const FilterSeparator = ComboboxSeparator
const FilterOptionIndicator = ComboboxItemIndicator

/* One value to choose: a combobox item, keyed by its value. */
function FilterOption(props: React.ComponentProps<typeof ComboboxItem<string>>) {
  return <ComboboxItem<string> {...props} />
}

/* The "Clear filter" row at the foot of the list. Only there while something is chosen; choosing it
   clears the filter. */
function FilterClear({ children, ...props }: Omit<React.ComponentProps<typeof ComboboxItem<string>>, "value">) {
  const { value } = useFilterState("FilterClear")
  if (!value.length) return null
  return (
    <ComboboxItem<string> value={FILTER_CLEAR} label="Clear filter" {...props}>
      {children ?? "Clear filter"}
    </ComboboxItem>
  )
}

const { Root: FilterBarRoot, Reset: FilterBarResetPart } = createParts(filterBar, { root: "div", reset: "button" })

/* The row of filters. Marks `data-active` while any filter inside has a value. */
function FilterBar(props: React.ComponentProps<typeof FilterBarRoot>) {
  return <FilterBarRoot aria-label="Filters" {...props} />
}

/* Clears every filter in the bar. Slides in from the left while one is active, and out again. */
function FilterBarReset({ className, ...props }: React.ComponentProps<typeof FilterBarResetPart>) {
  return (
    <FilterBarResetPart
      className={withClass(
        cn(
          press,
          "transition-[opacity,translate,filter,scale,background-color,color] duration-[calc(420ms*var(--kf-speed,1))] ease-spring",
          "data-hidden:pointer-events-none data-hidden:-translate-x-2 data-hidden:opacity-0 data-hidden:blur-[3px] data-hidden:duration-[calc(180ms*var(--kf-speed,1))] data-hidden:ease-house",
        ),
        className,
      )}
      {...props}
    />
  )
}

export {
  FILTER_CLEAR,
  Filter,
  FilterBar,
  FilterBarReset,
  FilterClear,
  FilterContent,
  FilterEmpty,
  FilterInput,
  FilterList,
  FilterOption,
  FilterOptionIndicator,
  FilterSeparator,
  FilterTrigger,
  FilterValues,
}
export type { FilterOption as FilterOptionData, FilterOptions } from "@/components/keyframery/core/filter-core"
```

**components/keyframery/core/filter-core.ts**

```ts
/* Faceted filters, as UI SDK primitives. UI SDK ships no filter, so these are defined with its core:
   the same definitions render in React, Vue, Svelte, Solid and web components.

   `filter` is one facet of a data table's toolbar: a chip named after a column ("Status") that opens
   a searchable list of that column's values, each with a count. It owns which values are chosen,
   whether its list is open and what is typed in its search. The list itself is UI SDK's combobox
   (multiple, with its input inside the popup), rendered by the adapter and controlled from this
   state: the combobox's `onValueChange`, `onOpenChange` and `onQueryChange` call `choose`,
   `setOpen` and `search` here. The value is always a list of strings; with `multiple: false`,
   choosing a value replaces the one before and closes the list.

   `filterBar` is the row that holds several filters. It counts the filters inside it that have
   something chosen, and its reset button clears them all (each filter hears a `filter-reset`
   event on its root and clears itself, so controlled and uncontrolled filters both work). */

import { type ChangeDetails, createChange, definePrimitive, dispatch } from "@ui-sdk/core"

/** One value a filter offers. */
type FilterOption = {
  /** What the filter's value holds when this option is chosen. */
  value: string
  /** What the option and its badge say. */
  label: string
  /** How many rows have this value. Shown at the option's end. */
  count?: number
  /** Can't be chosen. */
  disabled?: boolean
}

/** The value the "Clear filter" row of the list carries. The filter never stores it. */
const FILTER_CLEAR = "kf-filter-clear"

/* "clear-press", "reset-press" and "imperative" aren't in the shared vocabulary. The combobox's own
   reasons ("item-press", "chip-remove-press", "backspace-key", …) pass through as they are. */
type FilterValueChangeReason = "item-press" | "clear-press" | "reset-press" | "imperative" | (string & {})
type FilterOpenChangeReason = "trigger-press" | "item-press" | "escape-key" | "outside-press" | "focus-out" | "imperative" | (string & {})

type FilterOptions = {
  /** The column or facet the filter narrows, like "Status". Names the chip, its list and the filter for agents. */
  label?: string
  /** The values to choose from. */
  options?: readonly FilterOption[]
  /** The chosen values, controlled. */
  value?: string[]
  /** The chosen values at first, when uncontrolled. */
  defaultValue?: string[]
  /** Runs when the chosen values want to change. `details.cancel()` keeps them. */
  onValueChange?: (value: string[], details: ChangeDetails<FilterValueChangeReason>) => void
  /** Several values at once (the default), or one that replaces the last. */
  multiple?: boolean
  /** Whether the list is open, controlled. */
  open?: boolean
  /** Whether the list starts open, when uncontrolled. */
  defaultOpen?: boolean
  /** Runs when the list wants to open or close. */
  onOpenChange?: (open: boolean, details: ChangeDetails<FilterOpenChangeReason>) => void
}

type FilterState = {
  label: string
  options: readonly FilterOption[]
  value: string[]
  /** The chosen options' labels, in the options' order. */
  chosen: string[]
  multiple: boolean
  open: boolean
  query: string
}

const labelsOf = (options: readonly FilterOption[], value: readonly string[]) =>
  options.filter((option) => value.includes(option.value)).map((option) => option.label)

/* Chosen values in the options' order, so badges don't reorder as people pick. Values the options
   don't know (yet) stay at the end. */
const ordered = (options: readonly FilterOption[], value: readonly string[]) => [
  ...options.filter((option) => value.includes(option.value)).map((option) => option.value),
  ...value.filter((entry) => !options.some((option) => option.value === entry)),
]

const filter = definePrimitive({
  name: "filter",
  options: {
    label: "string",
    options: "value",
    value: "list",
    defaultValue: "list",
    onValueChange: "callback",
    multiple: "boolean",
    open: "boolean",
    defaultOpen: "boolean",
    onOpenChange: "callback",
  },
  state: (options: FilterOptions): FilterState => {
    const value = options.value ?? options.defaultValue ?? []
    const list = options.options ?? []
    return {
      label: options.label ?? "Filter",
      options: list,
      value,
      chosen: labelsOf(list, value),
      multiple: options.multiple ?? true,
      open: options.open ?? options.defaultOpen ?? false,
      query: "",
    }
  },
  sync: (options) => ({
    label: options.label ?? "Filter",
    options: options.options ?? [],
    multiple: options.multiple ?? true,
    ...(options.value === undefined ? {} : { value: options.value }),
    ...(options.open === undefined ? {} : { open: options.open }),
  }),
  controlled: ["value", "open", "chosen"],
  api: (context) => {
    const { store } = context
    const change = createChange(context)

    /* `chosen` follows the value and the options, however either changes. */
    let from = { options: store.get().options, value: store.get().value }
    context.onDestroy(
      store.subscribe(() => {
        const { options, value } = store.get()
        if (options === from.options && value === from.value) return
        from = { options, value }
        store.set({ chosen: labelsOf(options, value) })
      }),
    )

    /* A value or a label, matched without regard to case, as an agent or a person might name it. */
    const resolve = (name: string) => {
      const options = store.get().options
      const exact = options.find((option) => option.value === name)
      if (exact) return exact.value
      const lower = name.trim().toLowerCase()
      return options.find((option) => option.label.toLowerCase() === lower || option.value.toLowerCase() === lower)?.value ?? name
    }

    const write = (next: string[], reason: FilterValueChangeReason, event?: Event) => {
      const value = ordered(store.get().options, next)
      const now = store.get().value
      if (value.length === now.length && value.every((entry, index) => entry === now[index])) return false
      return change("value", value, { reason, event })
    }

    const api = {
      /** Chooses exactly these values (by value or label). With `multiple: false`, only the first counts. */
      setValue(value: string[] | string, event?: Event) {
        const list = (Array.isArray(value) ? value : [value]).map(resolve)
        return write(store.get().multiple ? list : list.slice(0, 1), "imperative", event)
      },
      /** Adds a value if it isn't chosen, removes it if it is. */
      toggle(value: string, event?: Event) {
        const key = resolve(value)
        const now = store.get().value
        if (now.includes(key)) return write(now.filter((entry) => entry !== key), "imperative", event)
        return write(store.get().multiple ? [...now, key] : [key], "imperative", event)
      },
      /** Removes every chosen value. */
      clear(event?: Event, reason: FilterValueChangeReason = "clear-press") {
        return write([], reason, event)
      },
      /** What the combobox inside wants the value to be: a toggle, the clear row, or Backspace. */
      choose(next: readonly string[], details: { reason: string; event?: Event }) {
        const { value: now, multiple } = store.get()
        if (next.includes(FILTER_CLEAR)) {
          api.clear(details.event)
          return
        }
        if (multiple) {
          write([...next], details.reason, details.event)
          return
        }
        const added = next.find((entry) => !now.includes(entry))
        write(added ? [added] : [...next].slice(-1).filter((entry) => !now.includes(entry)), details.reason, details.event)
        if (added) api.setOpen(false, { reason: "item-press", event: details.event })
      },
      /** Opens or closes the list. Opening starts the search over. */
      setOpen(open: boolean, details: { reason?: FilterOpenChangeReason; event?: Event } = {}) {
        if (open === store.get().open) return true
        const done = change("open", open, { reason: details.reason ?? "imperative", event: details.event })
        if (done && open) store.set({ query: "" })
        return done
      },
      /** What is typed in the list's search field. */
      search(query: string) {
        if (query !== store.get().query) store.set({ query })
      },
      /** The options, for agents to choose from. */
      items() {
        return store.get().options.map((option) => ({ value: option.value, label: option.label }))
      },
    }
    return api
  },
  slots: (slot) => ({
    /* Wraps the chip and its list. Named after the facet, so the filter reads as "Status". */
    root: slot<{}, { value: string[]; chosen: string[]; open: boolean; query: string; active: boolean }>({
      role: "group",
      state: (state) => ({ value: state.value, chosen: state.chosen, open: state.open, query: state.query, active: state.value.length > 0 }),
      attrs: (state) => ({
        "aria-label": state.label,
        "data-active": state.value.length > 0 ? "" : undefined,
        "data-open": state.open ? "" : undefined,
        "data-count": String(state.value.length),
      }),
      bind: (el, part) => {
        const reset = (event: Event) => part.api.clear(event, "reset-press")
        el.addEventListener("filter-reset", reset)
        return () => el.removeEventListener("filter-reset", reset)
      },
    }),
  }),
  agent: { actions: ["setValue", "toggle", "clear"], items: (api) => api.items() },
})

type FilterValuesOptions = {
  /** The chosen values. */
  value?: string[]
  /** Their labels, in the same order. */
  chosen?: string[]
}

/* The chosen values inside the chip, as a primitive of their own: the chip belongs to the combobox
   (which the filter hides from agents, since the filter already offers everything it does), so its
   contents can't be parts of the filter without hiding the filter too. Its width follows what it
   holds (`--filter-values-width`, measured from its first child), so the chip can widen and narrow
   smoothly. Decorative: the chip's accessible name carries the chosen labels as text. */
const filterValues = definePrimitive({
  name: "filter-values",
  options: { value: "list", chosen: "list" },
  state: (options: FilterValuesOptions) => ({ value: options.value ?? [], chosen: options.chosen ?? [] }),
  sync: (options) => ({ value: options.value ?? [], chosen: options.chosen ?? [] }),
  controlled: [],
  api: () => ({}),
  slots: (slot) => ({
    root: slot<{}, { value: string[]; chosen: string[]; count: number; summary: string }>({
      state: (state) => ({
        value: state.value,
        chosen: state.chosen,
        count: state.value.length,
        summary: state.chosen.length ? `, ${state.chosen.length} selected: ${state.chosen.join(", ")}` : "",
      }),
      attrs: (state) => ({
        "data-empty": state.value.length ? undefined : "",
        "data-count": String(state.value.length),
      }),
      bind: (el) => {
        const measure = () => {
          const inner = el.querySelector<HTMLElement>("[data-filter-values-row]")
          el.style.setProperty("--filter-values-width", `${inner ? inner.offsetWidth : 0}px`)
        }
        const resize = new ResizeObserver(measure)
        const watch = () => {
          resize.disconnect()
          const inner = el.querySelector("[data-filter-values-row]")
          if (inner) resize.observe(inner)
          measure()
        }
        watch()
        const children = new MutationObserver(watch)
        children.observe(el, { childList: true })
        return () => {
          resize.disconnect()
          children.disconnect()
        }
      },
    }),
  }),
  agent: { actions: [] },
})

type FilterBarOptions = {
  /** Runs when the reset button is pressed, before the filters inside clear themselves. `details.cancel()` stops it. */
  onReset?: (value: null, details: ChangeDetails<"reset-press" | "imperative">) => void
}

type FilterBarState = {
  /** How many filters inside have something chosen. */
  active: number
}

const filterBar = definePrimitive({
  name: "filter-bar",
  options: { onReset: "callback" },
  state: (_options: FilterBarOptions): FilterBarState => ({ active: 0 }),
  controlled: ["active"],
  api: (context) => {
    let root: HTMLElement | undefined
    return {
      /** @internal Where the filters are. */
      attach(el: HTMLElement) {
        root = el
        const count = () => {
          const active = el.querySelectorAll('[data-slot="filter"][data-active]').length
          if (active !== context.store.get().active) context.store.set({ active })
        }
        count()
        const observer = new MutationObserver(count)
        observer.observe(el, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-active"] })
        return () => {
          observer.disconnect()
          root = undefined
        }
      },
      /** Clears every filter in the bar. */
      reset(event?: Event) {
        if (!root || !context.store.get().active) return false
        if (dispatch(context, "onReset", null, { reason: event ? "reset-press" : "imperative", event })) return false
        for (const el of root.querySelectorAll('[data-slot="filter"][data-active]')) el.dispatchEvent(new CustomEvent("filter-reset"))
        return true
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { active: number }>({
      role: "group",
      state: (state) => ({ active: state.active }),
      attrs: (state) => ({ "data-active": state.active ? "" : undefined, "data-count": String(state.active) }),
      bind: (el, part) => part.api.attach(el),
    }),
    /* Stays in the page so it can slide out; while nothing is chosen it is inert and hidden. */
    reset: slot<{}, { active: number }>({
      role: "button",
      focus: "native",
      state: (state) => ({ active: state.active }),
      attrs: (state) => ({
        type: "button",
        "data-hidden": state.active ? undefined : "",
        "aria-hidden": state.active ? undefined : "true",
        inert: state.active ? undefined : "",
      }),
      press: ({ api }, event) => api.reset(event),
    }),
  }),
  agent: { actions: ["reset"] },
})

export { FILTER_CLEAR, filter, filterBar, filterValues, type FilterBarOptions, type FilterOption, type FilterOptions, type FilterState }
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

## Usage [#usage]

```tsx
import { Filter } from "@/components/keyframery/filter"

export default function Usage() {
  return (
    <Filter
      label="Status"
      options={[
        { value: "paid", label: "Paid", count: 12 },
        { value: "pending", label: "Pending", count: 4 },
      ]}
    />
  )
}
```

## Examples [#examples]

### A filter with counts [#a-filter-with-counts]

Each option shows how many rows have it. Chosen values appear in the chip as badges; past two they read "3 selected".

<ExamplePreview name="filter/basic">
  ```tsx
  import { Filter } from "@/components/keyframery/filter"

  const priorities = [
    { value: "urgent", label: "Urgent", count: 3 },
    { value: "high", label: "High", count: 8 },
    { value: "medium", label: "Medium", count: 21 },
    { value: "low", label: "Low", count: 14 },
  ]

  export default function FilterBasic() {
    return <Filter label="Priority" options={priorities} defaultValue={["urgent", "high"]} />
  }
  ```
</ExamplePreview>

### A bar of filters, controlled [#a-bar-of-filters-controlled]

The value is always a list of strings. Reset slides in while any filter in the bar is active and clears them all.

<ExamplePreview name="filter/bar">
  ```tsx
  import * as React from "react"

  import { Filter, FilterBar, FilterBarReset } from "@/components/keyframery/filter"

  const tasks = [
    { title: "Renew SSL certificate", status: "todo", owner: "ana" },
    { title: "Ship invoice export", status: "done", owner: "leo" },
    { title: "Fix checkout tax", status: "doing", owner: "ana" },
    { title: "Draft holiday email", status: "todo", owner: "sam" },
  ]

  export default function FilterBarExample() {
    const [status, setStatus] = React.useState<string[]>([])
    const [owner, setOwner] = React.useState<string[]>([])
    const count = (key: "status" | "owner", value: string) =>
      tasks.filter((task) => task[key] === value && (key === "status" ? !owner.length || owner.includes(task.owner) : !status.length || status.includes(task.status))).length
    const shown = tasks.filter((task) => (!status.length || status.includes(task.status)) && (!owner.length || owner.includes(task.owner)))

    return (
      <div className="flex w-full max-w-md flex-col gap-3 text-[13px]">
        <FilterBar>
          <Filter
            label="Status"
            value={status}
            onValueChange={setStatus}
            options={["todo", "doing", "done"].map((value) => ({ value, label: { todo: "To do", doing: "In progress", done: "Done" }[value]!, count: count("status", value) }))}
          />
          <Filter
            label="Owner"
            value={owner}
            onValueChange={setOwner}
            options={["ana", "leo", "sam"].map((value) => ({ value, label: value[0].toUpperCase() + value.slice(1), count: count("owner", value) }))}
          />
          <FilterBarReset />
        </FilterBar>
        <ul className="text-muted-foreground">
          {shown.map((task) => (
            <li key={task.title}>{task.title}</li>
          ))}
        </ul>
      </div>
    )
  }
  ```
</ExamplePreview>

### One value at a time [#one-value-at-a-time]

With `multiple={false}` choosing a value replaces the last one and closes the list. The value is still a list, of one.

<ExamplePreview name="filter/single">
  ```tsx
  import { Filter } from "@/components/keyframery/filter"

  export default function FilterSingle() {
    return (
      <Filter
        label="Plan"
        multiple={false}
        hideSearch
        options={[
          { value: "free", label: "Free", count: 1204 },
          { value: "pro", label: "Pro", count: 318 },
          { value: "team", label: "Team", count: 46 },
        ]}
      />
    )
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                |
| ----------- | ------------------------------------------------------------------------------------------- |
| **Unfold**  | The list grows out of its chip, its rows cascade in, and one highlight glides between them. |
| **Draw**    | A chosen option's box fills with a pop and its check draws itself.                          |
| **Widen**   | The chip's width follows its badges on a spring, so it never stretches its text.            |
| **Cascade** | Badges pop in one after another, from a smaller, blurred start.                             |
| **Roll**    | "3 selected" and every option's count roll to their new number.                             |
| **Slide**   | The bar's Reset slides in from the left while a filter is active, and out again.            |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this filter moves, pass `speed`:

```tsx
<Filter speed="fast">
  …
</Filter>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable              | What it changes                           | Default      |
| --------------------- | ----------------------------------------- | ------------ |
| `--filter-face`       | The chip while open, and the list's sheet | --popover    |
| `--filter-ink`        | The chip's label and the options          | --foreground |
| `--filter-border`     | The chip's dashed outline                 | --border     |
| `--filter-accent`     | A chosen option's box                     | --primary    |
| `--filter-badge`      | The chosen values' badges                 | --secondary  |
| `--filter-radius`     | The chip's corners                        | 9px          |
| `--filter-height`     | The chip's height                         | 2rem         |
| `--filter-list-width` | The list's width                          | 15rem        |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### Filter [#filter]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast it moves: \&#x22;fast\&#x22;, \&#x22;normal\&#x22;, \&#x22;slow\&#x22; or a multiplier.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The column or facet, like \&#x22;Status\&#x22;. Names the chip, the search field and the filter for agents.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultValue&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The chosen values at first, when uncontrolled.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The chosen values, controlled. Always a list of strings, also with `multiple={false}`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;open&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Whether the list is open, controlled, with `defaultOpen` and `onOpenChange`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;multiple&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Several values (the default) or one that replaces the last and closes the list.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onOpenChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(open: boolean, details: ChangeDetails<\&#x22;trigger-press\&#x22; | \&#x22;imperative\&#x22; | (string & {}) | \&#x22;item-press\&#x22; | \&#x22;outside-press\&#x22; | \&#x22;escape-key\&#x22; | \&#x22;focus-out\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs when the list wants to open or close.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultOpen&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Whether the list starts open, when uncontrolled.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onValueChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(value: string[], details: ChangeDetails<\&#x22;imperative\&#x22; | (string & {}) | \&#x22;item-press\&#x22; | \&#x22;clear-press\&#x22; | \&#x22;reset-press\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs with the next list. `details.reason` is \&#x22;item-press\&#x22;, \&#x22;clear-press\&#x22;, \&#x22;reset-press\&#x22;, \&#x22;backspace-key\&#x22; or \&#x22;imperative\&#x22;; `details.cancel()` keeps the current value.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;comboboxProps&#x22;,&#x22;type&#x22;:&#x22;Omit<…>&#x22;,&#x22;full&#x22;:&#x22;Omit<ComboboxProps<string, true>, \&#x22;defaultValue\&#x22; | \&#x22;value\&#x22; | \&#x22;open\&#x22; | \&#x22;multiple\&#x22; | \&#x22;onOpenChange\&#x22; | \&#x22;onValueChange\&#x22; | \&#x22;query\&#x22; | \&#x22;onQueryChange\&#x22;>&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Passed to the combobox inside, like `loop` or `autoHighlight`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;options&#x22;,&#x22;type&#x22;:&#x22;readonly FilterItem[]&#x22;,&#x22;full&#x22;:&#x22;readonly FilterItem[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The values: `{ value, label, icon?, count?, disabled? }`. `count` shows at the row's end and rolls when it changes.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;maxBadges&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:&#x22;2&#x22;,&#x22;description&#x22;:&#x22;How many chosen values show as badges before they read \&#x22;3 selected\&#x22;. Defaults to 2.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;placeholder&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The search field's placeholder. Defaults to the label.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;emptyText&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:&#x22;\&#x22;No results.\&#x22;&#x22;,&#x22;description&#x22;:&#x22;What the list says when nothing matches. Defaults to \&#x22;No results.\&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;hideSearch&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Leaves out the search field, for short lists.&#x22;,&#x22;required&#x22;:false}]" />

### FilterBar [#filterbar]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;onReset&#x22;,&#x22;type&#x22;:&#x22;(value: null, details: ChangeDetails<…>) => void&#x22;,&#x22;full&#x22;:&#x22;(value: null, details: ChangeDetails<\&#x22;reset-press\&#x22; | \&#x22;imperative\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs when Reset is pressed, before the filters clear. `details.cancel()` stops the reset.&#x22;,&#x22;required&#x22;:false}]" />

### FilterClear [#filterclear]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The text the input shows once chosen, and filtering matches, when the content isn't plain text. Not the accessible name: use `aria-label` for that.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;disabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Keeps the item from being chosen. The keyboard and the pointer skip it. Sets `data-disabled` and `aria-disabled`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;keywords&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;More words filtering matches.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;index&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The item's position among all visible items, for virtualized lists that render only some. Sets `aria-posinset` and `aria-setsize`.&#x22;,&#x22;required&#x22;:false}]" />

### FilterContent [#filtercontent]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;side&#x22;,&#x22;type&#x22;:&#x22;\&#x22;end\&#x22; | \&#x22;start\&#x22; | \&#x22;top\&#x22; | \&#x22;bottom\&#x22; | \&#x22;left\&#x22; | \&#x22;right\&#x22;&#x22;,&#x22;full&#x22;:&#x22;Side&#x22;,&#x22;default&#x22;:&#x22;\&#x22;bottom\&#x22;&#x22;,&#x22;description&#x22;:&#x22;Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the input the list opens on.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;align&#x22;,&#x22;type&#x22;:&#x22;\&#x22;center\&#x22; | \&#x22;end\&#x22; | \&#x22;start\&#x22;&#x22;,&#x22;full&#x22;:&#x22;Align&#x22;,&#x22;default&#x22;:&#x22;\&#x22;start\&#x22;&#x22;,&#x22;description&#x22;:&#x22;How the popup lines up with the anchor along that side. `start` and `end` follow the reading direction. How the list lines up with the input along that side.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;sideOffset&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:&#x22;6&#x22;,&#x22;description&#x22;:&#x22;Gap between the anchor and the popup, in pixels. Gap between the input and the list, in pixels.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;alignOffset&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:&#x22;0&#x22;,&#x22;description&#x22;:&#x22;Shift along the anchor, in pixels. Shift along the input, in pixels.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;collisionPadding&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:&#x22;8&#x22;,&#x22;description&#x22;:&#x22;Space to keep from the viewport edges, in pixels.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;arrowPadding&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:&#x22;6&#x22;,&#x22;description&#x22;:&#x22;Space to keep between the arrow and the popup's corners, in pixels.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;anchor&#x22;,&#x22;type&#x22;:&#x22;string | Anchor&#x22;,&#x22;full&#x22;:&#x22;string | Anchor&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Positions the popup against this instead of its trigger: an element, a CSS selector, a point like `{ x, y }`, or anything with `getBoundingClientRect()`. It's read on every check, so it can move. A controller's `open({ anchor })` wins for that open.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;container&#x22;,&#x22;type&#x22;:&#x22;Element | DocumentFragment&#x22;,&#x22;full&#x22;:&#x22;Element | DocumentFragment&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;keepMounted&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Whether the list stays in the page, hidden, while closed.&#x22;,&#x22;required&#x22;:false}]" />

### FilterOption [#filteroption]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;icon&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;count&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The text the input shows once chosen, and filtering matches, when the content isn't plain text. Not the accessible name: use `aria-label` for that.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;keywords&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;More words filtering matches.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;disabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Keeps the item from being chosen. The keyboard and the pointer skip it. Sets `data-disabled` and `aria-disabled`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;index&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The item's position among all visible items, for virtualized lists that render only some. Sets `aria-posinset` and `aria-setsize`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What the value becomes when the item is chosen. A string, or any value with `itemToValue`.&#x22;,&#x22;required&#x22;:true}]" />

### FilterOptionIndicator [#filteroptionindicator]

Renders a `<span>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;keepMounted&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Whether the indicator stays in the page while its item isn't selected.&#x22;,&#x22;required&#x22;:false}]" />

### FilterValues [#filtervalues]

Renders a `<span>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;innerClassName&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Classes for the row inside, which is measured.&#x22;,&#x22;required&#x22;:false}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `FilterBarReset`: a `<button>`
* `FilterEmpty`: a `<div>`
* `FilterInput`: a `<input>`
* `FilterList`: a `<div>`
* `FilterSeparator`: a `<div>`
* `FilterTrigger`: a `<button>`

## Keyboard [#keyboard]

| Key                            | What it does                                                                       |
| ------------------------------ | ---------------------------------------------------------------------------------- |
| <kbd>Enter / Space</kbd>       | On the chip: opens the list with focus in its search field.                        |
| <kbd>Type</kbd>                | Narrows the options.                                                               |
| <kbd>ArrowDown / ArrowUp</kbd> | Moves the highlight, wrapping at the ends.                                         |
| <kbd>Home / End</kbd>          | Highlights the first or last row (End reaches Clear filter).                       |
| <kbd>Enter</kbd>               | Chooses or unchooses the highlighted option, or clears the filter on Clear filter. |
| <kbd>Backspace</kbd>           | In the empty search field: removes the last chosen value.                          |
| <kbd>Escape</kbd>              | Closes the list and returns focus to the chip.                                     |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a filter, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/filter-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/filter`.

## Questions

### How does the animated Filter for UI SDK move?

Unfold: The list grows out of its chip, its rows cascade in, and one highlight glides between them. Draw: A chosen option's box fills with a pop and its check draws itself. Widen: The chip's width follows its badges on a spring, so it never stretches its text. Cascade: Badges pop in one after another, from a smaller, blurred start. Roll: "3 selected" and every option's count roll to their new number. Slide: The bar's Reset slides in from the left while a filter is active, and out again.

### Do I need Motion or Framer Motion for the animated Filter?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no filter. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/filter-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Filter when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
