@github/auto-complete-element

中文文档
3.8.0发布于 2025/03/12MITTypeScriptES Module近 30 天下载 17.2万

Auto-complete input values from server results

原始使用文档
文档目录16 节
  1. Installation
  2. Usage
  3. Script
  4. Markup
  5. A Note on Clear button
  6. Attributes
  7. Properties
  8. Events
  9. Network request lifecycle events
  10. Auto-complete events
  11. CSP Trusted Types
  12. Browser support
  13. Development
  14. Accessibility Testing
  15. Validate usage in your project
  16. License

<auto-complete> element

Auto-complete input values from server search results.

Installation

$ npm install --save @github/auto-complete-element

Usage

Script

Import as ES modules:

import '@github/auto-complete-element'

With a script tag:

<script type="module" src="./node_modules/@github/auto-complete-element/dist/bundle.js">

Markup

<auto-complete src="/users/search" for="users-popup">
  <input type="text" name="users">
  <!--
    Optional clear button:
    - id must match the id of the input or the name of the input plus "-clear"
    - recommended to be *before* UL elements to avoid conflicting with their blur logic

    Please see Note below on this button for more details
  -->
  <button id="users-clear">X</button>
  <ul id="users-popup"></ul>
  <!--
    Optional div for screen reader feedback. Note the ID matches the ul, but with -feedback appended.
    Recommended: Use a "Screen Reader Only" class to position the element off the visual boundary of the page.
  -->
  <div id="users-popup-feedback" class="sr-only"></div>
</auto-complete>

If you want to enable auto-select (pressing Enter in the input will select the first option), using the above example:

<auto-complete data-autoselect="true" src="/users/search" for="users-popup">
...
</auto-complete>

The server response should include the items that matched the search query.

<li role="option">Hubot</li>
<li role="option">Bender</li>
<li role="option">BB-8</li>
<li role="option" aria-disabled="true">R2-D2 (powered down)</li>

The data-autocomplete-value attribute can be used to define the value for an item whose display text needs to be different:

<li role="option" data-autocomplete-value="bb8">BB-8 (astromech)</li>

Use data-no-result-found="true" to show a no results message inside the autocomplete popover. Be sure to add role="presentation" to this element so that screen readers do not mistake this as an auto-complete option. The auto-complete-element has built in functionality that handles aria-live announcing number of search results so this should be purely decorative.

<li role="presentation" aria-hidden="true" data-no-result-found="true">No results found!</li>

A Note on Clear button

While input type="search" comes with an x that clears the content of the field and refocuses it on many browsers, the implementation for this control is not keyboard accessible, and so we've opted to enable a customizable clear button so that your keyboard users will be able to interact with it.

As an example:

In Chrome, this 'x' isn't a button but a div with a pseudo="-webkit-search-cancel-button". It doesn't have a tab index or a way to navigate to it without a mouse. Additionally, this control is only visible on mouse hover.

Attributes

  • open is true when the auto-complete result list is visible
  • value is the selected value from the list or the empty string when cleared

Properties

  • fetchResult you can override the default method used to query for results by overriding this property: document.querySelector('auto-complete').fetchResult = async (url) => (await fetch(url)).text()

Events

Network request lifecycle events

Request lifecycle events are dispatched on the <auto-complete> element. These events do not bubble.

  • loadstart - The server fetch has started.
  • load - The network request completed successfully.
  • error - The network request failed.
  • loadend - The network request has completed.

Network events are useful for displaying progress states while the request is in-flight.

const completer = document.querySelector('auto-complete')
const container = completer.parentElement
completer.addEventListener('loadstart', () => container.classList.add('is-loading'))
completer.addEventListener('loadend', () => container.classList.remove('is-loading'))
completer.addEventListener('load', () => container.classList.add('is-success'))
completer.addEventListener('error', () => container.classList.add('is-error'))

Auto-complete events

auto-complete-change is dispatched after a value is selected. In event you can find:

  • relatedTarget: The HTMLInputElement controlling the auto-complete result list.
completer.addEventListener('auto-complete-change', function(event) {
  console.log('Auto-completed value chosen or cleared', completer.value)
  console.log('Related input element', event.relatedTarget)
})

CSP Trusted Types

