# TagsField

Crate: `libero`
Import: `use libero::components::TagsField;`
Feature: `tags-field` (off by default, turns on `combobox`, `chip`, `select`, `action-icon`; [features.md](features.md))
Source: <https://github.com/tdymel/libero/tree/main/libero/src/components/form/tags_field.rs>
Index: [index.md](index.md) lists every other page
Description: A field whose value is a `Vec<String>` of typed tags, drawn as chips around the input.

A field whose value is a list of typed strings, drawn as chips around the
input. A comma, any other `split_chars` entry, or Enter adds what was typed,
and so does leaving the field. A tag is trimmed first. To pick from a fixed set
instead, use [MultiSelect](multi_select.md), whose value is a `Vec<T>` of your
own type.

To fetch suggestions while the user types, answer `onquery` with a new
`suggestions` list and set `prefiltered`. `option` draws a richer row, and a
pick still adds the row's text as a tag.

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

## Usage

```rust
use dioxus::prelude::*;
use libero::components::{FieldStatus, TagRejectReason, TagRejection, TagsField};
use libero::sx::sx;

/// The on-screen message for a rejected tag.
fn why(rejection: TagRejection) -> String {
    let tag = rejection.tag;
    match rejection.reason {
        TagRejectReason::Duplicate => format!("\"{tag}\" is already a topic."),
        TagRejectReason::Full => format!("\"{tag}\" was not added: the topic limit is reached."),
        TagRejectReason::NotAllowed => format!("\"{tag}\" is too short: 3 characters at least."),
    }
}

#[component]
fn Demo() -> Element {
    let mut topics = use_signal(Vec::<String>::new);
    let mut refused = use_signal(|| None::<String>);

    rsx! {
        TagsField {
            sx: sx().width("100%").max_width("320px"),
            value: topics(),
            onchange: move |next| { refused.set(None); topics.set(next) },
            onreject: move |rejection: TagRejection| refused.set(Some(why(rejection))),
            status: refused().map(FieldStatus::Error).unwrap_or(FieldStatus::Valid),
            label: "Topics",
            placeholder: "Add a topic",
        }
    }
}
```

## Props

### `TagsField`

