# `ixfx-ac-token`

Token/tag input with per-token autocomplete. Looks like a text box — committed tokens appear as inline chips, and a suggestion popup follows the typing cursor. Typical use cases are email To: fields and tag pickers.

Tokens are delimited by space, comma, or semicolon by default. Typing a delimiter commits the current word as a chip. Pressing Enter commits the current text (non-strict mode) or the highlighted suggestion (strict mode).

```html
<!-- Static suggestion list from attribute -->
<ixfx-ac-token
  placeholder="Add tags…"
  data-tokens="javascript typescript python rust go"
></ixfx-ac-token>

<!-- Dynamic async provider -->
<ixfx-ac-token placeholder="Add recipients…"></ixfx-ac-token>
```

```js
const el = document.querySelector('ixfx-ac-token');

el.completionProvider = async (token, signal) => {
  const results = await searchPeople(token);
  return results.map(p => ({ label: p.name, subLabel: p.email }));
};

el.addEventListener('ac-token-change', e => {
  console.log(e.detail.tokens.map(t => t.label)); // ['Alice', 'Bob']
});
```

---

### Properties / attributes

| Attribute / Property  | Type                              | Default     | Description                                                         |
|-----------------------|-----------------------------------|-------------|---------------------------------------------------------------------|
| `completionProvider`  | `AcTokenCompletionProvider \| undefined` | `undefined` | Async or sync function returning suggestions for the current draft token. Takes precedence over `data-tokens`. |
| `tokenizer`           | `AcTokenizerFn \| undefined`      | `undefined` | Custom function to split text into tokens. Default splits on space, comma, semicolon. |
| `tokenStyle`          | `AcTokenStyleFn \| undefined`     | `undefined` | Called per committed chip with the `AcTokenItem`; return `{ background?, color?, borderColor? }` (any CSS colour) or undefined for the default look. Not applied while the chip is selected. |
| `data-tokens`         | `string` (attribute only)         | `''`        | Space/comma/semicolon-separated list of static suggestion labels. Used when no `completionProvider` is set. |
| `placeholder`         | `string`                          | `''`        | Placeholder shown when no tokens or draft text are present.         |
| `strict`              | `boolean`                         | `false`     | When true, only suggestions from the popup can be committed. Free-form typed text is ignored. |
| `cacheSize`           | `number`                          | `20`        | LRU cache size for provider results.                                |
| `debounceMs`          | `number`                          | `150`       | Debounce delay in ms before invoking the provider after a keystroke.|
| `tokens` (property)   | `readonly AcTokenItem[]`          | `[]`        | Get or set the full token list programmatically. Setting it dispatches `ac-token-change`, same as a user edit — beware feedback loops if a parent updates this binding from its own `ac-token-change` handler. Use `setTokens()` to avoid that. |
| `value` (property, read-only) | `string`                | —           | All committed token labels joined with `, `.                        |

### Methods

| Method | Description |
|--------|-------------|
| `setTokens(tokens)` | Set the token list programmatically without dispatching `ac-token-change`. Prefer this over the `tokens` property for initialisation or any other update driven by the component's own state. |

---

### Performance

- **Suggestions** render 50 rows at first and add 50 more as the popup scrolls near its end or the keyboard cursor
  approaches it, so a query matching most of a 100k list costs ~50 rows, not tens of thousands. Every suggestion stays
  reachable (`aria-setsize` / `aria-posinset` report the full list). `ArrowUp` with no cursor jumps to the last one
  only for lists up to 1,000; longer lists start at the top. Result lists longer than 5,000 aren't kept in the LRU cache.
- **Pasting many words** (or any input that commits several at once) copies the token list once and fires **one**
  `ac-token-change` with the final list; `ac-token-add` still fires once per token (with its final index).
- Chips are only re-rendered when the token list, the selection or `tokenStyle` changes, not on every keystroke, and
  share one pointer handler (index read from `data-index`).
- Used-label filtering (`allow-duplicates` off) keeps one `Set` per token list instead of rebuilding it per query.

Reference, 100k in Chrome (`pnpm bench:ac-token`, needs `pnpm start`): a keystroke matching most of 100k suggestions
≈ 50 ms (was 1.4 s, 61k rows), ArrowDown ≈ 1.4 ms (was ≈ 107 ms), heap after a broad query ≈ 25 MB (was 113 MB);
pasting 100k tokens ≈ 0.75 s (was 7.5 s, 100k change events), retained heap ≈ 69 MB (was 90 MB). With 100k chips on
screen a keystroke still costs ≈ 50 ms and a commit / remove ≈ 130 ms: that's browser layout of 100k inline chips,
which a wrapping layout can't virtualise.

### Events

| Event             | Detail                                      | Description                        |
|-------------------|---------------------------------------------|------------------------------------|
| `ac-token-change` | `{ tokens: readonly AcTokenItem[] }`        | Fired on any change to the token list (add or remove). |
| `ac-token-add`    | `{ item: AcTokenItem, index: number }`      | Fired when a single token is committed. |
| `ac-token-remove` | `{ item: AcTokenItem, index: number }`      | Fired when a single token is removed. |

---

### Keyboard interactions

