方向键选择,Enter 确认;Escape 取消本次输入并恢复上次选择。
查询失败时可以原地重试,不会把失败伪装成没有结果。
这个字段允许自由输入,离开时保留内容。
<div class="demo-col" style="width:100%"><label class="demo-label" for="demo-autocomplete-input">查找项目</label><div class="icen-input-wrap icen-control" style="width:100%"><input class="icen-input" id="demo-autocomplete-input" placeholder="输入本真、像素或海边" /></div><p class="demo-label" id="autocomplete-log" role="status"><bdi>方向键选择,Enter 确认;Escape 取消本次输入并恢复上次选择。</bdi></p><label class="demo-label" for="demo-autocomplete-async">查找负责人</label><div class="icen-input-wrap icen-control" style="width:100%"><input class="icen-input" id="demo-autocomplete-async" placeholder="输入林、沈或 ali,体验异步查找" /></div><div class="demo-row"><button class="icen-btn icen-btn-sm" type="button" id="autocomplete-fail">模拟一次查询失败</button></div><p class="demo-label" id="autocomplete-async-log" role="status"><bdi>查询失败时可以原地重试,不会把失败伪装成没有结果。</bdi></p><label class="demo-label" for="demo-autocomplete-free">自定义分类</label><div class="icen-input-wrap icen-control" style="width:100%"><input class="icen-input" id="demo-autocomplete-free" placeholder="选择建议,也可以保留自己的分类名" /></div><p class="demo-label" id="autocomplete-free-log" role="status"><bdi>这个字段允许自由输入,离开时保留内容。</bdi></p></div>
行为与接口说明
同步或异步建议源,支持安全高亮、自定义行、自由输入和键盘选择。加载、无匹配和查询失败分开呈现;AbortSignal 与代际检查阻止旧结果,列表与状态按钮各有独立语义,卸载后还原宿主字段。
安装
bun add @icen.ai/ui pnpm add @icen.ai/ui npm install @icen.ai/ui yarn add @icen.ai/ui 一行引入该组件(CSS 与 behavior 自动带上,无需关心内部 CSS 文件名):
import '@icen.ai/ui/kit/autocomplete';
也可以用脚手架直接打印引入行:
bunx --bun @icen.ai/ui add autocomplete
Astro 项目注意:kit 入口里的 CSS import 在页面 <script> 里会被 Astro 的 client bundle 摇掉——请改在布局 frontmatter 里引 CSS(import '@icen.ai/ui/components/autocomplete.css';),JS 行为仍可走 kit。Vite SPA / webpack 项目无此问题。
用法
import {createAutocomplete} from '@icen.ai/ui/kit/autocomplete';const handle=createAutocomplete(input,{ source:async (query,{signal})=>{ const response=await fetch('/api/projects?q='+encodeURIComponent(query),{signal}); if(!response.ok)throw new Error('Project lookup failed'); return response.json(); // string[] 或 {value,label}[] }, minChars:1,debounceMs:160,maxItems:8,freeSolo:false, loadingLabel:'正在查找项目…',errorLabel:'暂时无法查找项目,请重试。', noResultsLabel:'没有匹配的项目', // renderItem:(item,query)=>Node | string,});// role=combobox 控制真实 listbox;状态和重试动作不混入 option。// Enter 在失败态重试;Tab 也可进入重试按钮,Escape 返回输入。// source 失败会展示反馈;关闭/换词/失焦/销毁会 abort 在途请求。input.addEventListener('icen:autocomplete-select',(event)=>console.log(event.detail));handle.getValue(); // 选中 value;input 显示 labelhandle.setValue('value');handle.open();handle.close();handle.destroy();