{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "async-select",
  "title": "Async Select",
  "description": "Searchable single-select combobox that loads options from an async fetcher, with debounced search, preloading and custom option rendering.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "command",
    "popover"
  ],
  "files": [
    {
      "path": "components/dentil/async-select/async-select.tsx",
      "content": "'use client';\n\nimport { CheckIcon, ChevronDownIcon, Loader2 } from 'lucide-react';\nimport * as React from 'react';\n\nimport { Button } from '@/components/ui/button';\nimport { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { cn } from '@/lib/utils';\n\nexport interface AsyncSelectEmptyState {\n  /** The current search field text. */\n  query: string;\n  /** Closes the popover. */\n  close: () => void;\n}\n\nexport interface AsyncSelectProps<T> extends Omit<\n  React.ComponentProps<'button'>,\n  'value' | 'onChange' | 'children' | 'type'\n> {\n  /**\n   * Loads options for a search. `''` asks for the unfiltered list.\n   * `signal` aborts the previous request. The latest function is used on the next search.\n   */\n  fetcher: (query: string, signal: AbortSignal) => Promise<T[]>;\n  /** The selected option's value. `null`, `undefined` and `''` are empty. */\n  value: string | null | undefined;\n  /** Called with the picked option, or `null` when the selection is cleared. */\n  onChange: (option: T | null) => void;\n  /** Unique value for an option. Compared with `value`. */\n  getOptionValue: (option: T) => string;\n  /** Trigger contents for the selected option. */\n  getDisplayValue: (option: T) => React.ReactNode;\n  /** Row contents. A check mark is rendered after this. */\n  renderOption: (option: T) => React.ReactNode;\n  /**\n   * Shown on the trigger when `value` matches it and that option is not in the current results.\n   * Pass the selection you already have so its label shows before the list loads.\n   */\n  defaultOption?: T | null;\n  /** Load once with `''`, then filter in the browser. Otherwise each search calls `fetcher`. */\n  preload?: boolean;\n  /** Client filter used when `preload` is set. Return true to keep the option. */\n  filterFn?: (option: T, query: string) => boolean;\n  /** Extra text the default preload filter matches, besides the option value. */\n  getSearchValue?: (option: T) => string;\n  /** Disabled options stay in the list and cannot be picked. */\n  isOptionDisabled?: (option: T) => boolean;\n  /** Trigger label when nothing is selected. */\n  placeholder?: string;\n  /** Search field placeholder. */\n  searchPlaceholder?: string;\n  /** Shown when the list is empty. A function receives the query and a way to close the popover. */\n  emptyText?: React.ReactNode | ((state: AsyncSelectEmptyState) => React.ReactNode);\n  /** Replaces the loading rows. */\n  loadingSkeleton?: React.ReactNode;\n  /** Wait before calling `fetcher` after a keystroke, in milliseconds. Ignored when `preload` is set. */\n  debounce?: number;\n  /** Picking the selected option again clears it. */\n  clearable?: boolean;\n}\n\nconst skeletonWidths = ['w-40', 'w-32', 'w-36'] as const;\n\nfunction optionMatches<T>(\n  option: T,\n  query: string,\n  getOptionValue: (option: T) => string,\n  getSearchValue?: (option: T) => string\n) {\n  const q = query.toLowerCase();\n  if (getOptionValue(option).toLowerCase().includes(q)) return true;\n  return getSearchValue?.(option).toLowerCase().includes(q) ?? false;\n}\n\nfunction EmptyNotice({\n  query,\n  close,\n  render,\n}: {\n  query: string;\n  close: () => void;\n  render: (state: AsyncSelectEmptyState) => React.ReactNode;\n}) {\n  return render({ query, close });\n}\n\nfunction DefaultLoadingSkeleton() {\n  return (\n    <div aria-hidden=\"true\" className=\"flex flex-col gap-1 p-1\">\n      {skeletonWidths.map((width) => (\n        <div key={width} className=\"flex flex-col gap-1 px-2 py-1.5\">\n          <div className={cn('bg-muted h-4 animate-pulse rounded-md', width)} />\n          <div className=\"bg-muted h-3 w-24 animate-pulse rounded-md\" />\n        </div>\n      ))}\n    </div>\n  );\n}\n\nexport function AsyncSelect<T>({\n  fetcher,\n  value,\n  onChange,\n  getOptionValue,\n  getDisplayValue,\n  renderOption,\n  defaultOption,\n  preload = false,\n  filterFn,\n  getSearchValue,\n  isOptionDisabled,\n  placeholder = 'Select...',\n  searchPlaceholder = 'Search...',\n  emptyText = 'No results.',\n  loadingSkeleton,\n  debounce = 300,\n  clearable = true,\n  disabled = false,\n  className,\n  ...props\n}: AsyncSelectProps<T>) {\n  const [open, setOpen] = React.useState(false);\n  const [width, setWidth] = React.useState<number>();\n  const [query, setQuery] = React.useState('');\n  const [debouncedQuery, setDebouncedQuery] = React.useState('');\n  const [options, setOptions] = React.useState<T[]>([]);\n  const [loading, setLoading] = React.useState(false);\n  const [error, setError] = React.useState<string | null>(null);\n  const [hasLoaded, setHasLoaded] = React.useState(false);\n  const [picked, setPicked] = React.useState<T | null>(null);\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const fetcherRef = React.useRef(fetcher);\n  const abortRef = React.useRef<AbortController | null>(null);\n  const debounceRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  React.useEffect(() => {\n    fetcherRef.current = fetcher;\n  });\n\n  const startRequest = React.useCallback((search: string, markLoaded: boolean) => {\n    abortRef.current?.abort();\n    const controller = new AbortController();\n    abortRef.current = controller;\n\n    void Promise.resolve()\n      .then(() => fetcherRef.current(search, controller.signal))\n      .then(\n        (data) => {\n          if (controller.signal.aborted) return;\n          setOptions(data);\n          if (markLoaded) setHasLoaded(true);\n          setError(null);\n          setLoading(false);\n        },\n        (err: unknown) => {\n          if (controller.signal.aborted) return;\n          setError(err instanceof Error && err.message ? err.message : 'Could not load options.');\n          setLoading(false);\n        }\n      );\n  }, []);\n\n  React.useEffect(() => {\n    if (!open || !preload || hasLoaded) return;\n    startRequest('', true);\n    return () => abortRef.current?.abort();\n  }, [open, preload, hasLoaded, startRequest]);\n\n  React.useEffect(() => {\n    if (!open || preload) return;\n    startRequest(debouncedQuery, false);\n    return () => abortRef.current?.abort();\n  }, [open, preload, debouncedQuery, startRequest]);\n\n  React.useEffect(\n    () => () => {\n      if (debounceRef.current) clearTimeout(debounceRef.current);\n      abortRef.current?.abort();\n    },\n    []\n  );\n\n  const scheduleSearch = (next: string) => {\n    setQuery(next);\n    setError(null);\n    if (preload || !open) return;\n    setLoading(true);\n    if (debounceRef.current) clearTimeout(debounceRef.current);\n    if (next === '' || debounce <= 0) {\n      if (next === debouncedQuery) setLoading(false);\n      else setDebouncedQuery(next);\n      return;\n    }\n    debounceRef.current = setTimeout(() => setDebouncedQuery(next), debounce);\n  };\n\n  const visible = React.useMemo(() => {\n    if (!preload) return options;\n    const q = query.trim();\n    if (!q) return options;\n    if (filterFn) return options.filter((option) => filterFn(option, q));\n    return options.filter((option) => optionMatches(option, q, getOptionValue, getSearchValue));\n  }, [preload, options, query, filterFn, getOptionValue, getSearchValue]);\n\n  const selected = React.useMemo(() => {\n    if (value == null || value === '') return null;\n    const fromList = options.find((option) => getOptionValue(option) === value);\n    if (fromList) return fromList;\n    if (defaultOption && getOptionValue(defaultOption) === value) return defaultOption;\n    if (picked && getOptionValue(picked) === value) return picked;\n    return null;\n  }, [value, options, defaultOption, picked, getOptionValue]);\n\n  const close = React.useCallback(() => {\n    if (debounceRef.current) {\n      clearTimeout(debounceRef.current);\n      debounceRef.current = null;\n    }\n    setOpen(false);\n  }, []);\n\n  const handleOpenChange = (next: boolean) => {\n    if (next) {\n      setWidth(triggerRef.current?.offsetWidth);\n      setQuery('');\n      setDebouncedQuery('');\n      if (!preload || !hasLoaded) {\n        setLoading(true);\n        setError(null);\n        if (!preload) setOptions([]);\n      }\n      setOpen(true);\n      return;\n    }\n    close();\n  };\n\n  const handleSelect = (option: T) => {\n    if (isOptionDisabled?.(option)) return;\n    const optionValue = getOptionValue(option);\n    if (optionValue === value) {\n      if (clearable) {\n        setPicked(null);\n        onChange(null);\n      }\n    } else {\n      setPicked(option);\n      onChange(option);\n    }\n    close();\n  };\n\n  const showSkeleton = loading && visible.length === 0 && !error;\n  const showEmpty = !loading && !error && visible.length === 0;\n\n  return (\n    <Popover open={open} onOpenChange={handleOpenChange}>\n      <PopoverTrigger asChild>\n        <Button\n          ref={triggerRef}\n          type=\"button\"\n          variant=\"outline\"\n          role=\"combobox\"\n          aria-expanded={open}\n          disabled={disabled}\n          data-slot=\"async-select\"\n          className={cn('w-full justify-between px-3 font-normal', className)}\n          {...props}>\n          <span className={cn('min-w-0 flex-1 truncate text-left', !selected && 'text-muted-foreground')}>\n            {selected ? getDisplayValue(selected) : placeholder}\n          </span>\n          <ChevronDownIcon className=\"text-muted-foreground size-4 shrink-0\" aria-hidden=\"true\" />\n        </Button>\n      </PopoverTrigger>\n      <PopoverContent className=\"min-w-48 p-0\" style={{ width }} align=\"start\">\n        <Command shouldFilter={false}>\n          <div className=\"relative\">\n            <CommandInput\n              placeholder={searchPlaceholder}\n              value={query}\n              className={loading && visible.length > 0 ? 'pr-8' : undefined}\n              onValueChange={(next) => {\n                if (next === query) return;\n                scheduleSearch(next);\n              }}\n            />\n            {loading && visible.length > 0 ? (\n              <Loader2\n                className=\"text-muted-foreground pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 animate-spin motion-reduce:animate-none\"\n                aria-hidden=\"true\"\n              />\n            ) : null}\n          </div>\n          {error && visible.length > 0 ? (\n            <p role=\"alert\" className=\"text-destructive border-b px-3 py-2 text-center text-xs\">\n              {error}\n            </p>\n          ) : null}\n          <CommandList aria-busy={loading}>\n            {showSkeleton ? (\n              <>\n                <span className=\"sr-only\">Loading</span>\n                {loadingSkeleton ?? <DefaultLoadingSkeleton />}\n              </>\n            ) : null}\n            {error && visible.length === 0 && !loading ? (\n              <div role=\"alert\" className=\"flex flex-col items-center gap-2 px-3 py-6 text-center\">\n                <p className=\"text-destructive text-sm\">{error}</p>\n                <Button\n                  type=\"button\"\n                  variant=\"outline\"\n                  size=\"sm\"\n                  onClick={() => {\n                    setLoading(true);\n                    setError(null);\n                    startRequest(preload ? '' : query, preload);\n                  }}>\n                  Try again\n                </Button>\n              </div>\n            ) : null}\n            {showEmpty ? (\n              typeof emptyText === 'function' ? (\n                <EmptyNotice query={query} close={close} render={emptyText} />\n              ) : (\n                <CommandEmpty>{emptyText}</CommandEmpty>\n              )\n            ) : null}\n            {visible.length > 0 ? (\n              <CommandGroup>\n                {visible.map((option) => {\n                  const optionValue = getOptionValue(option);\n                  const optionDisabled = isOptionDisabled?.(option) ?? false;\n                  return (\n                    <CommandItem\n                      key={optionValue}\n                      value={optionValue}\n                      disabled={optionDisabled}\n                      onSelect={() => handleSelect(option)}>\n                      <span className=\"min-w-0 flex-1\">{renderOption(option)}</span>\n                      <CheckIcon\n                        className={cn('ml-auto size-4', optionValue === value ? 'opacity-100' : 'opacity-0')}\n                        aria-hidden=\"true\"\n                      />\n                    </CommandItem>\n                  );\n                })}\n              </CommandGroup>\n            ) : null}\n          </CommandList>\n        </Command>\n      </PopoverContent>\n    </Popover>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/async-select/async-select.tsx"
    }
  ],
  "type": "registry:component"
}
