# Autocomplete

Crate: `libero`
Import: `use libero::components::Autocomplete;`
Feature: `autocomplete` (off by default, turns on `combobox`, `action-icon`; [features.md](features.md))
Source: <https://github.com/tdymel/libero/tree/main/libero/src/components/form/autocomplete.rs>
Index: [index.md](index.md) lists every other page
Description: A text field that offers completions from any `Options` type, while the value stays a `String`.

A [TextField](text_field.md) that offers completions. The value stays a
`String`, and picking a suggestion inserts its label. To choose from a fixed
set, use [Select](select.md).

The field turns the browser's saved entries off, so they do not cover the list.
You can pass your own `autocomplete` token, such as `address-level2` for a
city, and the saved entries then cover the list.

## Usage

```rust
use dioxus::prelude::*;
use libero::components::Autocomplete;
use libero::sx::sx;

const CITIES: [(&str, &str); 6] = [
    ("Amsterdam", "Netherlands"),
    ("Antwerp", "Belgium"),
    ("Berlin", "Germany"),
    ("Bern", "Switzerland"),
    ("Copenhagen", "Denmark"),
    ("Cologne", "Germany"),
];
fn cities() -> Vec<String> {
    CITIES.iter().map(|(city, _)| city.to_string()).collect()
}

#[component]
fn Demo() -> Element {
    let mut value = use_signal(String::new);

    rsx! {
        Autocomplete {
            sx: sx().width("280px").max_width("100%"),
            options: cities(),
            value: value(),
            oninput: move |next| value.set(next),
            placeholder: "Start typing",
            label: "City",
        }
    }
}
```

## Props

### `Autocomplete`

| Prop | Type | Default | Description |
|---|---|---|---|
| `size` | `Responsive<Size>` | `md` | Height, padding and font size of the field and its rows. Or one per breakpoint, `size: responsive(Size::Sm).md(Size::Lg)`; the open list follows it. |
| `radius` | `Responsive<ThemeAwareValue>` | `sm` | Corner radius of the frame and the list. Or any CSS, e.g. `radius: "0"`. Or one per breakpoint, `radius: responsive(Size::Sm).md(Size::Xl)`. |
| `value` | `String` | `""` | The text. Pair it with `oninput`. Picking a suggestion inserts its label. |
| `oninput` | `EventHandler<String>` | - | Fires per keystroke, and again with the label when a suggestion is picked or the field is cleared. |
| `name` | `FieldName<String>` | - | What the field posts as. A path such as `Signup::FIELDS.city()` also binds it to the surrounding `Form`'s value when it has no `oninput`. |
| `validate` | `Validators<String>` | - | Rules over the text, shown once the field loses focus or its form is submitted. |
| `options` | `OptionSource<T>` | `[]` | The suggestions to offer. `T` is inferred from it. A `Vec<T>` converts, and so does a `Resource<Vec<T>>` or an `Option<OptionList<T>>` that is `None` while you fetch: a pending list shows the loader and says `loading_label`, never "No results" for an answer that has not arrived. Groups and disabled options of an `OptionList` are not drawn. `String` is an `Options`, so a `Vec<String>` works as is. |
| `option` | `Callback<AutocompleteOptionArgs<T>, Element>` | `T::label()` | Draws one row's content. The highlight and click stay the component's. |
| `onpick` | `EventHandler<T>` | - | A suggestion was accepted, with the whole value behind the text. Fires after `oninput`. |
| `filter` | `Callback<AutocompleteFilterArgs<T>, bool>` | `contains` | Narrows `options`. Defaults to a case-insensitive `contains` over the label, ignoring spaces around the text. |
| `prefiltered` | `bool` | `false` | `options` arrives already narrowed, such as a list fetched per keystroke. Skips filtering, so `filter` never runs. |
| `placeholder` | `String` | - | Shown while the field is empty. |
| `clearable` | `bool` | `false` | Shows an x at the end of the frame that empties the field. |
| `open_on_focus` | `bool` | `false` | Opens the list when the field takes focus, by Tab or a press. Focus coming back after a pick or Escape leaves it closed. |
| `empty` | `Element` | - | Shown in place of the list when typed text matches nothing. Screen readers hear the localization's `combobox.nothing_found` either way, so change that string to match. |
| `loading_label` | `String` | `common.loading` | What screen readers hear while `options` is pending. |
| `leading` | `Element` | - | Inside the frame, before the control, such as a search icon. |
| `trailing` | `Element` | - | Inside the frame, after the control, before the clear x. |
| `describe_leading` | `bool` | `false` | `leading` is text that describes the value, such as a unit, so screen readers read it with the input. |
| `describe_trailing` | `bool` | `false` | The same for `trailing`. |
| `label` | `Caption` | - | The caption above the control, and the field's name. |
| `description` | `Caption` | - | Between the label and the control. What to enter. |
| `label_trailing` | `Caption` | - | Content in the label row, outside the `<label>`, at the row's end: a button cannot sit inside the label. Takes a string or an `Element`. |
| `description_position` | `DescriptionPosition` | `Above` | Where the description sits: `above` the control, or `below` it. `below` keeps the controls of side-by-side fields level when only some have a description; give the row `align: "flex-start"`. Unset, the theme's `field.description_position`. A checkbox, switch or radio draws its description under the label either way. |
| `helper` | `Caption` | - | Under the control. Formatting rules, or what the entry changes. |
| `status` | `FieldStatus` | `Valid` | Validation state, under the helper. A bare `&str` is an error; an empty one or `None` is `Valid`. |
| `required` | `bool` | `false` | Sets `aria-required` and marks the label; a field without a visible `label` shows no mark. Inside a `Form`, an empty one fails the submit. |
| `disabled` | `bool` | `false` | Takes the input out of the tab order and dims the field. |
| `readonly` | `bool` | `false` | Focusable and posted with the form, but not editable. `disabled` drops the field from the tab order and the post instead. |
| `dropdown_parts` | `Parts<DropdownPart>` | - | Styles the portaled dropdown and its inner parts. |

