# ColorField

Crate: `libero`
Import: `use libero::components::{ColorField, ColorCode};`
Feature: `color` (off by default, turns on `slider`, `action-icon`, `use-media-query`, `use-swipe`, `use-timers`; [features.md](features.md))
Source: <https://github.com/tdymel/libero/tree/main/libero/src/components/form/color/color_field.rs>
Index: [index.md](index.md) lists every other page
Description: A text field holding a `ColorCode`, with a preview swatch, an eyedropper and a `ColorPicker` in a dropdown.

A text field holding a `ColorCode`, with a preview swatch, an eyedropper and a
[ColorPicker](color_picker.md) in a dropdown. The text accepts every form a
`ColorCode` parses, such as hex, `rgb()` or `hsl()`. It stays as typed while
the field has focus, each parse sends the color, and on blur it shows `value`
in `format`.

On a phone the dropdown opens as a sheet at the foot of the screen, with a
full-width panel, 44px sliders and one row of swatches. Under a finger, a tap
opens only the picker; the color's text box under it takes typing.

## Usage

```rust
use dioxus::prelude::*;
use libero::components::{ColorCode, ColorField, SliderChangeEvent, Swatches};

const SWATCHES: [(&str, &str); 7] = [
    ("#2e2e2e", "Dark"),
    ("#fa5252", "Red"),
    ("#be4bdb", "Grape"),
    ("#228be6", "Blue"),
    ("#12b886", "Teal"),
    ("#fab005", "Yellow"),
    ("#fd7e14", "Orange"),
];

#[component]
fn Demo() -> Element {
    let mut color = use_signal(|| ColorCode::hex(0x228be6));

    rsx! {
        ColorField {
            value: color(),
            oninput: move |event: SliderChangeEvent<ColorCode>| color.set(event.value()),
            label: "Brand color",
            swatches: Swatches::labelled(SWATCHES),
            recent_colors: 6,
        }
    }
}
```

## Props

### `ColorField`

