组件Controls
Autocomplete
@mox-hub/ui 组件 · Controls · canonical
autocomplete@mox-hub/uiControlscanonicalsrc/components/autocomplete.tsx变体演示autocomplete
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| defaultValue | string | number | readonly string[] | — | The uncontrolled input value of the autocomplete when it's initially rendered. |
| form | string | — | Identifies the form that owns the internal input. |
| filter | (item: Items[number]["items"][number], query: string, itemToString?: (item: Items[number]["items"][number]) => string) => boolean | — | Filter function used to match items against the input query. |
| id | string | — | The id of the component. |
| children | React.ReactNode | — | — |
| modal | boolean | — | Determines if the popup enters a modal state when open. |
| onOpenChange | (open: boolean, eventDetails: AutocompleteRootOpenChangeEventDetails) => void | — | Event handler called when the popup is opened or closed. |
| actionsRef | React.RefObject<AutocompleteRootActions> | — | A ref to imperative actions. |
| open | boolean | — | Whether the popup is currently open. Use when controlled. |
| defaultOpen | boolean | — | Whether the popup is initially open. |
| onOpenChangeComplete | (open: boolean) => void | — | Event handler called after any animations complete when the popup is opened or closed. |
| mode | "none" | "inline" | "list" | "both" | — | Controls how the autocomplete behaves with respect to list filtering and inline autocompletion. |
| itemToStringValue | (itemValue: Items[number]["items"][number]) => string | — | When the item values are objects (`<Autocomplete.Item value={object}>`), this function converts the object value to a string representation for both display in the input and form submission. |
| inline | boolean | — | Whether the list is rendered inline without using the component's own popup. |
| autoHighlight | boolean | "always" | — | Whether the first matching item is highlighted automatically. |
| keepHighlight | boolean | — | Whether the highlighted item should be preserved when the pointer leaves the list. |
| highlightItemOnHover | boolean | — | Whether moving the pointer over items should highlight them. |
| openOnInputClick | boolean | — | Whether the popup opens when clicking the input. |
| filteredItems | readonly Items[number]["items"][number][] | readonly Group<Items[number]["items"][number]>[] | — | Filtered items to display in the list. |
| name | string | — | Identifies the field when a form is submitted. |
| required | boolean | — | Whether the user must choose a value before submitting a form. |
| readOnly | boolean | — | Whether the user should be unable to choose a different option from the popup. |
| disabled | boolean | — | Whether the component should ignore user interaction. |
| loopFocus | boolean | — | Whether to loop keyboard focus back to the input when the end of the list is reached while using the arrow keys. The first item can then be reached by pressing <kbd>ArrowDown</kbd> again from the input, or the last item can be reached by pressing <kbd>ArrowUp</kbd> from the input. |
| onItemHighlighted | (highlightedValue: Items[number]["items"][number], eventDetails: AutocompleteRootHighlightEventDetails) => void | — | Callback fired when an item is highlighted or unhighlighted. |
| inputRef | React.Ref<HTMLInputElement> | — | A ref to the hidden input element. |
| grid | boolean | — | Whether list items are presented in a grid layout. |
| virtualized | boolean | — | Whether the items are being externally virtualized. |
| limit | number | — | The maximum number of items to display in the list. |
| locale | Intl.LocalesArgument | — | The locale to use for string comparison. |
| submitOnItemClick | boolean | — | Whether clicking an item should submit the autocomplete's owning form. |
| value | string | number | readonly string[] | — | The input value of the autocomplete. Use when controlled. |
| onValueChange | (value: string, eventDetails: AutocompleteRootChangeEventDetails) => void | — | Event handler called when the input value of the autocomplete changes. |
| items* | Items | — | The items to be displayed in the list. |
源码
"use client"
import { Autocomplete as AutocompletePrimitive } from "@base-ui/react/autocomplete"
import { ChevronsUpDownIcon, XIcon } from "lucide-react"
import type React from "react"
import { cn } from "../lib/utils"
import { Input } from "./input"
import {
SURFACE_MENU_CLASS,
menuItemVariants,
menuLabelVariants,
} from "./menu-styles"
import { ScrollArea } from "./scroll-area"
/*
* coss ui Autocomplete(base-ui 配方移植,registry @coss/autocomplete)
* 适配:Input 无 nativeInput/size 视觉 prop,尺寸用高度 class 映射。
*/
/** size → 高度 class(对齐 Input 的 control-sm / md / lg 三档,随 density 缩放) */
const SIZE_HEIGHT: Record<string, string> = {
sm: "h-control-sm",
default: "h-control-md",
lg: "h-control-lg",
}
export const Autocomplete: typeof AutocompletePrimitive.Root =
AutocompletePrimitive.Root
export function AutocompleteInput({
className,
showTrigger = false,
showClear = false,
startAddon,
size = "default",
triggerProps,
clearProps,
...props
}: Omit<AutocompletePrimitive.Input.Props, "size"> & {
showTrigger?: boolean
showClear?: boolean
startAddon?: React.ReactNode
size?: "sm" | "default" | "lg"
ref?: React.Ref<HTMLInputElement>
triggerProps?: AutocompletePrimitive.Trigger.Props
clearProps?: AutocompletePrimitive.Clear.Props
}): React.ReactElement {
const heightClass = SIZE_HEIGHT[size]
return (
<AutocompletePrimitive.InputGroup
className="group/autocomplete-input relative not-has-[>*.w-full]:w-fit w-full text-foreground has-disabled:opacity-50"
data-slot="autocomplete-input-group"
>
{startAddon && (
<div
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 start-px z-sticky flex items-center ps-[calc(--spacing(3)-1px)] opacity-80 has-[+[data-size=sm]]:ps-[calc(--spacing(2.5)-1px)] group-has-disabled/autocomplete-input:opacity-50 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:-mx-0.5"
data-slot="autocomplete-start-addon"
>
{startAddon}
</div>
)}
<AutocompletePrimitive.Input
className={cn(
startAddon &&
"*:data-[slot=input]:ps-9 sm:*:data-[slot=input]:ps-8.5",
size === "sm"
? "has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-6.5"
: "has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-7",
className
)}
data-slot="autocomplete-input"
render={<Input className={cn(heightClass, startAddon && "ps-9 sm:ps-8.5", (showTrigger || showClear) && "pe-8")} />}
{...props}
/>
{showTrigger && (
<AutocompleteTrigger
className={cn(
"absolute top-1/2 inline-flex size-control-sm shrink-0 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors duration-fast focus-visible:ring-2 focus-visible:ring-ring/50 pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-control-2xs [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
size === "sm" ? "end-0" : "end-0.5"
)}
{...triggerProps}
>
<AutocompletePrimitive.Icon data-slot="autocomplete-icon">
<ChevronsUpDownIcon />
</AutocompletePrimitive.Icon>
</AutocompleteTrigger>
)}
{showClear && (
<AutocompleteClear
className={cn(
"absolute top-1/2 inline-flex size-control-sm shrink-0 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-[color,background-color,box-shadow,opacity] duration-fast focus-visible:ring-2 focus-visible:ring-ring/50 pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 sm:size-control-2xs [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
size === "sm" ? "end-0" : "end-0.5"
)}
{...clearProps}
>
<XIcon />
</AutocompleteClear>
)}
</AutocompletePrimitive.InputGroup>
)
}
export function AutocompletePopup({
className,
children,
side = "bottom",
sideOffset = 4,
alignOffset,
align = "start",
anchor,
portalProps,
...props
}: AutocompletePrimitive.Popup.Props & {
align?: AutocompletePrimitive.Positioner.Props["align"]
sideOffset?: AutocompletePrimitive.Positioner.Props["sideOffset"]
alignOffset?: AutocompletePrimitive.Positioner.Props["alignOffset"]
side?: AutocompletePrimitive.Positioner.Props["side"]
anchor?: AutocompletePrimitive.Positioner.Props["anchor"]
portalProps?: AutocompletePrimitive.Portal.Props
}): React.ReactElement {
return (
<AutocompletePrimitive.Portal {...portalProps}>
<AutocompletePrimitive.Positioner
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-modal select-none"
data-slot="autocomplete-positioner"
side={side}
sideOffset={sideOffset}
>
<span
className={cn(
"relative flex max-h-full min-w-(--anchor-width) max-w-(--available-width) origin-(--transform-origin) not-dark:bg-clip-padding transition-[scale,opacity] duration-fast before:pointer-events-none before:absolute before:inset-0 before:rounded-inset-menu before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
SURFACE_MENU_CLASS,
className
)}
>
<AutocompletePrimitive.Popup
className="flex max-h-[min(var(--available-height),23rem)] flex-1 flex-col text-foreground"
data-slot="autocomplete-popup"
{...props}
>
{children}
</AutocompletePrimitive.Popup>
</span>
</AutocompletePrimitive.Positioner>
</AutocompletePrimitive.Portal>
)
}
export function AutocompleteItem({
className,
children,
...props
}: AutocompletePrimitive.Item.Props): React.ReactElement {
return (
<AutocompletePrimitive.Item
className={cn(menuItemVariants(), className)}
data-slot="autocomplete-item"
{...props}
>
{children}
</AutocompletePrimitive.Item>
)
}
export function AutocompleteSeparator({
className,
...props
}: AutocompletePrimitive.Separator.Props): React.ReactElement {
return (
<AutocompletePrimitive.Separator
className={cn("mx-2 my-1 h-px bg-border last:hidden", className)}
data-slot="autocomplete-separator"
{...props}
/>
)
}
export function AutocompleteGroup({
className,
...props
}: AutocompletePrimitive.Group.Props): React.ReactElement {
return (
<AutocompletePrimitive.Group
className={cn("[[role=group]+&]:mt-1.5", className)}
data-slot="autocomplete-group"
{...props}
/>
)
}
export function AutocompleteGroupLabel({
className,
...props
}: AutocompletePrimitive.GroupLabel.Props): React.ReactElement {
return (
<AutocompletePrimitive.GroupLabel
className={cn(menuLabelVariants(), className)}
data-slot="autocomplete-group-label"
{...props}
/>
)
}
export function AutocompleteEmpty({
className,
...props
}: AutocompletePrimitive.Empty.Props): React.ReactElement {
return (
<AutocompletePrimitive.Empty
className={cn(
"not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",
className
)}
data-slot="autocomplete-empty"
{...props}
/>
)
}
export function AutocompleteRow({
className,
...props
}: AutocompletePrimitive.Row.Props): React.ReactElement {
return (
<AutocompletePrimitive.Row
className={className}
data-slot="autocomplete-row"
{...props}
/>
)
}
export const AutocompleteValue: typeof AutocompletePrimitive.Value =
AutocompletePrimitive.Value
export function AutocompleteList({
className,
scrollAreaClassName,
...props
}: AutocompletePrimitive.List.Props & {
/** 高度约束等样式落在 ScrollArea 根上(List 本体在 viewport 内部) */
scrollAreaClassName?: string
}) {
return (
<ScrollArea
className={scrollAreaClassName}
overscrollContain
scrollbarGutter
scrollFade
>
<AutocompletePrimitive.List
className={cn(
"not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3",
className
)}
data-slot="autocomplete-list"
{...props}
/>
</ScrollArea>
)
}
export function AutocompleteClear({
className,
...props
}: AutocompletePrimitive.Clear.Props): React.ReactElement {
return (
<AutocompletePrimitive.Clear
className={cn(
"absolute end-0.5 top-1/2 inline-flex size-control-sm shrink-0 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-[color,background-color,box-shadow,opacity] duration-fast focus-visible:ring-2 focus-visible:ring-ring/50 pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 sm:size-control-2xs [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className
)}
data-slot="autocomplete-clear"
{...props}
>
<XIcon />
</AutocompletePrimitive.Clear>
)
}
export function AutocompleteStatus({
className,
...props
}: AutocompletePrimitive.Status.Props): React.ReactElement {
return (
<AutocompletePrimitive.Status
className={cn(
"px-3 py-2 font-medium text-muted-foreground text-xs empty:m-0 empty:p-0",
className
)}
data-slot="autocomplete-status"
{...props}
/>
)
}
export const AutocompleteCollection: typeof AutocompletePrimitive.Collection =
AutocompletePrimitive.Collection
export function AutocompleteTrigger({
className,
children,
...props
}: AutocompletePrimitive.Trigger.Props): React.ReactElement {
return (
<AutocompletePrimitive.Trigger
className={className}
data-slot="autocomplete-trigger"
{...props}
>
{children}
</AutocompletePrimitive.Trigger>
)
}
export const useAutocompleteFilter: typeof AutocompletePrimitive.useFilter =
AutocompletePrimitive.useFilter
export { AutocompletePrimitive }
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
输入即筛的下拉选择,由 Autocomplete、Input、Popup、Item 组合;异步搜索需自行接数据源与防抖。