diff --git a/.vscode/cspell.json b/.vscode/cspell.json
index b96c9fdbe..4c4637432 100644
--- a/.vscode/cspell.json
+++ b/.vscode/cspell.json
@@ -37,7 +37,13 @@
"stylelint",
"webcomponents",
"noopener",
- "noreferrer"
+ "noreferrer",
+ "srgb",
+ "rgba",
+ "oklch",
+ "oklab",
+ "currentcolor",
+ "WCAG"
],
"ignoreRegExpList": ["θ"]
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 13f680b4c..24bd84133 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,22 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
### Added
+- #### Color panel
+ - New `igc-color-panel` component: the surface of the color picker, alone in the page, for theme editors and sidebars. It has `value`, `format`, `show-alpha`, `hide-formats` and `swatches`. It emits `igcInput` while the user changes the color and `igcChange` when the change ends, as a native range input does. It is not a form control. The color picker shows a panel in its popup, and its parts and behavior do not change.
+ - New `igc-color-swatch` and `igc-color-swatch-group` components: swatches as light DOM children of a color panel or a color picker, in groups with a label. A swatch has `color` and `label`. A swatch without a color is the no-color swatch, and a pick of it clears the value. A swatch resolves `var()`, and a pick writes the resolved color.
+ - All swatches are the options of one listbox: the arrow keys move the focus, also to the row above or below, Home and End go to the first and last swatch, and Enter or Space picks. The first swatch that has the color of the value is selected, with `aria-selected`, the `ig-selected` custom state, and the `selected` part for a swatch of `swatches`.
+ - `views` (`gradient`, `swatches` or both) and `active-view` set the views of the panel. With both views, a view switcher shows at the top.
+- #### Color picker
+ - `format` takes `oklch`, also in the color panel, and the format select has an OKLCH item. The value writes as `oklch(L% C H)`, with an alpha below 1 as `oklch(L% C H / A)`. Firefox and Safari read the same 8-bit color back from it. Chromium converts OKLCH with other matrices, so for 0.45 % of the colors a channel near 0 comes back one step off. A gray writes its hue as 0.
+ - `selection-commit="confirm"` makes the changes in the popup a draft. `value` keeps its color, and the picker emits no `igcInput` until the user applies the draft with Apply, or with Enter on the canvas marker, a slider or a swatch. Apply emits one `igcChange` at once. Cancel and every other close drop the draft. A preview shows the initial color beside the draft, and a click on the initial color restores it. The `footer` slot adds content below the color panel in both modes. The `footer`, `actions`, `preview`, `preview-initial`, `preview-current`, `cancel-button` and `apply-button` parts style them, and the `color_picker_apply`, `color_picker_cancel` and `color_picker_initial_color` strings give their texts. The preview, Cancel and Apply styles are temporary until the design is ready.
+ - The picker shows its `igc-color-swatch` and `igc-color-swatch-group` children in its popup, and passes `views` and `active-view` to the color panel. A view that the user picks becomes the `activeView` of the picker.
+ - The hue and alpha sliders have value text for assistive technology, also in the color panel: the angle and the name of the hue, such as "120 degrees, green", and the alpha percentage, in the number format of the locale. The value text of the saturation and value marker ends with the color name, such as "dark vibrant blue", while a color is set. The picker makes the color name from the OKLCH lightness, chroma and hue of the color, with the `color_picker_name_*` words and word order of the resource strings, and `color_picker_value_with_name` joins a value and a name.
+ - After a copy, the copy button shows a check icon and the name "Copied" for one second, or an error icon and "Copy failed". A copy without a clipboard API, as outside a secure context, also shows "Copy failed". The `color_picker_copied` and `color_picker_copy_failed` strings give the names.
+ - `contrast-against` shows a contrast readout at the bottom of the popup, also in the color panel: the WCAG 2 contrast ratio of the color over that background, such as "Contrast 4.54:1", and "pass" or "fail" for the AA (4.5:1) and AAA (7:1) levels for normal text. A color with alpha goes over the background, and a background with alpha over white. `contrast-against` takes any CSS color, and a color that depends on its context, such as a `var()`, `currentcolor` or `light-dark()`, resolves from the popup. An empty or invalid color, or an empty value, hides the readout. The `contrast`, `contrast-ratio`, `contrast-mark`, `pass` and `fail` parts style it, and the `color_picker_contrast_ratio`, `color_picker_contrast_pass`, `color_picker_contrast_fail`, `color_picker_contrast_aa` and `color_picker_contrast_aaa` strings give its texts. Its styles are temporary until the design is ready.
+ - In the `oklch` format, the area of the popup shows the OKLCH lightness by chroma at the OKLCH hue, also in the color panel. The hue slider is the OKLCH hue, so the area, the slider and the color text show the same numbers. The chroma axis goes from 0 to 0.33 for every hue. The area paints only the sRGB colors, and a drag beyond the gamut edge keeps the lightness and cuts the chroma back to the edge. A gray keeps its hue, also across a format switch. The marker is named "Lightness and chroma" for assistive technology. The out-of-gamut look is temporary until the design is ready.
+ - The new strings of the color names, the copy button, the contrast readout and the OKLCH area show in English until igniteui-i18n-core ships them.
+ - In input mode, a clear icon shows in the text field while a color is set. A click clears the value, and `igcChange` reports it when the focus leaves the picker. The `clear-icon` slot and part customize it, and `clear()` clears the value from code with no events. Assistive technology reads it as a "Clear color" button. [#2647](https://github.com/IgniteUI/igniteui-webcomponents/issues/2647)
+ - In input mode, the `field` part is the text field, so `--ig-input-group-*` variables set on `::part(field)` style it and not the inputs inside the picker. The field also forwards `input`, `native-input`, `label`, `prefix` and `suffix`, as in the select and the combo. [#2637](https://github.com/IgniteUI/igniteui-webcomponents/issues/2637)
- #### QR code
- `dot-style`, `square-style` and `corner-dot-style` take `squircle`, a square with soft corners.
- `corner-dot-style` sets the shape of the inner corner dots. When you do not set it, the inner corner dots use `dot-style`, as before.
@@ -26,6 +42,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- The Material switch moves its thumb with a transition only. Before, it also played a keyframe animation, also on the first render.
- #### Chip
- A selection change by the user animates the chip, as in Ignite UI for Angular. The colors fade, and the selection indicator opens and fades in, or fades out and closes. A change from code and the first render show at once, so a virtualized list does not animate its chips while it scrolls. With `prefers-reduced-motion: reduce`, the chip does not animate. [#2621](https://github.com/IgniteUI/igniteui-webcomponents/issues/2621)
+- #### Color picker
+ - A swatch of `swatches` is an `igc-color-swatch` element, not a `button`, and an empty string in `swatches` gives the no-color swatch. The swatch list is always in the DOM, hidden without swatches. The swatch list is one tab stop, and the arrow keys move between the swatches. Before, each swatch was a tab stop.
+ - A swatch without a `label` is named by its color name, such as "vibrant red", with its alpha when it is not opaque, such as "vibrant red, alpha 50%". Before, its name was the color string.
+ - The names of the formats in the format select come from the resource strings. Before, they were fixed English text.
+ - A value from code with the same color keeps the hue of a gray, as the user set it.
+ - An arrow key moves the saturation and value marker 1 % of the area, at any area size, and Shift + Arrow, Page Up, Page Down, Home and End move it 10 %. Before, an arrow key moved it 1 pixel, and there was no large step.
+ - In input mode, the picker is a block and the text field fills its container, as in the date picker. The clear icon takes its space from the text, so the field keeps its width when the value clears. Before, the field had the width of its content. To keep a narrow field, set the width of the picker. [#2647](https://github.com/IgniteUI/igniteui-webcomponents/issues/2647)
- #### Combo
- A change of `showSelectAll` or `groupSelection` keeps the active item. Before, no option was active after the change. When the change removes the active select-all option, or an active group header is no longer an option, no option is active.
- #### Date picker
@@ -71,6 +94,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- #### Checkbox, Radio, Switch
- A change of `value` no longer makes a checked control dirty, so a later `defaultChecked` still sets the checked state, as for a native checkbox or radio.
- #### Color picker
+ - A value in a notation other than hex, `rgb()` and `hsl()`, such as `oklch()`, `lab()`, `lch()`, `color()`, a relative color or `color-mix()`, gave `NaN` channels in Chromium and Safari. The picker now converts it to sRGB, and clips a color outside the sRGB gamut to it, as Firefox already did.
+ - A color that depends on its context, such as `currentcolor`, `var()`, `light-dark()` or a system color like `Canvas`, is invalid and clears the value, also when the user types it. Before, Chromium and Safari turned `currentcolor` into black and a system color into its light value.
- A color change of the user marks the picker touched, so a change that fails validation shows the invalid styles at once.
- A value set from code while the focus is in the picker no longer emits `igcChange` when the focus leaves.
- In input mode, the text input no longer shows the invalid styles when the focus moves from it to the color button. The text input shows the invalid state of the picker, together with its validation message.
diff --git a/api-reference/igc-color-panel.md b/api-reference/igc-color-panel.md
new file mode 100644
index 000000000..2ebef9704
--- /dev/null
+++ b/api-reference/igc-color-panel.md
@@ -0,0 +1,105 @@
+# igc-color-panel
+
+A color selection surface that stays in the page.
+
+The user picks a color with the color area, the hue slider and the optional
+alpha slider. The area is saturation by value, or lightness by chroma at the
+OKLCH hue in the `oklch` format. The user can also type any CSS color string,
+such as hex, `rgb()`, `hsl()`, `oklch()` or a named color, pick a swatch, or
+pick a color from the screen with the native EyeDropper API, where the
+browser provides one.
+
+The panel is not a form control. The color picker shows it in a popup.
+
+```ts
+import { defineComponents, IgcColorPanelComponent } from 'igniteui-webcomponents';
+
+defineComponents(IgcColorPanelComponent);
+```
+
+## Properties
+
+- `value`: `string`. Attribute: `value`.
+ The value of the component as a CSS color string, in `format`. Accepts any
+ CSS color, such as hex, `rgb()`, `hsl()`, `oklch()`, `color()` or a named
+ color. A color outside the sRGB gamut is clipped to it.
+
+ An empty, whitespace-only or invalid string clears the value. So does a
+ color that depends on its context: `currentcolor`, `var()`, `light-dark()`
+ or a system color.
+- `format`: `'hex' | 'rgb' | 'hsl' | 'oklch'`. Default: `'hex'`. Attribute: `format`.
+ The color format of the string value.
+
+ A format change renders `value` in the new notation. The color does not
+ change, so the component emits no `igcInput` or `igcChange`.
+- `hideFormats`: `boolean`. Default: `false`. Attribute: `hide-formats`.
+ Whether the format select is hidden.
+- `showAlpha`: `boolean`. Default: `false`. Attribute: `show-alpha`.
+ Whether to show the alpha slider and input.
+- `swatches`: `string[]`. Default: `[]`. No attribute.
+ Pre-defined color strings. The component renders them as swatches in its
+ swatch list, in front of the swatch children. An empty string gives the
+ no-color swatch.
+- `views`: `string`. Default: `'gradient'`. Attribute: `views`.
+ The views of the component, as a space-separated list of `gradient` and
+ `swatches`. With both views, a view switcher shows at the top.
+
+ With only the gradient view, the swatch list shows below the gradient
+ controls. With the swatch view, the swatch list shows only in that view.
+- `activeView`: `'gradient' | 'swatches'`. Default: `'gradient'`. Attribute: `active-view`.
+ The view on screen: `gradient` or `swatches`. The view switcher sets it
+ and emits no event. A view that `views` does not have gives the first
+ view of `views`.
+- `contrastAgainst`: `string`. Default: `''`. Attribute: `contrast-against`.
+ The background color of the contrast readout, as any CSS color. A color
+ that depends on its context, such as a `var()`, resolves from the
+ component. The readout shows the WCAG 2 contrast ratio of the value over
+ this color, with the AA and AAA levels for normal text. An empty or
+ invalid color hides it.
+- `locale`: `string`. Attribute: `locale`.
+ The locale of the component. Without it, the component takes its own
+ `lang`, else the locale of the nearest ancestor that has a `locale` (a
+ component) or a `lang`, and then the global locale.
+- `resourceStrings`: `Required`. No attribute.
+ The texts of the component. The strings that you set replace the
+ strings of the current locale. Reading returns all the strings, with
+ your strings over the locale strings.
+
+## Events
+
+- `igcInput`
+ Emitted when the user changes the color with the canvas, the sliders, the alpha input, a swatch or the eye dropper.
+- `igcChange`
+ Emitted when the user ends a change of the color: on the release of the canvas or a slider, on each key that moves them, on a commit of the color text or the alpha input, and on a swatch or an eye dropper pick.
+
+## Slots
+
+- default: The color swatches and swatch groups. The panel shows them in its swatch list, after the swatches of `swatches`.
+
+## CSS parts
+
+- `base`: The wrapper of the panel.
+- `picker-canvas`: The area: saturation by value, or lightness by chroma in the `oklch` format.
+- `marker`: The marker on the area that shows the picked color.
+- `dragging`: Added to the marker part while the user drags it.
+- `main-row`: The row containing the hue slider and the copy/eyedropper buttons.
+- `alpha-row`: The row containing the alpha slider and input, rendered when `show-alpha` is set.
+- `inputs-row`: The row containing the format select and the color value input.
+- `buttons`: The wrapper around the copy and eyedropper buttons.
+- `hue`: The hue slider.
+- `alpha`: The alpha slider.
+- `alpha-input`: The input of the alpha value, rendered when `show-alpha` is set.
+- `copy`: The button that copies the current color value to the clipboard.
+- `eye-dropper`: The button that activates the EyeDropper API.
+- `format-select`: The select control used to switch the color string format.
+- `swatches`: The swatch list.
+- `swatch`: A swatch of the `swatches` property.
+- `selected`: Added to the swatch part of the selected swatch.
+- `view-switcher`: The view switcher, rendered when `views` has both views.
+- `view-button`: A button of the view switcher.
+- `active`: Added to the view-button part of the view on screen.
+- `contrast`: The contrast readout, rendered when `contrast-against` has a color and the value is not empty.
+- `contrast-ratio`: The contrast ratio of the value over `contrast-against`.
+- `contrast-mark`: A WCAG level of the contrast readout, AA or AAA.
+- `pass`: Added to the contrast-mark part of a level that the ratio passes.
+- `fail`: Added to the contrast-mark part of a level that the ratio fails.
diff --git a/api-reference/igc-color-picker.md b/api-reference/igc-color-picker.md
index b31efe06c..a5780ec2a 100644
--- a/api-reference/igc-color-picker.md
+++ b/api-reference/igc-color-picker.md
@@ -2,9 +2,10 @@
Color input component.
-The user picks a color with the HSV saturation/value canvas, the hue slider
-and the optional alpha slider. The user can also type a color string: hex,
-rgb(a), hsl(a) or a named CSS color.
+The user picks a color with the color area, the hue slider and the optional
+alpha slider. The area is saturation by value, or lightness by chroma at the
+OKLCH hue in the `oklch` format. The user can also type any CSS color string,
+such as hex, `rgb()`, `hsl()`, `oklch()` or a named color.
The component supports pre-defined swatches and the native EyeDropper API,
where the browser provides one. The anchor is a trigger button
@@ -24,11 +25,14 @@ defineComponents(IgcColorPickerComponent);
In `mode="input"` the component forwards the label to the anchor input.
In `mode="default"` it renders the label as a separate element.
- `value`: `string`. Attribute: `value`.
- The value of the component as a CSS color string. Accepts hex, rgb(a),
- hsl(a) and named colors.
-
- An empty, whitespace-only or invalid string clears the value.
-- `format`: `'hex' | 'rgb' | 'hsl'`. Default: `'hex'`. Attribute: `format`.
+ The value of the component as a CSS color string. Accepts any CSS color,
+ such as hex, `rgb()`, `hsl()`, `oklch()`, `color()` or a named color. A
+ color outside the sRGB gamut is clipped to it.
+
+ An empty, whitespace-only or invalid string clears the value. So does a
+ color that depends on its context: `currentcolor`, `var()`, `light-dark()`
+ or a system color.
+- `format`: `'hex' | 'rgb' | 'hsl' | 'oklch'`. Default: `'hex'`. Attribute: `format`.
The color format of the string value.
A format change renders `value` in the new notation. The color does not
@@ -43,15 +47,37 @@ defineComponents(IgcColorPickerComponent);
In `"default"` mode the anchor is a trigger button. In `"input"` mode the
anchor is an editable text field with a color swatch prefix. The prefix
also opens the picker.
+- `selectionCommit`: `'immediate' | 'confirm'`. Default: `'immediate'`. Attribute: `selection-commit`.
+ When the changes of the user in the popup apply. With `confirm`, they
+ change a draft: `value` keeps its color, and the popup shows the initial
+ color beside the draft. Apply, or Enter on the canvas marker, a slider or
+ a swatch, applies the draft with one `igcChange`. Cancel and every other
+ close drop it.
- `swatches`: `string[]`. Default: `[]`. No attribute.
- Pre-defined color strings. The component renders them as clickable
- swatches below the picker controls. A click on a swatch sets its color as
- the value.
+ Pre-defined color strings. The component renders them as swatches in the
+ swatch list of its popup, in front of the swatch children. An empty
+ string gives the no-color swatch.
+- `views`: `string`. Default: `'gradient'`. Attribute: `views`.
+ The views of the popup, as a space-separated list of `gradient` and
+ `swatches`. With both views, a view switcher shows at the top.
+
+ With only the gradient view, the swatch list shows below the gradient
+ controls. With the swatch view, the swatch list shows only in that view.
+- `activeView`: `'gradient' | 'swatches'`. Default: `'gradient'`. Attribute: `active-view`.
+ The view on screen in the popup: `gradient` or `swatches`. The view
+ switcher sets it and emits no event. A view that `views` does not have
+ gives the first view of `views`.
+- `contrastAgainst`: `string`. Default: `''`. Attribute: `contrast-against`.
+ The background color of the contrast readout in the popup, as any CSS
+ color. A color that depends on its context, such as a `var()`, resolves
+ from the popup. The readout shows the WCAG 2 contrast ratio of the value
+ over this color, with the AA and AAA levels for normal text. An empty or
+ invalid color hides it.
- `locale`: `string`. Attribute: `locale`.
The locale of the component. Without it, the component takes its own
`lang`, else the locale of the nearest ancestor that has a `locale` (a
component) or a `lang`, and then the global locale.
-- `resourceStrings`: `Required`. No attribute.
+- `resourceStrings`: `Required`. No attribute.
The texts of the component. The strings that you set replace the
strings of the current locale. Reading returns all the strings, with
your strings over the locale strings.
@@ -97,6 +123,9 @@ defineComponents(IgcColorPickerComponent);
Sets focus on the color picker.
- `blur(): void`
Removes focus from the color picker.
+- `clear(): void`
+ Clears the value and the text of the input. As for a value set from code,
+ the component emits no events.
- `reportValidity(): boolean`
Checks validity. As for a native control, an invalid control emits
`invalid` and takes the focus. It shows its own validation messages, not
@@ -131,9 +160,9 @@ defineComponents(IgcColorPickerComponent);
- `igcClosed`
Emitted after the picker dropdown closes on a user action.
- `igcInput`
- Emitted when the user changes the color with the canvas, the sliders, the alpha input, a swatch or the eyedropper.
+ Emitted when the user changes the color with the canvas, the sliders, the alpha input, a swatch or the eyedropper. In the confirm mode of `selectionCommit`, these changes emit nothing.
- `igcChange`
- Emitted when the focus leaves the component after the user changed the color.
+ Emitted when the focus leaves the component after the user changed the color, and when the user applies the draft of the confirm mode.
## Slots
@@ -141,6 +170,9 @@ defineComponents(IgcColorPickerComponent);
- `custom-error`: Renders content when setCustomValidity(message) is set.
- `invalid`: Renders content when the component is in invalid state (validity.valid = false).
- `helper-text`: Renders content below the picker.
+- `clear-icon`: Renders the clear icon in input mode.
+- default: The color swatches and swatch groups. The picker shows them in the swatch list of its popup.
+- `footer`: Renders content below the color panel in the popup. In the confirm mode of `selectionCommit`, the preview, Cancel and Apply show after it.
## CSS parts
@@ -148,10 +180,16 @@ defineComponents(IgcColorPickerComponent);
- `anchor`: The trigger element that opens the picker (the button in default mode, or the swatch prefix in input mode).
- `empty`: Applied alongside `anchor` when no color value is set, rendering a checkered background.
- `input-mode`: Added to the anchor part in input mode.
-- `label`: The label rendered after the anchor in default mode.
+- `label`: The label: the element after the anchor in default mode, or the label of the text field in input mode.
+- `field`: The text field in input mode. Set the `--ig-input-group-*` variables on it to style the field and not the inputs in the picker.
+- `input`: The container of the text field in input mode.
+- `native-input`: The native input of the text field in input mode.
+- `prefix`: The prefix wrapper of the text field in input mode. It holds the anchor.
+- `suffix`: The suffix wrapper of the text field in input mode. It holds the clear icon.
+- `clear-icon`: The clear icon wrapper in input mode. It shows while a color is set.
- `picker`: The popover container holding the canvas, sliders, inputs and swatches.
-- `picker-canvas`: The saturation and value canvas.
-- `marker`: The marker on the canvas that shows the saturation and value.
+- `picker-canvas`: The area: saturation by value, or lightness by chroma in the `oklch` format.
+- `marker`: The marker on the area that shows the picked color.
- `dragging`: Added to the marker part while the user drags it.
- `main-row`: The row containing the hue slider and the copy/eyedropper buttons.
- `alpha-row`: The row containing the alpha slider and input, rendered when `show-alpha` is set.
@@ -163,8 +201,24 @@ defineComponents(IgcColorPickerComponent);
- `copy`: The button that copies the current color value to the clipboard.
- `eye-dropper`: The button that activates the EyeDropper API.
- `format-select`: The select control used to switch the color string format.
-- `swatches`: The container of the pre-defined color swatches.
-- `swatch`: An individual color swatch button.
+- `swatches`: The swatch list.
+- `swatch`: A swatch of the `swatches` property.
+- `selected`: Added to the swatch part when the swatch has the color of the value.
+- `view-switcher`: The view switcher, rendered when `views` has both views.
+- `view-button`: A button of the view switcher.
+- `active`: Added to the view-button part of the view on screen.
+- `contrast`: The contrast readout, rendered when `contrast-against` has a color and the value is not empty.
+- `contrast-ratio`: The contrast ratio of the value over `contrast-against`.
+- `contrast-mark`: A WCAG level of the contrast readout, AA or AAA.
+- `pass`: Added to the contrast-mark part of a level that the ratio passes.
+- `fail`: Added to the contrast-mark part of a level that the ratio fails.
+- `footer`: The container below the color panel in the popup. It holds the `footer` slot and, in the confirm mode, the actions.
+- `actions`: The container of the preview, Cancel and Apply in the confirm mode.
+- `preview`: The preview of the initial color and the draft in the confirm mode.
+- `preview-initial`: The button that shows the initial color and restores it.
+- `preview-current`: The color of the draft.
+- `cancel-button`: The Cancel button of the confirm mode.
+- `apply-button`: The Apply button of the confirm mode.
## CSS custom properties
diff --git a/api-reference/igc-color-swatch-group.md b/api-reference/igc-color-swatch-group.md
new file mode 100644
index 000000000..f6445c643
--- /dev/null
+++ b/api-reference/igc-color-swatch-group.md
@@ -0,0 +1,18 @@
+# igc-color-swatch-group
+
+A labelled group of color swatches in a color panel or a color picker.
+
+```ts
+import { defineComponents, IgcColorSwatchGroupComponent } from 'igniteui-webcomponents';
+
+defineComponents(IgcColorSwatchGroupComponent);
+```
+
+## Slots
+
+- `label`: The label of the group. Its text also names the group.
+- default: The swatches of the group.
+
+## CSS parts
+
+- `label`: The label element.
diff --git a/api-reference/igc-color-swatch.md b/api-reference/igc-color-swatch.md
new file mode 100644
index 000000000..e18a7d1b8
--- /dev/null
+++ b/api-reference/igc-color-swatch.md
@@ -0,0 +1,33 @@
+# igc-color-swatch
+
+A color option of a color panel. A color panel and a color picker show
+their swatch children in their swatch list.
+
+A swatch without a `color` is the no-color swatch. A pick of it clears the
+value.
+
+```ts
+import { defineComponents, IgcColorSwatchComponent } from 'igniteui-webcomponents';
+
+defineComponents(IgcColorSwatchComponent);
+```
+
+## Properties
+
+- `color`: `string | undefined`. Attribute: `color`.
+ The color of the swatch. Accepts any CSS color, also with `var()`, which
+ resolves from the custom properties of the swatch. A pick writes the
+ resolved color.
+
+ Without a color, the swatch is the no-color swatch.
+- `label`: `string | undefined`. Attribute: `label`.
+ The accessible name of the swatch. Without it, the name is the color
+ name, such as "vibrant red", or "No color" for the no-color swatch.
+
+## CSS parts
+
+- `base`: The color fill of the swatch.
+
+## CSS custom states
+
+- `ig-selected`: The color of the swatch is the value of the panel.
diff --git a/public-api.json b/public-api.json
index b1076c174..2c64d52a9 100644
--- a/public-api.json
+++ b/public-api.json
@@ -21,8 +21,10 @@
"ChatTemplateRenderer",
"ChipResourceStringsEN",
"ColorFormat",
+ "ColorPanelView",
"ColorPickerMode",
"ColorPickerResourceStringsEN",
+ "ColorPickerSelectionCommit",
"ComboCloseTrigger",
"ComboFilteringMode",
"ComboGroupHeaderContext",
@@ -105,8 +107,13 @@
"IgcChipComponentEventMap",
"IgcCircularGradientComponent",
"IgcCircularProgressComponent",
+ "IgcColorPanelComponent",
+ "IgcColorPanelComponentEventMap",
"IgcColorPickerComponent",
"IgcColorPickerComponentEventMap",
+ "IgcColorPickerResourceStrings",
+ "IgcColorSwatchComponent",
+ "IgcColorSwatchGroupComponent",
"IgcComboChangeEventArgs",
"IgcComboClosingEventArgs",
"IgcComboComponent",
@@ -1120,11 +1127,77 @@
],
"cssProperties": []
},
+ "igc-color-panel": {
+ "class": "IgcColorPanelComponent",
+ "attributes": {
+ "active-view": "ColorPanelView ('gradient' | 'swatches')",
+ "contrast-against": "string",
+ "format": "ColorFormat ('hex' | 'hsl' | 'oklch' | 'rgb')",
+ "hide-formats": "boolean",
+ "locale": "string",
+ "show-alpha": "boolean",
+ "value": "string",
+ "views": "string"
+ },
+ "properties": {
+ "activeView": "ColorPanelView ('gradient' | 'swatches')",
+ "contrastAgainst": "string",
+ "format": "ColorFormat ('hex' | 'hsl' | 'oklch' | 'rgb')",
+ "hideFormats": "boolean",
+ "locale": "string",
+ "resourceStrings": "Required",
+ "showAlpha": "boolean",
+ "static tagName": "readonly string",
+ "swatches": "string[]",
+ "value": "string",
+ "views": "string"
+ },
+ "methods": {
+ "static register": "() => void"
+ },
+ "events": {
+ "igcChange": "unknown",
+ "igcInput": "unknown"
+ },
+ "slots": [
+ ""
+ ],
+ "cssParts": [
+ "active",
+ "alpha",
+ "alpha-input",
+ "alpha-row",
+ "base",
+ "buttons",
+ "contrast",
+ "contrast-mark",
+ "contrast-ratio",
+ "copy",
+ "dragging",
+ "eye-dropper",
+ "fail",
+ "format-select",
+ "hue",
+ "inputs-row",
+ "main-row",
+ "marker",
+ "pass",
+ "picker-canvas",
+ "selected",
+ "swatch",
+ "swatches",
+ "view-button",
+ "view-switcher"
+ ],
+ "cssProperties": []
+ },
"igc-color-picker": {
"class": "IgcColorPickerComponent",
"attributes": {
+ "active-view": "ColorPanelView ('gradient' | 'swatches')",
+ "contrast-against": "string",
"disabled": "boolean",
- "format": "ColorFormat ('hex' | 'hsl' | 'rgb')",
+ "format": "ColorFormat ('hex' | 'hsl' | 'oklch' | 'rgb')",
"hide-formats": "boolean",
"invalid": "boolean",
"label": "string | undefined",
@@ -1134,14 +1207,18 @@
"open": "boolean",
"required": "boolean",
"scroll-strategy": "PopoverScrollStrategy ('close' | 'hide' | 'scroll')",
+ "selection-commit": "ColorPickerSelectionCommit ('confirm' | 'immediate')",
"show-alpha": "boolean",
- "value": "string"
+ "value": "string",
+ "views": "string"
},
"properties": {
+ "activeView": "ColorPanelView ('gradient' | 'swatches')",
+ "contrastAgainst": "string",
"defaultValue": "unknown",
"disabled": "boolean",
"form": "readonly HTMLFormElement | null",
- "format": "ColorFormat ('hex' | 'hsl' | 'rgb')",
+ "format": "ColorFormat ('hex' | 'hsl' | 'oklch' | 'rgb')",
"hideFormats": "boolean",
"invalid": "boolean",
"label": "string | undefined",
@@ -1150,8 +1227,9 @@
"name": "string",
"open": "boolean",
"required": "boolean",
- "resourceStrings": "Required",
+ "resourceStrings": "Required",
"scrollStrategy": "PopoverScrollStrategy ('close' | 'hide' | 'scroll')",
+ "selectionCommit": "ColorPickerSelectionCommit ('confirm' | 'immediate')",
"showAlpha": "boolean",
"static formAssociated": "readonly boolean",
"static tagName": "readonly string",
@@ -1159,11 +1237,13 @@
"validationMessage": "readonly string",
"validity": "readonly ValidityState",
"value": "string",
+ "views": "string",
"willValidate": "readonly boolean"
},
"methods": {
"blur": "() => void",
"checkValidity": "() => boolean",
+ "clear": "() => void",
"focus": "(options?: FocusOptions) => void",
"hide": "() => Promise",
"reportValidity": "() => boolean",
@@ -1181,38 +1261,103 @@
"igcOpening": "unknown"
},
"slots": [
+ "",
+ "clear-icon",
"custom-error",
+ "footer",
"helper-text",
"invalid",
"value-missing"
],
"cssParts": [
+ "actions",
+ "active",
"alpha",
"alpha-input",
"alpha-row",
"anchor",
+ "apply-button",
"buttons",
+ "cancel-button",
+ "clear-icon",
"color-picker",
+ "contrast",
+ "contrast-mark",
+ "contrast-ratio",
"copy",
"dragging",
"empty",
"eye-dropper",
+ "fail",
+ "field",
+ "footer",
"format-select",
"hue",
+ "input",
"input-mode",
"inputs-row",
"label",
"main-row",
"marker",
+ "native-input",
+ "pass",
"picker",
"picker-canvas",
+ "prefix",
+ "preview",
+ "preview-current",
+ "preview-initial",
+ "selected",
+ "suffix",
"swatch",
- "swatches"
+ "swatches",
+ "view-button",
+ "view-switcher"
],
"cssProperties": [
"--ig-helper-min-lines"
]
},
+ "igc-color-swatch": {
+ "class": "IgcColorSwatchComponent",
+ "attributes": {
+ "color": "string | undefined",
+ "label": "string | undefined"
+ },
+ "properties": {
+ "color": "string | undefined",
+ "label": "string | undefined",
+ "static tagName": "readonly string"
+ },
+ "methods": {
+ "static register": "() => void"
+ },
+ "events": {},
+ "slots": [],
+ "cssParts": [
+ "base"
+ ],
+ "cssProperties": []
+ },
+ "igc-color-swatch-group": {
+ "class": "IgcColorSwatchGroupComponent",
+ "attributes": {},
+ "properties": {
+ "static tagName": "readonly string"
+ },
+ "methods": {
+ "static register": "() => void"
+ },
+ "events": {},
+ "slots": [
+ "",
+ "label"
+ ],
+ "cssParts": [
+ "label"
+ ],
+ "cssProperties": []
+ },
"igc-combo": {
"class": "IgcComboComponent",
"attributes": {
@@ -2784,15 +2929,18 @@
"currentColor": "string",
"markerColor": "string",
"markerLabel": "string",
- "markerValueFormat": "string"
+ "markerValueText": "string | undefined",
+ "space": "AreaSpace ('hsv' | 'oklch')"
},
"properties": {
"brightness": "number",
"currentColor": "string",
+ "hue": "number",
"markerColor": "string",
"markerLabel": "string",
- "markerValueFormat": "string",
+ "markerValueText": "string | undefined",
"saturation": "number",
+ "space": "AreaSpace ('hsv' | 'oklch')",
"static tagName": "readonly string",
"x": "number",
"y": "number"
@@ -2802,6 +2950,7 @@
"static register": "() => void"
},
"events": {
+ "change": "Event",
"igcColorPicked": "unknown"
},
"slots": [],
diff --git a/src/components/button/confirm-buttons.ts b/src/components/button/confirm-buttons.ts
new file mode 100644
index 000000000..a4d88179f
--- /dev/null
+++ b/src/components/button/confirm-buttons.ts
@@ -0,0 +1,50 @@
+import { html, type TemplateResult } from 'lit';
+import { ifDefined } from 'lit/directives/if-defined.js';
+import type { Theme } from '#theming/types.js';
+// Satisfies the lit-analyzer element resolution for `igc-button`. No side
+// effects; the consuming components register the button.
+import './button.js';
+
+interface ActionButton {
+ label: string;
+ onClick: (event: MouseEvent) => void;
+ part?: string;
+}
+
+interface ConfirmButtonsOptions {
+ theme: Theme;
+ cancel: ActionButton;
+ confirm: ActionButton;
+ slot?: string;
+}
+
+/**
+ * Renders the cancel and confirm buttons of a popup, such as Cancel and Apply:
+ * an outlined and a contained button in Indigo, two flat buttons in the other
+ * themes. The caller owns the wrapping element and registers the button.
+ */
+export function renderConfirmButtons({
+ theme,
+ cancel,
+ confirm,
+ slot,
+}: ConfirmButtonsOptions): TemplateResult {
+ const indigo = theme === 'indigo';
+
+ return html`
+ ${cancel.label}
+ ${confirm.label}
+ `;
+}
diff --git a/src/components/color-panel/color-panel.spec.ts b/src/components/color-panel/color-panel.spec.ts
new file mode 100644
index 000000000..72d384441
--- /dev/null
+++ b/src/components/color-panel/color-panel.spec.ts
@@ -0,0 +1,1760 @@
+import {
+ elementUpdated,
+ expect,
+ fixture,
+ html,
+ nextFrame,
+} from '@open-wc/testing';
+import { resetMouse, sendMouse } from '@web/test-runner-commands';
+import {
+ type SinonFakeTimers,
+ type SinonSpy,
+ spy,
+ stub,
+ useFakeTimers,
+} from 'sinon';
+
+import { internalsOf } from '#internals/controllers/internals.js';
+import {
+ arrowDown,
+ arrowLeft,
+ arrowRight,
+ arrowUp,
+ endKey,
+ enterKey,
+ homeKey,
+ spaceBar,
+} from '#internals/controllers/key-bindings.js';
+import { defineComponents } from '#internals/definitions/defineComponents.js';
+import {
+ axeHiddenLabelOptions,
+ withDocumentSheets,
+} from '#internals/testing/helpers.spec.js';
+import {
+ simulateClick,
+ simulateInput,
+ simulateKeyboard,
+} from '#internals/testing/simulate.spec.js';
+import { getDeepActiveElement } from '#internals/utils/dom.js';
+import { configureTheme } from '#theming/config.js';
+import { styles as bootstrap } from '../../styles/themes/light/bootstrap.css.js';
+import type IgcIconButtonComponent from '../button/icon-button.js';
+import IgcColorPickerComponent from '../color-picker/color-picker.js';
+import { converter } from '../color-picker/converters.js';
+import {
+ cuspColor,
+ gamutChroma,
+ OKLCH_AREA_CHROMA,
+ oklchHueTrack,
+ pureHueOklch,
+} from '../color-picker/oklch.js';
+import type IgcPickerCanvasComponent from '../color-picker/picker-canvas.js';
+import type IgcInputComponent from '../input/input.js';
+import type IgcSelectComponent from '../select/select.js';
+import IgcColorPanelComponent from './color-panel.js';
+import type IgcColorSwatchGroupComponent from './color-swatch-group.js';
+import type IgcColorSwatchComponent from './color-swatch.js';
+import { panelColor, swatchKey } from './common.js';
+
+function query(
+ panel: IgcColorPanelComponent,
+ selector: string
+): T {
+ return panel.renderRoot.querySelector(selector)!;
+}
+
+const getBase = (panel: IgcColorPanelComponent) =>
+ query(panel, '[part="base"]');
+const getCanvas = (panel: IgcColorPanelComponent) =>
+ query(panel, 'igc-picker-canvas');
+const getMarker = (panel: IgcColorPanelComponent) =>
+ getCanvas(panel).renderRoot.querySelector('[part~="marker"]')!;
+const getHue = (panel: IgcColorPanelComponent) =>
+ query(panel, '[part="hue"]');
+const getAlphaSlider = (panel: IgcColorPanelComponent) =>
+ query(panel, '[part="alpha"]');
+const getCopy = (panel: IgcColorPanelComponent) =>
+ query(panel, '[part="copy"]');
+const getColorInput = (panel: IgcColorPanelComponent) =>
+ query(panel, '#color-input');
+const getAlphaInput = (panel: IgcColorPanelComponent) =>
+ query(panel, '#alpha');
+const getFormatSelect = (panel: IgcColorPanelComponent) =>
+ query(panel, '#format-select');
+const getSwatchList = (panel: IgcColorPanelComponent) =>
+ query(panel, '[part="swatches"]');
+const getOwnSwatches = (panel: IgcColorPanelComponent) =>
+ Array.from(
+ panel.renderRoot.querySelectorAll(
+ '[part~="swatch"]'
+ )
+ );
+const getViewButtons = (panel: IgcColorPanelComponent) =>
+ Array.from(
+ panel.renderRoot.querySelectorAll('[part~="view-button"]')
+ );
+const getContrast = (panel: IgcColorPanelComponent) =>
+ panel.renderRoot.querySelector('[part="contrast"]');
+
+/** The texts of the contrast readout and the parts of its marks, or `null` without a readout. */
+function readout(
+ panel: IgcColorPanelComponent
+): { ratio: string; marks: [string, string][] } | null {
+ const contrast = getContrast(panel);
+
+ if (!contrast) {
+ return null;
+ }
+
+ return {
+ ratio: contrast.querySelector('[part="contrast-ratio"]')!.textContent!,
+ marks: Array.from(
+ contrast.querySelectorAll('[part~="contrast-mark"]'),
+ (mark) => [mark.getAttribute('part')!, mark.textContent!.trim()]
+ ),
+ };
+}
+
+/** Whether the swatch shows as the selected option. */
+function isSelected(swatch: IgcColorSwatchComponent): boolean {
+ const selected = swatch.matches(':state(ig-selected)');
+
+ expect(internalsOf(swatch)?.getARIA('ariaSelected')).to.equal(`${selected}`);
+ return selected;
+}
+
+/** The name of the swatch, as the accessibility tree and axe see it. */
+function nameOf(swatch: IgcColorSwatchComponent): string | null {
+ const name = internalsOf(swatch)?.getARIA('ariaLabel') ?? null;
+
+ expect(swatch.getAttribute('aria-label')).to.equal(name);
+ return name;
+}
+
+/** The swatch children connect, then the panel reads their colors. */
+async function swatchesSettled(panel: IgcColorPanelComponent): Promise {
+ await nextFrame();
+ await elementUpdated(panel);
+}
+
+/** Focuses `swatch` and presses `key` on it. */
+function pressOn(swatch: Element, key: string | string[]): void {
+ (swatch as HTMLElement).focus();
+ simulateKeyboard(swatch, key);
+}
+
+/** The names and details of the events that `emitEvent` sent. */
+function emitted(eventSpy: SinonSpy): [string, unknown][] {
+ return eventSpy
+ .getCalls()
+ .map((call) => [call.args[0], call.args[1]?.detail]);
+}
+
+function commitText(input: IgcInputComponent, value: string): void {
+ input.value = value;
+ input.dispatchEvent(
+ new CustomEvent('igcChange', {
+ detail: value,
+ bubbles: true,
+ composed: true,
+ })
+ );
+}
+
+function slide(slider: HTMLInputElement, value: string): void {
+ simulateInput(slider, { value });
+}
+
+/** Ends a gesture on a slider or the canvas. */
+function release(target: Element): void {
+ target.dispatchEvent(new Event('change', { bubbles: true }));
+}
+
+/** The marker offsets that put its center on `s`% and `100 - v`% of the canvas. */
+function markerOffsets(
+ canvas: IgcPickerCanvasComponent,
+ s: number,
+ v: number
+): { x: number; y: number } {
+ const rect = canvas.getBoundingClientRect();
+ const marker = canvas.getMarkerDimensions();
+
+ return {
+ x: (s / 100) * rect.width - marker.width,
+ y: ((100 - v) / 100) * rect.height - marker.height,
+ };
+}
+
+describe('Color panel', () => {
+ before(() => defineComponents(IgcColorPanelComponent));
+ afterEach(() => resetMouse());
+
+ let panel: IgcColorPanelComponent;
+
+ beforeEach(async () => {
+ panel = await fixture(
+ html``
+ );
+ });
+
+ describe('Rendering', () => {
+ it('is accessible', async () => {
+ panel.showAlpha = true;
+ panel.swatches = ['#ff0000', '#00ff00'];
+ await elementUpdated(panel);
+
+ const options = axeHiddenLabelOptions;
+
+ await expect(panel).shadowDom.to.be.accessible(options);
+ await expect(panel).lightDom.to.be.accessible(options);
+ });
+
+ it('renders the controls in the base part', async () => {
+ const base = getBase(panel);
+
+ for (const part of ['picker-canvas', 'main-row', 'inputs-row']) {
+ expect(base.querySelector(`[part="${part}"]`), part).to.exist;
+ }
+
+ expect(base.querySelector('[part="alpha-row"]')).to.be.null;
+ expect(getSwatchList(panel).hidden).to.be.true;
+
+ panel.showAlpha = true;
+ panel.hideFormats = true;
+ panel.swatches = ['#ff0000'];
+ await elementUpdated(panel);
+
+ expect(base.querySelector('[part="alpha-row"]')).to.exist;
+ expect(getSwatchList(panel).hidden).to.be.false;
+ expect(getFormatSelect(panel)).to.be.null;
+ });
+
+ it('paints its own surface alone in the page', async () => {
+ // The border color comes from the theme palette.
+ await withDocumentSheets([bootstrap.styleSheet!], () => {
+ const style = getComputedStyle(getBase(panel));
+
+ expect(style.borderTopWidth).to.equal('1px');
+ expect(style.backgroundColor).to.not.equal('rgba(0, 0, 0, 0)');
+ });
+ });
+
+ it('leaves the surface to the popup of the color picker', async () => {
+ defineComponents(IgcColorPickerComponent);
+
+ const picker = await fixture(
+ html``
+ );
+ const popup = picker.renderRoot.querySelector('[part="picker"]')!;
+ const inner = picker.renderRoot.querySelector('igc-color-panel')!;
+
+ await withDocumentSheets([bootstrap.styleSheet!], () => {
+ const base = getComputedStyle(getBase(inner));
+
+ expect(getComputedStyle(popup).borderTopWidth).to.equal('1px');
+ expect(base.borderTopWidth).to.equal('0px');
+ expect(base.backgroundColor).to.equal('rgba(0, 0, 0, 0)');
+ });
+ });
+ });
+
+ describe('Value and format', () => {
+ it('parses any CSS color and writes it in the format', async () => {
+ panel.value = 'oklch(70% 0.1 200)';
+ expect(panel.value).to.equal('#40b1b7');
+
+ panel.format = 'rgb';
+ await elementUpdated(panel);
+
+ expect(panel.value).to.equal('rgb(64 177 183)');
+ expect(getColorInput(panel).value).to.equal('rgb(64 177 183)');
+ });
+
+ it('writes a color and hints the notation in the oklch format', async () => {
+ panel.format = 'oklch';
+ await elementUpdated(panel);
+
+ expect(panel.value).to.equal('oklch(62.8% 0.25768 29.23)');
+ expect(getColorInput(panel).value).to.equal(panel.value);
+
+ panel.value = '';
+ await elementUpdated(panel);
+
+ expect(getColorInput(panel).placeholder).to.equal('oklch(l% c h)');
+ });
+
+ it('clears for an invalid color and a color that depends on its context', () => {
+ for (const value of ['not-a-color', 'currentcolor', 'var(--brand)']) {
+ panel.value = '#ff0000';
+ panel.value = value;
+
+ expect(panel.value, value).to.equal('');
+ }
+ });
+
+ it('keeps the hue of a gray for a write of the same color', async () => {
+ panel.value = '#808080';
+ await elementUpdated(panel);
+
+ slide(getHue(panel), '200');
+ await elementUpdated(panel);
+
+ expect(panel.value).to.equal('#808080');
+
+ panel.value = 'rgb(128 128 128)';
+ await elementUpdated(panel);
+
+ expect(getHue(panel).value).to.equal('200');
+ });
+
+ it('lists the formats with their names from the resource strings', async () => {
+ const select = getFormatSelect(panel);
+
+ expect(select.items.map(({ value }) => value)).to.eql([
+ 'hex',
+ 'rgb',
+ 'hsl',
+ 'oklch',
+ ]);
+ expect(select.items.map(({ textContent }) => textContent)).to.eql([
+ 'Hex',
+ 'RGB',
+ 'HSL',
+ 'OKLCH',
+ ]);
+
+ panel.resourceStrings = { color_picker_format_oklch: 'Perceptual' };
+ await elementUpdated(panel);
+
+ expect(select.items[3].textContent).to.equal('Perceptual');
+ });
+
+ it('emits no events for a value from code or a format switch', async () => {
+ const eventSpy = spy(panel, 'emitEvent');
+
+ panel.value = '#00ff00';
+ panel.format = 'hsl';
+ await elementUpdated(panel);
+
+ const select = getFormatSelect(panel);
+ simulateClick(select.renderRoot.querySelector('igc-input')!);
+ await elementUpdated(select);
+ simulateClick(select.items[1]);
+ await elementUpdated(panel);
+
+ expect(panel.format).to.equal('rgb');
+ expect(panel.value).to.equal('rgb(0 255 0)');
+ expect(eventSpy).not.called;
+ });
+ });
+
+ describe('Events', () => {
+ let eventSpy: SinonSpy;
+
+ beforeEach(async () => {
+ // Let the marker take its place first.
+ await nextFrame();
+ eventSpy = spy(panel, 'emitEvent');
+ });
+
+ it('emits igcInput while a slider moves and igcChange on its change', async () => {
+ const hue = getHue(panel);
+
+ slide(hue, '120');
+ slide(hue, '240');
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', '#00ff00'],
+ ['igcInput', '#0000ff'],
+ ]);
+
+ release(hue);
+ release(hue);
+ expect(emitted(eventSpy).slice(2)).to.eql([['igcChange', '#0000ff']]);
+ });
+
+ it('emits igcInput and igcChange for each key on the canvas', () => {
+ simulateKeyboard(getCanvas(panel), arrowDown);
+
+ expect(emitted(eventSpy).map(([name]) => name)).to.eql([
+ 'igcInput',
+ 'igcChange',
+ ]);
+ });
+
+ it('emits igcInput during a drag and one igcChange at its end', async () => {
+ const canvas = getCanvas(panel);
+ const { x, y } = canvas.getBoundingClientRect();
+
+ // A real mouse, because Firefox refuses pointer capture for a synthetic
+ // pointer event.
+ await sendMouse({ type: 'move', position: [x + 20, y + 20] });
+ await sendMouse({ type: 'down' });
+ await sendMouse({ type: 'move', position: [x + 40, y + 30] });
+ await sendMouse({ type: 'move', position: [x + 60, y + 40] });
+
+ const inputs = emitted(eventSpy).length;
+ expect(inputs).to.be.greaterThan(1);
+ expect(eventSpy).not.calledWith('igcChange');
+
+ await sendMouse({ type: 'up' });
+ await elementUpdated(panel);
+
+ expect(eventSpy.callCount).to.equal(inputs + 1);
+ expect(eventSpy.lastCall).calledWith('igcChange', {
+ detail: panel.value,
+ });
+ });
+
+ it('emits only igcChange for a commit of the color text', async () => {
+ commitText(getColorInput(panel), 'blue');
+ await elementUpdated(panel);
+
+ expect(emitted(eventSpy)).to.eql([['igcChange', '#0000ff']]);
+ });
+
+ it('reverts an invalid color text with no events', async () => {
+ const input = getColorInput(panel);
+
+ commitText(input, 'not-a-color');
+ await elementUpdated(panel);
+
+ expect(input.value).to.equal('#ff0000');
+ expect(panel.value).to.equal('#ff0000');
+ expect(eventSpy).not.called;
+ });
+
+ it('emits igcInput and igcChange for a swatch', async () => {
+ panel.swatches = ['#00ff00'];
+ await elementUpdated(panel);
+
+ simulateClick(query(panel, '[part="swatch"]'));
+
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', '#00ff00'],
+ ['igcChange', '#00ff00'],
+ ]);
+ });
+
+ it('emits igcInput while the alpha is typed and igcChange on its commit', async () => {
+ panel.showAlpha = true;
+ panel.format = 'rgb';
+ await elementUpdated(panel);
+
+ const alpha = getAlphaInput(panel);
+ const editor = alpha.renderRoot.querySelector('input')!;
+
+ editor.value = '40%';
+ simulateInput(editor, {
+ skipValueProperty: true,
+ inputType: 'insertText',
+ bubbles: true,
+ composed: true,
+ });
+ expect(emitted(eventSpy)).to.eql([['igcInput', 'rgb(255 0 0 / 0.4)']]);
+
+ alpha.dispatchEvent(
+ new CustomEvent('igcChange', {
+ detail: '40%',
+ bubbles: true,
+ composed: true,
+ })
+ );
+ expect(emitted(eventSpy).slice(1)).to.eql([
+ ['igcChange', 'rgb(255 0 0 / 0.4)'],
+ ]);
+ });
+
+ it('emits igcInput and igcChange for each step of the alpha keys', async () => {
+ panel.showAlpha = true;
+ panel.value = 'rgb(255 0 0 / 0.5)';
+ panel.format = 'rgb';
+ await elementUpdated(panel);
+ eventSpy.resetHistory();
+
+ simulateKeyboard(getAlphaInput(panel), arrowUp);
+
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', 'rgb(255 0 0 / 0.51)'],
+ ['igcChange', 'rgb(255 0 0 / 0.51)'],
+ ]);
+ });
+
+ it('emits no igcChange when a change returns to the reported color', () => {
+ const hue = getHue(panel);
+
+ slide(hue, '120');
+ slide(hue, '0');
+ release(hue);
+
+ expect(eventSpy).not.calledWith('igcChange');
+ });
+
+ it('takes a value from code as the reported color', () => {
+ panel.value = '#00ff00';
+
+ slide(getHue(panel), '120');
+ release(getHue(panel));
+
+ expect(eventSpy).not.calledWith('igcChange');
+ });
+
+ it('keeps the events of its inner elements inside', async () => {
+ const leaked: string[] = [];
+
+ for (const type of [
+ 'igcInput',
+ 'igcChange',
+ 'igcOpening',
+ 'igcColorPicked',
+ ]) {
+ panel.addEventListener(type, (event) => {
+ if (event.composedPath()[0] !== panel) {
+ leaked.push(type);
+ }
+ });
+ }
+
+ const input = getColorInput(panel);
+ simulateInput(input.renderRoot.querySelector('input')!, {
+ value: 'blue',
+ });
+ commitText(input, 'blue');
+ simulateKeyboard(getCanvas(panel), arrowDown);
+ simulateClick(
+ getFormatSelect(panel).renderRoot.querySelector('igc-input')!
+ );
+ await elementUpdated(panel);
+
+ expect(leaked).to.be.empty;
+ });
+ });
+
+ describe('Eye dropper', () => {
+ let original: unknown;
+
+ beforeEach(() => {
+ original = (globalThis as any).EyeDropper;
+ (globalThis as any).EyeDropper = class {
+ public open() {
+ return Promise.resolve({ sRGBHex: '#112233' });
+ }
+ };
+ });
+
+ afterEach(() => {
+ (globalThis as any).EyeDropper = original;
+ });
+
+ it('emits igcInput and igcChange for a pick', async () => {
+ panel = await fixture(
+ html``
+ );
+ const eventSpy = spy(panel, 'emitEvent');
+
+ simulateClick(query(panel, '[part="eye-dropper"]'));
+ await new Promise((resolve) => setTimeout(resolve));
+
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', '#112233'],
+ ['igcChange', '#112233'],
+ ]);
+ });
+ });
+
+ describe('Marker', () => {
+ it('moves the marker to a value from code', async () => {
+ panel.value = 'hsl(0 100% 25%)';
+ await elementUpdated(panel);
+ await nextFrame();
+
+ const canvas = getCanvas(panel);
+ const { x, y } = markerOffsets(canvas, 100, 50);
+
+ expect(canvas.x).to.be.closeTo(x, 0.5);
+ expect(canvas.y).to.be.closeTo(y, 0.5);
+ });
+
+ it('places the marker when a hidden panel shows', async () => {
+ panel = await fixture(
+ html``
+ );
+
+ panel.style.display = '';
+ // The resize observer reports the new size after the layout.
+ await nextFrame();
+ await nextFrame();
+
+ const canvas = getCanvas(panel);
+ const { x, y } = markerOffsets(canvas, 100, 50);
+
+ expect(canvas.x).to.be.closeTo(x, 0.5);
+ expect(canvas.y).to.be.closeTo(y, 0.5);
+ });
+ });
+ describe('Value text', () => {
+ beforeEach(async () => {
+ panel = await fixture(
+ html``
+ );
+ await elementUpdated(getCanvas(panel));
+ });
+
+ const markerText = () => getMarker(panel).getAttribute('aria-valuetext');
+
+ it('gives the hue slider the angle and the name of the hue', async () => {
+ expect(getHue(panel).getAttribute('aria-valuetext')).to.equal(
+ '240 degrees, blue'
+ );
+
+ panel.value = '#ff8000';
+ await elementUpdated(panel);
+
+ expect(getHue(panel).getAttribute('aria-valuetext')).to.equal(
+ '30 degrees, orange'
+ );
+ });
+
+ it('gives the alpha slider the alpha percentage', () => {
+ expect(getAlphaSlider(panel).getAttribute('aria-valuetext')).to.equal(
+ '25%'
+ );
+ });
+
+ it('adds the color name to the value text of the canvas marker', async () => {
+ expect(markerText()).to.equal(
+ 'Saturation 100%, brightness 100%, vibrant blue'
+ );
+
+ panel.value = '#808080';
+ await elementUpdated(panel);
+ await elementUpdated(getCanvas(panel));
+
+ expect(markerText()).to.equal('Saturation 0%, brightness 50%, gray');
+ });
+
+ it('gives an empty value no color name', async () => {
+ panel.value = '';
+ await elementUpdated(panel);
+ await elementUpdated(getCanvas(panel));
+
+ expect(markerText()).to.equal('Saturation 0%, brightness 100%');
+ expect(getHue(panel).getAttribute('aria-valuetext')).to.equal(
+ '0 degrees, red'
+ );
+ });
+
+ it('formats the numbers in the locale of the panel', async () => {
+ panel.locale = 'de';
+ await elementUpdated(panel);
+
+ const angle = new Intl.NumberFormat('de', {
+ style: 'unit',
+ unit: 'degree',
+ unitDisplay: 'long',
+ });
+ const percent = new Intl.NumberFormat('de', { style: 'percent' });
+
+ expect(getHue(panel).getAttribute('aria-valuetext')).to.equal(
+ `${angle.format(240)}, blue`
+ );
+ expect(getAlphaSlider(panel).getAttribute('aria-valuetext')).to.equal(
+ percent.format(0.25)
+ );
+ });
+
+ it('takes the words and the order from the resource strings', async () => {
+ panel.resourceStrings = {
+ color_picker_value_with_name: '{1} ({0})',
+ color_picker_name_blue: 'Blau',
+ color_picker_name_vibrant: 'kräftiges',
+ };
+ await elementUpdated(panel);
+ await elementUpdated(getCanvas(panel));
+
+ expect(getHue(panel).getAttribute('aria-valuetext')).to.equal(
+ 'Blau (240 degrees)'
+ );
+ expect(markerText()).to.equal(
+ 'kräftiges Blau (Saturation 100%, brightness 100%)'
+ );
+ });
+ });
+
+ describe('Copy', () => {
+ let clock: SinonFakeTimers | undefined;
+
+ beforeEach(async () => {
+ panel = await fixture(
+ html``
+ );
+ });
+
+ afterEach(() => {
+ clock?.restore();
+ clock = undefined;
+ });
+
+ /** The icon and the name of the copy button. */
+ function copyButton(): [string, string] {
+ const button = getCopy(panel);
+ return [button.name ?? '', button.textContent!.trim()];
+ }
+
+ const idle: [string, string] = [
+ 'copy_content',
+ 'Copy color value to clipboard',
+ ];
+
+ async function copy(): Promise {
+ simulateClick(getCopy(panel));
+ // The result shows after the clipboard promise settles.
+ await nextFrame();
+ await elementUpdated(panel);
+ }
+
+ async function tick(ms: number): Promise {
+ clock!.tick(ms);
+ await elementUpdated(panel);
+ }
+
+ it('shows the success icon and "Copied" for a second after a copy', async () => {
+ const writeText = stub(navigator.clipboard, 'writeText').resolves();
+ clock = useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+
+ try {
+ expect(copyButton()).to.eql(idle);
+
+ simulateClick(getCopy(panel));
+ await writeText.firstCall.returnValue;
+ await elementUpdated(panel);
+
+ expect(writeText).calledOnceWith('#ff0000');
+ expect(copyButton()).to.eql(['copy_success', 'Copied']);
+
+ await tick(999);
+ expect(copyButton()).to.eql(['copy_success', 'Copied']);
+
+ await tick(1);
+ expect(copyButton()).to.eql(idle);
+ } finally {
+ writeText.restore();
+ }
+ });
+
+ it('shows the error icon and "Copy failed" after a failed copy', async () => {
+ const writeText = stub(navigator.clipboard, 'writeText').rejects(
+ new DOMException('Denied', 'NotAllowedError')
+ );
+
+ try {
+ await copy();
+ expect(copyButton()).to.eql(['error', 'Copy failed']);
+ await expect(panel).shadowDom.to.be.accessible(axeHiddenLabelOptions);
+ await expect(panel).lightDom.to.be.accessible(axeHiddenLabelOptions);
+ } finally {
+ writeText.restore();
+ }
+ });
+
+ it('shows "Copy failed" without a clipboard', async () => {
+ const clipboard = stub(navigator, 'clipboard').value(undefined);
+
+ try {
+ await copy();
+ expect(copyButton()).to.eql(['error', 'Copy failed']);
+ } finally {
+ clipboard.restore();
+ }
+ });
+
+ it('shows the copy icon again one second after the latest copy', async () => {
+ const writeText = stub(navigator.clipboard, 'writeText').resolves();
+ clock = useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+
+ try {
+ simulateClick(getCopy(panel));
+ await writeText.firstCall.returnValue;
+ await tick(600);
+
+ simulateClick(getCopy(panel));
+ await writeText.secondCall.returnValue;
+ await tick(600);
+ expect(copyButton()).to.eql(['copy_success', 'Copied']);
+
+ await tick(400);
+ expect(copyButton()).to.eql(idle);
+ } finally {
+ writeText.restore();
+ }
+ });
+
+ it('shows only the result of the latest copy', async () => {
+ const first = Promise.withResolvers();
+ const writeText = stub(navigator.clipboard, 'writeText');
+ writeText.onFirstCall().returns(first.promise);
+ writeText.onSecondCall().resolves();
+
+ try {
+ simulateClick(getCopy(panel));
+ await copy();
+ expect(copyButton()).to.eql(['copy_success', 'Copied']);
+ await expect(panel).shadowDom.to.be.accessible(axeHiddenLabelOptions);
+ await expect(panel).lightDom.to.be.accessible(axeHiddenLabelOptions);
+
+ // The first copy fails after the second one ends.
+ first.reject(new DOMException('Denied', 'NotAllowedError'));
+ await nextFrame();
+ await elementUpdated(panel);
+
+ expect(copyButton()).to.eql(['copy_success', 'Copied']);
+ } finally {
+ writeText.restore();
+ }
+ });
+
+ it('shows nothing for a copy that ends after a disconnect', async () => {
+ const pending = Promise.withResolvers();
+ const writeText = stub(navigator.clipboard, 'writeText').returns(
+ pending.promise
+ );
+
+ try {
+ simulateClick(getCopy(panel));
+ const parent = panel.parentElement!;
+
+ panel.remove();
+ parent.append(panel);
+ pending.resolve();
+ await nextFrame();
+ await elementUpdated(panel);
+
+ expect(copyButton()).to.eql(idle);
+ } finally {
+ writeText.restore();
+ }
+ });
+
+ it('shows the copy icon again when the panel disconnects', async () => {
+ const writeText = stub(navigator.clipboard, 'writeText').resolves();
+
+ try {
+ await copy();
+ const parent = panel.parentElement!;
+
+ panel.remove();
+ parent.append(panel);
+ await elementUpdated(panel);
+
+ expect(copyButton()).to.eql(idle);
+ } finally {
+ writeText.restore();
+ }
+ });
+ });
+
+ describe('Swatches', () => {
+ let children: IgcColorSwatchComponent[];
+ let group: IgcColorSwatchGroupComponent;
+
+ beforeEach(async () => {
+ panel = await fixture(html`
+
+
+
+
+ Brand
+
+
+
+
+ `);
+ children = Array.from(panel.querySelectorAll('igc-color-swatch'));
+ group = panel.querySelector('igc-color-swatch-group')!;
+ await swatchesSettled(panel);
+ });
+
+ it('is accessible', async () => {
+ panel.swatches = ['#ff0000', '#0000ff'];
+ await swatchesSettled(panel);
+
+ const options = axeHiddenLabelOptions;
+
+ await expect(panel).shadowDom.to.be.accessible(options);
+ await expect(panel).lightDom.to.be.accessible(options);
+ });
+
+ it('shows the swatch children in a named listbox', () => {
+ const list = getSwatchList(panel);
+
+ expect(list.hidden).to.be.false;
+ expect(list.role).to.equal('listbox');
+ expect(list.ariaLabel).to.equal('Color swatches');
+ expect(children.map((swatch) => swatch.role)).to.eql([
+ 'option',
+ 'option',
+ 'option',
+ 'option',
+ ]);
+ });
+
+ it('renders the swatches property in front of the children', async () => {
+ panel.swatches = ['#0000ff', ''];
+ await swatchesSettled(panel);
+
+ const own = getOwnSwatches(panel);
+
+ expect(own.map((swatch) => swatch.color)).to.eql(['#0000ff', '']);
+ expect(nameOf(own[0])).to.equal('vibrant blue');
+ // An empty string gives the no-color swatch.
+ expect(nameOf(own[1])).to.equal('No color');
+
+ own[0].focus();
+ simulateKeyboard(own[0], endKey);
+ expect(getDeepActiveElement()).to.equal(children.at(-1));
+
+ simulateKeyboard(children.at(-1)!, homeKey);
+ expect(getDeepActiveElement()).to.equal(own[0]);
+ });
+
+ it('names a swatch by its label, else its color name, else "No color"', () => {
+ // `var(--brand)` is #123456. The alpha of #ff000080 is 50%.
+ expect(children.map(nameOf)).to.eql([
+ 'No color',
+ 'Green',
+ 'dark blue',
+ 'vibrant red, alpha 50%',
+ ]);
+ });
+
+ it('names a swatch with the words and the locale of the panel', async () => {
+ panel.locale = 'fr';
+ panel.resourceStrings = {
+ color_picker_name_pattern: '{2} {0} {1}',
+ color_picker_name_red: 'rouge',
+ color_picker_name_vibrant: 'vif',
+ };
+ await swatchesSettled(panel);
+ await elementUpdated(children[3]);
+
+ const percent = new Intl.NumberFormat('fr', { style: 'percent' });
+
+ expect(nameOf(children[3])).to.equal(
+ `rouge vif, alpha ${percent.format(0.5)}`
+ );
+ });
+
+ it('names a swatch by its color string while the color is invalid', async () => {
+ children[3].color = 'not-a-color';
+ await swatchesSettled(panel);
+
+ expect(nameOf(children[3])).to.equal('not-a-color');
+ });
+
+ it('renames a swatch when its color changes', async () => {
+ children[3].color = '#00ffff';
+ await elementUpdated(children[3]);
+
+ expect(nameOf(children[3])).to.equal('vibrant cyan');
+ });
+
+ it('names the no-color swatch with the resource strings of the panel', async () => {
+ panel.resourceStrings = { color_picker_no_color: 'Sans couleur' };
+ await swatchesSettled(panel);
+ await elementUpdated(children[0]);
+
+ expect(nameOf(children[0])).to.equal('Sans couleur');
+ });
+
+ it('names a group by its label', () => {
+ const internals = internalsOf(group);
+
+ expect(internals?.getARIA('role')).to.equal('group');
+ expect(internals?.getARIA('ariaLabel')).to.equal('Brand');
+ expect(group.renderRoot.querySelector('[part="label"]')).to.exist;
+ });
+
+ it('selects the swatch that has the color of the value, alpha included', async () => {
+ expect(children.map(isSelected)).to.eql([false, false, false, false]);
+
+ panel.value = 'rgb(255 0 0 / 0.5)';
+ await swatchesSettled(panel);
+ expect(children.map(isSelected)).to.eql([false, false, false, true]);
+
+ panel.value = 'lime';
+ await swatchesSettled(panel);
+ expect(children.map(isSelected)).to.eql([false, true, false, false]);
+ });
+
+ it('marks a selected swatch of the swatches property with a part', async () => {
+ panel.swatches = ['#ff0000', '#0000ff'];
+ await swatchesSettled(panel);
+
+ const own = getOwnSwatches(panel);
+
+ expect(own.map((swatch) => swatch.part.value)).to.eql([
+ 'swatch selected',
+ 'swatch',
+ ]);
+ // A child is not a part of the panel.
+ expect(children[1].hasAttribute('part')).to.be.false;
+ });
+
+ it('selects only the first swatch that has the color of the value', async () => {
+ children[3].color = 'lime';
+ panel.value = '#00ff00';
+ await elementUpdated(children[3]);
+ await swatchesSettled(panel);
+
+ expect(children[3][swatchKey]).to.equal(children[1][swatchKey]);
+ expect(children.map(isSelected)).to.eql([false, true, false, false]);
+ expect(children[1].tabIndex).to.equal(0);
+ });
+
+ it('selects the no-color swatch while the value is empty', async () => {
+ panel.value = '';
+ await swatchesSettled(panel);
+
+ expect(isSelected(children[0])).to.be.true;
+ });
+
+ it('resolves a var() swatch from its context', async () => {
+ panel.value = '#123456';
+ await swatchesSettled(panel);
+ expect(isSelected(children[2])).to.be.true;
+
+ panel.format = 'rgb';
+ panel.value = '';
+ await swatchesSettled(panel);
+
+ const eventSpy = spy(panel, 'emitEvent');
+ simulateClick(children[2]);
+
+ expect(panel.value).to.equal('rgb(18 52 86)');
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', 'rgb(18 52 86)'],
+ ['igcChange', 'rgb(18 52 86)'],
+ ]);
+ });
+
+ it('resolves a var() swatch again when the panel shows', async () => {
+ panel.style.display = 'none';
+ panel.style.setProperty('--brand', '#abcdef');
+ await nextFrame();
+
+ panel.style.display = '';
+ // The resize observer reports the new size after the layout.
+ await nextFrame();
+ await swatchesSettled(panel);
+
+ panel.value = '#abcdef';
+ await swatchesSettled(panel);
+
+ expect(isSelected(children[2])).to.be.true;
+ });
+
+ it('emits igcInput and igcChange for a pick of a child swatch', () => {
+ const eventSpy = spy(panel, 'emitEvent');
+ simulateClick(children[1]);
+
+ expect(panel.value).to.equal('#00ff00');
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', '#00ff00'],
+ ['igcChange', '#00ff00'],
+ ]);
+ });
+
+ it('clears the value with a pick of the no-color swatch', () => {
+ const eventSpy = spy(panel, 'emitEvent');
+ simulateClick(children[0]);
+
+ expect(panel.value).to.equal('');
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', ''],
+ ['igcChange', ''],
+ ]);
+ });
+
+ it('ignores a pick of a swatch with an invalid color', async () => {
+ children[1].color = 'not-a-color';
+ // An undefined variable, and a variable that is not a color.
+ children[2].color = 'var(--undefined)';
+ children[3].color = 'var(--not-a-color)';
+ panel.style.setProperty('--not-a-color', '12px');
+ await swatchesSettled(panel);
+
+ const eventSpy = spy(panel, 'emitEvent');
+
+ for (const swatch of children.slice(1)) {
+ simulateClick(swatch);
+ }
+
+ expect(panel.value).to.equal('#ff0000');
+ expect(eventSpy).not.called;
+ });
+
+ it('follows swatch children that the app adds and removes', async () => {
+ const swatch = document.createElement('igc-color-swatch');
+ swatch.color = '#ff0000';
+ group.append(swatch);
+ await swatchesSettled(panel);
+
+ expect(isSelected(swatch)).to.be.true;
+ expect(swatch.tabIndex).to.equal(0);
+
+ swatch.remove();
+ await swatchesSettled(panel);
+
+ expect(children[0].tabIndex).to.equal(0);
+ });
+
+ it('hides the list without swatches', async () => {
+ panel.replaceChildren();
+ await swatchesSettled(panel);
+
+ expect(getSwatchList(panel).hidden).to.be.true;
+ });
+ });
+
+ describe('Swatch keyboard', () => {
+ let swatches: IgcColorSwatchComponent[];
+
+ beforeEach(async () => {
+ // Ten swatches in rows of eight.
+ panel.swatches = [
+ '#000000',
+ '#111111',
+ '#222222',
+ '#333333',
+ '#444444',
+ '#555555',
+ '#666666',
+ '#777777',
+ '#888888',
+ '#999999',
+ ];
+ await swatchesSettled(panel);
+ swatches = getOwnSwatches(panel);
+ });
+
+ it('has one tab stop: the selected swatch, else the first one', async () => {
+ expect(swatches.map((swatch) => swatch.tabIndex)).to.eql([
+ 0, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ ]);
+
+ panel.value = '#333333';
+ await swatchesSettled(panel);
+
+ expect(swatches.findIndex((swatch) => swatch.tabIndex === 0)).to.equal(3);
+ });
+
+ it('moves the focus with the arrow keys in reading order', () => {
+ pressOn(swatches[0], arrowRight);
+ expect(getDeepActiveElement()).to.equal(swatches[1]);
+ expect(swatches[1].tabIndex).to.equal(0);
+ expect(swatches[0].tabIndex).to.equal(-1);
+
+ pressOn(swatches[1], arrowLeft);
+ expect(getDeepActiveElement()).to.equal(swatches[0]);
+
+ // The ends wrap.
+ pressOn(swatches[0], arrowLeft);
+ expect(getDeepActiveElement()).to.equal(swatches[9]);
+ });
+
+ it('swaps the left and right arrows in a right-to-left layout', async () => {
+ panel.dir = 'rtl';
+ await elementUpdated(panel);
+
+ pressOn(swatches[1], arrowRight);
+ expect(getDeepActiveElement()).to.equal(swatches[0]);
+ });
+
+ it('moves the focus to the next and previous row', () => {
+ pressOn(swatches[1], arrowDown);
+ expect(getDeepActiveElement()).to.equal(swatches[9]);
+
+ pressOn(swatches[9], arrowUp);
+ expect(getDeepActiveElement()).to.equal(swatches[1]);
+
+ // No row above the first one.
+ pressOn(swatches[1], arrowUp);
+ expect(getDeepActiveElement()).to.equal(swatches[1]);
+ });
+
+ it('moves to the nearest swatch of a shorter next row', () => {
+ pressOn(swatches[7], arrowDown);
+ expect(getDeepActiveElement()).to.equal(swatches[9]);
+ });
+
+ it('moves the focus to the first and last swatch', () => {
+ pressOn(swatches[4], endKey);
+ expect(getDeepActiveElement()).to.equal(swatches[9]);
+
+ pressOn(swatches[9], homeKey);
+ expect(getDeepActiveElement()).to.equal(swatches[0]);
+ });
+
+ it('picks the focused swatch with Enter and Space, as one change', () => {
+ const eventSpy = spy(panel, 'emitEvent');
+
+ pressOn(swatches[2], enterKey);
+ expect(panel.value).to.equal('#222222');
+
+ pressOn(swatches[3], spaceBar);
+ expect(panel.value).to.equal('#333333');
+
+ expect(emitted(eventSpy)).to.eql([
+ ['igcInput', '#222222'],
+ ['igcChange', '#222222'],
+ ['igcInput', '#333333'],
+ ['igcChange', '#333333'],
+ ]);
+ });
+
+ it('does not pick a swatch with the arrow keys', () => {
+ const eventSpy = spy(panel, 'emitEvent');
+
+ pressOn(swatches[0], arrowRight);
+ pressOn(swatches[1], arrowDown);
+
+ expect(panel.value).to.equal('#ff0000');
+ expect(eventSpy).not.called;
+ });
+
+ it('moves the tab stop to a clicked swatch', () => {
+ simulateClick(swatches[5]);
+ swatches[5].focus();
+
+ expect(swatches[5].tabIndex).to.equal(0);
+ expect(swatches[0].tabIndex).to.equal(-1);
+ });
+ });
+
+ describe('Views', () => {
+ beforeEach(async () => {
+ panel.swatches = ['#00ff00'];
+ await swatchesSettled(panel);
+ });
+
+ it('shows the gradient view with the swatch list below it by default', () => {
+ expect(panel.activeView).to.equal('gradient');
+ expect(query(panel, '[part="view-switcher"]')).to.be.null;
+ expect(getCanvas(panel)).to.exist;
+ expect(getSwatchList(panel).hidden).to.be.false;
+ expect(query(panel, 'igc-divider')).to.exist;
+ });
+
+ it('is accessible with both views', async () => {
+ // The switcher buttons become radios when the group context arrives.
+ const settled = async () => {
+ await elementUpdated(panel);
+ await nextFrame();
+ };
+ const options = axeHiddenLabelOptions;
+
+ panel.views = 'gradient swatches';
+ await settled();
+ await expect(panel).shadowDom.to.be.accessible(options);
+ await expect(panel).lightDom.to.be.accessible(options);
+
+ panel.activeView = 'swatches';
+ await settled();
+ await expect(panel).shadowDom.to.be.accessible(options);
+ await expect(panel).lightDom.to.be.accessible(options);
+ });
+
+ it('shows a view switcher for both views', async () => {
+ panel.views = 'gradient swatches';
+ await elementUpdated(panel);
+
+ expect(getViewButtons(panel).map((button) => button.part.value)).to.eql([
+ 'view-button active',
+ 'view-button',
+ ]);
+ expect(
+ getViewButtons(panel).map((button) => button.textContent?.trim())
+ ).to.eql(['Gradient', 'Swatches']);
+ // The swatch list is in the swatch view only.
+ expect(getCanvas(panel)).to.exist;
+ expect(getSwatchList(panel).hidden).to.be.true;
+ });
+
+ it('shows only the swatch list in the swatch view', async () => {
+ panel.views = 'gradient swatches';
+ panel.activeView = 'swatches';
+ await elementUpdated(panel);
+
+ expect(getCanvas(panel)).to.be.null;
+ expect(query(panel, '[part="inputs-row"]')).to.be.null;
+ expect(query(panel, 'igc-divider')).to.be.null;
+ expect(getSwatchList(panel).hidden).to.be.false;
+ expect(getViewButtons(panel).map((button) => button.part.value)).to.eql([
+ 'view-button',
+ 'view-button active',
+ ]);
+ });
+
+ it('switches the view on a click of the switcher, with no events', async () => {
+ panel.views = 'gradient swatches';
+ await elementUpdated(panel);
+
+ const eventSpy = spy(panel, 'emitEvent');
+ simulateClick(getViewButtons(panel)[1]);
+ await elementUpdated(panel);
+
+ expect(panel.activeView).to.equal('swatches');
+ expect(getCanvas(panel)).to.be.null;
+ expect(eventSpy).not.called;
+ });
+
+ it('places the marker when the gradient view shows again', async () => {
+ panel.views = 'gradient swatches';
+ panel.activeView = 'swatches';
+ panel.value = '#800000';
+ await elementUpdated(panel);
+
+ panel.activeView = 'gradient';
+ await elementUpdated(panel);
+ await nextFrame();
+
+ const canvas = getCanvas(panel);
+ const { x, y } = markerOffsets(canvas, 100, 50);
+
+ expect(canvas.x).to.be.closeTo(x, 0.5);
+ expect(canvas.y).to.be.closeTo(y, 0.5);
+ });
+
+ it('shows the first view of views for a view that it does not have', async () => {
+ panel.views = 'swatches';
+ await elementUpdated(panel);
+
+ expect(panel.activeView).to.equal('swatches');
+ expect(query(panel, '[part="view-switcher"]')).to.be.null;
+ expect(getSwatchList(panel).hidden).to.be.false;
+ });
+
+ it('ignores unknown view tokens', async () => {
+ panel.views = 'palette wheel';
+ await elementUpdated(panel);
+
+ expect(panel.activeView).to.equal('gradient');
+ expect(getCanvas(panel)).to.exist;
+
+ panel.views = 'swatches gradient swatches';
+ await elementUpdated(panel);
+
+ expect(
+ getViewButtons(panel).map((button) => button.getAttribute('value'))
+ ).to.eql(['gradient', 'swatches']);
+ });
+ });
+
+ describe('Contrast', () => {
+ beforeEach(async () => {
+ panel.value = '#767676';
+ panel.contrastAgainst = '#ffffff';
+ await elementUpdated(panel);
+ });
+
+ it('is accessible', async () => {
+ await expect(panel).shadowDom.to.be.accessible(axeHiddenLabelOptions);
+ await expect(panel).lightDom.to.be.accessible(axeHiddenLabelOptions);
+ });
+
+ it('hides the readout without a color to compare with', async () => {
+ panel = await fixture(
+ html``
+ );
+
+ expect(panel.contrastAgainst).to.equal('');
+ expect(readout(panel)).to.be.null;
+ });
+
+ it('shows the ratio and the AA and AAA levels for normal text', async () => {
+ expect(readout(panel)).to.eql({
+ ratio: 'Contrast 4.54:1',
+ marks: [
+ ['contrast-mark pass', 'AA pass'],
+ ['contrast-mark fail', 'AAA fail'],
+ ],
+ });
+
+ panel.value = '#000000';
+ await elementUpdated(panel);
+
+ expect(readout(panel)).to.eql({
+ ratio: 'Contrast 21:1',
+ marks: [
+ ['contrast-mark pass', 'AA pass'],
+ ['contrast-mark pass', 'AAA pass'],
+ ],
+ });
+ });
+
+ it('takes the attribute', async () => {
+ panel = await fixture(
+ html``
+ );
+
+ expect(readout(panel)?.ratio).to.equal('Contrast 4.47:1');
+ expect(readout(panel)?.marks[0]).to.eql([
+ 'contrast-mark fail',
+ 'AA fail',
+ ]);
+ });
+
+ it('follows the color that the user picks', async () => {
+ commitText(getColorInput(panel), '#595959');
+ await elementUpdated(panel);
+
+ expect(readout(panel)?.marks).to.eql([
+ ['contrast-mark pass', 'AA pass'],
+ ['contrast-mark pass', 'AAA pass'],
+ ]);
+ });
+
+ it('puts the value over the color and the color over white, with their alpha', async () => {
+ panel.value = 'rgb(0 0 0 / 0.5)';
+ await elementUpdated(panel);
+
+ expect(readout(panel)?.ratio).to.equal('Contrast 3.97:1');
+
+ panel.value = '#ffffff';
+ panel.contrastAgainst = 'rgb(0 0 0 / 0.5)';
+ await elementUpdated(panel);
+
+ expect(readout(panel)?.ratio).to.equal('Contrast 3.97:1');
+ });
+
+ it('hides the readout for an empty value', async () => {
+ panel.value = '';
+ await elementUpdated(panel);
+
+ expect(readout(panel)).to.be.null;
+ });
+
+ it('hides the readout for an invalid color and a var() that is not a color', async () => {
+ panel.style.setProperty('--not-a-color', '12px');
+
+ for (const color of [
+ 'nope',
+ 'var(--undefined)',
+ 'var(--not-a-color)',
+ '',
+ ]) {
+ panel.contrastAgainst = color;
+ await elementUpdated(panel);
+
+ expect(readout(panel), color).to.be.null;
+ }
+ });
+
+ it('resolves a color that depends on its context from the panel', async () => {
+ panel.value = '#ffffff';
+ panel.style.color = '#000000';
+ panel.style.setProperty('--surface', 'light-dark(#000000, #ffffff)');
+
+ for (const color of [
+ 'currentcolor',
+ 'light-dark(#000000, #ffffff)',
+ 'var(--surface)',
+ ]) {
+ panel.contrastAgainst = color;
+ await elementUpdated(panel);
+
+ expect(readout(panel)?.ratio, color).to.equal('Contrast 21:1');
+ }
+ });
+
+ it('resolves var() from the custom properties of the panel', async () => {
+ panel.style.setProperty('--surface', '#000000');
+ panel.value = '#ffffff';
+ panel.contrastAgainst = 'color-mix(in srgb, var(--surface) 100%, white)';
+ await elementUpdated(panel);
+
+ expect(readout(panel)?.ratio).to.equal('Contrast 21:1');
+ expect(panel.style.getPropertyValue('--_context-color')).to.equal('');
+ expect(panel.style.outlineColor).to.equal('');
+ });
+
+ it('resolves var() again when the panel shows', async () => {
+ panel.style.setProperty('--surface', '#ffffff');
+ panel.contrastAgainst = 'var(--surface)';
+ await elementUpdated(panel);
+
+ panel.style.display = 'none';
+ panel.style.setProperty('--surface', '#000000');
+ await nextFrame();
+
+ panel.style.display = '';
+ // The resize observer reports the new size after the layout.
+ await nextFrame();
+ await elementUpdated(panel);
+
+ expect(readout(panel)?.ratio).to.equal('Contrast 4.62:1');
+ });
+
+ it('resolves var() again when the theme changes', async () => {
+ panel.style.setProperty('--surface', '#ffffff');
+ panel.contrastAgainst = 'var(--surface)';
+ await elementUpdated(panel);
+
+ panel.style.setProperty('--surface', '#000000');
+ await elementUpdated(panel);
+ expect(readout(panel)?.ratio).to.equal('Contrast 4.54:1');
+
+ try {
+ configureTheme('material');
+ await elementUpdated(panel);
+
+ expect(readout(panel)?.ratio).to.equal('Contrast 4.62:1');
+ } finally {
+ configureTheme('bootstrap');
+ }
+ });
+
+ it('shows the readout at the end of the panel in both views', async () => {
+ panel.swatches = ['#00ff00'];
+ panel.views = 'gradient swatches';
+ await elementUpdated(panel);
+
+ expect(getBase(panel).lastElementChild).to.equal(getContrast(panel));
+
+ panel.activeView = 'swatches';
+ await elementUpdated(panel);
+
+ expect(getBase(panel).lastElementChild).to.equal(getContrast(panel));
+ expect(readout(panel)?.ratio).to.equal('Contrast 4.54:1');
+ });
+
+ it('takes the text from the resource strings and the number format from the locale', async () => {
+ panel.locale = 'de';
+ panel.resourceStrings = {
+ color_picker_contrast_ratio: 'Kontrast {0}:1',
+ color_picker_contrast_pass: '{0} bestanden',
+ color_picker_contrast_fail: '{0} nicht bestanden',
+ color_picker_contrast_aa: 'Stufe AA',
+ };
+ await elementUpdated(panel);
+
+ expect(readout(panel)).to.eql({
+ ratio: 'Kontrast 4,54:1',
+ marks: [
+ ['contrast-mark pass', 'Stufe AA bestanden'],
+ ['contrast-mark fail', 'AAA nicht bestanden'],
+ ],
+ });
+ });
+ });
+
+ describe('OKLCH area', () => {
+ /** Picks a point of the area, as a drag or a key does. */
+ function pickArea(x: number, y: number): void {
+ getCanvas(panel).dispatchEvent(
+ new CustomEvent('igcColorPicked', { detail: { x, y } })
+ );
+ }
+
+ /** The OKLCH values in the value text, as numbers. */
+ function valueOklch(): number[] {
+ return panel.value.match(/[\d.]+/g)!.map(Number);
+ }
+
+ beforeEach(async () => {
+ panel.format = 'oklch';
+ panel.value = '#ff00ff';
+ await elementUpdated(panel);
+ await nextFrame();
+ });
+
+ it('is accessible', async () => {
+ await expect(panel).shadowDom.to.be.accessible(axeHiddenLabelOptions);
+ await expect(panel).lightDom.to.be.accessible(axeHiddenLabelOptions);
+ });
+
+ it('shows lightness by chroma at the OKLCH hue, and puts the marker there', () => {
+ const [lightness, chroma, hue] = converter.rgb.oklch([255, 0, 255]);
+ const canvas = getCanvas(panel);
+ const across = (chroma / OKLCH_AREA_CHROMA) * 100;
+ const { x, y } = markerOffsets(canvas, across, lightness);
+
+ expect(canvas.space).to.equal('oklch');
+ expect(canvas.hue).to.be.closeTo(hue, 1e-9);
+ expect(canvas.saturation).to.be.closeTo(across, 1e-9);
+ expect(canvas.brightness).to.be.closeTo(lightness, 1e-9);
+ expect(canvas.x).to.be.closeTo(x, 0.5);
+ expect(canvas.y).to.be.closeTo(y, 0.5);
+ });
+
+ it('takes the OKLCH hue on the hue slider, with the cusps on its track', async () => {
+ const hue = getHue(panel);
+
+ expect(hue.value).to.equal('328');
+ expect(hue.getAttribute('aria-valuetext')).to.equal(
+ '328 degrees, magenta'
+ );
+ expect(panel.style.getPropertyValue('--_hue-slider-track')).to.equal(
+ oklchHueTrack()
+ );
+ expect(panel.style.getPropertyValue('--_current-color')).to.equal(
+ cuspColor(converter.rgb.oklch([255, 0, 255])[2])
+ );
+
+ panel.format = 'hex';
+ await elementUpdated(panel);
+
+ expect(hue.value).to.equal('300');
+ expect(panel.style.getPropertyValue('--_hue-slider-track')).to.equal('');
+ });
+
+ it('names the marker and gives the lightness and chroma as its value text', async () => {
+ const marker = getMarker(panel);
+
+ expect(marker.getAttribute('aria-label')).to.equal(
+ 'Lightness and chroma'
+ );
+ expect(marker.getAttribute('aria-valuetext')).to.equal(
+ 'Lightness 70%, chroma 0.322, vibrant magenta'
+ );
+
+ panel.locale = 'de';
+ panel.resourceStrings = {
+ color_picker_canvas_oklch_value: 'Helligkeit {0} %, Buntheit {1}',
+ };
+ await elementUpdated(panel);
+
+ expect(marker.getAttribute('aria-valuetext')).to.match(
+ /^Helligkeit 70 %, Buntheit 0,322, /
+ );
+ });
+
+ it('writes the lightness and chroma of a pick, at the OKLCH hue', () => {
+ const [, , hue] = converter.rgb.oklch([255, 0, 255]);
+ const eventSpy = spy(panel, 'emitEvent');
+
+ pickArea(25, 50);
+
+ const [lightness, chroma, valueHue] = valueOklch();
+
+ expect(lightness).to.equal(50);
+ expect(chroma).to.be.closeTo(0.0825, 1e-5);
+ expect(valueHue).to.be.closeTo(hue, 0.01);
+ expect(emitted(eventSpy)).to.eql([['igcInput', panel.value]]);
+ });
+
+ it('keeps the lightness and cuts the chroma at the gamut edge, and so does the marker', async () => {
+ const [, , hue] = converter.rgb.oklch([255, 0, 255]);
+ const canvas = getCanvas(panel);
+
+ pickArea(100, 10);
+
+ const [lightness, chroma] = valueOklch();
+ const edge = gamutChroma([90, OKLCH_AREA_CHROMA, hue]);
+ const { x } = markerOffsets(canvas, (edge / OKLCH_AREA_CHROMA) * 100, 90);
+
+ expect(lightness).to.equal(90);
+ expect(chroma).to.be.closeTo(edge, 1e-5);
+ expect(canvas.x).to.be.closeTo(x, 0.5);
+
+ // A second pick beyond the edge gives the same color, so no event.
+ const eventSpy = spy(panel, 'emitEvent');
+ pickArea(95, 10);
+
+ expect(eventSpy).not.called;
+ });
+
+ it('does nothing for Arrow Right at the gamut edge', async () => {
+ pickArea(100, 30);
+ release(getCanvas(panel));
+ await elementUpdated(panel);
+
+ const value = panel.value;
+ const eventSpy = spy(panel, 'emitEvent');
+ const marker = getMarker(panel);
+
+ marker.focus();
+ simulateKeyboard(marker, arrowRight);
+
+ expect(panel.value).to.equal(value);
+ expect(eventSpy).not.called;
+ });
+
+ it('moves the OKLCH hue with the slider and cuts the chroma to the new gamut', async () => {
+ const [lightness, chroma] = converter.rgb.oklch([255, 0, 255]);
+
+ slide(getHue(panel), '110');
+ await elementUpdated(panel);
+ await nextFrame();
+
+ const [l, c, h] = getPanelOklch();
+ const canvas = getCanvas(panel);
+ const { x } = markerOffsets(canvas, (c / OKLCH_AREA_CHROMA) * 100, l);
+
+ expect(l).to.be.closeTo(lightness, 1e-9);
+ expect(c).to.equal(gamutChroma([lightness, chroma, 110]));
+ expect(h).to.equal(110);
+ expect(canvas.x).to.be.closeTo(x, 0.5);
+ });
+
+ it('keeps the hue of a gray', async () => {
+ slide(getHue(panel), '264');
+ pickArea(0, 50);
+ await elementUpdated(panel);
+
+ expect(getHue(panel).value).to.equal('264');
+ expect(getCanvas(panel).hue).to.equal(264);
+
+ pickArea(30, 50);
+
+ expect(valueOklch()[2]).to.be.closeTo(264, 0.01);
+ });
+
+ it('takes the hue of a gray from HSV through the cusp on a format switch', async () => {
+ panel.format = 'hex';
+ panel.value = 'hsl(210 50% 50%)';
+ await elementUpdated(panel);
+
+ // A drag to the left edge of the HSV area makes a gray that keeps the
+ // HSV hue of the value, about 210.
+ pickArea(0, 50);
+ panel.format = 'oklch';
+ await elementUpdated(panel);
+
+ const hue = pureHueOklch(getPanelHsvHue())[2];
+
+ expect(getHue(panel).value).to.equal(String(Math.round(hue)));
+ expect(getCanvas(panel).hue).to.be.closeTo(hue, 1e-6);
+ });
+
+ it('starts an empty value at white, with the hue slider at the OKLCH hue of red', async () => {
+ panel.value = '';
+ await elementUpdated(panel);
+ await nextFrame();
+
+ const canvas = getCanvas(panel);
+ const { x, y } = markerOffsets(canvas, 0, 100);
+
+ expect(getHue(panel).value).to.equal('29');
+ expect(canvas.x).to.be.closeTo(x, 0.5);
+ expect(canvas.y).to.be.closeTo(y, 0.5);
+ });
+
+ /** The OKLCH values of the panel color, unrounded. */
+ function getPanelOklch(): number[] {
+ return panel[panelColor]().toOKLCH();
+ }
+
+ function getPanelHsvHue(): number {
+ return panel[panelColor]().toHSV()[0];
+ }
+ });
+});
diff --git a/src/components/color-panel/color-panel.ts b/src/components/color-panel/color-panel.ts
new file mode 100644
index 000000000..31ecef64b
--- /dev/null
+++ b/src/components/color-panel/color-panel.ts
@@ -0,0 +1,1367 @@
+import {
+ html,
+ LitElement,
+ nothing,
+ type PropertyValues,
+ type TemplateResult,
+} from 'lit';
+import { property, state } from 'lit/decorators.js';
+import { cache } from 'lit/directives/cache.js';
+import { live } from 'lit/directives/live.js';
+import { createRef, ref } from 'lit/directives/ref.js';
+import {
+ type ColorPanelContext,
+ colorPanelContext,
+ colorPickerContext,
+} from '#internals/context.js';
+import { addAsyncContextConsumer } from '#internals/controllers/async-consumer.js';
+import { addContextProvider } from '#internals/controllers/context-provider.js';
+import { internalsOf } from '#internals/controllers/internals.js';
+import {
+ addKeybindings,
+ arrowDown,
+ arrowRight,
+ arrowUp,
+ endKey,
+ enterKey,
+ isKey,
+} from '#internals/controllers/key-bindings.js';
+import { addResizeObserverController } from '#internals/controllers/resize-observer.js';
+import { addRovingFocusController } from '#internals/controllers/roving-focus.js';
+import {
+ addSlotController,
+ DefaultSlot,
+ setSlots,
+} from '#internals/controllers/slot.js';
+import { registerComponent } from '#internals/definitions/register.js';
+import { EventEmitterMixin } from '#internals/mixins/event-emitter.js';
+import { HydrationMixin } from '#internals/mixins/hydration.js';
+import { I18nMixin } from '#internals/mixins/i18n.js';
+import { partMap } from '#internals/part-map.js';
+import { createTimer } from '#internals/timing.js';
+import { isEmpty } from '#internals/utils/arrays.js';
+import {
+ getElementFromPath,
+ stopPropagation,
+} from '#internals/utils/events.js';
+import { asNumber, clamp } from '#internals/utils/math.js';
+import { formatString } from '#internals/utils/strings.js';
+import { all } from '#themes/color-panel/themes/themes.js';
+import { addThemingController } from '#theming/theming-controller.js';
+import { styles as componentBase } from '../../styles/common/component.css.js';
+import IgcButtonGroupComponent from '../button-group/button-group.js';
+import IgcToggleButtonComponent from '../button-group/toggle-button.js';
+import IgcIconButtonComponent from '../button/icon-button.js';
+import {
+ formatColorName,
+ formatHueValue,
+ formatOklchAreaValue,
+ formatPercent,
+ formatSwatchName,
+ formatValueWithName,
+} from '../color-picker/color-name.js';
+import {
+ CONTRAST_LEVELS,
+ contrastRatio,
+ formatContrastRatio,
+} from '../color-picker/contrast.js';
+import { colorPickerI18nConfig, formatNameKeys } from '../color-picker/i18n.js';
+import {
+ ColorModel,
+ colorFormats,
+ colorKey,
+ formatPlaceholders,
+ parseTypedColor,
+ opaqueColor,
+} from '../color-picker/model.js';
+import {
+ type AreaSpace,
+ cuspColor,
+ OKLCH_AREA_CHROMA,
+ oklchHueTrack,
+} from '../color-picker/oklch.js';
+import IgcPickerCanvasComponent, {
+ type PickerCanvasEventDetail,
+} from '../color-picker/picker-canvas.js';
+import IgcDividerComponent from '../divider/divider.js';
+import IgcInputComponent from '../input/input.js';
+import IgcSelectItemComponent from '../select/select-item.js';
+import IgcSelectComponent from '../select/select.js';
+import type { ColorFormat, ColorPanelView } from '../types.js';
+import IgcVisuallyHiddenComponent from '../visually-hidden/visually-hidden.js';
+import IgcColorSwatchGroupComponent from './color-swatch-group.js';
+import IgcColorSwatchComponent from './color-swatch.js';
+import {
+ panelColor,
+ parseViews,
+ resolveSwatch,
+ resolveView,
+ SWATCH_SELECTED_STATE,
+ swatchKey,
+ syncMarker,
+ parseContextColor,
+ VIEWS,
+} from './common.js';
+import { styles } from './themes/color-panel.base.css.js';
+import { styles as shared } from './themes/shared/color-panel.common.css.js';
+
+export interface IgcColorPanelComponentEventMap {
+ igcInput: CustomEvent;
+ igcChange: CustomEvent;
+}
+
+/** The alpha text is `%`. An edit removes every other character. */
+const nonDigits = /\D/g;
+
+/** The last caret offset in `%`, the position in front of the `%`. */
+function caretLimit(text: string): number {
+ return Math.max(text.length - 1, 0);
+}
+
+/**
+ * The EyeDropper API subset in use. The baseline DOM typings do not include it.
+ * Firefox and Safari do not implement it.
+ */
+interface EyeDropperLike {
+ open(): Promise<{ sRGBHex: string }>;
+}
+
+type EyeDropperConstructor = new () => EyeDropperLike;
+
+function getEyeDropper(): EyeDropperConstructor | undefined {
+ return (globalThis as { EyeDropper?: EyeDropperConstructor }).EyeDropper;
+}
+
+/** The vertical distance in pixels within which two swatches share a row. */
+const ROW_TOLERANCE = 1;
+
+/** The icon and the name of the copy button in each status. */
+const COPY_STATUSES = {
+ copy: { icon: 'copy_content', labelKey: 'color_picker_copy' },
+ success: { icon: 'copy_success', labelKey: 'color_picker_copied' },
+ error: { icon: 'error', labelKey: 'color_picker_copy_failed' },
+} as const;
+
+type CopyStatus = keyof typeof COPY_STATUSES;
+
+/** How long the copy button shows the result of a copy, in milliseconds. */
+const COPY_RESET_DELAY = 1000;
+
+/** The controls where Enter applies the draft of a color picker in the confirm mode. */
+const valueControls = `${IgcColorSwatchComponent.tagName}, ${IgcPickerCanvasComponent.tagName}, input[type="range"]`;
+
+/**
+ * A color selection surface that stays in the page.
+ *
+ * The user picks a color with the color area, the hue slider and the optional
+ * alpha slider. The area is saturation by value, or lightness by chroma at the
+ * OKLCH hue in the `oklch` format. The user can also type any CSS color string,
+ * such as hex, `rgb()`, `hsl()`, `oklch()` or a named color, pick a swatch, or
+ * pick a color from the screen with the native EyeDropper API, where the
+ * browser provides one.
+ *
+ * The panel is not a form control. The color picker shows it in a popup.
+ *
+ * @element igc-color-panel
+ *
+ * @slot - The color swatches and swatch groups. The panel shows them in its swatch list, after the swatches of `swatches`.
+ *
+ * @fires igcInput - Emitted when the user changes the color with the canvas, the sliders, the alpha input, a swatch or the eye dropper.
+ * @fires igcChange - Emitted when the user ends a change of the color: on the release of the canvas or a slider, on each key that moves them, on a commit of the color text or the alpha input, and on a swatch or an eye dropper pick.
+ *
+ * @csspart base - The wrapper of the panel.
+ * @csspart picker-canvas - The area: saturation by value, or lightness by chroma in the `oklch` format.
+ * @csspart marker - The marker on the area that shows the picked color.
+ * @csspart dragging - Added to the marker part while the user drags it.
+ * @csspart main-row - The row containing the hue slider and the copy/eyedropper buttons.
+ * @csspart alpha-row - The row containing the alpha slider and input, rendered when `show-alpha` is set.
+ * @csspart inputs-row - The row containing the format select and the color value input.
+ * @csspart buttons - The wrapper around the copy and eyedropper buttons.
+ * @csspart hue - The hue slider.
+ * @csspart alpha - The alpha slider.
+ * @csspart alpha-input - The input of the alpha value, rendered when `show-alpha` is set.
+ * @csspart copy - The button that copies the current color value to the clipboard.
+ * @csspart eye-dropper - The button that activates the EyeDropper API.
+ * @csspart format-select - The select control used to switch the color string format.
+ * @csspart swatches - The swatch list.
+ * @csspart swatch - A swatch of the `swatches` property.
+ * @csspart selected - Added to the swatch part of the selected swatch.
+ * @csspart view-switcher - The view switcher, rendered when `views` has both views.
+ * @csspart view-button - A button of the view switcher.
+ * @csspart active - Added to the view-button part of the view on screen.
+ * @csspart contrast - The contrast readout, rendered when `contrast-against` has a color and the value is not empty.
+ * @csspart contrast-ratio - The contrast ratio of the value over `contrast-against`.
+ * @csspart contrast-mark - A WCAG level of the contrast readout, AA or AAA.
+ * @csspart pass - Added to the contrast-mark part of a level that the ratio passes.
+ * @csspart fail - Added to the contrast-mark part of a level that the ratio fails.
+ */
+export default class IgcColorPanelComponent extends HydrationMixin(
+ I18nMixin(
+ EventEmitterMixin(LitElement),
+ colorPickerI18nConfig
+ )
+) {
+ public static readonly tagName = 'igc-color-panel';
+ public static override styles = [componentBase, styles, shared];
+
+ /* blazorSuppress */
+ public static register(): void {
+ registerComponent(
+ IgcColorPanelComponent,
+ IgcPickerCanvasComponent,
+ IgcInputComponent,
+ IgcSelectComponent,
+ IgcSelectItemComponent,
+ IgcDividerComponent,
+ IgcIconButtonComponent,
+ IgcButtonGroupComponent,
+ IgcToggleButtonComponent,
+ IgcColorSwatchComponent,
+ IgcColorSwatchGroupComponent,
+ IgcVisuallyHiddenComponent
+ );
+ }
+
+ //#region Internal state and properties
+
+ private readonly _picker = addAsyncContextConsumer(this, colorPickerContext);
+
+ private readonly _alphaInputRef = createRef();
+ private readonly _canvasRef = createRef();
+ private readonly _listboxRef = createRef();
+
+ private readonly _supportsEyeDropper = Boolean(getEyeDropper());
+ private _color = ColorModel.empty();
+
+ /** The color of the last `igcChange` or the last value from code. */
+ private _reportedKey = '';
+
+ /** Whether the marker waits for a move to the color. */
+ private _markerStale = false;
+
+ private readonly _appliedProperties = new Map();
+
+ private _activeView: ColorPanelView = 'gradient';
+
+ /** Whether a swatch connected, disconnected or changed its color. */
+ private _swatchesStale = true;
+
+ private _selectedKey?: string;
+
+ private _hasSlottedSwatches = false;
+
+ /** The color of `contrastAgainst`. It is empty when it does not resolve. */
+ private _contrastColor = ColorModel.empty();
+
+ /** Whether `contrastAgainst` depends on its context, such as a `var()`. */
+ private _contrastInContext = false;
+
+ @state()
+ private _copyStatus: CopyStatus = 'copy';
+
+ /** Only the latest copy in the page shows its result. */
+ private _copyId = 0;
+
+ private readonly _copyTimer = createTimer(
+ () => (this._copyStatus = 'copy'),
+ COPY_RESET_DELAY
+ );
+
+ private readonly _panelContext: ColorPanelContext = {
+ noColorLabel: () => this.resourceStrings.color_picker_no_color,
+ swatchName: (color) => formatSwatchName(color, this),
+ refreshSwatches: () => {
+ this._swatchesStale = true;
+ this.requestUpdate();
+ },
+ };
+
+ private readonly _slots = addSlotController(this, {
+ slots: setSlots(),
+ onChange: this._panelContext.refreshSwatches,
+ });
+
+ //#endregion
+
+ //#region Public attributes and properties
+
+ /**
+ * The value of the component as a CSS color string, in `format`. Accepts any
+ * CSS color, such as hex, `rgb()`, `hsl()`, `oklch()`, `color()` or a named
+ * color. A color outside the sRGB gamut is clipped to it.
+ *
+ * An empty, whitespace-only or invalid string clears the value. So does a
+ * color that depends on its context: `currentcolor`, `var()`, `light-dark()`
+ * or a system color.
+ *
+ * @attr value
+ */
+ @property()
+ public set value(value: string) {
+ const color = ColorModel.parse(value);
+ const key = colorKey(color);
+
+ this._reportedKey = key;
+
+ // The same color keeps the hue and the saturation that a gray does not
+ // carry. Only an empty color has an empty key.
+ if (key === colorKey(this._color)) {
+ return;
+ }
+
+ this._color = color;
+ this._markerStale = true;
+ }
+
+ public get value(): string {
+ return this._color.asString(this.format);
+ }
+
+ /**
+ * The color format of the string value.
+ *
+ * A format change renders `value` in the new notation. The color does not
+ * change, so the component emits no `igcInput` or `igcChange`.
+ *
+ * @attr format
+ * @default 'hex'
+ */
+ @property()
+ public format: ColorFormat = 'hex';
+
+ /**
+ * Whether the format select is hidden.
+ *
+ * @attr hide-formats
+ * @default false
+ */
+ @property({ type: Boolean, attribute: 'hide-formats' })
+ public hideFormats = false;
+
+ /**
+ * Whether to show the alpha slider and input.
+ *
+ * @attr show-alpha
+ * @default false
+ */
+ @property({ type: Boolean, attribute: 'show-alpha' })
+ public showAlpha = false;
+
+ /**
+ * Pre-defined color strings. The component renders them as swatches in its
+ * swatch list, in front of the swatch children. An empty string gives the
+ * no-color swatch.
+ */
+ @property({ attribute: false })
+ public swatches: string[] = [];
+
+ /**
+ * The views of the component, as a space-separated list of `gradient` and
+ * `swatches`. With both views, a view switcher shows at the top.
+ *
+ * With only the gradient view, the swatch list shows below the gradient
+ * controls. With the swatch view, the swatch list shows only in that view.
+ *
+ * @attr views
+ * @default 'gradient'
+ */
+ @property()
+ public views = 'gradient';
+
+ /**
+ * The view on screen: `gradient` or `swatches`. The view switcher sets it
+ * and emits no event. A view that `views` does not have gives the first
+ * view of `views`.
+ *
+ * @attr active-view
+ * @default 'gradient'
+ */
+ @property({ attribute: 'active-view' })
+ public set activeView(value: ColorPanelView) {
+ this._activeView = value;
+ }
+
+ public get activeView(): ColorPanelView {
+ return resolveView(this.views, this._activeView);
+ }
+
+ /**
+ * The background color of the contrast readout, as any CSS color. A color
+ * that depends on its context, such as a `var()`, resolves from the
+ * component. The readout shows the WCAG 2 contrast ratio of the value over
+ * this color, with the AA and AAA levels for normal text. An empty or
+ * invalid color hides it.
+ *
+ * @attr contrast-against
+ */
+ @property({ attribute: 'contrast-against' })
+ public contrastAgainst = '';
+
+ //#endregion
+
+ constructor() {
+ super();
+
+ // A theme can change the `var()` colors.
+ addThemingController(this, all, {
+ themeChange: () => this._refreshContextColors(),
+ });
+
+ addContextProvider(this, {
+ context: colorPanelContext,
+ value: () => this._panelContext,
+ // The locale formats the alpha of a swatch name.
+ watch: ['resourceStrings', 'locale'],
+ });
+
+ // The canvas has no size while the panel is hidden, as in a closed popup.
+ // A panel that shows again can have new `var()` colors, and a swatch in a
+ // group that rendered late reads its color from the page only now.
+ addResizeObserverController(this, {
+ callback: () => {
+ this[syncMarker]();
+ this._refreshContextColors();
+ },
+ requestUpdate: false,
+ });
+
+ // The `focusin` handler moves the tab stop.
+ addRovingFocusController(this, {
+ items: () => this._swatchElements(),
+ current: () => this._focusedSwatch(),
+ focusItem: (swatch) => swatch.focus(),
+ activateItem: this._pickSwatch,
+ keybindings: { ref: this._listboxRef },
+ });
+
+ addKeybindings(this, { ref: this._listboxRef })
+ .set(arrowUp, () => this._focusRow(-1))
+ .set(arrowDown, () => this._focusRow(1));
+
+ addKeybindings(this, {
+ skip: () => !this._alphaInputRef.value,
+ ref: this._alphaInputRef,
+ bindingDefaults: { repeat: true },
+ })
+ .set(arrowUp, () => this._handleAlphaInputSpin(1))
+ .set(arrowDown, () => this._handleAlphaInputSpin(-1))
+ .set(arrowRight, this._handleAlphaInputCaretForward, {
+ preventDefault: false,
+ })
+ .set(endKey, this._handleAlphaInputCaretForward, {
+ preventDefault: false,
+ });
+
+ // After the roving focus, so the picker gets a swatch that Enter picks.
+ addKeybindings(this, {
+ skip: (_, event) => !getElementFromPath(valueControls, event),
+ }).set(enterKey, () => this._picker.value!.applyDraft(), {
+ when: () => this._picker.value?.isConfirmMode() ?? false,
+ });
+ }
+
+ //#region Lit lifecycle methods
+
+ public override disconnectedCallback(): void {
+ this._copyId++;
+ this._copyTimer.stop();
+ this._copyStatus = 'copy';
+ super.disconnectedCallback();
+ }
+
+ protected override update(props: PropertyValues): void {
+ this._applyColorProperties();
+ super.update(props);
+ }
+
+ protected override willUpdate(props: PropertyValues): void {
+ // A switch to the gradient view renders the canvas again, and the area
+ // of the OKLCH format has other axes.
+ if (props.has('activeView') || props.has('views') || props.has('format')) {
+ this._markerStale = true;
+ }
+
+ if (this._swatchesStale) {
+ this._hasSlottedSwatches = !isEmpty(this._slottedSwatches());
+ }
+
+ if (props.has('contrastAgainst')) {
+ this._resolveContrastColor();
+ }
+ }
+
+ protected override updated(): void {
+ if (this._markerStale) {
+ this._markerStale = false;
+ // Wait for the paint, then move the marker to the color.
+ requestAnimationFrame(() => this[syncMarker]());
+ }
+
+ const key = colorKey(this._color);
+
+ if (this._swatchesStale || key !== this._selectedKey) {
+ this._syncSwatches(key);
+ }
+ }
+
+ //#endregion
+
+ //#region Event handlers
+
+ private _handleCanvasColorPicked(
+ event: CustomEvent
+ ): void {
+ stopPropagation(event);
+
+ const { x, y } = event.detail;
+
+ if (this._areaSpace === 'oklch') {
+ this._pickLightnessAndChroma(100 - y, (x / 100) * OKLCH_AREA_CHROMA);
+ return;
+ }
+
+ this._color.setSaturationAndValue(x, 100 - y);
+ this._applyUserColor();
+ }
+
+ private _handleHueValueChange(event: Event): void {
+ stopPropagation(event);
+
+ const hue = asNumber((event.target as HTMLInputElement).value);
+
+ if (this._areaSpace === 'oklch') {
+ // The gamut of the new hue can cut the chroma, which moves the marker.
+ if (this._color.setOklchHue(hue)) {
+ this[syncMarker]();
+ }
+ } else {
+ this._color.h = hue;
+ }
+
+ this._applyUserColor();
+ }
+
+ private _handleAlphaSliderValueChange(event: Event): void {
+ stopPropagation(event);
+
+ this._setAlpha(asNumber((event.target as HTMLInputElement).value));
+ }
+
+ /** The `change` of a slider or the canvas: at the release, or on a key. */
+ private _handleGestureEnd(event: Event): void {
+ stopPropagation(event);
+ this._endChange();
+ }
+
+ /**
+ * Writes the alpha field again as `%` after each edit, because
+ * `beforeinput` carries `data` only for typing, not for paste, drop,
+ * composition, undo or autofill.
+ */
+ private _handleAlphaInputEdit(event: Event): void {
+ const input = this._alphaInputRef.value;
+ const native = getElementFromPath('input', event);
+
+ if (!input || !native) return;
+
+ const caret = native.selectionStart ?? native.value.length;
+ const typed = native.value.slice(0, caret).replace(nonDigits, '').length;
+ const digits = native.value.replace(nonDigits, '');
+ const percent = clamp(asNumber(digits), 0, 100);
+
+ const text = digits ? `${percent}%` : '';
+
+ this._writeAlphaText(input, text, Math.min(typed, caretLimit(text)));
+
+ if (digits) {
+ this._setAlpha(percent);
+ }
+ }
+
+ /**
+ * Keeps the caret and the selection in the digits. `keyup`, `focusin` and
+ * `click` can put the caret after the `%`.
+ */
+ private _handleAlphaInputCaret(event: Event): void {
+ const native = getElementFromPath('input', event);
+ if (!native) return;
+
+ const limit = caretLimit(native.value);
+
+ native.setSelectionRange(
+ Math.min(native.selectionStart ?? 0, limit),
+ Math.min(native.selectionEnd ?? 0, limit)
+ );
+ }
+
+ /**
+ * Steps the alpha from the color, not the text, because a held key repeats
+ * faster than a render. It writes the text itself, because a write from the
+ * render applies one frame late and the caret jumps.
+ */
+ private _handleAlphaInputSpin(increment: -1 | 1): void {
+ const input = this._alphaInputRef.value;
+ const percent = clamp(this._alphaPercent + increment, 0, 100);
+
+ if (!input || percent === this._alphaPercent) return;
+
+ this._writeAlphaText(input, `${percent}%`);
+ this._setAlpha(percent);
+ this._endChange();
+ }
+
+ /**
+ * Holds the caret at the `%`. Without this handler the caret steps past the
+ * `%`, and `keyup` pulls it back. This is the frame-late jump that
+ * {@link _handleAlphaInputSpin} describes.
+ */
+ private _handleAlphaInputCaretForward(event: KeyboardEvent): void {
+ const native = getElementFromPath('input', event);
+ if (!native) return;
+
+ const limit = caretLimit(native.value);
+
+ if (isKey(event, endKey) || (native.selectionEnd ?? 0) >= limit) {
+ event.preventDefault();
+ native.setSelectionRange(limit, limit);
+ }
+ }
+
+ private _handleAlphaInputChange(event: CustomEvent): void {
+ stopPropagation(event);
+
+ const input = event.target as IgcInputComponent;
+
+ if (!input.value) {
+ input.value = `${this._alphaPercent}%`;
+ }
+
+ this._endChange();
+ }
+
+ private _handleFormatChange(
+ event: CustomEvent
+ ): void {
+ stopPropagation(event);
+
+ this.format = event.detail.value as ColorFormat;
+ this._picker.value?.setFormat(this.format);
+ }
+
+ private _handleColorInputChange(event: CustomEvent): void {
+ stopPropagation(event);
+
+ const color = parseTypedColor(event.detail);
+
+ if (!color) {
+ (event.target as IgcInputComponent).value = this.value;
+ return;
+ }
+
+ // A commit of the text, so no `igcInput`.
+ this._color = color;
+ this._markerStale = true;
+ this.requestUpdate();
+ this._endChange();
+ }
+
+ private _handleEyeDropperClick(): void {
+ const EyeDropper = getEyeDropper();
+
+ if (!EyeDropper) return;
+
+ new EyeDropper()
+ .open()
+ .then((result) => this._pickColor(result.sRGBHex))
+ .catch(() => {});
+ }
+
+ private async _handleCopy(): Promise {
+ const id = ++this._copyId;
+ let status: CopyStatus = 'success';
+
+ try {
+ // Outside a secure context there is no clipboard, and this throws.
+ await navigator.clipboard.writeText(this.value);
+ } catch {
+ status = 'error';
+ }
+
+ if (id === this._copyId) {
+ this._copyStatus = status;
+ this._copyTimer.start();
+ }
+ }
+
+ private _handleSwatchClick(event: Event): void {
+ const swatch = this._swatchFromEvent(event);
+
+ if (swatch) {
+ this._pickSwatch(swatch);
+ }
+ }
+
+ private _handleSwatchFocusIn(event: FocusEvent): void {
+ const swatch = this._swatchFromEvent(event);
+
+ if (swatch) {
+ this._setTabStop(swatch, this._swatchElements());
+ }
+ }
+
+ private _handleViewSelect(event: CustomEvent): void {
+ stopPropagation(event);
+
+ this.activeView = event.detail as ColorPanelView;
+ this._picker.value?.setActiveView(this.activeView);
+ }
+
+ //#endregion
+
+ //#region Color changes
+
+ private get _areaSpace(): AreaSpace {
+ return this.format === 'oklch' ? 'oklch' : 'hsv';
+ }
+
+ /**
+ * The marker position in percent of the area: across, and up from the
+ * bottom. In the OKLCH format, the chroma and the lightness.
+ */
+ private get _areaPosition(): [across: number, up: number] {
+ if (this._areaSpace === 'oklch') {
+ const [lightness, chroma] = this._color.toOKLCH();
+ return [(chroma / OKLCH_AREA_CHROMA) * 100, lightness];
+ }
+
+ const [, saturation, value] = this._color.toHSV();
+ return [saturation, value];
+ }
+
+ /**
+ * Takes a pick on the OKLCH area. Beyond the gamut edge the chroma stops at
+ * the edge, and so does the marker. A pick of the same color reports
+ * nothing.
+ */
+ private _pickLightnessAndChroma(lightness: number, chroma: number): void {
+ const previous = this.value;
+
+ if (this._color.setLightnessAndChroma(lightness, chroma)) {
+ this[syncMarker]();
+ }
+
+ if (this.value !== previous) {
+ this._applyUserColor();
+ }
+ }
+
+ /** The alpha channel as the whole percentage that both alpha controls use. */
+ private get _alphaPercent(): number {
+ return Math.round(this._color.alpha * 100);
+ }
+
+ /**
+ * The pure hue that the HSV area and the hue thumb use. In the OKLCH format,
+ * the cusp of the hue.
+ */
+ private get _currentColor(): string {
+ return this._areaSpace === 'oklch'
+ ? cuspColor(this._color.toOKLCH()[2])
+ : `hsl(${this._color.h} 100% 50%)`;
+ }
+
+ /**
+ * Copies the colors that the stylesheet needs onto the host. `update()` calls
+ * it, so it also runs on a first render with no value.
+ */
+ private _applyColorProperties(): void {
+ this._setHostColor('--_current-color', this._currentColor);
+ this._setHostColor('--_selected-color', opaqueColor(this._color));
+ this._setHostColor(
+ '--_hue-slider-track',
+ this._areaSpace === 'oklch' ? oklchHueTrack() : ''
+ );
+ }
+
+ private _setHostColor(name: string, value: string): void {
+ if (this._appliedProperties.get(name) !== value) {
+ this._appliedProperties.set(name, value);
+ this.style.setProperty(name, value);
+ }
+ }
+
+ /** Replaces the alpha text. The caret goes in front of the `%` by default. */
+ private _writeAlphaText(
+ input: IgcInputComponent,
+ text: string,
+ caret = caretLimit(text)
+ ): void {
+ input.setRangeText(text, 0, input.value.length);
+ input.setSelectionRange(caret, caret);
+ }
+
+ private _setAlpha(percent: number): void {
+ const alpha = clamp(percent, 0, 100) / 100;
+
+ if (this._color.alpha === alpha) {
+ return;
+ }
+
+ this._color.alpha = alpha;
+ this._applyUserColor();
+ }
+
+ private _applyUserColor(): void {
+ this.requestUpdate();
+ this.emitEvent('igcInput', { detail: this.value });
+ }
+
+ /** Takes a whole color from a swatch or the eye dropper, as one change. */
+ private _pickColor(value: string): void {
+ this._color = ColorModel.parse(value);
+ this._markerStale = true;
+ this._applyUserColor();
+ this._endChange();
+ }
+
+ private _endChange(): void {
+ const key = colorKey(this._color);
+
+ if (key !== this._reportedKey) {
+ this._reportedKey = key;
+ this.emitEvent('igcChange', { detail: this.value });
+ }
+ }
+
+ /** Reads the colors that depend on the context again. */
+ private _refreshContextColors(): void {
+ if (this._contrastInContext) {
+ this._resolveContrastColor();
+ }
+
+ this._panelContext.refreshSwatches();
+ }
+
+ /** Reads the color of `contrastAgainst`, also from the context. */
+ private _resolveContrastColor(): void {
+ const value = this.contrastAgainst ?? '';
+ const color = ColorModel.parse(value);
+
+ // The parser rejects the colors that depend on the context.
+ this._contrastInContext = color.isEmpty && Boolean(value);
+ this._contrastColor = this._contrastInContext
+ ? parseContextColor(this, value)
+ : color;
+ }
+
+ //#endregion
+
+ //#region Swatch list
+
+ /**
+ * All swatches of the list, in order: the swatches of `swatches`, then the
+ * slotted swatches and the swatches inside the slotted elements, such as a
+ * swatch group.
+ */
+ private _swatchElements(): IgcColorSwatchComponent[] {
+ const own = Array.from(
+ this._listboxRef.value?.querySelectorAll(
+ `:scope > ${IgcColorSwatchComponent.tagName}`
+ ) ?? []
+ );
+
+ return [...own, ...this._slottedSwatches()];
+ }
+
+ /** The slotted swatches and the swatches inside the slotted elements. */
+ private _slottedSwatches(): IgcColorSwatchComponent[] {
+ const tag = IgcColorSwatchComponent.tagName;
+
+ // A swatch that is not defined yet has no internal API.
+ return this._slots
+ .getAssignedElements(DefaultSlot, { flatten: true })
+ .flatMap((element) =>
+ element.localName === tag
+ ? [element]
+ : Array.from(element.querySelectorAll(tag))
+ )
+ .filter(
+ (swatch): swatch is IgcColorSwatchComponent =>
+ swatch instanceof IgcColorSwatchComponent
+ );
+ }
+
+ private _swatchFromEvent(event: Event): IgcColorSwatchComponent | undefined {
+ const swatch = getElementFromPath(IgcColorSwatchComponent.tagName, event);
+ return swatch instanceof IgcColorSwatchComponent ? swatch : undefined;
+ }
+
+ private _focusedSwatch(): IgcColorSwatchComponent | undefined {
+ return this._swatchElements().find((swatch) => swatch.matches(':focus'));
+ }
+
+ /**
+ * Moves the focus to the nearest swatch in the next row of the list, up or
+ * down. Rows come from the layout, so the swatch groups and the column count
+ * of the theme count.
+ */
+ private _focusRow(direction: -1 | 1): void {
+ const current = this._focusedSwatch();
+
+ if (!current) {
+ return;
+ }
+
+ const from = current.getBoundingClientRect();
+ const center = from.left + from.width / 2;
+ let best:
+ | { swatch: IgcColorSwatchComponent; dy: number; dx: number }
+ | undefined;
+
+ for (const swatch of this._swatchElements()) {
+ const rect = swatch.getBoundingClientRect();
+ const dy =
+ direction > 0 ? rect.top - from.bottom : from.top - rect.bottom;
+
+ // The same row, a row on the other side, or a hidden swatch.
+ if (dy < -ROW_TOLERANCE || swatch === current || !rect.width) {
+ continue;
+ }
+
+ const dx = Math.abs(rect.left + rect.width / 2 - center);
+
+ if (
+ !best ||
+ dy < best.dy - ROW_TOLERANCE ||
+ (Math.abs(dy - best.dy) <= ROW_TOLERANCE && dx < best.dx)
+ ) {
+ best = { swatch, dy, dx };
+ }
+ }
+
+ if (best) {
+ best.swatch.focus();
+ }
+ }
+
+ private _setTabStop(
+ stop: IgcColorSwatchComponent | undefined,
+ swatches: IgcColorSwatchComponent[]
+ ): void {
+ for (const swatch of swatches) {
+ const tabIndex = swatch === stop ? '0' : '-1';
+
+ // A write restyles the swatch, also for the same value.
+ if (swatch.getAttribute('tabindex') !== tabIndex) {
+ swatch.setAttribute('tabindex', tabIndex);
+ }
+ }
+ }
+
+ /**
+ * Selects the first swatch that has the color of the value: the list is a
+ * single-select listbox. The tab stop is the focused swatch, else the
+ * selected swatch, else the first swatch.
+ */
+ private _syncSwatches(key: string): void {
+ const swatches = this._swatchElements();
+ const readColors = this._swatchesStale;
+
+ this._swatchesStale = false;
+ this._selectedKey = key;
+
+ if (readColors) {
+ for (const swatch of swatches) {
+ swatch[resolveSwatch]();
+ }
+ }
+
+ const selected = swatches.find((swatch) => swatch[swatchKey] === key);
+
+ for (const swatch of swatches) {
+ const isSelected = swatch === selected;
+ const internals = internalsOf(swatch);
+
+ internals?.setARIA({ ariaSelected: `${isSelected}` });
+ internals?.setState(SWATCH_SELECTED_STATE, isSelected);
+
+ // Only the swatches of the `swatches` shortcut are parts of the panel.
+ if (swatch.getRootNode() === this.renderRoot) {
+ swatch.part.toggle('selected', isSelected);
+ }
+ }
+
+ this._setTabStop(
+ swatches.find((swatch) => swatch.matches(':focus')) ??
+ selected ??
+ swatches[0],
+ swatches
+ );
+ }
+
+ private _pickSwatch(swatch: IgcColorSwatchComponent): void {
+ swatch[resolveSwatch]();
+
+ const key = swatch[swatchKey];
+
+ if (key !== null) {
+ this._pickColor(key);
+ }
+ }
+
+ //#endregion
+
+ //#region Internal API
+
+ /** @internal */
+ public [panelColor](): ColorModel {
+ return this._color.clone();
+ }
+
+ /** @internal */
+ public [syncMarker](): void {
+ const canvas = this._canvasRef.value;
+
+ if (!canvas) return;
+
+ const rect = canvas.getBoundingClientRect();
+
+ // A hidden canvas has no size to place the marker on.
+ if (!(rect.width && rect.height)) return;
+
+ const { width: markerWidth, height: markerHeight } =
+ canvas.getMarkerDimensions();
+
+ const [across, up] = this._areaPosition;
+
+ canvas.x = (across / 100) * rect.width - markerWidth;
+ canvas.y = ((100 - up) / 100) * rect.height - markerHeight;
+ }
+
+ //#endregion
+
+ private _renderCanvasGradient(): TemplateResult {
+ const strings = this.resourceStrings;
+ const space = this._areaSpace;
+ const oklch = space === 'oklch';
+ const [across, up] = this._areaPosition;
+ const [, chroma, hue] = this._color.toOKLCH();
+ const axes = oklch
+ ? formatOklchAreaValue(up, chroma, this)
+ : formatString(
+ strings.color_picker_canvas_value,
+ Math.round(across),
+ Math.round(up)
+ );
+ // An empty value has no color name.
+ const valueText = this._color.isEmpty
+ ? axes
+ : formatValueWithName(
+ axes,
+ formatColorName(this._color.toRGB(), strings),
+ strings
+ );
+
+ return html`
+
+
+ `;
+ }
+
+ private _renderHueSlider(): TemplateResult {
+ const space = this._areaSpace;
+ const hue = Math.round(
+ space === 'oklch' ? this._color.toOKLCH()[2] : this._color.h
+ );
+
+ return html`
+
+ `;
+ }
+
+ private _renderIconButton(
+ part: string,
+ icon: string,
+ label: string,
+ handler: () => void,
+ disabled = false
+ ): TemplateResult {
+ return html`
+
+ ${label}
+
+ `;
+ }
+
+ private _renderButtons(): TemplateResult {
+ const strings = this.resourceStrings;
+ const copy = COPY_STATUSES[this._copyStatus];
+
+ return html`
+