@drupal/autocomplete

0.0.2 • Public • Published

@drupal/autocomplete

A standalone autocomplete, optimized for accessibility.

Examples

Example (Initialization)

<!-- Ensure the assets are included in the page. -->
<link rel="stylesheet" href="[path]/a11y.autocomplete.css" />
<script src="[path]/a11y.autocomplete.js"></script>
<!-- Element to receive autocomplete functionality. -->
<input id="an-input" />

<script>
  const input = document.querySelector('#an-input');
  // Initialize the autocomplete with a fixed list of items.
  const autocompleteInstanceFixedList = A11yAutocomplete(input, {
    source: ['first item', 'second item', 'third item'],
  });
  // Or initialize the autocomplete with dynamic results.
  const autocompleteInstanceDynamicList = A11yAutocomplete(input, {
    source: (query, result) => {
      result(['first item', 'second item', 'third item']);
    },
  });
  // When the autocomplete is initialized, markup is added.
</script>

Example (HTML structure)

<!-- The input is wrapped in a div, making is possible to position the results list with CSS. -->
<div data-drupal-autocomplete-wrapper>
  <!-- Several attributes are added to the input, used for accessibility and being identifiable by JavaScript. -->
  <input id="an-input" aria-autocomplete="list" autocomplete="off" data-drupal-autocomplete-input aria-owns="autocomplete-l0" role="combobox" aria-expanded="false" aria-describedby="assistive-hint-0">
    <!-- This span provides assistive technology such as screenreaders with additional information when the input is focused. -->
    <span class="visually-hidden" id="assistive-hint-0">Type 2 or more characters for results. When autocomplete results are available use up and down arrows to review and enter to select. Touch device users, explore by touch or with swipe gestures.</span>
    <!-- This is the <ul> that will list the query results when characters are typed in the input. -->
    <ul role="listbox" data-drupal-autocomplete-list="" id="autocomplete-l0" hidden=""></ul>
    <!-- This is a live region, used for conveying the results of interactions to assistive technology, such as the number of results available after typing. -->
    <span data-drupal-autocomplete-live-region="" aria-live="assertive"></span>
</div>

Example (Setting Options)

<!-- Options can be set in three ways, listed from highest precedence to lowest: -->

<!-- 1. An object literal in the input's `data-autocomplete` attribute with the format {camelCaseOptionName: value}. -->
<input data-autocomplete='{"minChars": "3", "source":["first item", "second item", "third item"]}' />

<!-- 2. Via the data-autocomplete-(hyphen delimited option name) attribute. -->
<input data-autocomplete-min-chars="3" data-autocomplete-source="['first item', 'second item', 'third item']" />

<script>
  // 3. Via the options argument when initializing a new instance
  A11yAutocomplete(input, {minChars: 3, , source: ['first item', 'second item', 'third item']})
</script>

API

Functions

A11yAutocomplete(input, options)Api

Main entrypoint to the library.

A11yAutocomplete(input, options) ⇒ Api

Main entrypoint to the library.

Kind: global function
Returns: Api - API to manage an input's autocomplete functionality.
Emits: autocomplete-change, autocomplete-close, autocomplete-created, autocomplete-destroy, autocomplete-highlight, autocomplete-open, autocomplete-pre-search, autocomplete-response, autocomplete-select, autocomplete-selection-added

Param Type Description
input HTMLElement

The element to be used as an autocomplete.

options Options

Autocomplete options.


"autocomplete-created"

Fires after initialization and markup additions.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.


"autocomplete-change"

Fires after an item is blurred and another item hasn't been highlighted.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.


"autocomplete-highlight"

Fires when an item is highlighted.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.

detail.selected SourceData

The original item as provided in the source.


"autocomplete-select"

Fires when an item is selected for addition. This event can be canceled and prevent the addition of the item.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.

detail.selected SourceData

The original item as provided in the source.


"autocomplete-selection-added"

Fires after an item is added to the autocomplete

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.

detail.added string

The text added to the input value.


"autocomplete-pre-search"

