npm package: @lipet/autosuggest
Description: A lightweight, accessible autosuggest library with no runtime dependencies.
Author: Petri Liuska
Latest version: 0.3.0

# @lipet/autosuggest

A lightweight, accessible autosuggest library with no runtime dependencies.

The library is intentionally non-opinionated and unstyled. It handles the behaviour, ARIA wiring and keyboard navigation, but leaves the styling and markup up to you.

## Development notes

AI tools were used to assist with the initial structure, implemention ideas and writing documentation. The final architecture and code were iterated and refined manually, and all code was written by hand.

## Installation

```bash
npm install @lipet/autosuggest
```

## Basic usage

Provide a container element with an input inside it. The library will find the input and inject the suggestion listbox into the container.

```html
<div id="autosuggest">
  <label for="search">Search:</label>
  <input id="search" type="text" placeholder="Type to search..." />
</div>
```

```ts
import { createAutosuggest } from "@lipet/autosuggest";

const autosuggest = createAutosuggest("#search", {
  listboxLabel: "Search suggestions",
  items: ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"],
});
```

> **Note:** The container must not be the `<label>` element itself. Pass a wrapper element instead.
> Wrap both the label and input in a neutral element like a `<div>`.

```html
<!-- Don't do this! -->
<label id="autosuggest">
	Search:

	<input type="text" placeholder="Type to search..." />
</label>

<!-- Do this instead -->
<div id="autosuggest">
	<label>
		Search:
		<input type="text" placeholder="Type to search..." />
	</label>
</div>
```

## Destroying the instance

```ts
autosuggest.destroy();
```

Cleans up all event listeners and DOM elements created by the library.

## Updating items at runtime

```ts
autosuggest.setItems(["New", "List", "Of", "Items"]);
```

## Asynchronous source

```ts
autosuggest.setSource(async (query, signal) => {
  const res = await fetch(`/search?q=${query}`, { signal });
  return res.json();
});
```

The `signal` parameter is an `AbortSignal` that is used to automatically cancel in-flight requests when the user keeps typing. Handling this signal is optional.

## Handling selection

The lbirary dispatches an `autosuggest-select` event on the input element when an item is selected.

```ts
document.querySelector("#search").addEventListener("autosuggest-select", (event) => {
  console.log(e.detail.value); // The display string of the selected item
  console.log(e.detail.item); // The original item from the items array
});
```

## Generic items

ITems don't have to be strings. Provide a `getValue` function to extract the display string from your objects.

```ts
interface Item {
  id: number;
  name: string;
  // other properties...
}

const autosuggest = createAutosuggest<Item>("#search", {
  items: [
    { id: 1, name: "Apple" },
    { id: 2, name: "Banana" },
    { id: 3, name: "Cherry" },
  ],
  getValue: (item) => item.name,
});
```

`e.detail.item` in the select event will be the full `Item` object in this case.

## Options

| Option              | Type                  | Default        | Description                                              |
| ------------------- | --------------------- | -------------- | -------------------------------------------------------- |
| `items`             | `T[]`                 | `[]`           | Initial list of items                                    |
| `source`            | `AsyncSourceFn<T>`    | -              | Async source function, replaces static items             |
| `getValue`          | `(item: T) => string` | `String(item)` | Extracts display string from item                        |
| `mode`              | `AutosuggestMode`     | `StartsWith`   | Matching mode                                            |
| `matcher`           | `MatcherFn<T>`        | -              | Custom matcher, overrides `mode`                         |
| `caseSensitive`     | `boolean`             | `false`        | Case sensitive matching                                  |
| `debounceMs`        | `number`              | `300`          | Debounce delay for input events                          |
| `inputSelector`     | `string`              | `'input'`      | CSS selector for the input within the container          |
| `listboxLabel`      | `string`              | -              | `aria-label` for the listbox                             |
| `listboxLabelledBy` | `string`              | -              | `aria-labelledby` for the listbox, provide an element ID |

## Matching modes

```ts
import { createAutosuggest, AutosuggestMode } from "@lipet/autosuggest";

// StartsWith (default): only matches items beginning with the query
createAutosuggest("#search", { mode: AutosuggestMode.StartsWith });

// Fuzzy: matches items containing the query characters in order
createAutosuggest("#search", { mode: AutosuggestMode.Fuzzy });

// Custom: provide your own matcher function
createAutosuggest("#search", {
  mode: AutosuggestMode.Custom,
  matcher: (query, items, options) => items.filter(/* your logic */),
});
```

## Custom matcher

The `MatcherFn` type is exported so you can write typed custom matchers.

```ts
import type { MatcherFn } from "@lipet/autosuggest";

const myMatcher: MatcherFn<string> = (query, items, options) => {
  return items.filter((item) => item.includes(query));
};
```

## Instance API

```ts
const autosuggest = createAutosuggest("#search", options);

autosuggest.setItems(items); // Replace the list of items (only for static source)
autosuggest.setSource(fn); // Switch to an asynchronous source
autosuggest.destroy(); // Clean up all resources and event listeners used by the instance
```

## Accessibility

The library follows the [ARIA combobox pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/). It sets the required ARIA attributes on the input and listbox elements, and manages `aria-activedescendant` and `aria-selected` states during keyboard navigation.

**You must provide either `listboxLabel` or `listboxLabelledBy` to give the listbox an accessible name.** The library will warn in the console if neither is provided.

```ts
// Option 1: Provide a label directly
createAutosuggest("#search", {
  listboxLabel: "Search suggestions",
});

// Option 2: Reference an existing label element by ID
createAutosuggest("#search", {
  listboxLabelledBy: "my-listbox-label",
});
```

Keyboard navigation follows the specification:

- ArrowUp navigates upward, wrapping to last item
- ArrowDown opens and navigates the list, wrapping to first item
- Enter selects the active item
- Escape closes the listbox
- Tab closes the listbox and moves focus as normal

## Styling

The library injects a `<ul>` element with the class `las-listbox` directly into given container. List items have the class `las-option`. The active item during keyboard navigation receives the `aria-selected="true"` attribute. You can use these classes and attributes to style the listbox and options as needed.

The library ships with no visual styles. A minimal example:

```css
.las-listbox {
  list-style: none;
  margin: 0;
  padding: 0;
  position: absolute;
  width: 100%;

  /* Add your own styles for background, border, z-index etc */
}

.las-option {
  cursor: pointer;

  /* Add your own styles for padding, hover effects etc */
}

.las-option[aria-selected="true"] {
  /* Styles for the active option during keyboard navigation */
}
```

Your container likely should have `position: relative` to position the listbox correctly.

## License

MIT. Do not use the code for evil, apart from that, do whatever you want with it.