For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/llms-full.txt, and this page is available as Markdown at https://ifhover.github.io/leaf-ui/components/auto-complete.md.

AutoComplete 自动完成

在允许自由填写的同时提供输入建议。

基础用法

建议默认进行不区分大小写的包含匹配,仍允许自由填写。onChange 响应输入和选择,onSelect 只响应选择建议。带 disabled 的建议不可选中。

输入:空最近选中:无
basic.tsx
import { AutoComplete, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

const options = [
  { value: 'Leaf Garden' },
  { value: 'Leaf Studio' },
  { value: 'Pine Forest' },
  { value: 'Archived Garden', disabled: true },
];

export function AutoCompleteBasic() {
  const [value, setValue] = useState('');
  const [selected, setSelected] = useState('');

  return (
    <Form layout="vertical">
      <FormField label="项目名称">
        <AutoComplete
          aria-label="项目名称"
          options={options}
          placeholder="输入 Leaf 或自由填写"
          value={value}
          onChange={setValue}
          onSelect={setSelected}
        />
      </FormField>
      <Flex direction="column" gap={8} role="status">
        <Text tone="muted">输入:{value || '空'}</Text>
        <Text tone="muted">最近选中:{selected || '无'}</Text>
      </Flex>
    </Form>
  );
}

聚焦或输入时展开建议。方向键高亮可用项,Enter 选择,Escape 收起,Tab 继续访问后续控件;输入法合成期间的 Enter 不会选中建议。

示例

动态建议

onSearch 接收输入文本,清除时收到空字符串,选择建议时不触发。建议由应用生成或从服务端获取时,设置 filterOption={false} 可直接展示结果,不再进行本地过滤。

search.tsx
import { AutoComplete, type AutoCompleteOption, Form, FormField } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function AutoCompleteSearch() {
  const [options, setOptions] = useState<AutoCompleteOption[]>([]);

  return (
    <Form layout="vertical">
      <FormField label="邮箱地址">
        <AutoComplete
          aria-label="邮箱地址"
          placeholder="输入邮箱前缀"
          options={options}
          allowClear
          filterOption={false}
          onSearch={(query) => {
            const prefix = query.split('@')[0] ?? '';
            setOptions(
              prefix
                ? ['gmail.com', 'outlook.com', 'icloud.com'].map((domain) => ({
                    value: `${prefix}@${domain}`,
                  }))
                : [],
            );
          }}
        />
      </FormField>
    </Form>
  );
}

分组建议

通过分组标题和对应的 options 组织建议。富文本名称使用 searchLabel 提供搜索文字;选择后写入输入框的是 value,不是 label。

capabilities.tsx
import { AutoComplete, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';

const options = [
  {
    label: '团队',
    options: [
      {
        value: 'alice@example.com',
        label: (
          <Flex gap={8} align="center">
            <Text strong>Alice</Text>
            <Text tone="muted">设计</Text>
          </Flex>
        ),
        searchLabel: 'Alice 设计',
      },
      {
        value: 'bob@example.com',
        label: (
          <Flex gap={8} align="center">
            <Text strong>Bob</Text>
            <Text tone="muted">工程</Text>
          </Flex>
        ),
        searchLabel: 'Bob 工程',
      },
    ],
  },
];

export function Capabilities() {
  return (
    <Form layout="vertical">
      <FormField label="团队邮箱">
        <AutoComplete aria-label="团队邮箱" options={options} placeholder="搜索姓名或职责" />
      </FormField>
    </Form>
  );
}

加载与重试

本例模拟一次加载失败,重试会异步加载本地建议并替换错误内容。实际远程请求的防抖与响应顺序由应用处理。受控 open 需要在 onOpenChange 中更新。

加载失败
loading.tsx
import { AutoComplete, type AutoCompleteOption, Button, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';
import { useRef, useState } from 'react';

export function AutoCompleteLoading() {
  const [state, setState] = useState<'loading' | 'error' | 'ready'>('error');
  const [options, setOptions] = useState<AutoCompleteOption[]>([]);
  const [open, setOpen] = useState(false);
  const input = useRef<HTMLInputElement>(null);

  const retry = async () => {
    setState('loading');
    setOpen(true);
    input.current?.focus();
    await new Promise((resolve) => setTimeout(resolve, 800));
    setOptions([{ value: 'Leaf Garden' }, { value: 'Leaf Studio' }]);
    setState('ready');
  };

  return (
    <Form layout="vertical">
      <FormField label="远程项目">
        <AutoComplete
          ref={input}
          aria-label="远程项目"
          options={options}
          filterOption={false}
          open={open}
          onOpenChange={setOpen}
          loading={state === 'loading'}
          errorContent={
            state === 'error' ? (
              <Flex direction="column" align="start" gap={8}>
                <Text>建议加载失败</Text>
                <Button onClick={retry} size="sm">
                  重试
                </Button>
              </Flex>
            ) : undefined
          }
        />
      </FormField>
      <Text tone="muted" role="status">
        {state === 'loading' ? '正在加载' : state === 'error' ? '加载失败' : '已加载 2 条建议'}
      </Text>
      <Flex>
        <Button
          disabled={state === 'loading'}
          onClick={() => {
            setOptions([]);
            setState('error');
            setOpen(true);
          }}
        >
          模拟失败
        </Button>
      </Flex>
    </Form>
  );
}

禁用与只读

disabled 禁用整个控件;readOnly 允许聚焦与复制,但不允许编辑、选择或清除。

states.tsx
import { AutoComplete, Form, FormField } from '@ifhover/leaf-ui';

const options = [{ value: 'Leaf Garden' }, { value: 'Leaf Studio' }];

export function AutoCompleteStates() {
  return (
    <Form layout="vertical">
      <FormField label="禁用">
        <AutoComplete aria-label="禁用" options={options} defaultValue="Leaf Garden" disabled />
      </FormField>
      <FormField label="只读">
        <AutoComplete aria-label="只读" options={options} defaultValue="Leaf Garden" readOnly />
      </FormField>
    </Form>
  );
}

支持 name、required、form 等原生输入属性。非受控值随原生表单重置,受控值由应用重置。字段名称和建议内容需要应用自行翻译。

API

AutoComplete API

属性类型默认值说明
optionsreadonly (AutoCompleteOption|AutoCompleteOptionGroup)[]必填该分组内的建议。
valuestring—受控文本;省略时使用内部非受控值。
defaultValuestring''非受控模式的初始文本;支持表单重置。
onChange(value: string) => void—输入、清除或选择建议后返回完整文本。
onSelect(value: string, option: AutoCompleteOption) => void—仅选择建议时触发,返回写入的 value 与完整选项。
onSearch(query: string) => void—用户输入时返回查询文字;清除时返回空字符串,选择建议不触发。
size'sm' | 'md' | 'lg''md'输入框尺寸
status'error' | 'warning'—校验状态
disabledbooleanfalse禁用交互。
readOnlybooleanfalse锁定业务值,禁止输入、选择、清除和删除。
allowClearboolean—展示清除操作。
filterOptionfalse | ((query: string, option: AutoCompleteOption) => boolean)包含匹配false 关闭本地过滤;函数可定制过滤
loadingboolean—展示加载状态。
errorContentReactNode—展示加载错误和重试内容。
notFoundContentReactNode—没有匹配选项时的内容。
optionRender(option: AutoCompleteOption) => ReactNode—自定义选项内容。
openboolean—受控的展开状态。
defaultOpenbooleanfalse非受控模式的初始展开状态。
onOpenChange(open: boolean) => void—面板展开或收起时调用。
virtualboolean过滤后超过 100 项时启用仅渲染可见建议;默认在过滤后建议超过 100 项时启用。
listHeightnumber248建议面板的最大可视高度。
optionHeightnumber由主题和密度计算虚拟列表的预估行高;默认由主题和密度计算,实际行会被测量。
popupWidthnumber | string'trigger'浮层宽度;trigger 与触发控件等宽,auto 按内容定宽(可比控件窄),数字为固定像素值,也支持 CSS 长度。
popupMaxWidthnumber | string—可选的浮层最大宽度;未设置时不额外限制,仍受可视区域限制。
popupPlacementPopupOptions['popupPlacement']—浮层相对触发控件的位置。
popupClassNamestring—浮层的自定义类名。
popupStylePopupOptions['popupStyle']—浮层的自定义样式。
popupRenderPopupOptions['popupRender']—包装或补充面板内容,保留传入的内容以维持交互。
getPopupContainerPopupOptions['getPopupContainer']—返回浮层的挂载容器,也可返回 ShadowRoot。
refRef<HTMLInputElement>—输入框引用

placeholder、name、required、form、maxLength、aria-* 等属性传递给输入框;className 和 style 作用于外层容器。

AutoCompleteOption

属性类型默认值说明
valuestring必填唯一建议值;选择后写入输入框。
labelReactNode—建议的显示文字;默认也用于本地过滤。
searchLabelstring—搜索纯文本;省略时使用字符串 label,其他内容使用 value。
disabledbooleanfalse禁用该建议。

AutoCompleteOptionGroup

属性类型默认值说明
labelReactNode必填建议分组的标题。
optionsreadonly AutoCompleteOption[]必填该分组内的建议。