| Prop | Type | Default | Description |
|---|---|---|---|
| `value` | `ColorCode` | - | Strictly controlled. Pair it with `oninput`. |
| `oninput` | `EventHandler<SliderChangeEvent<ColorCode>>` | - | Every new color. A drag in the dropdown sends `Start` and `End` around its moves. A key press, a swatch and the eyedropper send `Change` then `End`. Typed text sends `Change` each time it parses and one `End` on Enter or blur. |
| `validate` | `Validators<ColorCode>` | - | Rules over the color, shown once the field loses focus or its form is submitted. |
| `format` | `ColorFormat` | hex, or hexa with alpha | How the text shows the color once the field loses focus. Typing accepts every hex, `rgb()` and `hsl()` form either way, with commas, spaces or `/` between values and a value out of range clamped, as CSS does. Named colors such as `red` do not parse. |
| `with_alpha` | `bool` | `false` | Shows the alpha slider in the dropdown. Without it a translucent color arrives opaque. |
| `swatches` | `Swatches` | - | Preset colors in the dropdown. Takes `ColorCode`s or CSS strings. |
| `swatches_per_row` | `usize` | - | Caps how many swatches share a row. Unset, they wrap to fill the width. |
| `recent_colors` | `usize` | - | Keeps up to this many recently picked colors, newest first and each once, in a row under the swatches. A color counts when the dropdown closes on a new one, the eyedropper picks it, or typed text settles. They live in the field and are gone on unmount; to keep them, pass them back as `swatches`. Unset or `0`, no row. |
| `with_picker` | `bool` | `true` | `false` leaves only the swatches in the dropdown, and no dropdown without them. |
| `with_preview` | `bool` | `true` | Shows the color as a swatch in the leading slot. |
| `with_eye_dropper` | `bool` | `true` | Adds a button in the trailing slot that picks a color off the screen. Shown only where the browser supports it, Chromium today. |
| `disallow_input` | `bool` | `false` | Makes the text read-only, so a color comes from the dropdown alone. |
| `fix_on_blur` | `bool` | `true` | Text that does not parse goes back to the last valid color on blur. Off, it stays and shows `color.invalid` as an error. Either way the blur announces `color.invalid`. |
| `close_on_swatch_click` | `bool` | `false` | Picking a swatch closes the dropdown. |
| `name` | `FieldName<ColorCode>` | - | What the field posts as: its color in `format`, from a hidden input as `ColorPicker` posts it, never the text being typed. A path such as `Theme::FIELDS.accent()` also binds the color to the surrounding `Form`'s value when the field has no `oninput`. |
| `placeholder` | `String` | - | Shown while the text is empty. |
| `variant` | `ColorFieldVariant` | `Field` | `Swatch` leaves the text, the preview and the eyedropper: a swatch button opens the same dropdown, `Escape` and a picked swatch bring focus back to it, and the label names it. A swatch holding no dropdown is a plain image. |
| `swatch_background` | `String` | - | With `variant: Swatch`, any CSS `background` for the swatch, such as a conic gradient for a hue wheel, in place of the color. The dropdown still edits `value`. |
| `swatch_selected` | `bool` | `false` | With `variant: Swatch`, draws a check on the swatch and marks it `aria-current="true"`, for a row of presets you build around it: set it while the field's colour is none of them. The row and its other swatches are yours. |
| `size` | `Responsive<Size>` | `md` | Control height, font size and the dropdown's picker. Or one per breakpoint, `size: responsive(Size::Sm).md(Size::Lg)`; the open picker follows too. |
| `radius` | `Responsive<ThemeAwareValue>` | `sm` | Corner radius of the frame. Or any CSS, e.g. `radius: "0"`. Or one per breakpoint, `radius: responsive(Size::Sm).md(Size::Xl)`. |
| `label` | `Caption` | - | The field's caption. |
| `description` | `Caption` | - | Between the label and the control. |
| `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. |
| `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. |
| `disabled` | `bool` | `false` | Disables typing and the dropdown, 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<ColorDropdownPart>` | - | Styles the portaled dropdown and the picker in it. |

`ColorField` 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.

## 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 |
|---|---|---|
| `ColorDropdownPart::Panel` | `dropdown` | The dropdown box itself. |
| `ColorDropdownPart::SheetHandle` | `sheet-handle` | Below `sm`: the swipe strip atop the sheet. |
| `ColorDropdownPart::Saturation` | `saturation` | The saturation and brightness panel. |
| `ColorDropdownPart::Body` | `body` | The row under the panel: the sliders and the preview. |
| `ColorDropdownPart::Sliders` | `sliders` | The column of the hue and alpha sliders. |
| `ColorDropdownPart::Hue` | `hue` | The hue slider. |
| `ColorDropdownPart::Alpha` | `alpha` | The alpha slider, with `with_alpha`. |
| `ColorDropdownPart::Track` | `track` | Both sliders' gradient tracks. |
| `ColorDropdownPart::Thumb` | `thumb` | Every handle: the panel's and the sliders'. |
| `ColorDropdownPart::Preview` | `preview` | The current color beside the sliders, with `with_alpha`. |
| `ColorDropdownPart::Swatches` | `swatches` | The row of preset swatches. |
| `ColorDropdownPart::Swatch` | `swatch` | One preset swatch. |

## Accessibility

### Keyboard

| Key | Action |
|---|---|
| `Down` or `Alt+Down` | Opens the dropdown and moves focus into the picker, onto the saturation area or the first swatch, where the [ColorPicker](color_picker.md#accessibility) keys apply. |
| `Enter` | On text that does not parse: announces the refusal and keeps the text. On text that parses: sends `End`, which typing alone does not. A revert on blur is announced too. |
| `Escape` | Closes the dropdown. From inside it, moves focus back to the text, or to the swatch with `variant: Swatch`. |
| `Enter` or `Space` | On the swatch of `variant: Swatch`: opens the dropdown, or closes it when open. |
| `Tab` or `Shift+Tab` | Past the dropdown's last stop: moves on as Tab from the text would. Before its first stop: back to the text. |

### Libero handles

- Focus alone does not open the dropdown, so tabbing through the form changes
  nothing. A click opens it and stays in the text, so typing works at once.
- A swatch that closes the dropdown moves focus back to the text.
- The recent colors are a group named by the localization's `color.recent`, its swatches buttons like the presets.
- Focus leaving both the text and the dropdown closes it.
- Leaving text that does not parse announces the localization's
  `color.invalid`, whether `fix_on_blur` reverts it or keeps it. It is said
  once, so a blur after Enter does not repeat it.
- A mouse click in the dropdown leaves focus in the text.
- Android's Back button closes the dropdown rather than the app. Focus in the
  dropdown goes back to the text.
- With `variant: Swatch` the swatch is a button that names the dropdown
  (`aria-haspopup`, `aria-expanded`), named by the label, or by the
  localization's `color.choose` when there is none.

### Example

A brand color field, `ColorField { label: "Brand color" }`: type `#228be6` at
once, click to open the dropdown with the caret staying in the text, or press
Down to open it and move into the picker. Escape brings focus back to the text.

## Theme defaults

`ColorFieldDefaults` holds `size`, `radius`, `with_preview`,
`with_eye_dropper`, `fix_on_blur` and `close_on_swatch_click`. The dropdown's
picker reads `ColorPickerDefaults`.