Fires just before a search. Can be used to cancel the search.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.


"autocomplete-response"

Fires after suggestion items are retrieved, but before they are added to the DOM.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.

detail.list Array.<Suggestion>

The normalized array of suggestions to display.


"autocomplete-response"

Fires after suggestion items are retrieved, but before they are added to the DOM.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.

detail.list Array.<Suggestion>

The normalized array of suggestions to display.


"autocomplete-open"

Fires after the suggestion list opens.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.


"autocomplete-close"

Fires after the suggestion list closes.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.


"autocomplete-destroy"

Fires after the instance is destroyed.

Kind: event emitted by A11yAutocomplete
Properties

Name Type Description
detail object

Detail property of the event.

detail.autocomplete Api

The autocomplete instance.


A11yAutocomplete~Api : object

The API to manage an input's autocomplete functionality.

This is part of the public API and triggers semver increment on change.

Kind: inner typedef of A11yAutocomplete
Access: public
Properties

Name Type Description
destroy destroy

Function to destroy the autocomplete instance.

id string

The id of the instance.


A11yAutocomplete~sourceObject : object

Default suggestion structure, one of label or value is required.

This is the expected structure for a suggestion item. If the structure is different make sure to override options.templates.suggestion and options.templates.inputValue to generate the appropriate label and value from the custom object structure.

Kind: inner typedef of A11yAutocomplete
Access: public
Properties

Name Type Description
[label] string

The text used to show the suggestion in the dropdown.

[value] string

The text added to the input field upon selection.


A11yAutocomplete~SourceData : sourceObject | string

Original source data.

This data is passed directly to the suggestionTemplate callback to generate the suggestion label displayed in the dropdown and the inputValueTemplate callback to generate the suggestion value that will be added to the input field upon selection.

Kind: inner typedef of A11yAutocomplete
Access: public
See

  • A11yAutocomplete~suggestionTemplate
  • A11yAutocomplete~inputValueTemplate

A11yAutocomplete~Suggestion : object

Structure of a normalized suggestion item.

This is part of the public API and triggers semver increment on change.

Kind: inner typedef of A11yAutocomplete
Access: public
Properties

Name Type Description
label string

Text or HTML used to display the item in the listbox. Result of the A11yAutocomplete~Options.templates.suggestion callback.

value string

Text added to the input field on selection. Result of the A11yAutocomplete~Options.templates.inputValue callback.

index number

When the suggestion list is displayed, an index is assigned to the suggestion to be able to know its place in the list of results.

item SourceData

Original object passed before normalization.


A11yAutocomplete~sourceCallback : function

A callback to return autocomplete results dynamically.

This is part of the public API and triggers semver increment on change.

Kind: inner typedef of A11yAutocomplete
Access: public

Param Type Description
searchTerm string

The search term being searched for.

results sourceResultsCallback

A callback to populate the results list.

Example (Simple fetch call)

 // Example querying an endpoint that provides JSON.
 source: (searchTerm, results) => {
   // Query the remote source
   fetch(`https://an-endpoint/?q=${searchTerm}`)
      .then((response) => response.json())
      // Use the callback to send the results to the
      .then(results);
 },

A11yAutocomplete~sourceResultsCallback : function

A callback that will display the results passed according to the configured constraints.

This is part of the public API and triggers semver increment on change.

Kind: inner typedef of A11yAutocomplete
Access: public

Param Type Description
results Array.<SourceData>

A callback to populate the results list.


A11yAutocomplete~Options : object

Options sent to the Autocomplete constructor that will override the default options.

This is part of the public API and triggers semver increment on change.

Kind: inner typedef of A11yAutocomplete
Access: public
Properties

Name Type Default Description
[source] Array.<SourceData> | sourceCallback