You can call setCSPTrustedTypesPolicy(policy: TrustedTypePolicy | Promise<TrustedTypePolicy> | null) from JavaScript to set a CSP trusted types policy, which can perform (synchronous) filtering or rejection of the fetch response before it is inserted into the page:

import AutoCompleteElement from 'auto-complete-element'
import DOMPurify from 'dompurify' // Using https://github.com/cure53/DOMPurify

// This policy removes all HTML markup except links.
const policy = trustedTypes.createPolicy('links-only', {
  createHTML: (htmlText: string) => {
    return DOMPurify.sanitize(htmlText, {
      ALLOWED_TAGS: ['a'],
      ALLOWED_ATTR: ['href'],
      RETURN_TRUSTED_TYPE: true
    })
  }
})
AutoCompleteElement.setCSPTrustedTypesPolicy(policy)

The policy has access to the fetch response object. Due to platform constraints, only synchronous information from the response (in addition to the HTML text body) can be used in the policy:

import AutoCompleteElement from 'auto-complete-element'

const policy = trustedTypes.createPolicy('require-server-header', {
  createHTML: (htmlText: string, response: Response) => {
    if (response.headers.get('X-Server-Sanitized') !== 'sanitized=true') {
      // Note: this will reject the contents, but the error may be caught before it shows in the JS console.
      throw new Error('Rejecting HTML that was not marked by the server as sanitized.')
    }
    return htmlText
  }
})
AutoCompleteElement.setCSPTrustedTypesPolicy(policy)

Note that:

  • Only a single policy can be set, shared by all AutoCompleteElement fetches.
  • You should call setCSPTrustedTypesPolicy() ahead of any other load of auto-complete element in your code.
    • If your policy itself requires asynchronous work to construct, you can also pass a Promise<TrustedTypePolicy>.
    • Pass null to remove the policy.
  • Not all browsers support the trusted types API in JavaScript. You may want to use the recommended tinyfill to construct a policy without causing issues in other browsers.

Browser support

Browsers without native custom element support require a polyfill.

  • Chrome
  • Firefox
  • Safari
  • Microsoft Edge

Development

npm install
npm test

To view changes locally, run npm run examples.

In examples/index.html, uncomment <!--<script type="module" src="./dist/bundle.js"></script>--> and comment out the script referencing the unpkg version. This allows you to use the src code in this repo. Otherwise, you will be pulling the latest published code, which will not reflect the local changes you are making.

Accessibility Testing

We have included some custom rules that assist in providing guardrails to confirm this component is being used accessibly.

If you are using the axe-core library in your project,

import axe from 'axe-core'
import autoCompleteRulesBuilder from '@github/auto-complete-element/validator'

const autoCompleteRules = autoCompleteRulesBuilder() // optionally, pass in your app's custom rules object, it will build and return the full object

axe.configure(autoCompleteRules)
axe.run(document)

Validate usage in your project

To confirm your usage is working as designed,

import {validate} from '@github/auto-complete-element/validator' 

validate(document)

Passes and failures may be determined by the length of the passes and violations arrays on the returned object:

{
  passes: [],
  violations: []
}

License

Distributed under the MIT license. See LICENSE for details.

版本与发布记录

@github/auto-complete-element 共发布 37 个版本,首次发布于 2018/04/13;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.8.0latest2025/03/121.7 年前
3.7.12025/02/141.8 年前
3.6.22024/03/062 年前
3.6.12024/02/232 年前
3.6.02023/11/133 年前
3.5.12023/07/043 年前

关于 @github/auto-complete-element 的常见问题

@github/auto-complete-element 是什么?

Auto-complete input values from server results

如何安装 @github/auto-complete-element?

在项目目录运行 npm install @github/auto-complete-element,或使用 pnpm add / yarn add / bun add。

@github/auto-complete-element 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@github/auto-complete-element 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@github/auto-complete-element 可以商用吗?

@github/auto-complete-element 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@github/auto-complete-element 的下载量有多少?

根据 npm 官方下载统计,@github/auto-complete-element 在 2026/10/17 – 2026/11/15 这 30 天内被下载 171,988 次,日均约 5,733 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@github/auto-complete-element 还在维护吗?

最新版本 3.8.0 发布于 2025/03/12(1.7 年前);至今共发布 37 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/04/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。