{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "search-field",
  "title": "Search field",
  "description": "A text field for searching: a clear button once there is text, Escape to clear, a shortcut that focuses it from anywhere, a spinner while results come, and a count of what it found. It can sit short in a toolbar and widen while in use.",
  "dependencies": [
    "@ui-sdk/core",
    "@ui-sdk/react",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/input-group.json",
    "https://kinoui.com/r/kbd.json",
    "https://kinoui.com/r/spinner.json",
    "https://kinoui.com/r/keys.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/roll.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/search-field.tsx",
      "content": "'use client'\n\nimport type { InputControl } from '@/registry/components/kino/input'\nimport {\n  InputGroup,\n  InputGroupAddon,\n  InputGroupButton,\n  InputGroupInput,\n  inputGroupPresence,\n} from '@/registry/components/kino/input-group'\nimport { KbdGroup } from '@/registry/components/kino/kbd'\nimport { Spinner, useSpinner } from '@/registry/components/kino/spinner'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { useAriaKeyshortcuts, useShortcut } from '@/registry/lib/keys'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { Roll } from '@/registry/lib/roll'\nimport { Swap, swapIconClassName } from '@/registry/lib/swap'\nimport { isComposing } from '@ui-sdk/core'\nimport { createInputController } from '@ui-sdk/react/input'\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport {\n  type ComponentProps,\n  type MouseEvent,\n  type PointerEvent,\n  useMemo,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A text field for searching. Its icon turns into the spinner while results\n * come, the end of the field trades the shortcut's keys for the clear button\n * once there is text, and Escape clears it before it closes anything around\n * it. Nothing else moves, unless the field is told to widen.\n */\n\nconst searchFieldVariants = cva('', {\n  variants: {\n    variant: {\n      default: '',\n      // Short at rest, so it sits in a toolbar; it widens into the room it is\n      // given while it is in use, and what sits beside it moves with it. The\n      // width moves on `layout`, the box's colours on `press`, scoped to the\n      // slot so it wins over the box's own transition; with less motion the\n      // width changes at once.\n      widen:\n        'w-(--search-field-width,15rem) max-w-full data-wide:w-full motion-safe:data-search-field:[transition:width_var(--motion-layout-duration)_var(--motion-layout-easing),color_var(--motion-press-duration)_var(--motion-press-fade-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing),border-color_var(--motion-press-duration)_var(--motion-press-fade-easing),box-shadow_var(--motion-press-duration)_var(--motion-press-fade-easing)]',\n    },\n  },\n  defaultVariants: {\n    variant: 'default',\n  },\n})\n\ntype SearchFieldProps = Omit<ComponentProps<typeof InputControl>, 'type'> &\n  VariantProps<typeof searchFieldVariants> & {\n    /** Results are on their way: the icon turns into a spinner once it lasts 200ms. */\n    loading?: boolean\n    /**\n     * Keys that focus the field from anywhere on the page, shown at its end\n     * until the person types, and not on a touch screen, as ui-sdk writes them:\n     * `'mod+k'` or `'/'`.\n     */\n    shortcut?: string\n    /** Called once the clear button or Escape has emptied the field. */\n    onClear?: () => void\n    /** How many results the search found, shown while there is text and read out. */\n    count?: number\n    /** What the count says, shown and read out: “24 results” by default. */\n    countLabel?: (count: number) => string\n  }\n\n/** The event a handler of ui-sdk's Input gets. */\ntype InputEvent<Handler extends 'onFocus' | 'onBlur' | 'onKeyDown'> = Parameters<\n  NonNullable<SearchFieldProps[Handler]>\n>[0]\n\nfunction SearchField({\n  className,\n  variant,\n  loading = false,\n  shortcut,\n  onClear,\n  count,\n  countLabel = resultsLabel,\n  value,\n  defaultValue,\n  onValueChange,\n  onKeyDown,\n  onFocus,\n  onBlur,\n  disabled,\n  readOnly,\n  controller: controllerProp,\n  ref,\n  ...props\n}: SearchFieldProps) {\n  const [ownController] = useState(createInputController)\n  const controller = controllerProp ?? ownController\n  const [input, setInput] = useState<HTMLInputElement | null>(null)\n  // One callback for the field's life, so React doesn't hand it the element again each render.\n  const ariaKeys = useAriaKeyshortcuts(disabled ? null : shortcut)\n  const inputRef = useMemo(\n    () => mergeRefs<HTMLInputElement>(setInput, ariaKeys, ref),\n    [ariaKeys, ref],\n  )\n  const [typed, setTyped] = useState(() => String(defaultValue ?? '') !== '')\n  const filled = value === undefined ? typed : String(value) !== ''\n  const [focused, setFocused] = useState(false)\n  const spinning = useSpinner(loading)\n  const editable = !disabled && !readOnly\n  const hinting = shortcut !== undefined && !filled && !focused && !disabled\n  const counting = filled && count !== undefined\n\n  // The last count stays while it fades out, and rolls up when it grew and down when it fell.\n  const label = count === undefined ? '' : countLabel(count)\n  const [counted, setCounted] = useState({ label, count, trend: 1 })\n  if (count !== undefined && label !== counted.label) {\n    setCounted({ label, count, trend: count - (counted.count ?? count) })\n  }\n  const number = countNumber(counted.label)\n\n  useShortcut(\n    disabled || !input ? undefined : shortcut,\n    () => {\n      input?.focus()\n      input?.select()\n    },\n    input,\n  )\n\n  return (\n    <InputGroup\n      data-search-field=''\n      data-wide={variant === 'widen' && (focused || filled) ? '' : undefined}\n      className={cn(searchFieldVariants({ variant }), className)}\n    >\n      <InputGroupAddon>\n        <Swap roll className={swapIconClassName}>\n          {spinning ? (\n            <Spinner />\n          ) : (\n            <IconPlaceholder\n              lucide='SearchIcon'\n              tabler='IconSearch'\n              hugeicons='Search01Icon'\n              phosphor='MagnifyingGlassIcon'\n              remixicon='RiSearchLine'\n              aria-hidden\n            />\n          )}\n        </Swap>\n      </InputGroupAddon>\n      <InputGroupInput\n        {...props}\n        ref={inputRef}\n        type='search'\n        enterKeyHint='search'\n        autoComplete='off'\n        spellCheck={false}\n        value={value}\n        defaultValue={defaultValue}\n        controller={controller}\n        disabled={disabled}\n        readOnly={readOnly}\n        onValueChange={(next, details) => {\n          setTyped(next !== '')\n          onValueChange?.(next, details)\n          if (next === '' && details.reason === 'clear-press') onClear?.()\n        }}\n        onFocus={(event: InputEvent<'onFocus'>) => {\n          setFocused(true)\n          onFocus?.(event)\n        }}\n        onBlur={(event: InputEvent<'onBlur'>) => {\n          setFocused(false)\n          onBlur?.(event)\n        }}\n        onKeyDown={(event: InputEvent<'onKeyDown'>) => {\n          onKeyDown?.(event)\n          // ui-sdk's own Escape needs its Clear part, which unmounts at once\n          // and so can't fade out as the button here does.\n          // With text, Escape empties the field and stops there, so the dialog\n          // or popover around it stays open; with none it closes them as usual.\n          // The browser's own clear on Escape is held back, since it lets the\n          // key carry on and one press would do both.\n          if (\n            event.key !== 'Escape' ||\n            event.defaultPrevented ||\n            // An Escape that ends an input method's text belongs to it.\n            isComposing(event) ||\n            // The input's own value, since a form's reset empties it without a word.\n            event.currentTarget.value === '' ||\n            !editable\n          )\n            return\n          event.preventDefault()\n          event.stopPropagation()\n          controller.clear({ reason: 'clear-press', event: event.nativeEvent })\n        }}\n      />\n      <InputGroupAddon align='inline-end' className='gap-1.5'>\n        <span\n          ref={markMounted}\n          data-slot='search-field-count'\n          data-shown={counting ? '' : undefined}\n          aria-hidden\n          className={cn(\n            inputGroupPresence,\n            // It leaves the row while hidden, so it fades in from\n            // @starting-style; one there on page load is simply there.\n            'text-xs whitespace-pre tabular-nums not-data-shown:hidden data-mounted:starting:opacity-0 motion-safe:data-mounted:starting:scale-95',\n          )}\n        >\n          {/* Only the number rolls, so the words around it read in their own direction. */}\n          {number ? (\n            <>\n              {counted.label.slice(0, number.start)}\n              <Roll value={number.text} trend={counted.trend} />\n              {counted.label.slice(number.end)}\n            </>\n          ) : (\n            counted.label\n          )}\n        </span>\n        {/* There before the first count, so every count is heard. */}\n        <span className='sr-only' role='status'>\n          {counting ? label : ''}\n        </span>\n        <span className='grid justify-items-end *:col-start-1 *:row-start-1'>\n          {shortcut ? (\n            // The field says the shortcut as `aria-keyshortcuts`. A touch screen\n            // has no keys to press, so its room goes to the text there.\n            <KbdGroup\n              ref={markMounted}\n              data-slot='search-field-shortcut'\n              data-shown={hinting ? '' : undefined}\n              aria-hidden\n              // It leaves the row once hidden, so its room goes to the text.\n              className={cn(\n                inputGroupPresence,\n                'me-1 text-xs not-data-shown:hidden pointer-coarse:hidden data-mounted:starting:opacity-0 motion-safe:data-mounted:starting:scale-95',\n              )}\n              keys={shortcut}\n            />\n          ) : null}\n          {/* The wrapper shows and hides it, so the button keeps its own hover and press, and its room. */}\n          <span\n            data-slot='search-field-clear'\n            data-shown={filled && editable ? '' : undefined}\n            className={cn(inputGroupPresence, 'flex')}\n          >\n            {/* Out of the tab order, as the browser's own is, since Escape clears; a screen reader still reaches it. */}\n            <InputGroupButton\n              size='icon-xs'\n              aria-label='Clear search'\n              tabIndex={-1}\n              // An agent clears the field with the field's own `clear`, so an empty state's Clear search names one control.\n              data-agent-hidden\n              // Pressing it leaves focus in the field, so a phone's keyboard stays up.\n              onPointerDown={(event: PointerEvent) => event.preventDefault()}\n              // ui-sdk's clear, so the change reaches `onValueChange` as a `clear-press`.\n              onClick={(event: MouseEvent) =>\n                controller.clear({\n                  reason: 'clear-press',\n                  event: event.nativeEvent,\n                })\n              }\n              className='text-muted-foreground'\n            >\n              <IconPlaceholder\n                lucide='XIcon'\n                tabler='IconX'\n                hugeicons='Cancel01Icon'\n                phosphor='XIcon'\n                remixicon='RiCloseLine'\n                aria-hidden\n              />\n            </InputGroupButton>\n          </span>\n        </span>\n      </InputGroupAddon>\n    </InputGroup>\n  )\n}\n\nconst plural = new Intl.PluralRules('en-US')\n\n/** “1 result”, “1,024 results”, or the same with another `noun`, given as its one and its many. */\nfunction resultsLabel(\n  count: number,\n  noun: readonly [one: string, many: string] = ['result', 'results'],\n) {\n  return `${numberFormatter('en-US').format(count)} ${plural.select(count) === 'one' ? noun[0] : noun[1]}`\n}\n\n/**\n * Where the number sits in a count's words, in any script's digits and with\n * its group separators, or null when it has none: in “1,024 results” it is\n * `1,024`, from 0 to 5.\n */\nfunction countNumber(label: string): { text: string; start: number; end: number } | null {\n  const match = /\\p{Nd}(?:[\\p{Nd},.\\u00A0\\u202F]*\\p{Nd})?/u.exec(label)\n  if (!match) return null\n  return {\n    text: match[0],\n    start: match.index,\n    end: match.index + match[0].length,\n  }\n}\n\nexport { SearchField, searchFieldVariants }\nexport { countNumber, resultsLabel }\n",
      "type": "registry:component",
      "target": "@components/kino/search-field.tsx"
    }
  ],
  "type": "registry:component"
}