| Key                     | Condition                      | Action                                                   |
|-------------------------|--------------------------------|----------------------------------------------------------|
| Space / `,` / `;`       | Typed in the draft input       | Commit the current draft as a token and start a new one. |
| `Enter`                 | Suggestion highlighted         | Accept the highlighted suggestion.                       |
| `Enter`                 | No suggestion, non-strict mode | Commit the current draft as a free-form token.           |
| `ArrowDown` / `ArrowUp` | Popup open                     | Move the suggestion highlight.                           |
| `ArrowLeft`             | Draft cursor at position 0     | Move selection to the previous chip (or last if none selected). |
| `ArrowRight`            | A chip is selected             | Move selection to the next chip (or back to the draft input if at last). |
| `Backspace`             | Draft empty, no chip selected  | Delete the last chip.                                    |
| `Backspace`             | A chip is selected             | Delete the selected chip.                                |
| Any printable key       | A chip is selected             | Remove the selected chip and pre-fill the draft with its label + the typed key. |
| `Escape`                | Popup open                     | Close the popup without committing.                      |
| `Cmd/Ctrl+A`            | —                              | Copy all token labels and current draft to the clipboard as plain text. |

---

### Touch / pointer interactions

| Gesture                  | Action                  |
|--------------------------|-------------------------|
| Click a chip             | Select / deselect it (for keyboard editing or deletion). |
| Drag a chip up or down   | Remove it (threshold: 28 px vertical movement).          |
| Click outside any chip   | Focus the draft input.  |

---

### Paste

Pasting plain text tokenizes it using the configured tokenizer. Complete tokens are committed immediately; any partial trailing text becomes the new draft.

```
Paste: "alice, bob, carol"  →  chips [alice] [bob], draft "carol"
Paste: "alice, bob, carol " →  chips [alice] [bob] [carol], draft ""
```

---

### Completion provider

The provider receives the current draft token (not the full input value) and an `AbortSignal`. It can return a `Promise` or a plain array.

```ts
el.completionProvider = async (token: string, signal: AbortSignal) => {
  const res = await fetch(`/api/tags?q=${token}`, { signal });
  const data = await res.json();
  return data.map((item: Tag) => ({
    label: item.name,
    subLabel: item.count + ' uses',
    key: item.id,
    data: item,
  }));
};
```

When `token` is an empty string the provider is still called — use this to show all available options when the user hasn't typed anything yet.

---

### Custom tokenizer

The default tokenizer splits on whitespace, comma, and semicolon. Supply a custom function to change what counts as a token boundary:

```js
// Colon-separated path segments
el.tokenizer = text => text.split(':');

// Only comma-separated (spaces allowed inside tokens)
el.tokenizer = text => text.split(',').map(s => s.trimStart());
```

Splitting on whitespace by default means a tag such as `new york` becomes two tokens. For tags that may contain spaces, supply a tokenizer that splits on commas only (as above).

The tokenizer is also used when pasting text to bulk-commit multiple tokens at once.

---

### Per-token styling

```js
el.tokenStyle = item => item.label.startsWith('#')
  ? { background: 'teal', color: 'white' }
  : undefined;
```

Re-assign `tokenStyle` to re-evaluate chips if the rules change.

---

### `AcTokenItem` shape

```ts
type AcTokenItem = {
  readonly label: string;       // displayed text and committed value
  readonly subLabel?: string;   // right-aligned secondary text in popup
  readonly icon?: string;       // icon registry name (shown in chip and popup)
  readonly key?: string;        // stable identifier (defaults to label)
  readonly data?: unknown;      // arbitrary payload, passed through in events
};
```

---

### CSS custom properties

| Property                              | Default                  | Description                              |
|---------------------------------------|--------------------------|------------------------------------------|
| `--ac-token-input-background`         | `var(--surface-3)`       | Wrapper background.                      |
| `--ac-token-input-border`             | `var(--border)`          | Wrapper border.                          |
| `--ac-token-input-border-radius`      | `var(--radius-m)`        | Wrapper corner radius.                   |
| `--ac-token-input-padding`            | `var(--space-xs) var(--space-m)` | Wrapper padding.               |
| `--ac-token-chip-gap`                 | `var(--space-xs)`        | Gap between chips and the draft input.   |
| `--ac-token-chip-background`          | `var(--surface-4)`       | Chip background.                         |
| `--ac-token-chip-border`              | `var(--border)`          | Chip border.                             |
| `--ac-token-chip-border-radius`       | `var(--radius-s)`        | Chip corner radius.                      |
| `--ac-token-chip-selected-background` | `var(--accent)`          | Chip background when selected.           |
| `--ac-token-chip-selected-color`      | `var(--accent-text)`     | Chip text color when selected.           |
| `--ac-token-popup-font-size`          | `var(--text-s)`          | Suggestion popup font size.              |

---

### TypeScript types

```ts
import type {
  AcTokenItem,
  AcTokenCompletionProvider,
  AcTokenizerFn,
  AcTokensChangeDetail,
  AcTokenAddDetail,
  AcTokenRemoveDetail,
  AcTokenElementEventMap,
} from 'ixfxfun-components';
```

---

### Popup positioning

The suggestion popup uses CSS anchor positioning (`anchor-name` / `position-anchor` / `@position-try`) to stay anchored to the draft input. It opens below the input by default and automatically flips above when there is insufficient space below the viewport. No JavaScript resize or scroll listeners are involved.

Browser support: Chrome 125+. In browsers without CSS anchor positioning support the popup still renders but will not auto-flip.
