{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "filter-list",
  "title": "Filter list",
  "description": "The parts Combobox, Autocomplete, Command and Trigger menu share: the field, a box that grows out of it and moves to the height of what still matches, its rows, and one highlight that glides between them.",
  "dependencies": [
    "@ui-sdk/react"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/panel.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/select.json",
    "https://kinoui.com/r/list-rows.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/popup.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/filter-list.tsx",
      "content": "'use client'\n\nimport {\n  focusControl,\n  InputInvalidIcon,\n  inputBoxClassName,\n  inputControlClassName,\n} from '@/registry/components/kino/input'\nimport { selectTriggerVariants } from '@/registry/components/kino/select'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { followRows } from '@/registry/lib/highlight'\nimport {\n  MenuHighlight,\n  menuGutterClassName,\n  menuLabelClassName,\n  menuNoticeClassName,\n  menuRowVariants,\n  menuSeparatorClassName,\n} from '@/registry/lib/list-rows'\nimport {\n  PanelHandle,\n  panelSheetBackdropClassName,\n  popupSheetClassName,\n  popupSheetPanelClassName,\n} from '@/registry/lib/panel'\nimport {\n  popupGrowBoxClassName,\n  popupGrowContentClassName,\n  popupPlacedClassName,\n  popupSurfaceClassName,\n} from '@/registry/lib/popup'\nimport { followHeight } from '@/registry/lib/resize'\nimport { edgeFadeClassName } from '@/registry/lib/scroll'\nimport { matchRanges, matchSegments } from '@ui-sdk/core/text-match'\nimport { type PartProps, renderElement } from '@ui-sdk/react/primitive'\nimport { type ComponentProps, type ReactNode, useEffect, useRef } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The look the lists with an input share: the Combobox, the Autocomplete and\n * what sits on them. ui-sdk filters, highlights and picks; this is the field,\n * the box that grows out of it and moves to the height of what still\n * matches, its rows, and the one highlight that glides between them.\n */\n\n/**\n * The field: the input and the buttons beside it, in the box every text\n * control has. The list opens under it and is as wide as it.\n */\nfunction FilterListInputGroup({\n  className,\n  children,\n  render,\n  ...props\n}: Omit<PartProps<'div'>, 'className' | 'children'> & {\n  className?: string\n  children?: ReactNode\n}) {\n  return renderElement(\n    'div',\n    {\n      onPointerDown: focusControl,\n      className: cn(\n        inputBoxClassName,\n        // The buttons sit at the end, after the invalid mark, 4px from the edge.\n        'cursor-text gap-0.5 has-[>button]:pe-1',\n        className,\n      ),\n      ...props,\n      children: (\n        <>\n          {children}\n          <InputInvalidIcon className='group-has-[>button]/input:pe-1' />\n        </>\n      ),\n    },\n    render,\n  )\n}\n\n/**\n * The text you type. In a field it fills the room left; inside the list's\n * box, at its top or in a sheet's header, it is the box's search line.\n */\nconst filterListInputClassName = cn(\n  inputControlClassName,\n  'in-data-filter-list-content:h-(--control-height-lg) in-data-filter-list-content:flex-none in-data-filter-list-content:border-b in-data-filter-list-content:px-[calc(var(--control-padding)+0.25rem)] in-data-filter-list-content:focus-visible:border-ring',\n)\n\n/** A small icon button at the end of the field. */\nconst filterListButtonClassName = 'text-muted-foreground order-last'\n\nfunction FilterListClearIcon() {\n  return (\n    <IconPlaceholder\n      lucide='XIcon'\n      tabler='IconX'\n      hugeicons='Cancel01Icon'\n      phosphor='XIcon'\n      remixicon='RiCloseLine'\n      aria-hidden\n    />\n  )\n}\n\nfunction FilterListChevron() {\n  return (\n    <IconPlaceholder\n      lucide='ChevronDownIcon'\n      tabler='IconChevronDown'\n      hugeicons='ArrowDown01Icon'\n      phosphor='CaretDownIcon'\n      remixicon='RiArrowDownSLine'\n      aria-hidden\n    />\n  )\n}\n\n/** A trigger with the value inside, for a list whose search sits at its top: it looks like a select. */\nconst filterListValueTriggerClassName = selectTriggerVariants()\n\n/** What a trigger with the value inside shows, before its invalid mark and chevron. */\nfunction FilterListValue({ id, children }: { id?: string; children: ReactNode }) {\n  return (\n    <>\n      {/* A bare label truncates; an icon and a label sit in a row, the label in a span that truncates. */}\n      <span\n        id={id}\n        data-slot='filter-list-value'\n        data-cut\n        className='flex min-w-0 flex-1 items-center gap-2 truncate in-data-placeholder:text-muted-foreground [&>span:not([data-slot])]:min-w-0 [&>span:not([data-slot])]:truncate'\n      >\n        {children}\n      </span>\n      <InputInvalidIcon className='-me-1 pe-0' />\n      <FilterListChevron />\n    </>\n  )\n}\n\n/** The scroller around a list's rows: thin, its own scroll only, its edges fading (`useEdgeFades`). */\nconst filterListScrollerClassName = cn(\n  'scrollbar-thin relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain',\n  edgeFadeClassName,\n)\n\n/**\n * A list's rows and the highlight that glides between them, to where ui-sdk\n * highlights. Its parent is the scroller, inside a box marked\n * `data-filter-list-content`.\n */\nfunction FilterListRows({\n  className,\n  children,\n}: {\n  className?: string\n  children?: ReactNode\n}) {\n  const rowsRef = useRef<HTMLDivElement>(null)\n  const layerRef = useRef<HTMLDivElement>(null)\n  useEffect(() => {\n    const rows = rowsRef.current\n    const list = rows?.parentElement\n    const popup = list?.closest<HTMLElement>('[data-filter-list-content]')\n    if (!rows || !list || !popup || !layerRef.current) return\n    return followRows(rows, layerRef.current, { popup, bounds: list })\n  }, [])\n  return (\n    <div\n      ref={rowsRef}\n      data-slot='filter-list-rows'\n      className={cn(\n        // The 4px around the rows is the highlight's margin, not a surface's\n        // padding, so it stays the same at every density. With no rows, it\n        // takes no room, so the notice sits alone.\n        'group/menu relative flex flex-col p-1 [&:not(:has([data-menu-row]))]:p-0',\n        menuGutterClassName,\n        className,\n      )}\n    >\n      <MenuHighlight ref={layerRef} />\n      {children}\n    </div>\n  )\n}\n\n/**\n * A row: the menus' own. Rows out of view skip style, layout and paint, so a\n * list of every country opens at once. A skipped row keeps its own height:\n * the intrinsic size is its content's, inside its `py-1`, or the list opens a\n * row too tall, shrinks, and a long one flips to the other side as it does.\n */\nconst filterListItemClassName = cn(\n  menuRowVariants(),\n  'group/menu-row [contain-intrinsic-size:auto_calc(var(--control-height-sm)-0.5rem)] [content-visibility:auto]',\n)\n\n/** The marked part of a row's text, the part that matched what was typed. */\nconst filterListMatchClassName =\n  'min-w-0 [&_mark]:bg-transparent [&_mark]:font-medium [&_mark]:text-current'\n\n/** How a query matches a row's text: from the start of a word, anywhere, or as ui-sdk's matchRanges reads it. */\ntype MatchMode = Parameters<typeof matchRanges>[2]\n\n/**\n * `children` with the parts that match `query` in bold, so the eye finds why\n * a row matched: for a list that filters rows of its own, as ui-sdk's lists\n * mark theirs. With no query or no `mode`, the text as it is.\n */\nfunction MatchText({\n  query,\n  mode = 'contains',\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<'span'>, 'children'> & {\n  children: string\n  query: string\n  mode?: MatchMode | null\n}) {\n  const segments =\n    query && mode ? matchSegments(children, matchRanges(children, query, mode)) : []\n  return (\n    <span className={cn(filterListMatchClassName, className)} {...props}>\n      {segments.length > 0\n        ? segments.map((segment, at) =>\n            segment.match ? <mark key={at}>{segment.text}</mark> : segment.text,\n          )\n        : children}\n    </span>\n  )\n}\n\nconst filterListGroupLabelClassName = menuLabelClassName\nconst filterListSeparatorClassName = menuSeparatorClassName\nconst filterListNoticeClassName = menuNoticeClassName\n\n/**\n * The popup's own element, placed by ui-sdk, as wide as what is in it. As a\n * sheet, it is the panel, as wide as the screen up to 40rem, and the input\n * sits in its header.\n */\nfunction filterListContentClassName({\n  presentation,\n}: {\n  presentation: 'popover' | 'sheet'\n}) {\n  return cn(\n    popupPlacedClassName,\n    panelSheetBackdropClassName,\n    popupSheetClassName,\n    'flex max-w-(--available-width) flex-col text-sm',\n    // ui-sdk puts the input in a header of its own inside the content, so the content is the panel.\n    presentation === 'sheet' && popupSheetPanelClassName,\n  )\n}\n\n/**\n * What goes in the popup: in a box that grows out of the field and moves to\n * the height of what it holds, or under a sheet's handle.\n */\nfunction FilterListBody({\n  presentation,\n  className,\n  children,\n}: {\n  presentation: 'popover' | 'sheet'\n  className?: string\n  children: ReactNode\n}) {\n  if (presentation === 'sheet') {\n    return (\n      <>\n        {/* Above the header ui-sdk puts the input in. */}\n        <PanelHandle className='-order-1' />\n        <div className={cn('flex min-h-0 flex-1 flex-col', className)}>{children}</div>\n      </>\n    )\n  }\n  return (\n    <div\n      className={cn(\n        'relative rounded-(--list-radius)',\n        popupSurfaceClassName,\n        popupGrowBoxClassName,\n      )}\n    >\n      <FilterListFrame className={className}>{children}</FilterListFrame>\n    </div>\n  )\n}\n\n/*\n * The frame moves to the content's height, and the box grows with it. Inside\n * the popup, so its refs are set: ui-sdk renders it only while it is open.\n */\nfunction FilterListFrame({\n  className,\n  children,\n}: {\n  className?: string\n  children: ReactNode\n}) {\n  const frameRef = useRef<HTMLDivElement>(null)\n  const innerRef = useRef<HTMLDivElement>(null)\n  useEffect(() => {\n    if (!frameRef.current || !innerRef.current) return\n    const stops = [\n      holdRowsAsItCloses(frameRef.current, innerRef.current),\n      keepHighlightInView(innerRef.current),\n    ]\n    return () => {\n      for (const stop of stops) stop()\n    }\n  }, [])\n  return (\n    <div\n      ref={frameRef}\n      className='overflow-clip rounded-[inherit] transition-[height] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none'\n    >\n      <div\n        ref={innerRef}\n        className={cn(\n          // As wide as what it opens from, never narrower than a name and its\n          // tick; a long list stops at 24rem, so it never fills a tall screen.\n          'flex max-h-[min(var(--popup-available-height),24rem)] w-(--anchor-width) max-w-(--popup-available-width) min-w-56 flex-col',\n          // As it closes, only the rows it showed (`holdRowsAsItCloses`).\n          'data-holding:[&_[role=group]:not([data-held])]:hidden data-holding:[&_[role=option]:not([data-held])]:hidden data-holding:[&_[role=separator]:not([data-held])]:hidden',\n          popupGrowContentClassName,\n          className,\n        )}\n      >\n        {children}\n      </div>\n    </div>\n  )\n}\n\n/*\n * The frame follows the rows' height while the list is open. As it closes,\n * ui-sdk empties the filter, which would bring every row back while the box\n * fades: the rows it showed stay, and no other shows, until it has gone or\n * opens again, and so does the line saying nothing matches. Each row is\n * marked while it shows with the list open, since ui-sdk shows the rows\n * again in the same task that closes it. Kept outside the\n * component: the React Compiler can drop side effects written inside one.\n */\nfunction holdRowsAsItCloses(frame: HTMLElement, rows: HTMLElement) {\n  const content = frame.closest<HTMLElement>('[data-presentation]')\n  let stop: (() => void) | null = followHeight(frame, rows)\n  if (!content) return () => stop?.()\n  // What the line saying nothing matches said while the list was open.\n  let said: Node[] = []\n  const notice = () => rows.querySelector<HTMLElement>('[data-slot$=\"-empty\"]')\n  const mark = () => {\n    const closed = content.hasAttribute('data-closed')\n    rows.toggleAttribute('data-holding', closed)\n    if (closed) {\n      stop?.()\n      stop = null\n      // ui-sdk empties the line too: a copy of what it said stays, unread.\n      const empty = notice()\n      if (\n        empty &&\n        said.length > 0 &&\n        !empty.textContent?.trim() &&\n        !empty.querySelector('[data-held-copy]')\n      ) {\n        const copy = document.createElement('span')\n        copy.dataset.heldCopy = ''\n        copy.setAttribute('aria-hidden', 'true')\n        copy.className = 'contents'\n        copy.append(...said.map((node) => node.cloneNode(true)))\n        empty.append(copy)\n      }\n      return\n    }\n    for (const copy of rows.querySelectorAll('[data-held-copy]')) copy.remove()\n    const empty = notice()\n    said = empty?.textContent?.trim()\n      ? [...empty.childNodes].map((node) => node.cloneNode(true))\n      : []\n    for (const row of rows.querySelectorAll<HTMLElement>(\n      '[role=group], [role=option], [role=separator]',\n    )) {\n      row.toggleAttribute('data-held', !row.hidden)\n    }\n    stop ??= followHeight(frame, rows)\n  }\n  mark()\n  const watch = new MutationObserver(mark)\n  watch.observe(content, {\n    attributes: true,\n    attributeFilter: ['data-closed', 'hidden'],\n    characterData: true,\n    childList: true,\n    subtree: true,\n  })\n  return () => {\n    watch.disconnect()\n    stop?.()\n  }\n}\n\n/*\n * ui-sdk scrolls the highlighted row into view as the list opens, but rows\n * out of view take their real height only once drawn\n * (`filterListItemClassName`), so a long list, such as every country, moves\n * its picked row on as it settles. Until the person scrolls or a moment has\n * passed, the row is kept in view.\n */\nfunction keepHighlightInView(rows: HTMLElement) {\n  const scroller = rows.querySelector<HTMLElement>('[role=listbox]')?.parentElement\n  if (!scroller) return () => {}\n  const keep = () =>\n    rows\n      .querySelector<HTMLElement>('[role=option][data-highlighted]')\n      ?.scrollIntoView({ block: 'nearest' })\n  const sizes = new ResizeObserver(keep)\n  for (const list of rows.querySelectorAll('[role=listbox] > *')) sizes.observe(list)\n  const stop = () => {\n    sizes.disconnect()\n    clearTimeout(timer)\n    for (const type of ['wheel', 'touchstart', 'pointerdown'] as const)\n      scroller.removeEventListener(type, stop)\n  }\n  const timer = setTimeout(stop, 1000)\n  for (const type of ['wheel', 'touchstart', 'pointerdown'] as const)\n    scroller.addEventListener(type, stop, { passive: true })\n  return stop\n}\n\nexport {\n  FilterListBody,\n  FilterListChevron,\n  FilterListClearIcon,\n  FilterListInputGroup,\n  FilterListRows,\n  FilterListValue,\n  MatchText,\n  filterListButtonClassName,\n  filterListContentClassName,\n  filterListGroupLabelClassName,\n  filterListInputClassName,\n  filterListItemClassName,\n  filterListMatchClassName,\n  filterListNoticeClassName,\n  filterListScrollerClassName,\n  filterListSeparatorClassName,\n  filterListValueTriggerClassName,\n}\nexport type { MatchMode }\n",
      "type": "registry:lib",
      "target": "@lib/filter-list.tsx"
    }
  ],
  "type": "registry:lib"
}