The data the autocomplete searches, which can be provided in multiple ways:

  • An array of strings: [ "First choice", "Second Choice", ... ]
  • An array of objects. All objects must have either a 'label' or 'value' property: [ { label: "First Choice", value: "First Value" }, ... ] The label property is displayed in the suggestion list, and is what the autocomplete process searches. The value property is what is inserted into the input element when an item is selected. If just one property (value or label) is specified, it will be used for both, e.g., if only 'value' is provided, it will also be used as the label. Note that these objects can have additional properties beyond 'label' and 'value', but at least one of those two properties must be present for the autocomplete to work.
  • A string of valid JSON that can be parsed into an array of strings or an array of objects (i.e. either of the array options listed above).
  • A callback function sourceCallback.
[groupBy] string

Name of the key used to group suggestions.

[templates] object

Defines templates (functions) that are used for displaying parts of the autocomplete.

[templates.suggestions] suggestionTemplate

Defines template for suggestion labels.

[templates.inputValue] inputValueTemplate

Defines template for suggestion input values.

[classes] object

Defines classes to be added to the relevant Dom element.

[classes.wrapper] string

Defines classes for the autocomplete wrapper element.

[classes.input] string

Defines classes for the input field.

[classes.inputLoading] string

Defines classes for the input field applied while the source callback is in progress.

[classes.listbox] string

Defines classes for the suggestion item wrapper.

[classes.group] string

Defines classes for the group wrapper.

[classes.groupLabel] string

Defines classes for the item used as a group label.

[classes.option] string

Defines classes for the list item wrapper.

[allowRepeatValues] boolean | null

If true, autocomplete results can include items already included in the field. A null value functions the same as false, but a null value can be used to determine if this value was explicitly set or using defaults.

[autoFocus] boolean false

When true, the first result is focused as soon as a list of results becomes visible.

[separatorChar] string ","

The character used to separate multiple values in the same form.

[firstCharacterIgnoreList] string ","

Any characters in this string will not be incorporated in a search as the first character of a query. Typically, this string should at least include the value of separatorChar.

[minChars] number 1

Minimum number of characters that must be typed before displaying autocomplete results.

[cardinality] number 1

The number of values the input can reference, where multiple values are separated by the character specified in the separatorChar option. Set to -1 for unlimited cardinality.

[createLiveRegion] boolean true

When true, initialization includes adding a live region specifically that will convey autocomplete activity to assistive technology. This is typically only set to false if a site has a centralized live region for assistive technology announcements.

[inputAssistiveHint] string "When autocomplete results are available use up and down arrows to review and enter to select. Touch device users, explore by touch or with swipe gestures."

Message conveyed to assistive technology when the input is focused.

[minCharAssistiveHint] string "Type @count or more characters for results"

When minChars is greater than one, this is appended to inputAssistiveHint so users are aware how many characters are needed to trigger a search. @count is replaced with the value ofminChars.

[noResultsAssistiveHint] string "No results found"

Message conveyed to assistive technology when the query returns no results.

[someResultsAssistiveHint] string "There are @count results available."

Message conveyed to assistive technology when the number of results exceeds one. @count is replaced with the number of results returned.

[oneResultAssistiveHint] string "There is one result available."

Message conveyed to assistive technology when there is one result.

[highlightedAssistiveHint] string "@selectedItem @position of @count is highlighted"

Message conveyed to assistive technology when a result is selected from the list.


A11yAutocomplete~suggestionTemplate ⇒ string

Formats how a suggestion is structured in the suggestion list.

Kind: inner typedef of A11yAutocomplete
Returns: string - The text and html of a suggestion item.

Param Type Description
item SourceData

Item object from the source parameter.


A11yAutocomplete~inputValueTemplate ⇒ string

Format the text that will be added to the input field.

Kind: inner typedef of A11yAutocomplete
Returns: string - The text to add to the input field value.

Param Type Description
item SourceData

Item object from the source parameter.


A11yAutocomplete~destroy : function

Remove all event listeners added by this class.

Kind: inner typedef of A11yAutocomplete


Package Sidebar

Install

npm i @drupal/autocomplete

Weekly Downloads

8

Version

0.0.2

License

GPL-2.0-or-later

Unpacked Size

187 kB

Total Files

9

Last publish

Collaborators

  • mixologic
  • justafish
  • drupalengineering