| Prop | Type | Default | Description |
|---|---|---|---|
| `size` | `Responsive<Size>` | `md` | Height, padding, font size and the chips' size. A chip is one step smaller than the field. Or one per breakpoint, `size: responsive(Size::Sm).md(Size::Lg)`; the chips follow it. |
| `radius` | `Responsive<ThemeAwareValue>` | `sm` | Corner radius of the frame and the list, independent of `size`. Or any CSS, e.g. `radius: "0"`. Or one per breakpoint, `radius: responsive(Size::Sm).md(Size::Xl)`. |
| `value` | `Vec<String>` | `[]` | The tags, in order. Controlled with `onchange`; a path `name` binds the list to the `Form` instead. With neither, the field starts from it and keeps its own edits until a form reset. |
| `onchange` | `EventHandler<Vec<String>>` | - | Called with the whole list the caller should hold next. |
| `suggestions` | `OptionSource<String>` | - | Adds a dropdown of tags to pick. Tags already held are not offered. A `Vec<String>` converts, an `OptionList<String>` adds groups and disabled rows, and a `Resource<Vec<String>>` or an `Option<OptionList<String>>` that is `None` while you fetch shows the loader and says `loading_label`, never "No results" for an answer that has not arrived. Upgrading from an `Option<Vec<String>>`: pass the `Vec` itself, and leave the prop out for none, since `None` now means a list still on its way. |
| `option` | `Callback<TagsFieldOptionArgs, Element>` | the text | Draws one suggestion row's content. The highlight and click stay the field's, and a pick adds the row's `value`. |
| `filter` | `Callback<TagsFieldFilterArgs, bool>` | `contains` | Narrows `suggestions` by what is typed. Defaults to a case-insensitive `contains`, ignoring spaces around the text. |
| `prefiltered` | `bool` | `false` | `suggestions` arrives already narrowed, such as a list fetched per `onquery`. Skips filtering, so `filter` never runs. Held tags are still left out. |
| `onquery` | `EventHandler<String>` | - | Fires with the typed text, untrimmed, whenever it changes: per keystroke, and with `""` after a pick, Enter, the clear button or leaving the field. Not at mount. Fetch from it, debounced with `use_debounce` for a server. |
| `empty` | `Element` | - | Shown in place of the rows when the typed text matches nothing. Screen readers hear the localization's `combobox.nothing_found` either way. |
| `loading_label` | `String` | `common.loading` | What screen readers hear while `suggestions` is pending. |
| `open_on_focus` | `bool` | `false` | Opens the `suggestions` when the field takes focus, by Tab or a press, so a phone user sees them before typing. Focus coming back from a tag leaves them closed. |
| `split_chars` | `Vec<String>` | `[","]` | Each one commits the text before it, typed or pasted. |
| `allow_duplicates` | `bool` | `false` | Lets the same tag be added twice. Off, tags are compared trimmed and case-insensitive. Tags already held stay out of the `suggestions` either way. |
| `max_tags` | `usize` | - | The most tags the field accepts. A paste fills the room that is left and refuses the rest. |
| `tag_rules` | `Callback<String, bool>` | - | Accepts or refuses one tag before it is added. A refused tag stays in the input, and the field tells screen readers why. |
| `onreject` | `EventHandler<TagRejection>` | - | A tag was rejected: its `tag` and a `TagRejectReason` of `Duplicate`, `Full` (past `max_tags`) or `NotAllowed` (by `tag_rules`). Called after the same edit's `onchange`. The field shows no message, so say why on screen, such as through `status`, and clear it on the next change. |
| `validate` | `Validators<Vec<String>>` | - | Rules over the whole list, shown once the field loses focus or its form is submitted. |
| `name` | `FieldName<Vec<String>>` | - | Posts each tag under this name. A path such as `Article::FIELDS.topics()` also binds the list to the surrounding `Form`'s value when the field has no `onchange`. |
| `placeholder` | `String` | - | Shown while there are no tags. |
| `clearable` | `bool` | `false` | Shows an x at the end of the frame that empties the field. |
| `tag` | `Callback<SelectionArgs<String>, Element>` | `removable_chip` | Draws one tag, remove control included. `args.remove` removes it. Make that control a `<button>` with `tabindex: "-1"`, and leave it out when `args.disabled` or `args.readonly` is set. |
| `label` | `Caption` | - | The field's caption, above the control. |
| `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 affects. |
| `status` | `FieldStatus` | `Valid` | Validation state, under the helper. A bare `&str` is an error; an empty one or `None` is `Valid`. |
| `required` | `bool` | `false` | Marks the field required and adds an asterisk to 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 `suggestions` dropdown and its inner parts. |

`SelectionArgs<String>` carries `value`, `remove`, `disabled` and `readonly`, as it does for
`MultiSelect` and `FileField`.

`TagsField` also takes the `<input>` HTML attributes and, like every component,
the shared props `sx`, `class`, `style`, `states`, `hidden_from`, `visible_from`, and any extra HTML
attributes. They land on the input.

### `TagsFieldOptionArgs`

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

### `TagsFieldFilterArgs`

| Prop | Type | Default | Description |
|---|---|---|---|
| `value` | `String` | - | The suggestion under test. |
| `query` | `String` | - | The typed text, untrimmed. |

## 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 |
|---|---|---|
| `TagsFieldPart::Label` | `label` | The label above the control. |
| `TagsFieldPart::Required` | `required` | The required asterisk, in the label. |
| `TagsFieldPart::LabelRow` | `label-row` | The row holding the label and its `label_trailing`; drawn only with a trailing slot. |
| `TagsFieldPart::LabelTrailing` | `label-trailing` | The `label_trailing` slot, at the end of the label row. |
| `TagsFieldPart::Description` | `description` | The caption between the label and the control. |
| `TagsFieldPart::Frame` | `frame` | The bordered box around the control. |
| `TagsFieldPart::Control` | `control` | The element the label names. |
| `TagsFieldPart::Trailing` | `trailing` | The slot after the control. It holds only the clear button, when `clearable` shows it. |
| `TagsFieldPart::Tag` | `tag` | One tag's chip, before the draft input. |
| `TagsFieldPart::Helper` | `helper` | The caption under the control. |
| `TagsFieldPart::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 |
|---|---|
| `Backspace` | On an empty input: removes the last tag. |
| `Left` | On an empty input, or with the caret before the typed text: moves onto the tags and keeps the text. |
| `Left` or `Right` | On the tags: walk them. `Right` past the last returns to the input. |
| `Left` or `Right` | In a right-to-left layout they follow the direction you see, so the two swap: `Right` moves from the input onto the tags. |
| `Delete`, `Backspace` or `Enter` | On a tag: removes it. |
| `Down` or `Up` | With `suggestions`: open the list and move the highlight. |
| `PageUp` or `PageDown` | With `suggestions`, open: moves the highlight 10 rows, stopping at the first or last. |
| `Enter` | With `suggestions`: picks the highlighted row. |
| `Escape` | With `suggestions`: closes the list. |

### Libero handles

- The whole field is one tab stop, plus the clear button when `clearable` shows
  it.
- With `suggestions`, Android's Back button closes the list as Escape does,
  rather than the app.
- The clear button is named by the field's `label`, "Clear Topics" in the
  example, so two clear buttons on one form tell apart. Without a `label` it is
  "Clear" alone.

### You must

- A custom `tag` must make its remove control a button with `tabindex: "-1"`.
  The arrow keys focus it, and without the tabindex each tag adds a tab stop.

### Example

A topics field, `TagsField { label: "Topics" }`: type a topic and press Enter
to add it. Backspace on the empty input removes the last tag, and Left walks
the tags, where Delete removes one.

## Theme defaults

Most of it is `FieldDefaults`, shared by every field, and the list is
`ComboboxDefaults`. `TagsFieldDefaults` holds only the `size` and `radius` it
starts at.

| 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. |
| `tags_field.size` | `Size` | Default `size` when the prop is omitted, `md`. |
| `tags_field.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`.
Each tag sits in a `[data-slot='tag']` wrapper, and its x in
`[data-slot='remove']`. The rows are `ComboboxOption`s, marked `active`, never
`selected`.