Like every component, it also takes the shared props `sx`, `class`, `style`,
`states`, `hidden_from`, `visible_from`, and any extra HTML attributes. The attributes land on the input.

### `AutocompleteOptionArgs`

| Prop | Type | Default | Description |
|---|---|---|---|
| `value` | `T` | - | The suggestion this row draws. |
| `index` | `usize` | - | The row's position in the narrowed list. |

### `AutocompleteFilterArgs`

| Prop | Type | Default | Description |
|---|---|---|---|
| `value` | `T` | - | The suggestion under test. |
| `query` | `String` | - | The text in the field. |

## Style API

Style a part with the `parts` prop, or address it as `[data-slot='…']` in your
own CSS. The names are stable. [Style API in Styling](styling.md#style-api)
explains how parts work.

| Part | `data-slot` | Description |
|---|---|---|
| `FieldPart::Label` | `label` | The label above the control. |
| `FieldPart::Required` | `required` | The required asterisk, in the label. |
| `FieldPart::LabelRow` | `label-row` | The row holding the label and its `label_trailing`; drawn only with a trailing slot. |
| `FieldPart::LabelTrailing` | `label-trailing` | The `label_trailing` slot, at the end of the label row. |
| `FieldPart::Description` | `description` | The caption between the label and the control. |
| `FieldPart::Frame` | `frame` | The bordered box around the control. |
| `FieldPart::Leading` | `leading` | The slot before the control: an icon, a prefix. |
| `FieldPart::Control` | `control` | The element the label names. |
| `FieldPart::Trailing` | `trailing` | The slot after the control: a chevron, a toggle. |
| `FieldPart::Helper` | `helper` | The caption under the control. |
| `FieldPart::Status` | `status` | The validation message. |

### Dropdown

The dropdown is portaled out of the field, so its parts take the
`dropdown_parts` prop. They match from the dropdown box at any depth.

| Part | `data-slot` | Description |
|---|---|---|
| `DropdownPart::Panel` | `dropdown` | The dropdown box itself. |
| `DropdownPart::Listbox` | `listbox` | The scrolling list of rows. |
| `DropdownPart::Option` | `option` | A row. |
| `DropdownPart::OptionLabel` | `label` | A row's `span { "data-slot": "label" }`, which ends in an ellipsis. |
| `DropdownPart::Empty` | `nothing-found` | The text shown when the query matches nothing. |

## Accessibility

### Keyboard

| Key | Action |
|---|---|
| `Down` | Opens the list. Typing opens it too. |
| `Alt+Down` | Opens the list without moving the highlight. |
| `Up` or `Down` | Move the highlight. |
| `Home` or `End` | Once a row is highlighted: move the highlight to the first or last row. Before that, they move the text caret. |
| `PageUp` or `PageDown` | Open: moves the highlight 10 rows, stopping at the first or last. |
| `Enter` | Picks the highlighted row. |
| `Escape`, `Tab` or `Alt+Up` | Close the list. |

### Libero handles

- Nothing is highlighted until you arrow onto a row, so Enter on text that
  matches nothing still submits the form.
- With no `options` the field is plain text and says nothing for a query;
  `empty` or `prefiltered` makes it say "No results".
- Android's Back button closes the list as Escape does, rather than the app.
- A polite status region says how many options the typed text left
  (`ComboboxLabels::results`, "2 results"), or "No results".
- The clear button is named by the field's `label`, "Clear City" in the
  example, so two clear buttons on one form tell apart. Without a `label` it is
  "Clear" alone.

### Example

A city field, `Autocomplete { label: "City", .. }`: typing "ber" opens the
list and the status says "2 results", Down highlights Berlin, and Enter picks
it.

## Theme defaults

Almost everything is `FieldDefaults`, shared by every field, and the list is
`ComboboxDefaults`. `AutocompleteDefaults` holds only the starting `size` and
`radius`.

| Field | Type | Description |
|---|---|---|
| `field.sizes` | `Sizes<FieldSizeLevel>` | The frame's font size, height and padding per size. |
| `combobox.max_dropdown_height` | `String` | How tall the list grows before it scrolls. |
| `popover.gap` | `f64` | Pixels between the field and the list. |
| `autocomplete.size` | `Size` | Default `size` when the prop is omitted, `md`. |
| `autocomplete.radius` | `Size` | Default `radius` when the prop is omitted, `sm`. |

## Data attributes

The wrapper and the frame carry the field's `data-state` tokens `size-<size>`,
`radius-<size>`, `disabled`, `required`, `warning`, `error`. The rows are
`ComboboxOption`s, with `active` but never `selected`.
